* auto-profile.c (afdo_annotate_cfg): Use update_max_bb_count.
[official-gcc.git] / gcc / tree-vrp.c
blob6fae6b2efb84ddb2fdd2a4a480df74f8bb0b321f
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2017 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-general.h"
59 #include "target.h"
60 #include "case-cfn-macros.h"
61 #include "params.h"
62 #include "alloc-pool.h"
63 #include "domwalk.h"
64 #include "tree-cfgcleanup.h"
65 #include "stringpool.h"
66 #include "attribs.h"
67 #include "vr-values.h"
69 /* Set of SSA names found live during the RPO traversal of the function
70 for still active basic-blocks. */
71 static sbitmap *live;
73 /* Return true if the SSA name NAME is live on the edge E. */
75 static bool
76 live_on_edge (edge e, tree name)
78 return (live[e->dest->index]
79 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
82 /* Local functions. */
83 static int compare_values (tree val1, tree val2);
84 static int compare_values_warnv (tree val1, tree val2, bool *);
86 /* Location information for ASSERT_EXPRs. Each instance of this
87 structure describes an ASSERT_EXPR for an SSA name. Since a single
88 SSA name may have more than one assertion associated with it, these
89 locations are kept in a linked list attached to the corresponding
90 SSA name. */
91 struct assert_locus
93 /* Basic block where the assertion would be inserted. */
94 basic_block bb;
96 /* Some assertions need to be inserted on an edge (e.g., assertions
97 generated by COND_EXPRs). In those cases, BB will be NULL. */
98 edge e;
100 /* Pointer to the statement that generated this assertion. */
101 gimple_stmt_iterator si;
103 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
104 enum tree_code comp_code;
106 /* Value being compared against. */
107 tree val;
109 /* Expression to compare. */
110 tree expr;
112 /* Next node in the linked list. */
113 assert_locus *next;
116 /* If bit I is present, it means that SSA name N_i has a list of
117 assertions that should be inserted in the IL. */
118 static bitmap need_assert_for;
120 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
121 holds a list of ASSERT_LOCUS_T nodes that describe where
122 ASSERT_EXPRs for SSA name N_I should be inserted. */
123 static assert_locus **asserts_for;
125 struct switch_update {
126 gswitch *stmt;
127 tree vec;
130 static vec<edge> to_remove_edges;
131 static vec<switch_update> to_update_switch_stmts;
134 /* Return the maximum value for TYPE. */
136 static inline tree
137 vrp_val_max (const_tree type)
139 if (!INTEGRAL_TYPE_P (type))
140 return NULL_TREE;
142 return TYPE_MAX_VALUE (type);
145 /* Return the minimum value for TYPE. */
147 static inline tree
148 vrp_val_min (const_tree type)
150 if (!INTEGRAL_TYPE_P (type))
151 return NULL_TREE;
153 return TYPE_MIN_VALUE (type);
156 /* Return whether VAL is equal to the maximum value of its type.
157 We can't do a simple equality comparison with TYPE_MAX_VALUE because
158 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
159 is not == to the integer constant with the same value in the type. */
161 static inline bool
162 vrp_val_is_max (const_tree val)
164 tree type_max = vrp_val_max (TREE_TYPE (val));
165 return (val == type_max
166 || (type_max != NULL_TREE
167 && operand_equal_p (val, type_max, 0)));
170 /* Return whether VAL is equal to the minimum value of its type. */
172 static inline bool
173 vrp_val_is_min (const_tree val)
175 tree type_min = vrp_val_min (TREE_TYPE (val));
176 return (val == type_min
177 || (type_min != NULL_TREE
178 && operand_equal_p (val, type_min, 0)));
182 /* Set value range VR to VR_UNDEFINED. */
184 static inline void
185 set_value_range_to_undefined (value_range *vr)
187 vr->type = VR_UNDEFINED;
188 vr->min = vr->max = NULL_TREE;
189 if (vr->equiv)
190 bitmap_clear (vr->equiv);
193 /* Set value range VR to VR_VARYING. */
195 void
196 set_value_range_to_varying (value_range *vr)
198 vr->type = VR_VARYING;
199 vr->min = vr->max = NULL_TREE;
200 if (vr->equiv)
201 bitmap_clear (vr->equiv);
204 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
206 static void
207 set_value_range (value_range *vr, enum value_range_type t, tree min,
208 tree max, bitmap equiv)
210 /* Check the validity of the range. */
211 if (flag_checking
212 && (t == VR_RANGE || t == VR_ANTI_RANGE))
214 int cmp;
216 gcc_assert (min && max);
218 gcc_assert (!TREE_OVERFLOW_P (min) && !TREE_OVERFLOW_P (max));
220 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
221 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
223 cmp = compare_values (min, max);
224 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
227 if (flag_checking
228 && (t == VR_UNDEFINED || t == VR_VARYING))
230 gcc_assert (min == NULL_TREE && max == NULL_TREE);
231 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
234 vr->type = t;
235 vr->min = min;
236 vr->max = max;
238 /* Since updating the equivalence set involves deep copying the
239 bitmaps, only do it if absolutely necessary.
241 All equivalence bitmaps are allocated from the same obstack. So
242 we can use the obstack associated with EQUIV to allocate vr->equiv. */
243 if (vr->equiv == NULL
244 && equiv != NULL)
245 vr->equiv = BITMAP_ALLOC (equiv->obstack);
247 if (equiv != vr->equiv)
249 if (equiv && !bitmap_empty_p (equiv))
250 bitmap_copy (vr->equiv, equiv);
251 else
252 bitmap_clear (vr->equiv);
257 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
258 This means adjusting T, MIN and MAX representing the case of a
259 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
260 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
261 In corner cases where MAX+1 or MIN-1 wraps this will fall back
262 to varying.
263 This routine exists to ease canonicalization in the case where we
264 extract ranges from var + CST op limit. */
266 static void
267 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
268 tree min, tree max, bitmap equiv)
270 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
271 if (t == VR_UNDEFINED)
273 set_value_range_to_undefined (vr);
274 return;
276 else if (t == VR_VARYING)
278 set_value_range_to_varying (vr);
279 return;
282 /* Nothing to canonicalize for symbolic ranges. */
283 if (TREE_CODE (min) != INTEGER_CST
284 || TREE_CODE (max) != INTEGER_CST)
286 set_value_range (vr, t, min, max, equiv);
287 return;
290 /* Wrong order for min and max, to swap them and the VR type we need
291 to adjust them. */
292 if (tree_int_cst_lt (max, min))
294 tree one, tmp;
296 /* For one bit precision if max < min, then the swapped
297 range covers all values, so for VR_RANGE it is varying and
298 for VR_ANTI_RANGE empty range, so drop to varying as well. */
299 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
301 set_value_range_to_varying (vr);
302 return;
305 one = build_int_cst (TREE_TYPE (min), 1);
306 tmp = int_const_binop (PLUS_EXPR, max, one);
307 max = int_const_binop (MINUS_EXPR, min, one);
308 min = tmp;
310 /* There's one corner case, if we had [C+1, C] before we now have
311 that again. But this represents an empty value range, so drop
312 to varying in this case. */
313 if (tree_int_cst_lt (max, min))
315 set_value_range_to_varying (vr);
316 return;
319 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
322 /* Anti-ranges that can be represented as ranges should be so. */
323 if (t == VR_ANTI_RANGE)
325 bool is_min = vrp_val_is_min (min);
326 bool is_max = vrp_val_is_max (max);
328 if (is_min && is_max)
330 /* We cannot deal with empty ranges, drop to varying.
331 ??? This could be VR_UNDEFINED instead. */
332 set_value_range_to_varying (vr);
333 return;
335 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
336 && (is_min || is_max))
338 /* Non-empty boolean ranges can always be represented
339 as a singleton range. */
340 if (is_min)
341 min = max = vrp_val_max (TREE_TYPE (min));
342 else
343 min = max = vrp_val_min (TREE_TYPE (min));
344 t = VR_RANGE;
346 else if (is_min
347 /* As a special exception preserve non-null ranges. */
348 && !(TYPE_UNSIGNED (TREE_TYPE (min))
349 && integer_zerop (max)))
351 tree one = build_int_cst (TREE_TYPE (max), 1);
352 min = int_const_binop (PLUS_EXPR, max, one);
353 max = vrp_val_max (TREE_TYPE (max));
354 t = VR_RANGE;
356 else if (is_max)
358 tree one = build_int_cst (TREE_TYPE (min), 1);
359 max = int_const_binop (MINUS_EXPR, min, one);
360 min = vrp_val_min (TREE_TYPE (min));
361 t = VR_RANGE;
365 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
366 to make sure VRP iteration terminates, otherwise we can get into
367 oscillations. */
369 set_value_range (vr, t, min, max, equiv);
372 /* Copy value range FROM into value range TO. */
374 static inline void
375 copy_value_range (value_range *to, value_range *from)
377 set_value_range (to, from->type, from->min, from->max, from->equiv);
380 /* Set value range VR to a single value. This function is only called
381 with values we get from statements, and exists to clear the
382 TREE_OVERFLOW flag. */
384 static inline void
385 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
387 gcc_assert (is_gimple_min_invariant (val));
388 if (TREE_OVERFLOW_P (val))
389 val = drop_tree_overflow (val);
390 set_value_range (vr, VR_RANGE, val, val, equiv);
393 /* Set value range VR to a non-negative range of type TYPE. */
395 static inline void
396 set_value_range_to_nonnegative (value_range *vr, tree type)
398 tree zero = build_int_cst (type, 0);
399 set_value_range (vr, VR_RANGE, zero, vrp_val_max (type), vr->equiv);
402 /* Set value range VR to a non-NULL range of type TYPE. */
404 static inline void
405 set_value_range_to_nonnull (value_range *vr, tree type)
407 tree zero = build_int_cst (type, 0);
408 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
412 /* Set value range VR to a NULL range of type TYPE. */
414 static inline void
415 set_value_range_to_null (value_range *vr, tree type)
417 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
421 /* Set value range VR to a range of a truthvalue of type TYPE. */
423 static inline void
424 set_value_range_to_truthvalue (value_range *vr, tree type)
426 if (TYPE_PRECISION (type) == 1)
427 set_value_range_to_varying (vr);
428 else
429 set_value_range (vr, VR_RANGE,
430 build_int_cst (type, 0), build_int_cst (type, 1),
431 vr->equiv);
435 /* If abs (min) < abs (max), set VR to [-max, max], if
436 abs (min) >= abs (max), set VR to [-min, min]. */
438 static void
439 abs_extent_range (value_range *vr, tree min, tree max)
441 int cmp;
443 gcc_assert (TREE_CODE (min) == INTEGER_CST);
444 gcc_assert (TREE_CODE (max) == INTEGER_CST);
445 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
446 gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
447 min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
448 max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
449 if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
451 set_value_range_to_varying (vr);
452 return;
454 cmp = compare_values (min, max);
455 if (cmp == -1)
456 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
457 else if (cmp == 0 || cmp == 1)
459 max = min;
460 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
462 else
464 set_value_range_to_varying (vr);
465 return;
467 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
471 /* Return value range information for VAR.
473 If we have no values ranges recorded (ie, VRP is not running), then
474 return NULL. Otherwise create an empty range if none existed for VAR. */
476 value_range *
477 vr_values::get_value_range (const_tree var)
479 static const value_range vr_const_varying
480 = { VR_VARYING, NULL_TREE, NULL_TREE, NULL };
481 value_range *vr;
482 tree sym;
483 unsigned ver = SSA_NAME_VERSION (var);
485 /* If we have no recorded ranges, then return NULL. */
486 if (! vr_value)
487 return NULL;
489 /* If we query the range for a new SSA name return an unmodifiable VARYING.
490 We should get here at most from the substitute-and-fold stage which
491 will never try to change values. */
492 if (ver >= num_vr_values)
493 return CONST_CAST (value_range *, &vr_const_varying);
495 vr = vr_value[ver];
496 if (vr)
497 return vr;
499 /* After propagation finished do not allocate new value-ranges. */
500 if (values_propagated)
501 return CONST_CAST (value_range *, &vr_const_varying);
503 /* Create a default value range. */
504 vr_value[ver] = vr = vrp_value_range_pool.allocate ();
505 memset (vr, 0, sizeof (*vr));
507 /* Defer allocating the equivalence set. */
508 vr->equiv = NULL;
510 /* If VAR is a default definition of a parameter, the variable can
511 take any value in VAR's type. */
512 if (SSA_NAME_IS_DEFAULT_DEF (var))
514 sym = SSA_NAME_VAR (var);
515 if (TREE_CODE (sym) == PARM_DECL)
517 /* Try to use the "nonnull" attribute to create ~[0, 0]
518 anti-ranges for pointers. Note that this is only valid with
519 default definitions of PARM_DECLs. */
520 if (POINTER_TYPE_P (TREE_TYPE (sym))
521 && (nonnull_arg_p (sym)
522 || get_ptr_nonnull (var)))
523 set_value_range_to_nonnull (vr, TREE_TYPE (sym));
524 else if (INTEGRAL_TYPE_P (TREE_TYPE (sym)))
526 wide_int min, max;
527 value_range_type rtype = get_range_info (var, &min, &max);
528 if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
529 set_value_range (vr, rtype,
530 wide_int_to_tree (TREE_TYPE (var), min),
531 wide_int_to_tree (TREE_TYPE (var), max),
532 NULL);
533 else
534 set_value_range_to_varying (vr);
536 else
537 set_value_range_to_varying (vr);
539 else if (TREE_CODE (sym) == RESULT_DECL
540 && DECL_BY_REFERENCE (sym))
541 set_value_range_to_nonnull (vr, TREE_TYPE (sym));
544 return vr;
547 /* Set value-ranges of all SSA names defined by STMT to varying. */
549 void
550 vr_values::set_defs_to_varying (gimple *stmt)
552 ssa_op_iter i;
553 tree def;
554 FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
556 value_range *vr = get_value_range (def);
557 /* Avoid writing to vr_const_varying get_value_range may return. */
558 if (vr->type != VR_VARYING)
559 set_value_range_to_varying (vr);
564 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
566 bool
567 vrp_operand_equal_p (const_tree val1, const_tree val2)
569 if (val1 == val2)
570 return true;
571 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
572 return false;
573 return true;
576 /* Return true, if the bitmaps B1 and B2 are equal. */
578 static inline bool
579 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
581 return (b1 == b2
582 || ((!b1 || bitmap_empty_p (b1))
583 && (!b2 || bitmap_empty_p (b2)))
584 || (b1 && b2
585 && bitmap_equal_p (b1, b2)));
588 /* Update the value range and equivalence set for variable VAR to
589 NEW_VR. Return true if NEW_VR is different from VAR's previous
590 value.
592 NOTE: This function assumes that NEW_VR is a temporary value range
593 object created for the sole purpose of updating VAR's range. The
594 storage used by the equivalence set from NEW_VR will be freed by
595 this function. Do not call update_value_range when NEW_VR
596 is the range object associated with another SSA name. */
598 bool
599 vr_values::update_value_range (const_tree var, value_range *new_vr)
601 value_range *old_vr;
602 bool is_new;
604 /* If there is a value-range on the SSA name from earlier analysis
605 factor that in. */
606 if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
608 wide_int min, max;
609 value_range_type rtype = get_range_info (var, &min, &max);
610 if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
612 tree nr_min, nr_max;
613 nr_min = wide_int_to_tree (TREE_TYPE (var), min);
614 nr_max = wide_int_to_tree (TREE_TYPE (var), max);
615 value_range nr = VR_INITIALIZER;
616 set_and_canonicalize_value_range (&nr, rtype, nr_min, nr_max, NULL);
617 vrp_intersect_ranges (new_vr, &nr);
621 /* Update the value range, if necessary. */
622 old_vr = get_value_range (var);
623 is_new = old_vr->type != new_vr->type
624 || !vrp_operand_equal_p (old_vr->min, new_vr->min)
625 || !vrp_operand_equal_p (old_vr->max, new_vr->max)
626 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr->equiv);
628 if (is_new)
630 /* Do not allow transitions up the lattice. The following
631 is slightly more awkward than just new_vr->type < old_vr->type
632 because VR_RANGE and VR_ANTI_RANGE need to be considered
633 the same. We may not have is_new when transitioning to
634 UNDEFINED. If old_vr->type is VARYING, we shouldn't be
635 called. */
636 if (new_vr->type == VR_UNDEFINED)
638 BITMAP_FREE (new_vr->equiv);
639 set_value_range_to_varying (old_vr);
640 set_value_range_to_varying (new_vr);
641 return true;
643 else
644 set_value_range (old_vr, new_vr->type, new_vr->min, new_vr->max,
645 new_vr->equiv);
648 BITMAP_FREE (new_vr->equiv);
650 return is_new;
654 /* Add VAR and VAR's equivalence set to EQUIV. This is the central
655 point where equivalence processing can be turned on/off. */
657 void
658 vr_values::add_equivalence (bitmap *equiv, const_tree var)
660 unsigned ver = SSA_NAME_VERSION (var);
661 value_range *vr = get_value_range (var);
663 if (*equiv == NULL)
664 *equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
665 bitmap_set_bit (*equiv, ver);
666 if (vr && vr->equiv)
667 bitmap_ior_into (*equiv, vr->equiv);
671 /* Return true if VR is ~[0, 0]. */
673 static inline bool
674 range_is_nonnull (value_range *vr)
676 return vr->type == VR_ANTI_RANGE
677 && integer_zerop (vr->min)
678 && integer_zerop (vr->max);
682 /* Return true if VR is [0, 0]. */
684 static inline bool
685 range_is_null (value_range *vr)
687 return vr->type == VR_RANGE
688 && integer_zerop (vr->min)
689 && integer_zerop (vr->max);
692 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
693 a singleton. */
695 static inline bool
696 range_int_cst_p (value_range *vr)
698 return (vr->type == VR_RANGE
699 && TREE_CODE (vr->max) == INTEGER_CST
700 && TREE_CODE (vr->min) == INTEGER_CST);
703 /* Return true if VR is a INTEGER_CST singleton. */
705 static inline bool
706 range_int_cst_singleton_p (value_range *vr)
708 return (range_int_cst_p (vr)
709 && tree_int_cst_equal (vr->min, vr->max));
712 /* Return true if value range VR involves at least one symbol. */
714 static inline bool
715 symbolic_range_p (value_range *vr)
717 return (!is_gimple_min_invariant (vr->min)
718 || !is_gimple_min_invariant (vr->max));
721 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
722 otherwise. We only handle additive operations and set NEG to true if the
723 symbol is negated and INV to the invariant part, if any. */
725 static tree
726 get_single_symbol (tree t, bool *neg, tree *inv)
728 bool neg_;
729 tree inv_;
731 *inv = NULL_TREE;
732 *neg = false;
734 if (TREE_CODE (t) == PLUS_EXPR
735 || TREE_CODE (t) == POINTER_PLUS_EXPR
736 || TREE_CODE (t) == MINUS_EXPR)
738 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
740 neg_ = (TREE_CODE (t) == MINUS_EXPR);
741 inv_ = TREE_OPERAND (t, 0);
742 t = TREE_OPERAND (t, 1);
744 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
746 neg_ = false;
747 inv_ = TREE_OPERAND (t, 1);
748 t = TREE_OPERAND (t, 0);
750 else
751 return NULL_TREE;
753 else
755 neg_ = false;
756 inv_ = NULL_TREE;
759 if (TREE_CODE (t) == NEGATE_EXPR)
761 t = TREE_OPERAND (t, 0);
762 neg_ = !neg_;
765 if (TREE_CODE (t) != SSA_NAME)
766 return NULL_TREE;
768 if (inv_ && TREE_OVERFLOW_P (inv_))
769 inv_ = drop_tree_overflow (inv_);
771 *neg = neg_;
772 *inv = inv_;
773 return t;
776 /* The reverse operation: build a symbolic expression with TYPE
777 from symbol SYM, negated according to NEG, and invariant INV. */
779 static tree
780 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
782 const bool pointer_p = POINTER_TYPE_P (type);
783 tree t = sym;
785 if (neg)
786 t = build1 (NEGATE_EXPR, type, t);
788 if (integer_zerop (inv))
789 return t;
791 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
794 /* Return true if value range VR involves exactly one symbol SYM. */
796 static bool
797 symbolic_range_based_on_p (value_range *vr, const_tree sym)
799 bool neg, min_has_symbol, max_has_symbol;
800 tree inv;
802 if (is_gimple_min_invariant (vr->min))
803 min_has_symbol = false;
804 else if (get_single_symbol (vr->min, &neg, &inv) == sym)
805 min_has_symbol = true;
806 else
807 return false;
809 if (is_gimple_min_invariant (vr->max))
810 max_has_symbol = false;
811 else if (get_single_symbol (vr->max, &neg, &inv) == sym)
812 max_has_symbol = true;
813 else
814 return false;
816 return (min_has_symbol || max_has_symbol);
819 /* Return true if the result of assignment STMT is know to be non-zero. */
821 static bool
822 gimple_assign_nonzero_p (gimple *stmt)
824 enum tree_code code = gimple_assign_rhs_code (stmt);
825 bool strict_overflow_p;
826 switch (get_gimple_rhs_class (code))
828 case GIMPLE_UNARY_RHS:
829 return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
830 gimple_expr_type (stmt),
831 gimple_assign_rhs1 (stmt),
832 &strict_overflow_p);
833 case GIMPLE_BINARY_RHS:
834 return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
835 gimple_expr_type (stmt),
836 gimple_assign_rhs1 (stmt),
837 gimple_assign_rhs2 (stmt),
838 &strict_overflow_p);
839 case GIMPLE_TERNARY_RHS:
840 return false;
841 case GIMPLE_SINGLE_RHS:
842 return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
843 &strict_overflow_p);
844 case GIMPLE_INVALID_RHS:
845 gcc_unreachable ();
846 default:
847 gcc_unreachable ();
851 /* Return true if STMT is known to compute a non-zero value. */
853 static bool
854 gimple_stmt_nonzero_p (gimple *stmt)
856 switch (gimple_code (stmt))
858 case GIMPLE_ASSIGN:
859 return gimple_assign_nonzero_p (stmt);
860 case GIMPLE_CALL:
862 tree fndecl = gimple_call_fndecl (stmt);
863 if (!fndecl) return false;
864 if (flag_delete_null_pointer_checks && !flag_check_new
865 && DECL_IS_OPERATOR_NEW (fndecl)
866 && !TREE_NOTHROW (fndecl))
867 return true;
868 /* References are always non-NULL. */
869 if (flag_delete_null_pointer_checks
870 && TREE_CODE (TREE_TYPE (fndecl)) == REFERENCE_TYPE)
871 return true;
872 if (flag_delete_null_pointer_checks &&
873 lookup_attribute ("returns_nonnull",
874 TYPE_ATTRIBUTES (gimple_call_fntype (stmt))))
875 return true;
877 gcall *call_stmt = as_a<gcall *> (stmt);
878 unsigned rf = gimple_call_return_flags (call_stmt);
879 if (rf & ERF_RETURNS_ARG)
881 unsigned argnum = rf & ERF_RETURN_ARG_MASK;
882 if (argnum < gimple_call_num_args (call_stmt))
884 tree arg = gimple_call_arg (call_stmt, argnum);
885 if (SSA_VAR_P (arg)
886 && infer_nonnull_range_by_attribute (stmt, arg))
887 return true;
890 return gimple_alloca_call_p (stmt);
892 default:
893 gcc_unreachable ();
897 /* Like tree_expr_nonzero_p, but this function uses value ranges
898 obtained so far. */
900 bool
901 vr_values::vrp_stmt_computes_nonzero (gimple *stmt)
903 if (gimple_stmt_nonzero_p (stmt))
904 return true;
906 /* If we have an expression of the form &X->a, then the expression
907 is nonnull if X is nonnull. */
908 if (is_gimple_assign (stmt)
909 && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
911 tree expr = gimple_assign_rhs1 (stmt);
912 tree base = get_base_address (TREE_OPERAND (expr, 0));
914 if (base != NULL_TREE
915 && TREE_CODE (base) == MEM_REF
916 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
918 value_range *vr = get_value_range (TREE_OPERAND (base, 0));
919 if (range_is_nonnull (vr))
920 return true;
924 return false;
927 /* Returns true if EXPR is a valid value (as expected by compare_values) --
928 a gimple invariant, or SSA_NAME +- CST. */
930 static bool
931 valid_value_p (tree expr)
933 if (TREE_CODE (expr) == SSA_NAME)
934 return true;
936 if (TREE_CODE (expr) == PLUS_EXPR
937 || TREE_CODE (expr) == MINUS_EXPR)
938 return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
939 && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
941 return is_gimple_min_invariant (expr);
944 /* Return
945 1 if VAL < VAL2
946 0 if !(VAL < VAL2)
947 -2 if those are incomparable. */
948 static inline int
949 operand_less_p (tree val, tree val2)
951 /* LT is folded faster than GE and others. Inline the common case. */
952 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
953 return tree_int_cst_lt (val, val2);
954 else
956 tree tcmp;
958 fold_defer_overflow_warnings ();
960 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
962 fold_undefer_and_ignore_overflow_warnings ();
964 if (!tcmp
965 || TREE_CODE (tcmp) != INTEGER_CST)
966 return -2;
968 if (!integer_zerop (tcmp))
969 return 1;
972 return 0;
975 /* Compare two values VAL1 and VAL2. Return
977 -2 if VAL1 and VAL2 cannot be compared at compile-time,
978 -1 if VAL1 < VAL2,
979 0 if VAL1 == VAL2,
980 +1 if VAL1 > VAL2, and
981 +2 if VAL1 != VAL2
983 This is similar to tree_int_cst_compare but supports pointer values
984 and values that cannot be compared at compile time.
986 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
987 true if the return value is only valid if we assume that signed
988 overflow is undefined. */
990 static int
991 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
993 if (val1 == val2)
994 return 0;
996 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
997 both integers. */
998 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
999 == POINTER_TYPE_P (TREE_TYPE (val2)));
1001 /* Convert the two values into the same type. This is needed because
1002 sizetype causes sign extension even for unsigned types. */
1003 val2 = fold_convert (TREE_TYPE (val1), val2);
1004 STRIP_USELESS_TYPE_CONVERSION (val2);
1006 const bool overflow_undefined
1007 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
1008 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
1009 tree inv1, inv2;
1010 bool neg1, neg2;
1011 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
1012 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
1014 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
1015 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
1016 if (sym1 && sym2)
1018 /* Both values must use the same name with the same sign. */
1019 if (sym1 != sym2 || neg1 != neg2)
1020 return -2;
1022 /* [-]NAME + CST == [-]NAME + CST. */
1023 if (inv1 == inv2)
1024 return 0;
1026 /* If overflow is defined we cannot simplify more. */
1027 if (!overflow_undefined)
1028 return -2;
1030 if (strict_overflow_p != NULL
1031 /* Symbolic range building sets TREE_NO_WARNING to declare
1032 that overflow doesn't happen. */
1033 && (!inv1 || !TREE_NO_WARNING (val1))
1034 && (!inv2 || !TREE_NO_WARNING (val2)))
1035 *strict_overflow_p = true;
1037 if (!inv1)
1038 inv1 = build_int_cst (TREE_TYPE (val1), 0);
1039 if (!inv2)
1040 inv2 = build_int_cst (TREE_TYPE (val2), 0);
1042 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
1043 TYPE_SIGN (TREE_TYPE (val1)));
1046 const bool cst1 = is_gimple_min_invariant (val1);
1047 const bool cst2 = is_gimple_min_invariant (val2);
1049 /* If one is of the form '[-]NAME + CST' and the other is constant, then
1050 it might be possible to say something depending on the constants. */
1051 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
1053 if (!overflow_undefined)
1054 return -2;
1056 if (strict_overflow_p != NULL
1057 /* Symbolic range building sets TREE_NO_WARNING to declare
1058 that overflow doesn't happen. */
1059 && (!sym1 || !TREE_NO_WARNING (val1))
1060 && (!sym2 || !TREE_NO_WARNING (val2)))
1061 *strict_overflow_p = true;
1063 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
1064 tree cst = cst1 ? val1 : val2;
1065 tree inv = cst1 ? inv2 : inv1;
1067 /* Compute the difference between the constants. If it overflows or
1068 underflows, this means that we can trivially compare the NAME with
1069 it and, consequently, the two values with each other. */
1070 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
1071 if (wi::cmp (0, wi::to_wide (inv), sgn)
1072 != wi::cmp (diff, wi::to_wide (cst), sgn))
1074 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
1075 return cst1 ? res : -res;
1078 return -2;
1081 /* We cannot say anything more for non-constants. */
1082 if (!cst1 || !cst2)
1083 return -2;
1085 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1087 /* We cannot compare overflowed values. */
1088 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1089 return -2;
1091 return tree_int_cst_compare (val1, val2);
1093 else
1095 tree t;
1097 /* First see if VAL1 and VAL2 are not the same. */
1098 if (val1 == val2 || operand_equal_p (val1, val2, 0))
1099 return 0;
1101 /* If VAL1 is a lower address than VAL2, return -1. */
1102 if (operand_less_p (val1, val2) == 1)
1103 return -1;
1105 /* If VAL1 is a higher address than VAL2, return +1. */
1106 if (operand_less_p (val2, val1) == 1)
1107 return 1;
1109 /* If VAL1 is different than VAL2, return +2.
1110 For integer constants we either have already returned -1 or 1
1111 or they are equivalent. We still might succeed in proving
1112 something about non-trivial operands. */
1113 if (TREE_CODE (val1) != INTEGER_CST
1114 || TREE_CODE (val2) != INTEGER_CST)
1116 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1117 if (t && integer_onep (t))
1118 return 2;
1121 return -2;
1125 /* Compare values like compare_values_warnv. */
1127 static int
1128 compare_values (tree val1, tree val2)
1130 bool sop;
1131 return compare_values_warnv (val1, val2, &sop);
1135 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
1136 0 if VAL is not inside [MIN, MAX],
1137 -2 if we cannot tell either way.
1139 Benchmark compile/20001226-1.c compilation time after changing this
1140 function. */
1142 static inline int
1143 value_inside_range (tree val, tree min, tree max)
1145 int cmp1, cmp2;
1147 cmp1 = operand_less_p (val, min);
1148 if (cmp1 == -2)
1149 return -2;
1150 if (cmp1 == 1)
1151 return 0;
1153 cmp2 = operand_less_p (max, val);
1154 if (cmp2 == -2)
1155 return -2;
1157 return !cmp2;
1161 /* Return true if value ranges VR0 and VR1 have a non-empty
1162 intersection.
1164 Benchmark compile/20001226-1.c compilation time after changing this
1165 function.
1168 static inline bool
1169 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
1171 /* The value ranges do not intersect if the maximum of the first range is
1172 less than the minimum of the second range or vice versa.
1173 When those relations are unknown, we can't do any better. */
1174 if (operand_less_p (vr0->max, vr1->min) != 0)
1175 return false;
1176 if (operand_less_p (vr1->max, vr0->min) != 0)
1177 return false;
1178 return true;
1182 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
1183 include the value zero, -2 if we cannot tell. */
1186 range_includes_zero_p (tree min, tree max)
1188 tree zero = build_int_cst (TREE_TYPE (min), 0);
1189 return value_inside_range (zero, min, max);
1192 /* Return true if *VR is know to only contain nonnegative values. */
1194 static inline bool
1195 value_range_nonnegative_p (value_range *vr)
1197 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
1198 which would return a useful value should be encoded as a
1199 VR_RANGE. */
1200 if (vr->type == VR_RANGE)
1202 int result = compare_values (vr->min, integer_zero_node);
1203 return (result == 0 || result == 1);
1206 return false;
1209 /* If *VR has a value rante that is a single constant value return that,
1210 otherwise return NULL_TREE. */
1212 static tree
1213 value_range_constant_singleton (value_range *vr)
1215 if (vr->type == VR_RANGE
1216 && vrp_operand_equal_p (vr->min, vr->max)
1217 && is_gimple_min_invariant (vr->min))
1218 return vr->min;
1220 return NULL_TREE;
1223 /* If OP has a value range with a single constant value return that,
1224 otherwise return NULL_TREE. This returns OP itself if OP is a
1225 constant. */
1227 tree
1228 vr_values::op_with_constant_singleton_value_range (tree op)
1230 if (is_gimple_min_invariant (op))
1231 return op;
1233 if (TREE_CODE (op) != SSA_NAME)
1234 return NULL_TREE;
1236 return value_range_constant_singleton (get_value_range (op));
1239 /* Return true if op is in a boolean [0, 1] value-range. */
1241 bool
1242 vr_values::op_with_boolean_value_range_p (tree op)
1244 value_range *vr;
1246 if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
1247 return true;
1249 if (integer_zerop (op)
1250 || integer_onep (op))
1251 return true;
1253 if (TREE_CODE (op) != SSA_NAME)
1254 return false;
1256 vr = get_value_range (op);
1257 return (vr->type == VR_RANGE
1258 && integer_zerop (vr->min)
1259 && integer_onep (vr->max));
1262 /* Extract value range information for VAR when (OP COND_CODE LIMIT) is
1263 true and store it in *VR_P. */
1265 void
1266 vr_values::extract_range_for_var_from_comparison_expr (tree var,
1267 enum tree_code cond_code,
1268 tree op, tree limit,
1269 value_range *vr_p)
1271 tree min, max, type;
1272 value_range *limit_vr;
1273 type = TREE_TYPE (var);
1274 gcc_assert (limit != var);
1276 /* For pointer arithmetic, we only keep track of pointer equality
1277 and inequality. */
1278 if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
1280 set_value_range_to_varying (vr_p);
1281 return;
1284 /* If LIMIT is another SSA name and LIMIT has a range of its own,
1285 try to use LIMIT's range to avoid creating symbolic ranges
1286 unnecessarily. */
1287 limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
1289 /* LIMIT's range is only interesting if it has any useful information. */
1290 if (! limit_vr
1291 || limit_vr->type == VR_UNDEFINED
1292 || limit_vr->type == VR_VARYING
1293 || (symbolic_range_p (limit_vr)
1294 && ! (limit_vr->type == VR_RANGE
1295 && (limit_vr->min == limit_vr->max
1296 || operand_equal_p (limit_vr->min, limit_vr->max, 0)))))
1297 limit_vr = NULL;
1299 /* Initially, the new range has the same set of equivalences of
1300 VAR's range. This will be revised before returning the final
1301 value. Since assertions may be chained via mutually exclusive
1302 predicates, we will need to trim the set of equivalences before
1303 we are done. */
1304 gcc_assert (vr_p->equiv == NULL);
1305 add_equivalence (&vr_p->equiv, var);
1307 /* Extract a new range based on the asserted comparison for VAR and
1308 LIMIT's value range. Notice that if LIMIT has an anti-range, we
1309 will only use it for equality comparisons (EQ_EXPR). For any
1310 other kind of assertion, we cannot derive a range from LIMIT's
1311 anti-range that can be used to describe the new range. For
1312 instance, ASSERT_EXPR <x_2, x_2 <= b_4>. If b_4 is ~[2, 10],
1313 then b_4 takes on the ranges [-INF, 1] and [11, +INF]. There is
1314 no single range for x_2 that could describe LE_EXPR, so we might
1315 as well build the range [b_4, +INF] for it.
1316 One special case we handle is extracting a range from a
1317 range test encoded as (unsigned)var + CST <= limit. */
1318 if (TREE_CODE (op) == NOP_EXPR
1319 || TREE_CODE (op) == PLUS_EXPR)
1321 if (TREE_CODE (op) == PLUS_EXPR)
1323 min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (op, 1)),
1324 TREE_OPERAND (op, 1));
1325 max = int_const_binop (PLUS_EXPR, limit, min);
1326 op = TREE_OPERAND (op, 0);
1328 else
1330 min = build_int_cst (TREE_TYPE (var), 0);
1331 max = limit;
1334 /* Make sure to not set TREE_OVERFLOW on the final type
1335 conversion. We are willingly interpreting large positive
1336 unsigned values as negative signed values here. */
1337 min = force_fit_type (TREE_TYPE (var), wi::to_widest (min), 0, false);
1338 max = force_fit_type (TREE_TYPE (var), wi::to_widest (max), 0, false);
1340 /* We can transform a max, min range to an anti-range or
1341 vice-versa. Use set_and_canonicalize_value_range which does
1342 this for us. */
1343 if (cond_code == LE_EXPR)
1344 set_and_canonicalize_value_range (vr_p, VR_RANGE,
1345 min, max, vr_p->equiv);
1346 else if (cond_code == GT_EXPR)
1347 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1348 min, max, vr_p->equiv);
1349 else
1350 gcc_unreachable ();
1352 else if (cond_code == EQ_EXPR)
1354 enum value_range_type range_type;
1356 if (limit_vr)
1358 range_type = limit_vr->type;
1359 min = limit_vr->min;
1360 max = limit_vr->max;
1362 else
1364 range_type = VR_RANGE;
1365 min = limit;
1366 max = limit;
1369 set_value_range (vr_p, range_type, min, max, vr_p->equiv);
1371 /* When asserting the equality VAR == LIMIT and LIMIT is another
1372 SSA name, the new range will also inherit the equivalence set
1373 from LIMIT. */
1374 if (TREE_CODE (limit) == SSA_NAME)
1375 add_equivalence (&vr_p->equiv, limit);
1377 else if (cond_code == NE_EXPR)
1379 /* As described above, when LIMIT's range is an anti-range and
1380 this assertion is an inequality (NE_EXPR), then we cannot
1381 derive anything from the anti-range. For instance, if
1382 LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
1383 not imply that VAR's range is [0, 0]. So, in the case of
1384 anti-ranges, we just assert the inequality using LIMIT and
1385 not its anti-range.
1387 If LIMIT_VR is a range, we can only use it to build a new
1388 anti-range if LIMIT_VR is a single-valued range. For
1389 instance, if LIMIT_VR is [0, 1], the predicate
1390 VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
1391 Rather, it means that for value 0 VAR should be ~[0, 0]
1392 and for value 1, VAR should be ~[1, 1]. We cannot
1393 represent these ranges.
1395 The only situation in which we can build a valid
1396 anti-range is when LIMIT_VR is a single-valued range
1397 (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX). In that case,
1398 build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX]. */
1399 if (limit_vr
1400 && limit_vr->type == VR_RANGE
1401 && compare_values (limit_vr->min, limit_vr->max) == 0)
1403 min = limit_vr->min;
1404 max = limit_vr->max;
1406 else
1408 /* In any other case, we cannot use LIMIT's range to build a
1409 valid anti-range. */
1410 min = max = limit;
1413 /* If MIN and MAX cover the whole range for their type, then
1414 just use the original LIMIT. */
1415 if (INTEGRAL_TYPE_P (type)
1416 && vrp_val_is_min (min)
1417 && vrp_val_is_max (max))
1418 min = max = limit;
1420 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1421 min, max, vr_p->equiv);
1423 else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
1425 min = TYPE_MIN_VALUE (type);
1427 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1428 max = limit;
1429 else
1431 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1432 range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
1433 LT_EXPR. */
1434 max = limit_vr->max;
1437 /* If the maximum value forces us to be out of bounds, simply punt.
1438 It would be pointless to try and do anything more since this
1439 all should be optimized away above us. */
1440 if (cond_code == LT_EXPR
1441 && compare_values (max, min) == 0)
1442 set_value_range_to_varying (vr_p);
1443 else
1445 /* For LT_EXPR, we create the range [MIN, MAX - 1]. */
1446 if (cond_code == LT_EXPR)
1448 if (TYPE_PRECISION (TREE_TYPE (max)) == 1
1449 && !TYPE_UNSIGNED (TREE_TYPE (max)))
1450 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
1451 build_int_cst (TREE_TYPE (max), -1));
1452 else
1453 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
1454 build_int_cst (TREE_TYPE (max), 1));
1455 /* Signal to compare_values_warnv this expr doesn't overflow. */
1456 if (EXPR_P (max))
1457 TREE_NO_WARNING (max) = 1;
1460 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1463 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
1465 max = TYPE_MAX_VALUE (type);
1467 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1468 min = limit;
1469 else
1471 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1472 range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
1473 GT_EXPR. */
1474 min = limit_vr->min;
1477 /* If the minimum value forces us to be out of bounds, simply punt.
1478 It would be pointless to try and do anything more since this
1479 all should be optimized away above us. */
1480 if (cond_code == GT_EXPR
1481 && compare_values (min, max) == 0)
1482 set_value_range_to_varying (vr_p);
1483 else
1485 /* For GT_EXPR, we create the range [MIN + 1, MAX]. */
1486 if (cond_code == GT_EXPR)
1488 if (TYPE_PRECISION (TREE_TYPE (min)) == 1
1489 && !TYPE_UNSIGNED (TREE_TYPE (min)))
1490 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
1491 build_int_cst (TREE_TYPE (min), -1));
1492 else
1493 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
1494 build_int_cst (TREE_TYPE (min), 1));
1495 /* Signal to compare_values_warnv this expr doesn't overflow. */
1496 if (EXPR_P (min))
1497 TREE_NO_WARNING (min) = 1;
1500 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1503 else
1504 gcc_unreachable ();
1506 /* Finally intersect the new range with what we already know about var. */
1507 vrp_intersect_ranges (vr_p, get_value_range (var));
1510 /* Extract value range information from an ASSERT_EXPR EXPR and store
1511 it in *VR_P. */
1513 void
1514 vr_values::extract_range_from_assert (value_range *vr_p, tree expr)
1516 tree var = ASSERT_EXPR_VAR (expr);
1517 tree cond = ASSERT_EXPR_COND (expr);
1518 tree limit, op;
1519 enum tree_code cond_code;
1520 gcc_assert (COMPARISON_CLASS_P (cond));
1522 /* Find VAR in the ASSERT_EXPR conditional. */
1523 if (var == TREE_OPERAND (cond, 0)
1524 || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
1525 || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
1527 /* If the predicate is of the form VAR COMP LIMIT, then we just
1528 take LIMIT from the RHS and use the same comparison code. */
1529 cond_code = TREE_CODE (cond);
1530 limit = TREE_OPERAND (cond, 1);
1531 op = TREE_OPERAND (cond, 0);
1533 else
1535 /* If the predicate is of the form LIMIT COMP VAR, then we need
1536 to flip around the comparison code to create the proper range
1537 for VAR. */
1538 cond_code = swap_tree_comparison (TREE_CODE (cond));
1539 limit = TREE_OPERAND (cond, 0);
1540 op = TREE_OPERAND (cond, 1);
1542 extract_range_for_var_from_comparison_expr (var, cond_code, op,
1543 limit, vr_p);
1546 /* Extract range information from SSA name VAR and store it in VR. If
1547 VAR has an interesting range, use it. Otherwise, create the
1548 range [VAR, VAR] and return it. This is useful in situations where
1549 we may have conditionals testing values of VARYING names. For
1550 instance,
1552 x_3 = y_5;
1553 if (x_3 > y_5)
1556 Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
1557 always false. */
1559 void
1560 vr_values::extract_range_from_ssa_name (value_range *vr, tree var)
1562 value_range *var_vr = get_value_range (var);
1564 if (var_vr->type != VR_VARYING)
1565 copy_value_range (vr, var_vr);
1566 else
1567 set_value_range (vr, VR_RANGE, var, var, NULL);
1569 add_equivalence (&vr->equiv, var);
1573 /* Wrapper around int_const_binop. Return true if we can compute the
1574 result; i.e. if the operation doesn't overflow or if the overflow is
1575 undefined. In the latter case (if the operation overflows and
1576 overflow is undefined), then adjust the result to be -INF or +INF
1577 depending on CODE, VAL1 and VAL2. Return the value in *RES.
1579 Return false for division by zero, for which the result is
1580 indeterminate. */
1582 static bool
1583 vrp_int_const_binop (enum tree_code code, tree val1, tree val2, wide_int *res)
1585 bool overflow = false;
1586 signop sign = TYPE_SIGN (TREE_TYPE (val1));
1588 switch (code)
1590 case RSHIFT_EXPR:
1591 case LSHIFT_EXPR:
1593 wide_int wval2 = wi::to_wide (val2, TYPE_PRECISION (TREE_TYPE (val1)));
1594 if (wi::neg_p (wval2))
1596 wval2 = -wval2;
1597 if (code == RSHIFT_EXPR)
1598 code = LSHIFT_EXPR;
1599 else
1600 code = RSHIFT_EXPR;
1603 if (code == RSHIFT_EXPR)
1604 /* It's unclear from the C standard whether shifts can overflow.
1605 The following code ignores overflow; perhaps a C standard
1606 interpretation ruling is needed. */
1607 *res = wi::rshift (wi::to_wide (val1), wval2, sign);
1608 else
1609 *res = wi::lshift (wi::to_wide (val1), wval2);
1610 break;
1613 case MULT_EXPR:
1614 *res = wi::mul (wi::to_wide (val1),
1615 wi::to_wide (val2), sign, &overflow);
1616 break;
1618 case TRUNC_DIV_EXPR:
1619 case EXACT_DIV_EXPR:
1620 if (val2 == 0)
1621 return false;
1622 else
1623 *res = wi::div_trunc (wi::to_wide (val1),
1624 wi::to_wide (val2), sign, &overflow);
1625 break;
1627 case FLOOR_DIV_EXPR:
1628 if (val2 == 0)
1629 return false;
1630 *res = wi::div_floor (wi::to_wide (val1),
1631 wi::to_wide (val2), sign, &overflow);
1632 break;
1634 case CEIL_DIV_EXPR:
1635 if (val2 == 0)
1636 return false;
1637 *res = wi::div_ceil (wi::to_wide (val1),
1638 wi::to_wide (val2), sign, &overflow);
1639 break;
1641 case ROUND_DIV_EXPR:
1642 if (val2 == 0)
1643 return false;
1644 *res = wi::div_round (wi::to_wide (val1),
1645 wi::to_wide (val2), sign, &overflow);
1646 break;
1648 default:
1649 gcc_unreachable ();
1652 if (overflow
1653 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1)))
1655 /* If the operation overflowed return -INF or +INF depending
1656 on the operation and the combination of signs of the operands. */
1657 int sgn1 = tree_int_cst_sgn (val1);
1658 int sgn2 = tree_int_cst_sgn (val2);
1660 /* Notice that we only need to handle the restricted set of
1661 operations handled by extract_range_from_binary_expr.
1662 Among them, only multiplication, addition and subtraction
1663 can yield overflow without overflown operands because we
1664 are working with integral types only... except in the
1665 case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1666 for division too. */
1668 /* For multiplication, the sign of the overflow is given
1669 by the comparison of the signs of the operands. */
1670 if ((code == MULT_EXPR && sgn1 == sgn2)
1671 /* For addition, the operands must be of the same sign
1672 to yield an overflow. Its sign is therefore that
1673 of one of the operands, for example the first. */
1674 || (code == PLUS_EXPR && sgn1 >= 0)
1675 /* For subtraction, operands must be of
1676 different signs to yield an overflow. Its sign is
1677 therefore that of the first operand or the opposite of
1678 that of the second operand. A first operand of 0 counts
1679 as positive here, for the corner case 0 - (-INF), which
1680 overflows, but must yield +INF. */
1681 || (code == MINUS_EXPR && sgn1 >= 0)
1682 /* For division, the only case is -INF / -1 = +INF. */
1683 || code == TRUNC_DIV_EXPR
1684 || code == FLOOR_DIV_EXPR
1685 || code == CEIL_DIV_EXPR
1686 || code == EXACT_DIV_EXPR
1687 || code == ROUND_DIV_EXPR)
1688 *res = wi::max_value (TYPE_PRECISION (TREE_TYPE (val1)),
1689 TYPE_SIGN (TREE_TYPE (val1)));
1690 else
1691 *res = wi::min_value (TYPE_PRECISION (TREE_TYPE (val1)),
1692 TYPE_SIGN (TREE_TYPE (val1)));
1693 return true;
1696 return !overflow;
1700 /* For range VR compute two wide_int bitmasks. In *MAY_BE_NONZERO
1701 bitmask if some bit is unset, it means for all numbers in the range
1702 the bit is 0, otherwise it might be 0 or 1. In *MUST_BE_NONZERO
1703 bitmask if some bit is set, it means for all numbers in the range
1704 the bit is 1, otherwise it might be 0 or 1. */
1706 static bool
1707 zero_nonzero_bits_from_vr (const tree expr_type,
1708 value_range *vr,
1709 wide_int *may_be_nonzero,
1710 wide_int *must_be_nonzero)
1712 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1713 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1714 if (!range_int_cst_p (vr))
1715 return false;
1717 if (range_int_cst_singleton_p (vr))
1719 *may_be_nonzero = wi::to_wide (vr->min);
1720 *must_be_nonzero = *may_be_nonzero;
1722 else if (tree_int_cst_sgn (vr->min) >= 0
1723 || tree_int_cst_sgn (vr->max) < 0)
1725 wide_int xor_mask = wi::to_wide (vr->min) ^ wi::to_wide (vr->max);
1726 *may_be_nonzero = wi::to_wide (vr->min) | wi::to_wide (vr->max);
1727 *must_be_nonzero = wi::to_wide (vr->min) & wi::to_wide (vr->max);
1728 if (xor_mask != 0)
1730 wide_int mask = wi::mask (wi::floor_log2 (xor_mask), false,
1731 may_be_nonzero->get_precision ());
1732 *may_be_nonzero = *may_be_nonzero | mask;
1733 *must_be_nonzero = wi::bit_and_not (*must_be_nonzero, mask);
1737 return true;
1740 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
1741 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
1742 false otherwise. If *AR can be represented with a single range
1743 *VR1 will be VR_UNDEFINED. */
1745 static bool
1746 ranges_from_anti_range (value_range *ar,
1747 value_range *vr0, value_range *vr1)
1749 tree type = TREE_TYPE (ar->min);
1751 vr0->type = VR_UNDEFINED;
1752 vr1->type = VR_UNDEFINED;
1754 if (ar->type != VR_ANTI_RANGE
1755 || TREE_CODE (ar->min) != INTEGER_CST
1756 || TREE_CODE (ar->max) != INTEGER_CST
1757 || !vrp_val_min (type)
1758 || !vrp_val_max (type))
1759 return false;
1761 if (!vrp_val_is_min (ar->min))
1763 vr0->type = VR_RANGE;
1764 vr0->min = vrp_val_min (type);
1765 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
1767 if (!vrp_val_is_max (ar->max))
1769 vr1->type = VR_RANGE;
1770 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
1771 vr1->max = vrp_val_max (type);
1773 if (vr0->type == VR_UNDEFINED)
1775 *vr0 = *vr1;
1776 vr1->type = VR_UNDEFINED;
1779 return vr0->type != VR_UNDEFINED;
1782 /* Helper to extract a value-range *VR for a multiplicative operation
1783 *VR0 CODE *VR1. */
1785 static void
1786 extract_range_from_multiplicative_op_1 (value_range *vr,
1787 enum tree_code code,
1788 value_range *vr0, value_range *vr1)
1790 enum value_range_type rtype;
1791 wide_int val, min, max;
1792 tree type;
1794 /* Multiplications, divisions and shifts are a bit tricky to handle,
1795 depending on the mix of signs we have in the two ranges, we
1796 need to operate on different values to get the minimum and
1797 maximum values for the new range. One approach is to figure
1798 out all the variations of range combinations and do the
1799 operations.
1801 However, this involves several calls to compare_values and it
1802 is pretty convoluted. It's simpler to do the 4 operations
1803 (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
1804 MAX1) and then figure the smallest and largest values to form
1805 the new range. */
1806 gcc_assert (code == MULT_EXPR
1807 || code == TRUNC_DIV_EXPR
1808 || code == FLOOR_DIV_EXPR
1809 || code == CEIL_DIV_EXPR
1810 || code == EXACT_DIV_EXPR
1811 || code == ROUND_DIV_EXPR
1812 || code == RSHIFT_EXPR
1813 || code == LSHIFT_EXPR);
1814 gcc_assert (vr0->type == VR_RANGE
1815 && vr0->type == vr1->type);
1817 rtype = vr0->type;
1818 type = TREE_TYPE (vr0->min);
1819 signop sgn = TYPE_SIGN (type);
1821 /* Compute the 4 cross operations and their minimum and maximum value. */
1822 if (!vrp_int_const_binop (code, vr0->min, vr1->min, &val))
1824 set_value_range_to_varying (vr);
1825 return;
1827 min = max = val;
1829 if (vr1->max != vr1->min)
1831 if (!vrp_int_const_binop (code, vr0->min, vr1->max, &val))
1833 set_value_range_to_varying (vr);
1834 return;
1836 if (wi::lt_p (val, min, sgn))
1837 min = val;
1838 else if (wi::gt_p (val, max, sgn))
1839 max = val;
1842 if (vr0->max != vr0->min)
1844 if (!vrp_int_const_binop (code, vr0->max, vr1->min, &val))
1846 set_value_range_to_varying (vr);
1847 return;
1849 if (wi::lt_p (val, min, sgn))
1850 min = val;
1851 else if (wi::gt_p (val, max, sgn))
1852 max = val;
1855 if (vr0->min != vr0->max && vr1->min != vr1->max)
1857 if (!vrp_int_const_binop (code, vr0->max, vr1->max, &val))
1859 set_value_range_to_varying (vr);
1860 return;
1862 if (wi::lt_p (val, min, sgn))
1863 min = val;
1864 else if (wi::gt_p (val, max, sgn))
1865 max = val;
1868 /* If the new range has its limits swapped around (MIN > MAX),
1869 then the operation caused one of them to wrap around, mark
1870 the new range VARYING. */
1871 if (wi::gt_p (min, max, sgn))
1873 set_value_range_to_varying (vr);
1874 return;
1877 /* We punt for [-INF, +INF].
1878 We learn nothing when we have INF on both sides.
1879 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1880 if (wi::eq_p (min, wi::min_value (TYPE_PRECISION (type), sgn))
1881 && wi::eq_p (max, wi::max_value (TYPE_PRECISION (type), sgn)))
1883 set_value_range_to_varying (vr);
1884 return;
1887 set_value_range (vr, rtype,
1888 wide_int_to_tree (type, min),
1889 wide_int_to_tree (type, max), NULL);
1892 /* Extract range information from a binary operation CODE based on
1893 the ranges of each of its operands *VR0 and *VR1 with resulting
1894 type EXPR_TYPE. The resulting range is stored in *VR. */
1896 static void
1897 extract_range_from_binary_expr_1 (value_range *vr,
1898 enum tree_code code, tree expr_type,
1899 value_range *vr0_, value_range *vr1_)
1901 value_range vr0 = *vr0_, vr1 = *vr1_;
1902 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1903 enum value_range_type type;
1904 tree min = NULL_TREE, max = NULL_TREE;
1905 int cmp;
1907 if (!INTEGRAL_TYPE_P (expr_type)
1908 && !POINTER_TYPE_P (expr_type))
1910 set_value_range_to_varying (vr);
1911 return;
1914 /* Not all binary expressions can be applied to ranges in a
1915 meaningful way. Handle only arithmetic operations. */
1916 if (code != PLUS_EXPR
1917 && code != MINUS_EXPR
1918 && code != POINTER_PLUS_EXPR
1919 && code != MULT_EXPR
1920 && code != TRUNC_DIV_EXPR
1921 && code != FLOOR_DIV_EXPR
1922 && code != CEIL_DIV_EXPR
1923 && code != EXACT_DIV_EXPR
1924 && code != ROUND_DIV_EXPR
1925 && code != TRUNC_MOD_EXPR
1926 && code != RSHIFT_EXPR
1927 && code != LSHIFT_EXPR
1928 && code != MIN_EXPR
1929 && code != MAX_EXPR
1930 && code != BIT_AND_EXPR
1931 && code != BIT_IOR_EXPR
1932 && code != BIT_XOR_EXPR)
1934 set_value_range_to_varying (vr);
1935 return;
1938 /* If both ranges are UNDEFINED, so is the result. */
1939 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1941 set_value_range_to_undefined (vr);
1942 return;
1944 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1945 code. At some point we may want to special-case operations that
1946 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1947 operand. */
1948 else if (vr0.type == VR_UNDEFINED)
1949 set_value_range_to_varying (&vr0);
1950 else if (vr1.type == VR_UNDEFINED)
1951 set_value_range_to_varying (&vr1);
1953 /* We get imprecise results from ranges_from_anti_range when
1954 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1955 range, but then we also need to hack up vrp_meet. It's just
1956 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1957 if (code == EXACT_DIV_EXPR
1958 && vr0.type == VR_ANTI_RANGE
1959 && vr0.min == vr0.max
1960 && integer_zerop (vr0.min))
1962 set_value_range_to_nonnull (vr, expr_type);
1963 return;
1966 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1967 and express ~[] op X as ([]' op X) U ([]'' op X). */
1968 if (vr0.type == VR_ANTI_RANGE
1969 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1971 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1972 if (vrtem1.type != VR_UNDEFINED)
1974 value_range vrres = VR_INITIALIZER;
1975 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1976 &vrtem1, vr1_);
1977 vrp_meet (vr, &vrres);
1979 return;
1981 /* Likewise for X op ~[]. */
1982 if (vr1.type == VR_ANTI_RANGE
1983 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1985 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1986 if (vrtem1.type != VR_UNDEFINED)
1988 value_range vrres = VR_INITIALIZER;
1989 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1990 vr0_, &vrtem1);
1991 vrp_meet (vr, &vrres);
1993 return;
1996 /* The type of the resulting value range defaults to VR0.TYPE. */
1997 type = vr0.type;
1999 /* Refuse to operate on VARYING ranges, ranges of different kinds
2000 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
2001 because we may be able to derive a useful range even if one of
2002 the operands is VR_VARYING or symbolic range. Similarly for
2003 divisions, MIN/MAX and PLUS/MINUS.
2005 TODO, we may be able to derive anti-ranges in some cases. */
2006 if (code != BIT_AND_EXPR
2007 && code != BIT_IOR_EXPR
2008 && code != TRUNC_DIV_EXPR
2009 && code != FLOOR_DIV_EXPR
2010 && code != CEIL_DIV_EXPR
2011 && code != EXACT_DIV_EXPR
2012 && code != ROUND_DIV_EXPR
2013 && code != TRUNC_MOD_EXPR
2014 && code != MIN_EXPR
2015 && code != MAX_EXPR
2016 && code != PLUS_EXPR
2017 && code != MINUS_EXPR
2018 && code != RSHIFT_EXPR
2019 && (vr0.type == VR_VARYING
2020 || vr1.type == VR_VARYING
2021 || vr0.type != vr1.type
2022 || symbolic_range_p (&vr0)
2023 || symbolic_range_p (&vr1)))
2025 set_value_range_to_varying (vr);
2026 return;
2029 /* Now evaluate the expression to determine the new range. */
2030 if (POINTER_TYPE_P (expr_type))
2032 if (code == MIN_EXPR || code == MAX_EXPR)
2034 /* For MIN/MAX expressions with pointers, we only care about
2035 nullness, if both are non null, then the result is nonnull.
2036 If both are null, then the result is null. Otherwise they
2037 are varying. */
2038 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2039 set_value_range_to_nonnull (vr, expr_type);
2040 else if (range_is_null (&vr0) && range_is_null (&vr1))
2041 set_value_range_to_null (vr, expr_type);
2042 else
2043 set_value_range_to_varying (vr);
2045 else if (code == POINTER_PLUS_EXPR)
2047 /* For pointer types, we are really only interested in asserting
2048 whether the expression evaluates to non-NULL. */
2049 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
2050 set_value_range_to_nonnull (vr, expr_type);
2051 else if (range_is_null (&vr0) && range_is_null (&vr1))
2052 set_value_range_to_null (vr, expr_type);
2053 else
2054 set_value_range_to_varying (vr);
2056 else if (code == BIT_AND_EXPR)
2058 /* For pointer types, we are really only interested in asserting
2059 whether the expression evaluates to non-NULL. */
2060 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2061 set_value_range_to_nonnull (vr, expr_type);
2062 else if (range_is_null (&vr0) || range_is_null (&vr1))
2063 set_value_range_to_null (vr, expr_type);
2064 else
2065 set_value_range_to_varying (vr);
2067 else
2068 set_value_range_to_varying (vr);
2070 return;
2073 /* For integer ranges, apply the operation to each end of the
2074 range and see what we end up with. */
2075 if (code == PLUS_EXPR || code == MINUS_EXPR)
2077 const bool minus_p = (code == MINUS_EXPR);
2078 tree min_op0 = vr0.min;
2079 tree min_op1 = minus_p ? vr1.max : vr1.min;
2080 tree max_op0 = vr0.max;
2081 tree max_op1 = minus_p ? vr1.min : vr1.max;
2082 tree sym_min_op0 = NULL_TREE;
2083 tree sym_min_op1 = NULL_TREE;
2084 tree sym_max_op0 = NULL_TREE;
2085 tree sym_max_op1 = NULL_TREE;
2086 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
2088 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
2089 single-symbolic ranges, try to compute the precise resulting range,
2090 but only if we know that this resulting range will also be constant
2091 or single-symbolic. */
2092 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
2093 && (TREE_CODE (min_op0) == INTEGER_CST
2094 || (sym_min_op0
2095 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
2096 && (TREE_CODE (min_op1) == INTEGER_CST
2097 || (sym_min_op1
2098 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
2099 && (!(sym_min_op0 && sym_min_op1)
2100 || (sym_min_op0 == sym_min_op1
2101 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
2102 && (TREE_CODE (max_op0) == INTEGER_CST
2103 || (sym_max_op0
2104 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
2105 && (TREE_CODE (max_op1) == INTEGER_CST
2106 || (sym_max_op1
2107 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
2108 && (!(sym_max_op0 && sym_max_op1)
2109 || (sym_max_op0 == sym_max_op1
2110 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
2112 const signop sgn = TYPE_SIGN (expr_type);
2113 const unsigned int prec = TYPE_PRECISION (expr_type);
2114 wide_int type_min, type_max, wmin, wmax;
2115 int min_ovf = 0;
2116 int max_ovf = 0;
2118 /* Get the lower and upper bounds of the type. */
2119 if (TYPE_OVERFLOW_WRAPS (expr_type))
2121 type_min = wi::min_value (prec, sgn);
2122 type_max = wi::max_value (prec, sgn);
2124 else
2126 type_min = wi::to_wide (vrp_val_min (expr_type));
2127 type_max = wi::to_wide (vrp_val_max (expr_type));
2130 /* Combine the lower bounds, if any. */
2131 if (min_op0 && min_op1)
2133 if (minus_p)
2135 wmin = wi::to_wide (min_op0) - wi::to_wide (min_op1);
2137 /* Check for overflow. */
2138 if (wi::cmp (0, wi::to_wide (min_op1), sgn)
2139 != wi::cmp (wmin, wi::to_wide (min_op0), sgn))
2140 min_ovf = wi::cmp (wi::to_wide (min_op0),
2141 wi::to_wide (min_op1), sgn);
2143 else
2145 wmin = wi::to_wide (min_op0) + wi::to_wide (min_op1);
2147 /* Check for overflow. */
2148 if (wi::cmp (wi::to_wide (min_op1), 0, sgn)
2149 != wi::cmp (wmin, wi::to_wide (min_op0), sgn))
2150 min_ovf = wi::cmp (wi::to_wide (min_op0), wmin, sgn);
2153 else if (min_op0)
2154 wmin = wi::to_wide (min_op0);
2155 else if (min_op1)
2157 if (minus_p)
2159 wmin = -wi::to_wide (min_op1);
2161 /* Check for overflow. */
2162 if (sgn == SIGNED
2163 && wi::neg_p (wi::to_wide (min_op1))
2164 && wi::neg_p (wmin))
2165 min_ovf = 1;
2166 else if (sgn == UNSIGNED && wi::to_wide (min_op1) != 0)
2167 min_ovf = -1;
2169 else
2170 wmin = wi::to_wide (min_op1);
2172 else
2173 wmin = wi::shwi (0, prec);
2175 /* Combine the upper bounds, if any. */
2176 if (max_op0 && max_op1)
2178 if (minus_p)
2180 wmax = wi::to_wide (max_op0) - wi::to_wide (max_op1);
2182 /* Check for overflow. */
2183 if (wi::cmp (0, wi::to_wide (max_op1), sgn)
2184 != wi::cmp (wmax, wi::to_wide (max_op0), sgn))
2185 max_ovf = wi::cmp (wi::to_wide (max_op0),
2186 wi::to_wide (max_op1), sgn);
2188 else
2190 wmax = wi::to_wide (max_op0) + wi::to_wide (max_op1);
2192 if (wi::cmp (wi::to_wide (max_op1), 0, sgn)
2193 != wi::cmp (wmax, wi::to_wide (max_op0), sgn))
2194 max_ovf = wi::cmp (wi::to_wide (max_op0), wmax, sgn);
2197 else if (max_op0)
2198 wmax = wi::to_wide (max_op0);
2199 else if (max_op1)
2201 if (minus_p)
2203 wmax = -wi::to_wide (max_op1);
2205 /* Check for overflow. */
2206 if (sgn == SIGNED
2207 && wi::neg_p (wi::to_wide (max_op1))
2208 && wi::neg_p (wmax))
2209 max_ovf = 1;
2210 else if (sgn == UNSIGNED && wi::to_wide (max_op1) != 0)
2211 max_ovf = -1;
2213 else
2214 wmax = wi::to_wide (max_op1);
2216 else
2217 wmax = wi::shwi (0, prec);
2219 /* Check for type overflow. */
2220 if (min_ovf == 0)
2222 if (wi::cmp (wmin, type_min, sgn) == -1)
2223 min_ovf = -1;
2224 else if (wi::cmp (wmin, type_max, sgn) == 1)
2225 min_ovf = 1;
2227 if (max_ovf == 0)
2229 if (wi::cmp (wmax, type_min, sgn) == -1)
2230 max_ovf = -1;
2231 else if (wi::cmp (wmax, type_max, sgn) == 1)
2232 max_ovf = 1;
2235 /* If we have overflow for the constant part and the resulting
2236 range will be symbolic, drop to VR_VARYING. */
2237 if ((min_ovf && sym_min_op0 != sym_min_op1)
2238 || (max_ovf && sym_max_op0 != sym_max_op1))
2240 set_value_range_to_varying (vr);
2241 return;
2244 if (TYPE_OVERFLOW_WRAPS (expr_type))
2246 /* If overflow wraps, truncate the values and adjust the
2247 range kind and bounds appropriately. */
2248 wide_int tmin = wide_int::from (wmin, prec, sgn);
2249 wide_int tmax = wide_int::from (wmax, prec, sgn);
2250 if (min_ovf == max_ovf)
2252 /* No overflow or both overflow or underflow. The
2253 range kind stays VR_RANGE. */
2254 min = wide_int_to_tree (expr_type, tmin);
2255 max = wide_int_to_tree (expr_type, tmax);
2257 else if ((min_ovf == -1 && max_ovf == 0)
2258 || (max_ovf == 1 && min_ovf == 0))
2260 /* Min underflow or max overflow. The range kind
2261 changes to VR_ANTI_RANGE. */
2262 bool covers = false;
2263 wide_int tem = tmin;
2264 type = VR_ANTI_RANGE;
2265 tmin = tmax + 1;
2266 if (wi::cmp (tmin, tmax, sgn) < 0)
2267 covers = true;
2268 tmax = tem - 1;
2269 if (wi::cmp (tmax, tem, sgn) > 0)
2270 covers = true;
2271 /* If the anti-range would cover nothing, drop to varying.
2272 Likewise if the anti-range bounds are outside of the
2273 types values. */
2274 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
2276 set_value_range_to_varying (vr);
2277 return;
2279 min = wide_int_to_tree (expr_type, tmin);
2280 max = wide_int_to_tree (expr_type, tmax);
2282 else
2284 /* Other underflow and/or overflow, drop to VR_VARYING. */
2285 set_value_range_to_varying (vr);
2286 return;
2289 else
2291 /* If overflow does not wrap, saturate to the types min/max
2292 value. */
2293 if (min_ovf == -1)
2294 min = wide_int_to_tree (expr_type, type_min);
2295 else if (min_ovf == 1)
2296 min = wide_int_to_tree (expr_type, type_max);
2297 else
2298 min = wide_int_to_tree (expr_type, wmin);
2300 if (max_ovf == -1)
2301 max = wide_int_to_tree (expr_type, type_min);
2302 else if (max_ovf == 1)
2303 max = wide_int_to_tree (expr_type, type_max);
2304 else
2305 max = wide_int_to_tree (expr_type, wmax);
2308 /* If the result lower bound is constant, we're done;
2309 otherwise, build the symbolic lower bound. */
2310 if (sym_min_op0 == sym_min_op1)
2312 else if (sym_min_op0)
2313 min = build_symbolic_expr (expr_type, sym_min_op0,
2314 neg_min_op0, min);
2315 else if (sym_min_op1)
2317 /* We may not negate if that might introduce
2318 undefined overflow. */
2319 if (! minus_p
2320 || neg_min_op1
2321 || TYPE_OVERFLOW_WRAPS (expr_type))
2322 min = build_symbolic_expr (expr_type, sym_min_op1,
2323 neg_min_op1 ^ minus_p, min);
2324 else
2325 min = NULL_TREE;
2328 /* Likewise for the upper bound. */
2329 if (sym_max_op0 == sym_max_op1)
2331 else if (sym_max_op0)
2332 max = build_symbolic_expr (expr_type, sym_max_op0,
2333 neg_max_op0, max);
2334 else if (sym_max_op1)
2336 /* We may not negate if that might introduce
2337 undefined overflow. */
2338 if (! minus_p
2339 || neg_max_op1
2340 || TYPE_OVERFLOW_WRAPS (expr_type))
2341 max = build_symbolic_expr (expr_type, sym_max_op1,
2342 neg_max_op1 ^ minus_p, max);
2343 else
2344 max = NULL_TREE;
2347 else
2349 /* For other cases, for example if we have a PLUS_EXPR with two
2350 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
2351 to compute a precise range for such a case.
2352 ??? General even mixed range kind operations can be expressed
2353 by for example transforming ~[3, 5] + [1, 2] to range-only
2354 operations and a union primitive:
2355 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
2356 [-INF+1, 4] U [6, +INF(OVF)]
2357 though usually the union is not exactly representable with
2358 a single range or anti-range as the above is
2359 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
2360 but one could use a scheme similar to equivalences for this. */
2361 set_value_range_to_varying (vr);
2362 return;
2365 else if (code == MIN_EXPR
2366 || code == MAX_EXPR)
2368 if (vr0.type == VR_RANGE
2369 && !symbolic_range_p (&vr0))
2371 type = VR_RANGE;
2372 if (vr1.type == VR_RANGE
2373 && !symbolic_range_p (&vr1))
2375 /* For operations that make the resulting range directly
2376 proportional to the original ranges, apply the operation to
2377 the same end of each range. */
2378 min = int_const_binop (code, vr0.min, vr1.min);
2379 max = int_const_binop (code, vr0.max, vr1.max);
2381 else if (code == MIN_EXPR)
2383 min = vrp_val_min (expr_type);
2384 max = vr0.max;
2386 else if (code == MAX_EXPR)
2388 min = vr0.min;
2389 max = vrp_val_max (expr_type);
2392 else if (vr1.type == VR_RANGE
2393 && !symbolic_range_p (&vr1))
2395 type = VR_RANGE;
2396 if (code == MIN_EXPR)
2398 min = vrp_val_min (expr_type);
2399 max = vr1.max;
2401 else if (code == MAX_EXPR)
2403 min = vr1.min;
2404 max = vrp_val_max (expr_type);
2407 else
2409 set_value_range_to_varying (vr);
2410 return;
2413 else if (code == MULT_EXPR)
2415 /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
2416 drop to varying. This test requires 2*prec bits if both
2417 operands are signed and 2*prec + 2 bits if either is not. */
2419 signop sign = TYPE_SIGN (expr_type);
2420 unsigned int prec = TYPE_PRECISION (expr_type);
2422 if (!range_int_cst_p (&vr0)
2423 || !range_int_cst_p (&vr1))
2425 set_value_range_to_varying (vr);
2426 return;
2429 if (TYPE_OVERFLOW_WRAPS (expr_type))
2431 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) vrp_int;
2432 typedef generic_wide_int
2433 <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> > vrp_int_cst;
2434 vrp_int sizem1 = wi::mask <vrp_int> (prec, false);
2435 vrp_int size = sizem1 + 1;
2437 /* Extend the values using the sign of the result to PREC2.
2438 From here on out, everthing is just signed math no matter
2439 what the input types were. */
2440 vrp_int min0 = vrp_int_cst (vr0.min);
2441 vrp_int max0 = vrp_int_cst (vr0.max);
2442 vrp_int min1 = vrp_int_cst (vr1.min);
2443 vrp_int max1 = vrp_int_cst (vr1.max);
2444 /* Canonicalize the intervals. */
2445 if (sign == UNSIGNED)
2447 if (wi::ltu_p (size, min0 + max0))
2449 min0 -= size;
2450 max0 -= size;
2453 if (wi::ltu_p (size, min1 + max1))
2455 min1 -= size;
2456 max1 -= size;
2460 vrp_int prod0 = min0 * min1;
2461 vrp_int prod1 = min0 * max1;
2462 vrp_int prod2 = max0 * min1;
2463 vrp_int prod3 = max0 * max1;
2465 /* Sort the 4 products so that min is in prod0 and max is in
2466 prod3. */
2467 /* min0min1 > max0max1 */
2468 if (prod0 > prod3)
2469 std::swap (prod0, prod3);
2471 /* min0max1 > max0min1 */
2472 if (prod1 > prod2)
2473 std::swap (prod1, prod2);
2475 if (prod0 > prod1)
2476 std::swap (prod0, prod1);
2478 if (prod2 > prod3)
2479 std::swap (prod2, prod3);
2481 /* diff = max - min. */
2482 prod2 = prod3 - prod0;
2483 if (wi::geu_p (prod2, sizem1))
2485 /* the range covers all values. */
2486 set_value_range_to_varying (vr);
2487 return;
2490 /* The following should handle the wrapping and selecting
2491 VR_ANTI_RANGE for us. */
2492 min = wide_int_to_tree (expr_type, prod0);
2493 max = wide_int_to_tree (expr_type, prod3);
2494 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
2495 return;
2498 /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
2499 drop to VR_VARYING. It would take more effort to compute a
2500 precise range for such a case. For example, if we have
2501 op0 == 65536 and op1 == 65536 with their ranges both being
2502 ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
2503 we cannot claim that the product is in ~[0,0]. Note that we
2504 are guaranteed to have vr0.type == vr1.type at this
2505 point. */
2506 if (vr0.type == VR_ANTI_RANGE
2507 && !TYPE_OVERFLOW_UNDEFINED (expr_type))
2509 set_value_range_to_varying (vr);
2510 return;
2513 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2514 return;
2516 else if (code == RSHIFT_EXPR
2517 || code == LSHIFT_EXPR)
2519 /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
2520 then drop to VR_VARYING. Outside of this range we get undefined
2521 behavior from the shift operation. We cannot even trust
2522 SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
2523 shifts, and the operation at the tree level may be widened. */
2524 if (range_int_cst_p (&vr1)
2525 && compare_tree_int (vr1.min, 0) >= 0
2526 && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
2528 if (code == RSHIFT_EXPR)
2530 /* Even if vr0 is VARYING or otherwise not usable, we can derive
2531 useful ranges just from the shift count. E.g.
2532 x >> 63 for signed 64-bit x is always [-1, 0]. */
2533 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2535 vr0.type = type = VR_RANGE;
2536 vr0.min = vrp_val_min (expr_type);
2537 vr0.max = vrp_val_max (expr_type);
2539 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2540 return;
2542 /* We can map lshifts by constants to MULT_EXPR handling. */
2543 else if (code == LSHIFT_EXPR
2544 && range_int_cst_singleton_p (&vr1))
2546 bool saved_flag_wrapv;
2547 value_range vr1p = VR_INITIALIZER;
2548 vr1p.type = VR_RANGE;
2549 vr1p.min = (wide_int_to_tree
2550 (expr_type,
2551 wi::set_bit_in_zero (tree_to_shwi (vr1.min),
2552 TYPE_PRECISION (expr_type))));
2553 vr1p.max = vr1p.min;
2554 /* We have to use a wrapping multiply though as signed overflow
2555 on lshifts is implementation defined in C89. */
2556 saved_flag_wrapv = flag_wrapv;
2557 flag_wrapv = 1;
2558 extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
2559 &vr0, &vr1p);
2560 flag_wrapv = saved_flag_wrapv;
2561 return;
2563 else if (code == LSHIFT_EXPR
2564 && range_int_cst_p (&vr0))
2566 int prec = TYPE_PRECISION (expr_type);
2567 int overflow_pos = prec;
2568 int bound_shift;
2569 wide_int low_bound, high_bound;
2570 bool uns = TYPE_UNSIGNED (expr_type);
2571 bool in_bounds = false;
2573 if (!uns)
2574 overflow_pos -= 1;
2576 bound_shift = overflow_pos - tree_to_shwi (vr1.max);
2577 /* If bound_shift == HOST_BITS_PER_WIDE_INT, the llshift can
2578 overflow. However, for that to happen, vr1.max needs to be
2579 zero, which means vr1 is a singleton range of zero, which
2580 means it should be handled by the previous LSHIFT_EXPR
2581 if-clause. */
2582 wide_int bound = wi::set_bit_in_zero (bound_shift, prec);
2583 wide_int complement = ~(bound - 1);
2585 if (uns)
2587 low_bound = bound;
2588 high_bound = complement;
2589 if (wi::ltu_p (wi::to_wide (vr0.max), low_bound))
2591 /* [5, 6] << [1, 2] == [10, 24]. */
2592 /* We're shifting out only zeroes, the value increases
2593 monotonically. */
2594 in_bounds = true;
2596 else if (wi::ltu_p (high_bound, wi::to_wide (vr0.min)))
2598 /* [0xffffff00, 0xffffffff] << [1, 2]
2599 == [0xfffffc00, 0xfffffffe]. */
2600 /* We're shifting out only ones, the value decreases
2601 monotonically. */
2602 in_bounds = true;
2605 else
2607 /* [-1, 1] << [1, 2] == [-4, 4]. */
2608 low_bound = complement;
2609 high_bound = bound;
2610 if (wi::lts_p (wi::to_wide (vr0.max), high_bound)
2611 && wi::lts_p (low_bound, wi::to_wide (vr0.min)))
2613 /* For non-negative numbers, we're shifting out only
2614 zeroes, the value increases monotonically.
2615 For negative numbers, we're shifting out only ones, the
2616 value decreases monotomically. */
2617 in_bounds = true;
2621 if (in_bounds)
2623 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2624 return;
2628 set_value_range_to_varying (vr);
2629 return;
2631 else if (code == TRUNC_DIV_EXPR
2632 || code == FLOOR_DIV_EXPR
2633 || code == CEIL_DIV_EXPR
2634 || code == EXACT_DIV_EXPR
2635 || code == ROUND_DIV_EXPR)
2637 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2639 /* For division, if op1 has VR_RANGE but op0 does not, something
2640 can be deduced just from that range. Say [min, max] / [4, max]
2641 gives [min / 4, max / 4] range. */
2642 if (vr1.type == VR_RANGE
2643 && !symbolic_range_p (&vr1)
2644 && range_includes_zero_p (vr1.min, vr1.max) == 0)
2646 vr0.type = type = VR_RANGE;
2647 vr0.min = vrp_val_min (expr_type);
2648 vr0.max = vrp_val_max (expr_type);
2650 else
2652 set_value_range_to_varying (vr);
2653 return;
2657 /* For divisions, if flag_non_call_exceptions is true, we must
2658 not eliminate a division by zero. */
2659 if (cfun->can_throw_non_call_exceptions
2660 && (vr1.type != VR_RANGE
2661 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2663 set_value_range_to_varying (vr);
2664 return;
2667 /* For divisions, if op0 is VR_RANGE, we can deduce a range
2668 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
2669 include 0. */
2670 if (vr0.type == VR_RANGE
2671 && (vr1.type != VR_RANGE
2672 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2674 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
2675 int cmp;
2677 min = NULL_TREE;
2678 max = NULL_TREE;
2679 if (TYPE_UNSIGNED (expr_type)
2680 || value_range_nonnegative_p (&vr1))
2682 /* For unsigned division or when divisor is known
2683 to be non-negative, the range has to cover
2684 all numbers from 0 to max for positive max
2685 and all numbers from min to 0 for negative min. */
2686 cmp = compare_values (vr0.max, zero);
2687 if (cmp == -1)
2689 /* When vr0.max < 0, vr1.min != 0 and value
2690 ranges for dividend and divisor are available. */
2691 if (vr1.type == VR_RANGE
2692 && !symbolic_range_p (&vr0)
2693 && !symbolic_range_p (&vr1)
2694 && compare_values (vr1.min, zero) != 0)
2695 max = int_const_binop (code, vr0.max, vr1.min);
2696 else
2697 max = zero;
2699 else if (cmp == 0 || cmp == 1)
2700 max = vr0.max;
2701 else
2702 type = VR_VARYING;
2703 cmp = compare_values (vr0.min, zero);
2704 if (cmp == 1)
2706 /* For unsigned division when value ranges for dividend
2707 and divisor are available. */
2708 if (vr1.type == VR_RANGE
2709 && !symbolic_range_p (&vr0)
2710 && !symbolic_range_p (&vr1)
2711 && compare_values (vr1.max, zero) != 0)
2712 min = int_const_binop (code, vr0.min, vr1.max);
2713 else
2714 min = zero;
2716 else if (cmp == 0 || cmp == -1)
2717 min = vr0.min;
2718 else
2719 type = VR_VARYING;
2721 else
2723 /* Otherwise the range is -max .. max or min .. -min
2724 depending on which bound is bigger in absolute value,
2725 as the division can change the sign. */
2726 abs_extent_range (vr, vr0.min, vr0.max);
2727 return;
2729 if (type == VR_VARYING)
2731 set_value_range_to_varying (vr);
2732 return;
2735 else if (!symbolic_range_p (&vr0) && !symbolic_range_p (&vr1))
2737 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2738 return;
2741 else if (code == TRUNC_MOD_EXPR)
2743 if (range_is_null (&vr1))
2745 set_value_range_to_undefined (vr);
2746 return;
2748 /* ABS (A % B) < ABS (B) and either
2749 0 <= A % B <= A or A <= A % B <= 0. */
2750 type = VR_RANGE;
2751 signop sgn = TYPE_SIGN (expr_type);
2752 unsigned int prec = TYPE_PRECISION (expr_type);
2753 wide_int wmin, wmax, tmp;
2754 if (vr1.type == VR_RANGE && !symbolic_range_p (&vr1))
2756 wmax = wi::to_wide (vr1.max) - 1;
2757 if (sgn == SIGNED)
2759 tmp = -1 - wi::to_wide (vr1.min);
2760 wmax = wi::smax (wmax, tmp);
2763 else
2765 wmax = wi::max_value (prec, sgn);
2766 /* X % INT_MIN may be INT_MAX. */
2767 if (sgn == UNSIGNED)
2768 wmax = wmax - 1;
2771 if (sgn == UNSIGNED)
2772 wmin = wi::zero (prec);
2773 else
2775 wmin = -wmax;
2776 if (vr0.type == VR_RANGE && TREE_CODE (vr0.min) == INTEGER_CST)
2778 tmp = wi::to_wide (vr0.min);
2779 if (wi::gts_p (tmp, 0))
2780 tmp = wi::zero (prec);
2781 wmin = wi::smax (wmin, tmp);
2785 if (vr0.type == VR_RANGE && TREE_CODE (vr0.max) == INTEGER_CST)
2787 tmp = wi::to_wide (vr0.max);
2788 if (sgn == SIGNED && wi::neg_p (tmp))
2789 tmp = wi::zero (prec);
2790 wmax = wi::min (wmax, tmp, sgn);
2793 min = wide_int_to_tree (expr_type, wmin);
2794 max = wide_int_to_tree (expr_type, wmax);
2796 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
2798 bool int_cst_range0, int_cst_range1;
2799 wide_int may_be_nonzero0, may_be_nonzero1;
2800 wide_int must_be_nonzero0, must_be_nonzero1;
2802 int_cst_range0 = zero_nonzero_bits_from_vr (expr_type, &vr0,
2803 &may_be_nonzero0,
2804 &must_be_nonzero0);
2805 int_cst_range1 = zero_nonzero_bits_from_vr (expr_type, &vr1,
2806 &may_be_nonzero1,
2807 &must_be_nonzero1);
2809 if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR)
2811 value_range *vr0p = NULL, *vr1p = NULL;
2812 if (range_int_cst_singleton_p (&vr1))
2814 vr0p = &vr0;
2815 vr1p = &vr1;
2817 else if (range_int_cst_singleton_p (&vr0))
2819 vr0p = &vr1;
2820 vr1p = &vr0;
2822 /* For op & or | attempt to optimize:
2823 [x, y] op z into [x op z, y op z]
2824 if z is a constant which (for op | its bitwise not) has n
2825 consecutive least significant bits cleared followed by m 1
2826 consecutive bits set immediately above it and either
2827 m + n == precision, or (x >> (m + n)) == (y >> (m + n)).
2828 The least significant n bits of all the values in the range are
2829 cleared or set, the m bits above it are preserved and any bits
2830 above these are required to be the same for all values in the
2831 range. */
2832 if (vr0p && range_int_cst_p (vr0p))
2834 wide_int w = wi::to_wide (vr1p->min);
2835 int m = 0, n = 0;
2836 if (code == BIT_IOR_EXPR)
2837 w = ~w;
2838 if (wi::eq_p (w, 0))
2839 n = TYPE_PRECISION (expr_type);
2840 else
2842 n = wi::ctz (w);
2843 w = ~(w | wi::mask (n, false, w.get_precision ()));
2844 if (wi::eq_p (w, 0))
2845 m = TYPE_PRECISION (expr_type) - n;
2846 else
2847 m = wi::ctz (w) - n;
2849 wide_int mask = wi::mask (m + n, true, w.get_precision ());
2850 if ((mask & wi::to_wide (vr0p->min))
2851 == (mask & wi::to_wide (vr0p->max)))
2853 min = int_const_binop (code, vr0p->min, vr1p->min);
2854 max = int_const_binop (code, vr0p->max, vr1p->min);
2859 type = VR_RANGE;
2860 if (min && max)
2861 /* Optimized above already. */;
2862 else if (code == BIT_AND_EXPR)
2864 min = wide_int_to_tree (expr_type,
2865 must_be_nonzero0 & must_be_nonzero1);
2866 wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
2867 /* If both input ranges contain only negative values we can
2868 truncate the result range maximum to the minimum of the
2869 input range maxima. */
2870 if (int_cst_range0 && int_cst_range1
2871 && tree_int_cst_sgn (vr0.max) < 0
2872 && tree_int_cst_sgn (vr1.max) < 0)
2874 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2875 TYPE_SIGN (expr_type));
2876 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2877 TYPE_SIGN (expr_type));
2879 /* If either input range contains only non-negative values
2880 we can truncate the result range maximum to the respective
2881 maximum of the input range. */
2882 if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
2883 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2884 TYPE_SIGN (expr_type));
2885 if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
2886 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2887 TYPE_SIGN (expr_type));
2888 max = wide_int_to_tree (expr_type, wmax);
2889 cmp = compare_values (min, max);
2890 /* PR68217: In case of signed & sign-bit-CST should
2891 result in [-INF, 0] instead of [-INF, INF]. */
2892 if (cmp == -2 || cmp == 1)
2894 wide_int sign_bit
2895 = wi::set_bit_in_zero (TYPE_PRECISION (expr_type) - 1,
2896 TYPE_PRECISION (expr_type));
2897 if (!TYPE_UNSIGNED (expr_type)
2898 && ((int_cst_range0
2899 && value_range_constant_singleton (&vr0)
2900 && !wi::cmps (wi::to_wide (vr0.min), sign_bit))
2901 || (int_cst_range1
2902 && value_range_constant_singleton (&vr1)
2903 && !wi::cmps (wi::to_wide (vr1.min), sign_bit))))
2905 min = TYPE_MIN_VALUE (expr_type);
2906 max = build_int_cst (expr_type, 0);
2910 else if (code == BIT_IOR_EXPR)
2912 max = wide_int_to_tree (expr_type,
2913 may_be_nonzero0 | may_be_nonzero1);
2914 wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
2915 /* If the input ranges contain only positive values we can
2916 truncate the minimum of the result range to the maximum
2917 of the input range minima. */
2918 if (int_cst_range0 && int_cst_range1
2919 && tree_int_cst_sgn (vr0.min) >= 0
2920 && tree_int_cst_sgn (vr1.min) >= 0)
2922 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2923 TYPE_SIGN (expr_type));
2924 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2925 TYPE_SIGN (expr_type));
2927 /* If either input range contains only negative values
2928 we can truncate the minimum of the result range to the
2929 respective minimum range. */
2930 if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
2931 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2932 TYPE_SIGN (expr_type));
2933 if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
2934 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2935 TYPE_SIGN (expr_type));
2936 min = wide_int_to_tree (expr_type, wmin);
2938 else if (code == BIT_XOR_EXPR)
2940 wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
2941 | ~(may_be_nonzero0 | may_be_nonzero1));
2942 wide_int result_one_bits
2943 = (wi::bit_and_not (must_be_nonzero0, may_be_nonzero1)
2944 | wi::bit_and_not (must_be_nonzero1, may_be_nonzero0));
2945 max = wide_int_to_tree (expr_type, ~result_zero_bits);
2946 min = wide_int_to_tree (expr_type, result_one_bits);
2947 /* If the range has all positive or all negative values the
2948 result is better than VARYING. */
2949 if (tree_int_cst_sgn (min) < 0
2950 || tree_int_cst_sgn (max) >= 0)
2952 else
2953 max = min = NULL_TREE;
2956 else
2957 gcc_unreachable ();
2959 /* If either MIN or MAX overflowed, then set the resulting range to
2960 VARYING. */
2961 if (min == NULL_TREE
2962 || TREE_OVERFLOW_P (min)
2963 || max == NULL_TREE
2964 || TREE_OVERFLOW_P (max))
2966 set_value_range_to_varying (vr);
2967 return;
2970 /* We punt for [-INF, +INF].
2971 We learn nothing when we have INF on both sides.
2972 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
2973 if (vrp_val_is_min (min) && vrp_val_is_max (max))
2975 set_value_range_to_varying (vr);
2976 return;
2979 cmp = compare_values (min, max);
2980 if (cmp == -2 || cmp == 1)
2982 /* If the new range has its limits swapped around (MIN > MAX),
2983 then the operation caused one of them to wrap around, mark
2984 the new range VARYING. */
2985 set_value_range_to_varying (vr);
2987 else
2988 set_value_range (vr, type, min, max, NULL);
2991 /* Extract range information from a binary expression OP0 CODE OP1 based on
2992 the ranges of each of its operands with resulting type EXPR_TYPE.
2993 The resulting range is stored in *VR. */
2995 void
2996 vr_values::extract_range_from_binary_expr (value_range *vr,
2997 enum tree_code code,
2998 tree expr_type, tree op0, tree op1)
3000 value_range vr0 = VR_INITIALIZER;
3001 value_range vr1 = VR_INITIALIZER;
3003 /* Get value ranges for each operand. For constant operands, create
3004 a new value range with the operand to simplify processing. */
3005 if (TREE_CODE (op0) == SSA_NAME)
3006 vr0 = *(get_value_range (op0));
3007 else if (is_gimple_min_invariant (op0))
3008 set_value_range_to_value (&vr0, op0, NULL);
3009 else
3010 set_value_range_to_varying (&vr0);
3012 if (TREE_CODE (op1) == SSA_NAME)
3013 vr1 = *(get_value_range (op1));
3014 else if (is_gimple_min_invariant (op1))
3015 set_value_range_to_value (&vr1, op1, NULL);
3016 else
3017 set_value_range_to_varying (&vr1);
3019 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &vr1);
3021 /* Try harder for PLUS and MINUS if the range of one operand is symbolic
3022 and based on the other operand, for example if it was deduced from a
3023 symbolic comparison. When a bound of the range of the first operand
3024 is invariant, we set the corresponding bound of the new range to INF
3025 in order to avoid recursing on the range of the second operand. */
3026 if (vr->type == VR_VARYING
3027 && (code == PLUS_EXPR || code == MINUS_EXPR)
3028 && TREE_CODE (op1) == SSA_NAME
3029 && vr0.type == VR_RANGE
3030 && symbolic_range_based_on_p (&vr0, op1))
3032 const bool minus_p = (code == MINUS_EXPR);
3033 value_range n_vr1 = VR_INITIALIZER;
3035 /* Try with VR0 and [-INF, OP1]. */
3036 if (is_gimple_min_invariant (minus_p ? vr0.max : vr0.min))
3037 set_value_range (&n_vr1, VR_RANGE, vrp_val_min (expr_type), op1, NULL);
3039 /* Try with VR0 and [OP1, +INF]. */
3040 else if (is_gimple_min_invariant (minus_p ? vr0.min : vr0.max))
3041 set_value_range (&n_vr1, VR_RANGE, op1, vrp_val_max (expr_type), NULL);
3043 /* Try with VR0 and [OP1, OP1]. */
3044 else
3045 set_value_range (&n_vr1, VR_RANGE, op1, op1, NULL);
3047 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &n_vr1);
3050 if (vr->type == VR_VARYING
3051 && (code == PLUS_EXPR || code == MINUS_EXPR)
3052 && TREE_CODE (op0) == SSA_NAME
3053 && vr1.type == VR_RANGE
3054 && symbolic_range_based_on_p (&vr1, op0))
3056 const bool minus_p = (code == MINUS_EXPR);
3057 value_range n_vr0 = VR_INITIALIZER;
3059 /* Try with [-INF, OP0] and VR1. */
3060 if (is_gimple_min_invariant (minus_p ? vr1.max : vr1.min))
3061 set_value_range (&n_vr0, VR_RANGE, vrp_val_min (expr_type), op0, NULL);
3063 /* Try with [OP0, +INF] and VR1. */
3064 else if (is_gimple_min_invariant (minus_p ? vr1.min : vr1.max))
3065 set_value_range (&n_vr0, VR_RANGE, op0, vrp_val_max (expr_type), NULL);
3067 /* Try with [OP0, OP0] and VR1. */
3068 else
3069 set_value_range (&n_vr0, VR_RANGE, op0, op0, NULL);
3071 extract_range_from_binary_expr_1 (vr, code, expr_type, &n_vr0, &vr1);
3074 /* If we didn't derive a range for MINUS_EXPR, and
3075 op1's range is ~[op0,op0] or vice-versa, then we
3076 can derive a non-null range. This happens often for
3077 pointer subtraction. */
3078 if (vr->type == VR_VARYING
3079 && code == MINUS_EXPR
3080 && TREE_CODE (op0) == SSA_NAME
3081 && ((vr0.type == VR_ANTI_RANGE
3082 && vr0.min == op1
3083 && vr0.min == vr0.max)
3084 || (vr1.type == VR_ANTI_RANGE
3085 && vr1.min == op0
3086 && vr1.min == vr1.max)))
3087 set_value_range_to_nonnull (vr, TREE_TYPE (op0));
3090 /* Extract range information from a unary operation CODE based on
3091 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
3092 The resulting range is stored in *VR. */
3094 void
3095 extract_range_from_unary_expr (value_range *vr,
3096 enum tree_code code, tree type,
3097 value_range *vr0_, tree op0_type)
3099 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
3101 /* VRP only operates on integral and pointer types. */
3102 if (!(INTEGRAL_TYPE_P (op0_type)
3103 || POINTER_TYPE_P (op0_type))
3104 || !(INTEGRAL_TYPE_P (type)
3105 || POINTER_TYPE_P (type)))
3107 set_value_range_to_varying (vr);
3108 return;
3111 /* If VR0 is UNDEFINED, so is the result. */
3112 if (vr0.type == VR_UNDEFINED)
3114 set_value_range_to_undefined (vr);
3115 return;
3118 /* Handle operations that we express in terms of others. */
3119 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
3121 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
3122 copy_value_range (vr, &vr0);
3123 return;
3125 else if (code == NEGATE_EXPR)
3127 /* -X is simply 0 - X, so re-use existing code that also handles
3128 anti-ranges fine. */
3129 value_range zero = VR_INITIALIZER;
3130 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
3131 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
3132 return;
3134 else if (code == BIT_NOT_EXPR)
3136 /* ~X is simply -1 - X, so re-use existing code that also handles
3137 anti-ranges fine. */
3138 value_range minusone = VR_INITIALIZER;
3139 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
3140 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
3141 type, &minusone, &vr0);
3142 return;
3145 /* Now canonicalize anti-ranges to ranges when they are not symbolic
3146 and express op ~[] as (op []') U (op []''). */
3147 if (vr0.type == VR_ANTI_RANGE
3148 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
3150 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
3151 if (vrtem1.type != VR_UNDEFINED)
3153 value_range vrres = VR_INITIALIZER;
3154 extract_range_from_unary_expr (&vrres, code, type,
3155 &vrtem1, op0_type);
3156 vrp_meet (vr, &vrres);
3158 return;
3161 if (CONVERT_EXPR_CODE_P (code))
3163 tree inner_type = op0_type;
3164 tree outer_type = type;
3166 /* If the expression evaluates to a pointer, we are only interested in
3167 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
3168 if (POINTER_TYPE_P (type))
3170 if (range_is_nonnull (&vr0))
3171 set_value_range_to_nonnull (vr, type);
3172 else if (range_is_null (&vr0))
3173 set_value_range_to_null (vr, type);
3174 else
3175 set_value_range_to_varying (vr);
3176 return;
3179 /* If VR0 is varying and we increase the type precision, assume
3180 a full range for the following transformation. */
3181 if (vr0.type == VR_VARYING
3182 && INTEGRAL_TYPE_P (inner_type)
3183 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
3185 vr0.type = VR_RANGE;
3186 vr0.min = TYPE_MIN_VALUE (inner_type);
3187 vr0.max = TYPE_MAX_VALUE (inner_type);
3190 /* If VR0 is a constant range or anti-range and the conversion is
3191 not truncating we can convert the min and max values and
3192 canonicalize the resulting range. Otherwise we can do the
3193 conversion if the size of the range is less than what the
3194 precision of the target type can represent and the range is
3195 not an anti-range. */
3196 if ((vr0.type == VR_RANGE
3197 || vr0.type == VR_ANTI_RANGE)
3198 && TREE_CODE (vr0.min) == INTEGER_CST
3199 && TREE_CODE (vr0.max) == INTEGER_CST
3200 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
3201 || (vr0.type == VR_RANGE
3202 && integer_zerop (int_const_binop (RSHIFT_EXPR,
3203 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
3204 size_int (TYPE_PRECISION (outer_type)))))))
3206 tree new_min, new_max;
3207 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
3208 0, false);
3209 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
3210 0, false);
3211 set_and_canonicalize_value_range (vr, vr0.type,
3212 new_min, new_max, NULL);
3213 return;
3216 set_value_range_to_varying (vr);
3217 return;
3219 else if (code == ABS_EXPR)
3221 tree min, max;
3222 int cmp;
3224 /* Pass through vr0 in the easy cases. */
3225 if (TYPE_UNSIGNED (type)
3226 || value_range_nonnegative_p (&vr0))
3228 copy_value_range (vr, &vr0);
3229 return;
3232 /* For the remaining varying or symbolic ranges we can't do anything
3233 useful. */
3234 if (vr0.type == VR_VARYING
3235 || symbolic_range_p (&vr0))
3237 set_value_range_to_varying (vr);
3238 return;
3241 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
3242 useful range. */
3243 if (!TYPE_OVERFLOW_UNDEFINED (type)
3244 && ((vr0.type == VR_RANGE
3245 && vrp_val_is_min (vr0.min))
3246 || (vr0.type == VR_ANTI_RANGE
3247 && !vrp_val_is_min (vr0.min))))
3249 set_value_range_to_varying (vr);
3250 return;
3253 /* ABS_EXPR may flip the range around, if the original range
3254 included negative values. */
3255 if (!vrp_val_is_min (vr0.min))
3256 min = fold_unary_to_constant (code, type, vr0.min);
3257 else
3258 min = TYPE_MAX_VALUE (type);
3260 if (!vrp_val_is_min (vr0.max))
3261 max = fold_unary_to_constant (code, type, vr0.max);
3262 else
3263 max = TYPE_MAX_VALUE (type);
3265 cmp = compare_values (min, max);
3267 /* If a VR_ANTI_RANGEs contains zero, then we have
3268 ~[-INF, min(MIN, MAX)]. */
3269 if (vr0.type == VR_ANTI_RANGE)
3271 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3273 /* Take the lower of the two values. */
3274 if (cmp != 1)
3275 max = min;
3277 /* Create ~[-INF, min (abs(MIN), abs(MAX))]
3278 or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
3279 flag_wrapv is set and the original anti-range doesn't include
3280 TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE. */
3281 if (TYPE_OVERFLOW_WRAPS (type))
3283 tree type_min_value = TYPE_MIN_VALUE (type);
3285 min = (vr0.min != type_min_value
3286 ? int_const_binop (PLUS_EXPR, type_min_value,
3287 build_int_cst (TREE_TYPE (type_min_value), 1))
3288 : type_min_value);
3290 else
3291 min = TYPE_MIN_VALUE (type);
3293 else
3295 /* All else has failed, so create the range [0, INF], even for
3296 flag_wrapv since TYPE_MIN_VALUE is in the original
3297 anti-range. */
3298 vr0.type = VR_RANGE;
3299 min = build_int_cst (type, 0);
3300 max = TYPE_MAX_VALUE (type);
3304 /* If the range contains zero then we know that the minimum value in the
3305 range will be zero. */
3306 else if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3308 if (cmp == 1)
3309 max = min;
3310 min = build_int_cst (type, 0);
3312 else
3314 /* If the range was reversed, swap MIN and MAX. */
3315 if (cmp == 1)
3316 std::swap (min, max);
3319 cmp = compare_values (min, max);
3320 if (cmp == -2 || cmp == 1)
3322 /* If the new range has its limits swapped around (MIN > MAX),
3323 then the operation caused one of them to wrap around, mark
3324 the new range VARYING. */
3325 set_value_range_to_varying (vr);
3327 else
3328 set_value_range (vr, vr0.type, min, max, NULL);
3329 return;
3332 /* For unhandled operations fall back to varying. */
3333 set_value_range_to_varying (vr);
3334 return;
3338 /* Extract range information from a unary expression CODE OP0 based on
3339 the range of its operand with resulting type TYPE.
3340 The resulting range is stored in *VR. */
3342 void
3343 vr_values::extract_range_from_unary_expr (value_range *vr, enum tree_code code,
3344 tree type, tree op0)
3346 value_range vr0 = VR_INITIALIZER;
3348 /* Get value ranges for the operand. For constant operands, create
3349 a new value range with the operand to simplify processing. */
3350 if (TREE_CODE (op0) == SSA_NAME)
3351 vr0 = *(get_value_range (op0));
3352 else if (is_gimple_min_invariant (op0))
3353 set_value_range_to_value (&vr0, op0, NULL);
3354 else
3355 set_value_range_to_varying (&vr0);
3357 ::extract_range_from_unary_expr (vr, code, type, &vr0, TREE_TYPE (op0));
3361 /* Extract range information from a conditional expression STMT based on
3362 the ranges of each of its operands and the expression code. */
3364 void
3365 vr_values::extract_range_from_cond_expr (value_range *vr, gassign *stmt)
3367 tree op0, op1;
3368 value_range vr0 = VR_INITIALIZER;
3369 value_range vr1 = VR_INITIALIZER;
3371 /* Get value ranges for each operand. For constant operands, create
3372 a new value range with the operand to simplify processing. */
3373 op0 = gimple_assign_rhs2 (stmt);
3374 if (TREE_CODE (op0) == SSA_NAME)
3375 vr0 = *(get_value_range (op0));
3376 else if (is_gimple_min_invariant (op0))
3377 set_value_range_to_value (&vr0, op0, NULL);
3378 else
3379 set_value_range_to_varying (&vr0);
3381 op1 = gimple_assign_rhs3 (stmt);
3382 if (TREE_CODE (op1) == SSA_NAME)
3383 vr1 = *(get_value_range (op1));
3384 else if (is_gimple_min_invariant (op1))
3385 set_value_range_to_value (&vr1, op1, NULL);
3386 else
3387 set_value_range_to_varying (&vr1);
3389 /* The resulting value range is the union of the operand ranges */
3390 copy_value_range (vr, &vr0);
3391 vrp_meet (vr, &vr1);
3395 /* Extract range information from a comparison expression EXPR based
3396 on the range of its operand and the expression code. */
3398 void
3399 vr_values::extract_range_from_comparison (value_range *vr, enum tree_code code,
3400 tree type, tree op0, tree op1)
3402 bool sop;
3403 tree val;
3405 val = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, false, &sop,
3406 NULL);
3407 if (val)
3409 /* Since this expression was found on the RHS of an assignment,
3410 its type may be different from _Bool. Convert VAL to EXPR's
3411 type. */
3412 val = fold_convert (type, val);
3413 if (is_gimple_min_invariant (val))
3414 set_value_range_to_value (vr, val, vr->equiv);
3415 else
3416 set_value_range (vr, VR_RANGE, val, val, vr->equiv);
3418 else
3419 /* The result of a comparison is always true or false. */
3420 set_value_range_to_truthvalue (vr, type);
3423 /* Helper function for simplify_internal_call_using_ranges and
3424 extract_range_basic. Return true if OP0 SUBCODE OP1 for
3425 SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
3426 always overflow. Set *OVF to true if it is known to always
3427 overflow. */
3429 bool
3430 vr_values::check_for_binary_op_overflow (enum tree_code subcode, tree type,
3431 tree op0, tree op1, bool *ovf)
3433 value_range vr0 = VR_INITIALIZER;
3434 value_range vr1 = VR_INITIALIZER;
3435 if (TREE_CODE (op0) == SSA_NAME)
3436 vr0 = *get_value_range (op0);
3437 else if (TREE_CODE (op0) == INTEGER_CST)
3438 set_value_range_to_value (&vr0, op0, NULL);
3439 else
3440 set_value_range_to_varying (&vr0);
3442 if (TREE_CODE (op1) == SSA_NAME)
3443 vr1 = *get_value_range (op1);
3444 else if (TREE_CODE (op1) == INTEGER_CST)
3445 set_value_range_to_value (&vr1, op1, NULL);
3446 else
3447 set_value_range_to_varying (&vr1);
3449 if (!range_int_cst_p (&vr0)
3450 || TREE_OVERFLOW (vr0.min)
3451 || TREE_OVERFLOW (vr0.max))
3453 vr0.min = vrp_val_min (TREE_TYPE (op0));
3454 vr0.max = vrp_val_max (TREE_TYPE (op0));
3456 if (!range_int_cst_p (&vr1)
3457 || TREE_OVERFLOW (vr1.min)
3458 || TREE_OVERFLOW (vr1.max))
3460 vr1.min = vrp_val_min (TREE_TYPE (op1));
3461 vr1.max = vrp_val_max (TREE_TYPE (op1));
3463 *ovf = arith_overflowed_p (subcode, type, vr0.min,
3464 subcode == MINUS_EXPR ? vr1.max : vr1.min);
3465 if (arith_overflowed_p (subcode, type, vr0.max,
3466 subcode == MINUS_EXPR ? vr1.min : vr1.max) != *ovf)
3467 return false;
3468 if (subcode == MULT_EXPR)
3470 if (arith_overflowed_p (subcode, type, vr0.min, vr1.max) != *ovf
3471 || arith_overflowed_p (subcode, type, vr0.max, vr1.min) != *ovf)
3472 return false;
3474 if (*ovf)
3476 /* So far we found that there is an overflow on the boundaries.
3477 That doesn't prove that there is an overflow even for all values
3478 in between the boundaries. For that compute widest_int range
3479 of the result and see if it doesn't overlap the range of
3480 type. */
3481 widest_int wmin, wmax;
3482 widest_int w[4];
3483 int i;
3484 w[0] = wi::to_widest (vr0.min);
3485 w[1] = wi::to_widest (vr0.max);
3486 w[2] = wi::to_widest (vr1.min);
3487 w[3] = wi::to_widest (vr1.max);
3488 for (i = 0; i < 4; i++)
3490 widest_int wt;
3491 switch (subcode)
3493 case PLUS_EXPR:
3494 wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
3495 break;
3496 case MINUS_EXPR:
3497 wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
3498 break;
3499 case MULT_EXPR:
3500 wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
3501 break;
3502 default:
3503 gcc_unreachable ();
3505 if (i == 0)
3507 wmin = wt;
3508 wmax = wt;
3510 else
3512 wmin = wi::smin (wmin, wt);
3513 wmax = wi::smax (wmax, wt);
3516 /* The result of op0 CODE op1 is known to be in range
3517 [wmin, wmax]. */
3518 widest_int wtmin = wi::to_widest (vrp_val_min (type));
3519 widest_int wtmax = wi::to_widest (vrp_val_max (type));
3520 /* If all values in [wmin, wmax] are smaller than
3521 [wtmin, wtmax] or all are larger than [wtmin, wtmax],
3522 the arithmetic operation will always overflow. */
3523 if (wmax < wtmin || wmin > wtmax)
3524 return true;
3525 return false;
3527 return true;
3530 /* Try to derive a nonnegative or nonzero range out of STMT relying
3531 primarily on generic routines in fold in conjunction with range data.
3532 Store the result in *VR */
3534 void
3535 vr_values::extract_range_basic (value_range *vr, gimple *stmt)
3537 bool sop;
3538 tree type = gimple_expr_type (stmt);
3540 if (is_gimple_call (stmt))
3542 tree arg;
3543 int mini, maxi, zerov = 0, prec;
3544 enum tree_code subcode = ERROR_MARK;
3545 combined_fn cfn = gimple_call_combined_fn (stmt);
3546 scalar_int_mode mode;
3548 switch (cfn)
3550 case CFN_BUILT_IN_CONSTANT_P:
3551 /* If the call is __builtin_constant_p and the argument is a
3552 function parameter resolve it to false. This avoids bogus
3553 array bound warnings.
3554 ??? We could do this as early as inlining is finished. */
3555 arg = gimple_call_arg (stmt, 0);
3556 if (TREE_CODE (arg) == SSA_NAME
3557 && SSA_NAME_IS_DEFAULT_DEF (arg)
3558 && TREE_CODE (SSA_NAME_VAR (arg)) == PARM_DECL
3559 && cfun->after_inlining)
3561 set_value_range_to_null (vr, type);
3562 return;
3564 break;
3565 /* Both __builtin_ffs* and __builtin_popcount return
3566 [0, prec]. */
3567 CASE_CFN_FFS:
3568 CASE_CFN_POPCOUNT:
3569 arg = gimple_call_arg (stmt, 0);
3570 prec = TYPE_PRECISION (TREE_TYPE (arg));
3571 mini = 0;
3572 maxi = prec;
3573 if (TREE_CODE (arg) == SSA_NAME)
3575 value_range *vr0 = get_value_range (arg);
3576 /* If arg is non-zero, then ffs or popcount
3577 are non-zero. */
3578 if ((vr0->type == VR_RANGE
3579 && range_includes_zero_p (vr0->min, vr0->max) == 0)
3580 || (vr0->type == VR_ANTI_RANGE
3581 && range_includes_zero_p (vr0->min, vr0->max) == 1))
3582 mini = 1;
3583 /* If some high bits are known to be zero,
3584 we can decrease the maximum. */
3585 if (vr0->type == VR_RANGE
3586 && TREE_CODE (vr0->max) == INTEGER_CST
3587 && !operand_less_p (vr0->min,
3588 build_zero_cst (TREE_TYPE (vr0->min))))
3589 maxi = tree_floor_log2 (vr0->max) + 1;
3591 goto bitop_builtin;
3592 /* __builtin_parity* returns [0, 1]. */
3593 CASE_CFN_PARITY:
3594 mini = 0;
3595 maxi = 1;
3596 goto bitop_builtin;
3597 /* __builtin_c[lt]z* return [0, prec-1], except for
3598 when the argument is 0, but that is undefined behavior.
3599 On many targets where the CLZ RTL or optab value is defined
3600 for 0 the value is prec, so include that in the range
3601 by default. */
3602 CASE_CFN_CLZ:
3603 arg = gimple_call_arg (stmt, 0);
3604 prec = TYPE_PRECISION (TREE_TYPE (arg));
3605 mini = 0;
3606 maxi = prec;
3607 mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (arg));
3608 if (optab_handler (clz_optab, mode) != CODE_FOR_nothing
3609 && CLZ_DEFINED_VALUE_AT_ZERO (mode, zerov)
3610 /* Handle only the single common value. */
3611 && zerov != prec)
3612 /* Magic value to give up, unless vr0 proves
3613 arg is non-zero. */
3614 mini = -2;
3615 if (TREE_CODE (arg) == SSA_NAME)
3617 value_range *vr0 = get_value_range (arg);
3618 /* From clz of VR_RANGE minimum we can compute
3619 result maximum. */
3620 if (vr0->type == VR_RANGE
3621 && TREE_CODE (vr0->min) == INTEGER_CST)
3623 maxi = prec - 1 - tree_floor_log2 (vr0->min);
3624 if (maxi != prec)
3625 mini = 0;
3627 else if (vr0->type == VR_ANTI_RANGE
3628 && integer_zerop (vr0->min))
3630 maxi = prec - 1;
3631 mini = 0;
3633 if (mini == -2)
3634 break;
3635 /* From clz of VR_RANGE maximum we can compute
3636 result minimum. */
3637 if (vr0->type == VR_RANGE
3638 && TREE_CODE (vr0->max) == INTEGER_CST)
3640 mini = prec - 1 - tree_floor_log2 (vr0->max);
3641 if (mini == prec)
3642 break;
3645 if (mini == -2)
3646 break;
3647 goto bitop_builtin;
3648 /* __builtin_ctz* return [0, prec-1], except for
3649 when the argument is 0, but that is undefined behavior.
3650 If there is a ctz optab for this mode and
3651 CTZ_DEFINED_VALUE_AT_ZERO, include that in the range,
3652 otherwise just assume 0 won't be seen. */
3653 CASE_CFN_CTZ:
3654 arg = gimple_call_arg (stmt, 0);
3655 prec = TYPE_PRECISION (TREE_TYPE (arg));
3656 mini = 0;
3657 maxi = prec - 1;
3658 mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (arg));
3659 if (optab_handler (ctz_optab, mode) != CODE_FOR_nothing
3660 && CTZ_DEFINED_VALUE_AT_ZERO (mode, zerov))
3662 /* Handle only the two common values. */
3663 if (zerov == -1)
3664 mini = -1;
3665 else if (zerov == prec)
3666 maxi = prec;
3667 else
3668 /* Magic value to give up, unless vr0 proves
3669 arg is non-zero. */
3670 mini = -2;
3672 if (TREE_CODE (arg) == SSA_NAME)
3674 value_range *vr0 = get_value_range (arg);
3675 /* If arg is non-zero, then use [0, prec - 1]. */
3676 if ((vr0->type == VR_RANGE
3677 && integer_nonzerop (vr0->min))
3678 || (vr0->type == VR_ANTI_RANGE
3679 && integer_zerop (vr0->min)))
3681 mini = 0;
3682 maxi = prec - 1;
3684 /* If some high bits are known to be zero,
3685 we can decrease the result maximum. */
3686 if (vr0->type == VR_RANGE
3687 && TREE_CODE (vr0->max) == INTEGER_CST)
3689 maxi = tree_floor_log2 (vr0->max);
3690 /* For vr0 [0, 0] give up. */
3691 if (maxi == -1)
3692 break;
3695 if (mini == -2)
3696 break;
3697 goto bitop_builtin;
3698 /* __builtin_clrsb* returns [0, prec-1]. */
3699 CASE_CFN_CLRSB:
3700 arg = gimple_call_arg (stmt, 0);
3701 prec = TYPE_PRECISION (TREE_TYPE (arg));
3702 mini = 0;
3703 maxi = prec - 1;
3704 goto bitop_builtin;
3705 bitop_builtin:
3706 set_value_range (vr, VR_RANGE, build_int_cst (type, mini),
3707 build_int_cst (type, maxi), NULL);
3708 return;
3709 case CFN_UBSAN_CHECK_ADD:
3710 subcode = PLUS_EXPR;
3711 break;
3712 case CFN_UBSAN_CHECK_SUB:
3713 subcode = MINUS_EXPR;
3714 break;
3715 case CFN_UBSAN_CHECK_MUL:
3716 subcode = MULT_EXPR;
3717 break;
3718 case CFN_GOACC_DIM_SIZE:
3719 case CFN_GOACC_DIM_POS:
3720 /* Optimizing these two internal functions helps the loop
3721 optimizer eliminate outer comparisons. Size is [1,N]
3722 and pos is [0,N-1]. */
3724 bool is_pos = cfn == CFN_GOACC_DIM_POS;
3725 int axis = oacc_get_ifn_dim_arg (stmt);
3726 int size = oacc_get_fn_dim_size (current_function_decl, axis);
3728 if (!size)
3729 /* If it's dynamic, the backend might know a hardware
3730 limitation. */
3731 size = targetm.goacc.dim_limit (axis);
3733 tree type = TREE_TYPE (gimple_call_lhs (stmt));
3734 set_value_range (vr, VR_RANGE,
3735 build_int_cst (type, is_pos ? 0 : 1),
3736 size ? build_int_cst (type, size - is_pos)
3737 : vrp_val_max (type), NULL);
3739 return;
3740 case CFN_BUILT_IN_STRLEN:
3741 if (tree lhs = gimple_call_lhs (stmt))
3742 if (ptrdiff_type_node
3743 && (TYPE_PRECISION (ptrdiff_type_node)
3744 == TYPE_PRECISION (TREE_TYPE (lhs))))
3746 tree type = TREE_TYPE (lhs);
3747 tree max = vrp_val_max (ptrdiff_type_node);
3748 wide_int wmax = wi::to_wide (max, TYPE_PRECISION (TREE_TYPE (max)));
3749 tree range_min = build_zero_cst (type);
3750 tree range_max = wide_int_to_tree (type, wmax - 1);
3751 set_value_range (vr, VR_RANGE, range_min, range_max, NULL);
3752 return;
3754 break;
3755 default:
3756 break;
3758 if (subcode != ERROR_MARK)
3760 bool saved_flag_wrapv = flag_wrapv;
3761 /* Pretend the arithmetics is wrapping. If there is
3762 any overflow, we'll complain, but will actually do
3763 wrapping operation. */
3764 flag_wrapv = 1;
3765 extract_range_from_binary_expr (vr, subcode, type,
3766 gimple_call_arg (stmt, 0),
3767 gimple_call_arg (stmt, 1));
3768 flag_wrapv = saved_flag_wrapv;
3770 /* If for both arguments vrp_valueize returned non-NULL,
3771 this should have been already folded and if not, it
3772 wasn't folded because of overflow. Avoid removing the
3773 UBSAN_CHECK_* calls in that case. */
3774 if (vr->type == VR_RANGE
3775 && (vr->min == vr->max
3776 || operand_equal_p (vr->min, vr->max, 0)))
3777 set_value_range_to_varying (vr);
3778 return;
3781 /* Handle extraction of the two results (result of arithmetics and
3782 a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
3783 internal function. Similarly from ATOMIC_COMPARE_EXCHANGE. */
3784 else if (is_gimple_assign (stmt)
3785 && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
3786 || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
3787 && INTEGRAL_TYPE_P (type))
3789 enum tree_code code = gimple_assign_rhs_code (stmt);
3790 tree op = gimple_assign_rhs1 (stmt);
3791 if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
3793 gimple *g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
3794 if (is_gimple_call (g) && gimple_call_internal_p (g))
3796 enum tree_code subcode = ERROR_MARK;
3797 switch (gimple_call_internal_fn (g))
3799 case IFN_ADD_OVERFLOW:
3800 subcode = PLUS_EXPR;
3801 break;
3802 case IFN_SUB_OVERFLOW:
3803 subcode = MINUS_EXPR;
3804 break;
3805 case IFN_MUL_OVERFLOW:
3806 subcode = MULT_EXPR;
3807 break;
3808 case IFN_ATOMIC_COMPARE_EXCHANGE:
3809 if (code == IMAGPART_EXPR)
3811 /* This is the boolean return value whether compare and
3812 exchange changed anything or not. */
3813 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
3814 build_int_cst (type, 1), NULL);
3815 return;
3817 break;
3818 default:
3819 break;
3821 if (subcode != ERROR_MARK)
3823 tree op0 = gimple_call_arg (g, 0);
3824 tree op1 = gimple_call_arg (g, 1);
3825 if (code == IMAGPART_EXPR)
3827 bool ovf = false;
3828 if (check_for_binary_op_overflow (subcode, type,
3829 op0, op1, &ovf))
3830 set_value_range_to_value (vr,
3831 build_int_cst (type, ovf),
3832 NULL);
3833 else if (TYPE_PRECISION (type) == 1
3834 && !TYPE_UNSIGNED (type))
3835 set_value_range_to_varying (vr);
3836 else
3837 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
3838 build_int_cst (type, 1), NULL);
3840 else if (types_compatible_p (type, TREE_TYPE (op0))
3841 && types_compatible_p (type, TREE_TYPE (op1)))
3843 bool saved_flag_wrapv = flag_wrapv;
3844 /* Pretend the arithmetics is wrapping. If there is
3845 any overflow, IMAGPART_EXPR will be set. */
3846 flag_wrapv = 1;
3847 extract_range_from_binary_expr (vr, subcode, type,
3848 op0, op1);
3849 flag_wrapv = saved_flag_wrapv;
3851 else
3853 value_range vr0 = VR_INITIALIZER;
3854 value_range vr1 = VR_INITIALIZER;
3855 bool saved_flag_wrapv = flag_wrapv;
3856 /* Pretend the arithmetics is wrapping. If there is
3857 any overflow, IMAGPART_EXPR will be set. */
3858 flag_wrapv = 1;
3859 extract_range_from_unary_expr (&vr0, NOP_EXPR,
3860 type, op0);
3861 extract_range_from_unary_expr (&vr1, NOP_EXPR,
3862 type, op1);
3863 extract_range_from_binary_expr_1 (vr, subcode, type,
3864 &vr0, &vr1);
3865 flag_wrapv = saved_flag_wrapv;
3867 return;
3872 if (INTEGRAL_TYPE_P (type)
3873 && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
3874 set_value_range_to_nonnegative (vr, type);
3875 else if (vrp_stmt_computes_nonzero (stmt))
3876 set_value_range_to_nonnull (vr, type);
3877 else
3878 set_value_range_to_varying (vr);
3882 /* Try to compute a useful range out of assignment STMT and store it
3883 in *VR. */
3885 void
3886 vr_values::extract_range_from_assignment (value_range *vr, gassign *stmt)
3888 enum tree_code code = gimple_assign_rhs_code (stmt);
3890 if (code == ASSERT_EXPR)
3891 extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
3892 else if (code == SSA_NAME)
3893 extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
3894 else if (TREE_CODE_CLASS (code) == tcc_binary)
3895 extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
3896 gimple_expr_type (stmt),
3897 gimple_assign_rhs1 (stmt),
3898 gimple_assign_rhs2 (stmt));
3899 else if (TREE_CODE_CLASS (code) == tcc_unary)
3900 extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
3901 gimple_expr_type (stmt),
3902 gimple_assign_rhs1 (stmt));
3903 else if (code == COND_EXPR)
3904 extract_range_from_cond_expr (vr, stmt);
3905 else if (TREE_CODE_CLASS (code) == tcc_comparison)
3906 extract_range_from_comparison (vr, gimple_assign_rhs_code (stmt),
3907 gimple_expr_type (stmt),
3908 gimple_assign_rhs1 (stmt),
3909 gimple_assign_rhs2 (stmt));
3910 else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
3911 && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
3912 set_value_range_to_value (vr, gimple_assign_rhs1 (stmt), NULL);
3913 else
3914 set_value_range_to_varying (vr);
3916 if (vr->type == VR_VARYING)
3917 extract_range_basic (vr, stmt);
3920 /* Given a range VR, a LOOP and a variable VAR, determine whether it
3921 would be profitable to adjust VR using scalar evolution information
3922 for VAR. If so, update VR with the new limits. */
3924 void
3925 vr_values::adjust_range_with_scev (value_range *vr, struct loop *loop,
3926 gimple *stmt, tree var)
3928 tree init, step, chrec, tmin, tmax, min, max, type, tem;
3929 enum ev_direction dir;
3931 /* TODO. Don't adjust anti-ranges. An anti-range may provide
3932 better opportunities than a regular range, but I'm not sure. */
3933 if (vr->type == VR_ANTI_RANGE)
3934 return;
3936 chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
3938 /* Like in PR19590, scev can return a constant function. */
3939 if (is_gimple_min_invariant (chrec))
3941 set_value_range_to_value (vr, chrec, vr->equiv);
3942 return;
3945 if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
3946 return;
3948 init = initial_condition_in_loop_num (chrec, loop->num);
3949 tem = op_with_constant_singleton_value_range (init);
3950 if (tem)
3951 init = tem;
3952 step = evolution_part_in_loop_num (chrec, loop->num);
3953 tem = op_with_constant_singleton_value_range (step);
3954 if (tem)
3955 step = tem;
3957 /* If STEP is symbolic, we can't know whether INIT will be the
3958 minimum or maximum value in the range. Also, unless INIT is
3959 a simple expression, compare_values and possibly other functions
3960 in tree-vrp won't be able to handle it. */
3961 if (step == NULL_TREE
3962 || !is_gimple_min_invariant (step)
3963 || !valid_value_p (init))
3964 return;
3966 dir = scev_direction (chrec);
3967 if (/* Do not adjust ranges if we do not know whether the iv increases
3968 or decreases, ... */
3969 dir == EV_DIR_UNKNOWN
3970 /* ... or if it may wrap. */
3971 || scev_probably_wraps_p (NULL_TREE, init, step, stmt,
3972 get_chrec_loop (chrec), true))
3973 return;
3975 type = TREE_TYPE (var);
3976 if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
3977 tmin = lower_bound_in_type (type, type);
3978 else
3979 tmin = TYPE_MIN_VALUE (type);
3980 if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
3981 tmax = upper_bound_in_type (type, type);
3982 else
3983 tmax = TYPE_MAX_VALUE (type);
3985 /* Try to use estimated number of iterations for the loop to constrain the
3986 final value in the evolution. */
3987 if (TREE_CODE (step) == INTEGER_CST
3988 && is_gimple_val (init)
3989 && (TREE_CODE (init) != SSA_NAME
3990 || get_value_range (init)->type == VR_RANGE))
3992 widest_int nit;
3994 /* We are only entering here for loop header PHI nodes, so using
3995 the number of latch executions is the correct thing to use. */
3996 if (max_loop_iterations (loop, &nit))
3998 value_range maxvr = VR_INITIALIZER;
3999 signop sgn = TYPE_SIGN (TREE_TYPE (step));
4000 bool overflow;
4002 widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
4003 &overflow);
4004 /* If the multiplication overflowed we can't do a meaningful
4005 adjustment. Likewise if the result doesn't fit in the type
4006 of the induction variable. For a signed type we have to
4007 check whether the result has the expected signedness which
4008 is that of the step as number of iterations is unsigned. */
4009 if (!overflow
4010 && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
4011 && (sgn == UNSIGNED
4012 || wi::gts_p (wtmp, 0) == wi::gts_p (wi::to_wide (step), 0)))
4014 tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
4015 extract_range_from_binary_expr (&maxvr, PLUS_EXPR,
4016 TREE_TYPE (init), init, tem);
4017 /* Likewise if the addition did. */
4018 if (maxvr.type == VR_RANGE)
4020 value_range initvr = VR_INITIALIZER;
4022 if (TREE_CODE (init) == SSA_NAME)
4023 initvr = *(get_value_range (init));
4024 else if (is_gimple_min_invariant (init))
4025 set_value_range_to_value (&initvr, init, NULL);
4026 else
4027 return;
4029 /* Check if init + nit * step overflows. Though we checked
4030 scev {init, step}_loop doesn't wrap, it is not enough
4031 because the loop may exit immediately. Overflow could
4032 happen in the plus expression in this case. */
4033 if ((dir == EV_DIR_DECREASES
4034 && compare_values (maxvr.min, initvr.min) != -1)
4035 || (dir == EV_DIR_GROWS
4036 && compare_values (maxvr.max, initvr.max) != 1))
4037 return;
4039 tmin = maxvr.min;
4040 tmax = maxvr.max;
4046 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4048 min = tmin;
4049 max = tmax;
4051 /* For VARYING or UNDEFINED ranges, just about anything we get
4052 from scalar evolutions should be better. */
4054 if (dir == EV_DIR_DECREASES)
4055 max = init;
4056 else
4057 min = init;
4059 else if (vr->type == VR_RANGE)
4061 min = vr->min;
4062 max = vr->max;
4064 if (dir == EV_DIR_DECREASES)
4066 /* INIT is the maximum value. If INIT is lower than VR->MAX
4067 but no smaller than VR->MIN, set VR->MAX to INIT. */
4068 if (compare_values (init, max) == -1)
4069 max = init;
4071 /* According to the loop information, the variable does not
4072 overflow. */
4073 if (compare_values (min, tmin) == -1)
4074 min = tmin;
4077 else
4079 /* If INIT is bigger than VR->MIN, set VR->MIN to INIT. */
4080 if (compare_values (init, min) == 1)
4081 min = init;
4083 if (compare_values (tmax, max) == -1)
4084 max = tmax;
4087 else
4088 return;
4090 /* If we just created an invalid range with the minimum
4091 greater than the maximum, we fail conservatively.
4092 This should happen only in unreachable
4093 parts of code, or for invalid programs. */
4094 if (compare_values (min, max) == 1)
4095 return;
4097 /* Even for valid range info, sometimes overflow flag will leak in.
4098 As GIMPLE IL should have no constants with TREE_OVERFLOW set, we
4099 drop them. */
4100 if (TREE_OVERFLOW_P (min))
4101 min = drop_tree_overflow (min);
4102 if (TREE_OVERFLOW_P (max))
4103 max = drop_tree_overflow (max);
4105 set_value_range (vr, VR_RANGE, min, max, vr->equiv);
4109 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
4111 - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
4112 all the values in the ranges.
4114 - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
4116 - Return NULL_TREE if it is not always possible to determine the
4117 value of the comparison.
4119 Also set *STRICT_OVERFLOW_P to indicate whether comparision evaluation
4120 assumed signed overflow is undefined. */
4123 static tree
4124 compare_ranges (enum tree_code comp, value_range *vr0, value_range *vr1,
4125 bool *strict_overflow_p)
4127 /* VARYING or UNDEFINED ranges cannot be compared. */
4128 if (vr0->type == VR_VARYING
4129 || vr0->type == VR_UNDEFINED
4130 || vr1->type == VR_VARYING
4131 || vr1->type == VR_UNDEFINED)
4132 return NULL_TREE;
4134 /* Anti-ranges need to be handled separately. */
4135 if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
4137 /* If both are anti-ranges, then we cannot compute any
4138 comparison. */
4139 if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
4140 return NULL_TREE;
4142 /* These comparisons are never statically computable. */
4143 if (comp == GT_EXPR
4144 || comp == GE_EXPR
4145 || comp == LT_EXPR
4146 || comp == LE_EXPR)
4147 return NULL_TREE;
4149 /* Equality can be computed only between a range and an
4150 anti-range. ~[VAL1, VAL2] == [VAL1, VAL2] is always false. */
4151 if (vr0->type == VR_RANGE)
4153 /* To simplify processing, make VR0 the anti-range. */
4154 value_range *tmp = vr0;
4155 vr0 = vr1;
4156 vr1 = tmp;
4159 gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
4161 if (compare_values_warnv (vr0->min, vr1->min, strict_overflow_p) == 0
4162 && compare_values_warnv (vr0->max, vr1->max, strict_overflow_p) == 0)
4163 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4165 return NULL_TREE;
4168 /* Simplify processing. If COMP is GT_EXPR or GE_EXPR, switch the
4169 operands around and change the comparison code. */
4170 if (comp == GT_EXPR || comp == GE_EXPR)
4172 comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
4173 std::swap (vr0, vr1);
4176 if (comp == EQ_EXPR)
4178 /* Equality may only be computed if both ranges represent
4179 exactly one value. */
4180 if (compare_values_warnv (vr0->min, vr0->max, strict_overflow_p) == 0
4181 && compare_values_warnv (vr1->min, vr1->max, strict_overflow_p) == 0)
4183 int cmp_min = compare_values_warnv (vr0->min, vr1->min,
4184 strict_overflow_p);
4185 int cmp_max = compare_values_warnv (vr0->max, vr1->max,
4186 strict_overflow_p);
4187 if (cmp_min == 0 && cmp_max == 0)
4188 return boolean_true_node;
4189 else if (cmp_min != -2 && cmp_max != -2)
4190 return boolean_false_node;
4192 /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1. */
4193 else if (compare_values_warnv (vr0->min, vr1->max,
4194 strict_overflow_p) == 1
4195 || compare_values_warnv (vr1->min, vr0->max,
4196 strict_overflow_p) == 1)
4197 return boolean_false_node;
4199 return NULL_TREE;
4201 else if (comp == NE_EXPR)
4203 int cmp1, cmp2;
4205 /* If VR0 is completely to the left or completely to the right
4206 of VR1, they are always different. Notice that we need to
4207 make sure that both comparisons yield similar results to
4208 avoid comparing values that cannot be compared at
4209 compile-time. */
4210 cmp1 = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4211 cmp2 = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4212 if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
4213 return boolean_true_node;
4215 /* If VR0 and VR1 represent a single value and are identical,
4216 return false. */
4217 else if (compare_values_warnv (vr0->min, vr0->max,
4218 strict_overflow_p) == 0
4219 && compare_values_warnv (vr1->min, vr1->max,
4220 strict_overflow_p) == 0
4221 && compare_values_warnv (vr0->min, vr1->min,
4222 strict_overflow_p) == 0
4223 && compare_values_warnv (vr0->max, vr1->max,
4224 strict_overflow_p) == 0)
4225 return boolean_false_node;
4227 /* Otherwise, they may or may not be different. */
4228 else
4229 return NULL_TREE;
4231 else if (comp == LT_EXPR || comp == LE_EXPR)
4233 int tst;
4235 /* If VR0 is to the left of VR1, return true. */
4236 tst = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4237 if ((comp == LT_EXPR && tst == -1)
4238 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4239 return boolean_true_node;
4241 /* If VR0 is to the right of VR1, return false. */
4242 tst = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4243 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4244 || (comp == LE_EXPR && tst == 1))
4245 return boolean_false_node;
4247 /* Otherwise, we don't know. */
4248 return NULL_TREE;
4251 gcc_unreachable ();
4255 /* Given a value range VR, a value VAL and a comparison code COMP, return
4256 BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
4257 values in VR. Return BOOLEAN_FALSE_NODE if the comparison
4258 always returns false. Return NULL_TREE if it is not always
4259 possible to determine the value of the comparison. Also set
4260 *STRICT_OVERFLOW_P to indicate whether comparision evaluation
4261 assumed signed overflow is undefined. */
4263 static tree
4264 compare_range_with_value (enum tree_code comp, value_range *vr, tree val,
4265 bool *strict_overflow_p)
4267 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4268 return NULL_TREE;
4270 /* Anti-ranges need to be handled separately. */
4271 if (vr->type == VR_ANTI_RANGE)
4273 /* For anti-ranges, the only predicates that we can compute at
4274 compile time are equality and inequality. */
4275 if (comp == GT_EXPR
4276 || comp == GE_EXPR
4277 || comp == LT_EXPR
4278 || comp == LE_EXPR)
4279 return NULL_TREE;
4281 /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2. */
4282 if (value_inside_range (val, vr->min, vr->max) == 1)
4283 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4285 return NULL_TREE;
4288 if (comp == EQ_EXPR)
4290 /* EQ_EXPR may only be computed if VR represents exactly
4291 one value. */
4292 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0)
4294 int cmp = compare_values_warnv (vr->min, val, strict_overflow_p);
4295 if (cmp == 0)
4296 return boolean_true_node;
4297 else if (cmp == -1 || cmp == 1 || cmp == 2)
4298 return boolean_false_node;
4300 else if (compare_values_warnv (val, vr->min, strict_overflow_p) == -1
4301 || compare_values_warnv (vr->max, val, strict_overflow_p) == -1)
4302 return boolean_false_node;
4304 return NULL_TREE;
4306 else if (comp == NE_EXPR)
4308 /* If VAL is not inside VR, then they are always different. */
4309 if (compare_values_warnv (vr->max, val, strict_overflow_p) == -1
4310 || compare_values_warnv (vr->min, val, strict_overflow_p) == 1)
4311 return boolean_true_node;
4313 /* If VR represents exactly one value equal to VAL, then return
4314 false. */
4315 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0
4316 && compare_values_warnv (vr->min, val, strict_overflow_p) == 0)
4317 return boolean_false_node;
4319 /* Otherwise, they may or may not be different. */
4320 return NULL_TREE;
4322 else if (comp == LT_EXPR || comp == LE_EXPR)
4324 int tst;
4326 /* If VR is to the left of VAL, return true. */
4327 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4328 if ((comp == LT_EXPR && tst == -1)
4329 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4330 return boolean_true_node;
4332 /* If VR is to the right of VAL, return false. */
4333 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4334 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4335 || (comp == LE_EXPR && tst == 1))
4336 return boolean_false_node;
4338 /* Otherwise, we don't know. */
4339 return NULL_TREE;
4341 else if (comp == GT_EXPR || comp == GE_EXPR)
4343 int tst;
4345 /* If VR is to the right of VAL, return true. */
4346 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4347 if ((comp == GT_EXPR && tst == 1)
4348 || (comp == GE_EXPR && (tst == 0 || tst == 1)))
4349 return boolean_true_node;
4351 /* If VR is to the left of VAL, return false. */
4352 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4353 if ((comp == GT_EXPR && (tst == -1 || tst == 0))
4354 || (comp == GE_EXPR && tst == -1))
4355 return boolean_false_node;
4357 /* Otherwise, we don't know. */
4358 return NULL_TREE;
4361 gcc_unreachable ();
4365 /* Debugging dumps. */
4367 void dump_value_range (FILE *, const value_range *);
4368 void debug_value_range (value_range *);
4369 void dump_all_value_ranges (FILE *);
4370 void dump_vr_equiv (FILE *, bitmap);
4371 void debug_vr_equiv (bitmap);
4374 /* Dump value range VR to FILE. */
4376 void
4377 dump_value_range (FILE *file, const value_range *vr)
4379 if (vr == NULL)
4380 fprintf (file, "[]");
4381 else if (vr->type == VR_UNDEFINED)
4382 fprintf (file, "UNDEFINED");
4383 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4385 tree type = TREE_TYPE (vr->min);
4387 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
4389 if (INTEGRAL_TYPE_P (type)
4390 && !TYPE_UNSIGNED (type)
4391 && vrp_val_is_min (vr->min))
4392 fprintf (file, "-INF");
4393 else
4394 print_generic_expr (file, vr->min);
4396 fprintf (file, ", ");
4398 if (INTEGRAL_TYPE_P (type)
4399 && vrp_val_is_max (vr->max))
4400 fprintf (file, "+INF");
4401 else
4402 print_generic_expr (file, vr->max);
4404 fprintf (file, "]");
4406 if (vr->equiv)
4408 bitmap_iterator bi;
4409 unsigned i, c = 0;
4411 fprintf (file, " EQUIVALENCES: { ");
4413 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
4415 print_generic_expr (file, ssa_name (i));
4416 fprintf (file, " ");
4417 c++;
4420 fprintf (file, "} (%u elements)", c);
4423 else if (vr->type == VR_VARYING)
4424 fprintf (file, "VARYING");
4425 else
4426 fprintf (file, "INVALID RANGE");
4430 /* Dump value range VR to stderr. */
4432 DEBUG_FUNCTION void
4433 debug_value_range (value_range *vr)
4435 dump_value_range (stderr, vr);
4436 fprintf (stderr, "\n");
4440 /* Dump value ranges of all SSA_NAMEs to FILE. */
4442 void
4443 vr_values::dump_all_value_ranges (FILE *file)
4445 size_t i;
4447 for (i = 0; i < num_vr_values; i++)
4449 if (vr_value[i])
4451 print_generic_expr (file, ssa_name (i));
4452 fprintf (file, ": ");
4453 dump_value_range (file, vr_value[i]);
4454 fprintf (file, "\n");
4458 fprintf (file, "\n");
4461 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
4462 create a new SSA name N and return the assertion assignment
4463 'N = ASSERT_EXPR <V, V OP W>'. */
4465 static gimple *
4466 build_assert_expr_for (tree cond, tree v)
4468 tree a;
4469 gassign *assertion;
4471 gcc_assert (TREE_CODE (v) == SSA_NAME
4472 && COMPARISON_CLASS_P (cond));
4474 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
4475 assertion = gimple_build_assign (NULL_TREE, a);
4477 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
4478 operand of the ASSERT_EXPR. Create it so the new name and the old one
4479 are registered in the replacement table so that we can fix the SSA web
4480 after adding all the ASSERT_EXPRs. */
4481 tree new_def = create_new_def_for (v, assertion, NULL);
4482 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
4483 given we have to be able to fully propagate those out to re-create
4484 valid SSA when removing the asserts. */
4485 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
4486 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
4488 return assertion;
4492 /* Return false if EXPR is a predicate expression involving floating
4493 point values. */
4495 static inline bool
4496 fp_predicate (gimple *stmt)
4498 GIMPLE_CHECK (stmt, GIMPLE_COND);
4500 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
4503 /* If the range of values taken by OP can be inferred after STMT executes,
4504 return the comparison code (COMP_CODE_P) and value (VAL_P) that
4505 describes the inferred range. Return true if a range could be
4506 inferred. */
4508 bool
4509 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
4511 *val_p = NULL_TREE;
4512 *comp_code_p = ERROR_MARK;
4514 /* Do not attempt to infer anything in names that flow through
4515 abnormal edges. */
4516 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
4517 return false;
4519 /* If STMT is the last statement of a basic block with no normal
4520 successors, there is no point inferring anything about any of its
4521 operands. We would not be able to find a proper insertion point
4522 for the assertion, anyway. */
4523 if (stmt_ends_bb_p (stmt))
4525 edge_iterator ei;
4526 edge e;
4528 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
4529 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4530 break;
4531 if (e == NULL)
4532 return false;
4535 if (infer_nonnull_range (stmt, op))
4537 *val_p = build_int_cst (TREE_TYPE (op), 0);
4538 *comp_code_p = NE_EXPR;
4539 return true;
4542 return false;
4546 void dump_asserts_for (FILE *, tree);
4547 void debug_asserts_for (tree);
4548 void dump_all_asserts (FILE *);
4549 void debug_all_asserts (void);
4551 /* Dump all the registered assertions for NAME to FILE. */
4553 void
4554 dump_asserts_for (FILE *file, tree name)
4556 assert_locus *loc;
4558 fprintf (file, "Assertions to be inserted for ");
4559 print_generic_expr (file, name);
4560 fprintf (file, "\n");
4562 loc = asserts_for[SSA_NAME_VERSION (name)];
4563 while (loc)
4565 fprintf (file, "\t");
4566 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
4567 fprintf (file, "\n\tBB #%d", loc->bb->index);
4568 if (loc->e)
4570 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
4571 loc->e->dest->index);
4572 dump_edge_info (file, loc->e, dump_flags, 0);
4574 fprintf (file, "\n\tPREDICATE: ");
4575 print_generic_expr (file, loc->expr);
4576 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
4577 print_generic_expr (file, loc->val);
4578 fprintf (file, "\n\n");
4579 loc = loc->next;
4582 fprintf (file, "\n");
4586 /* Dump all the registered assertions for NAME to stderr. */
4588 DEBUG_FUNCTION void
4589 debug_asserts_for (tree name)
4591 dump_asserts_for (stderr, name);
4595 /* Dump all the registered assertions for all the names to FILE. */
4597 void
4598 dump_all_asserts (FILE *file)
4600 unsigned i;
4601 bitmap_iterator bi;
4603 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
4604 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4605 dump_asserts_for (file, ssa_name (i));
4606 fprintf (file, "\n");
4610 /* Dump all the registered assertions for all the names to stderr. */
4612 DEBUG_FUNCTION void
4613 debug_all_asserts (void)
4615 dump_all_asserts (stderr);
4618 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
4620 static void
4621 add_assert_info (vec<assert_info> &asserts,
4622 tree name, tree expr, enum tree_code comp_code, tree val)
4624 assert_info info;
4625 info.comp_code = comp_code;
4626 info.name = name;
4627 info.val = val;
4628 info.expr = expr;
4629 asserts.safe_push (info);
4632 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
4633 'EXPR COMP_CODE VAL' at a location that dominates block BB or
4634 E->DEST, then register this location as a possible insertion point
4635 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
4637 BB, E and SI provide the exact insertion point for the new
4638 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
4639 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
4640 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
4641 must not be NULL. */
4643 static void
4644 register_new_assert_for (tree name, tree expr,
4645 enum tree_code comp_code,
4646 tree val,
4647 basic_block bb,
4648 edge e,
4649 gimple_stmt_iterator si)
4651 assert_locus *n, *loc, *last_loc;
4652 basic_block dest_bb;
4654 gcc_checking_assert (bb == NULL || e == NULL);
4656 if (e == NULL)
4657 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
4658 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
4660 /* Never build an assert comparing against an integer constant with
4661 TREE_OVERFLOW set. This confuses our undefined overflow warning
4662 machinery. */
4663 if (TREE_OVERFLOW_P (val))
4664 val = drop_tree_overflow (val);
4666 /* The new assertion A will be inserted at BB or E. We need to
4667 determine if the new location is dominated by a previously
4668 registered location for A. If we are doing an edge insertion,
4669 assume that A will be inserted at E->DEST. Note that this is not
4670 necessarily true.
4672 If E is a critical edge, it will be split. But even if E is
4673 split, the new block will dominate the same set of blocks that
4674 E->DEST dominates.
4676 The reverse, however, is not true, blocks dominated by E->DEST
4677 will not be dominated by the new block created to split E. So,
4678 if the insertion location is on a critical edge, we will not use
4679 the new location to move another assertion previously registered
4680 at a block dominated by E->DEST. */
4681 dest_bb = (bb) ? bb : e->dest;
4683 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
4684 VAL at a block dominating DEST_BB, then we don't need to insert a new
4685 one. Similarly, if the same assertion already exists at a block
4686 dominated by DEST_BB and the new location is not on a critical
4687 edge, then update the existing location for the assertion (i.e.,
4688 move the assertion up in the dominance tree).
4690 Note, this is implemented as a simple linked list because there
4691 should not be more than a handful of assertions registered per
4692 name. If this becomes a performance problem, a table hashed by
4693 COMP_CODE and VAL could be implemented. */
4694 loc = asserts_for[SSA_NAME_VERSION (name)];
4695 last_loc = loc;
4696 while (loc)
4698 if (loc->comp_code == comp_code
4699 && (loc->val == val
4700 || operand_equal_p (loc->val, val, 0))
4701 && (loc->expr == expr
4702 || operand_equal_p (loc->expr, expr, 0)))
4704 /* If E is not a critical edge and DEST_BB
4705 dominates the existing location for the assertion, move
4706 the assertion up in the dominance tree by updating its
4707 location information. */
4708 if ((e == NULL || !EDGE_CRITICAL_P (e))
4709 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
4711 loc->bb = dest_bb;
4712 loc->e = e;
4713 loc->si = si;
4714 return;
4718 /* Update the last node of the list and move to the next one. */
4719 last_loc = loc;
4720 loc = loc->next;
4723 /* If we didn't find an assertion already registered for
4724 NAME COMP_CODE VAL, add a new one at the end of the list of
4725 assertions associated with NAME. */
4726 n = XNEW (struct assert_locus);
4727 n->bb = dest_bb;
4728 n->e = e;
4729 n->si = si;
4730 n->comp_code = comp_code;
4731 n->val = val;
4732 n->expr = expr;
4733 n->next = NULL;
4735 if (last_loc)
4736 last_loc->next = n;
4737 else
4738 asserts_for[SSA_NAME_VERSION (name)] = n;
4740 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
4743 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
4744 Extract a suitable test code and value and store them into *CODE_P and
4745 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
4747 If no extraction was possible, return FALSE, otherwise return TRUE.
4749 If INVERT is true, then we invert the result stored into *CODE_P. */
4751 static bool
4752 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
4753 tree cond_op0, tree cond_op1,
4754 bool invert, enum tree_code *code_p,
4755 tree *val_p)
4757 enum tree_code comp_code;
4758 tree val;
4760 /* Otherwise, we have a comparison of the form NAME COMP VAL
4761 or VAL COMP NAME. */
4762 if (name == cond_op1)
4764 /* If the predicate is of the form VAL COMP NAME, flip
4765 COMP around because we need to register NAME as the
4766 first operand in the predicate. */
4767 comp_code = swap_tree_comparison (cond_code);
4768 val = cond_op0;
4770 else if (name == cond_op0)
4772 /* The comparison is of the form NAME COMP VAL, so the
4773 comparison code remains unchanged. */
4774 comp_code = cond_code;
4775 val = cond_op1;
4777 else
4778 gcc_unreachable ();
4780 /* Invert the comparison code as necessary. */
4781 if (invert)
4782 comp_code = invert_tree_comparison (comp_code, 0);
4784 /* VRP only handles integral and pointer types. */
4785 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
4786 && ! POINTER_TYPE_P (TREE_TYPE (val)))
4787 return false;
4789 /* Do not register always-false predicates.
4790 FIXME: this works around a limitation in fold() when dealing with
4791 enumerations. Given 'enum { N1, N2 } x;', fold will not
4792 fold 'if (x > N2)' to 'if (0)'. */
4793 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
4794 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
4796 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
4797 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
4799 if (comp_code == GT_EXPR
4800 && (!max
4801 || compare_values (val, max) == 0))
4802 return false;
4804 if (comp_code == LT_EXPR
4805 && (!min
4806 || compare_values (val, min) == 0))
4807 return false;
4809 *code_p = comp_code;
4810 *val_p = val;
4811 return true;
4814 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
4815 (otherwise return VAL). VAL and MASK must be zero-extended for
4816 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
4817 (to transform signed values into unsigned) and at the end xor
4818 SGNBIT back. */
4820 static wide_int
4821 masked_increment (const wide_int &val_in, const wide_int &mask,
4822 const wide_int &sgnbit, unsigned int prec)
4824 wide_int bit = wi::one (prec), res;
4825 unsigned int i;
4827 wide_int val = val_in ^ sgnbit;
4828 for (i = 0; i < prec; i++, bit += bit)
4830 res = mask;
4831 if ((res & bit) == 0)
4832 continue;
4833 res = bit - 1;
4834 res = wi::bit_and_not (val + bit, res);
4835 res &= mask;
4836 if (wi::gtu_p (res, val))
4837 return res ^ sgnbit;
4839 return val ^ sgnbit;
4842 /* Helper for overflow_comparison_p
4844 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
4845 OP1's defining statement to see if it ultimately has the form
4846 OP0 CODE (OP0 PLUS INTEGER_CST)
4848 If so, return TRUE indicating this is an overflow test and store into
4849 *NEW_CST an updated constant that can be used in a narrowed range test.
4851 REVERSED indicates if the comparison was originally:
4853 OP1 CODE' OP0.
4855 This affects how we build the updated constant. */
4857 static bool
4858 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
4859 bool follow_assert_exprs, bool reversed, tree *new_cst)
4861 /* See if this is a relational operation between two SSA_NAMES with
4862 unsigned, overflow wrapping values. If so, check it more deeply. */
4863 if ((code == LT_EXPR || code == LE_EXPR
4864 || code == GE_EXPR || code == GT_EXPR)
4865 && TREE_CODE (op0) == SSA_NAME
4866 && TREE_CODE (op1) == SSA_NAME
4867 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
4868 && TYPE_UNSIGNED (TREE_TYPE (op0))
4869 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
4871 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
4873 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
4874 if (follow_assert_exprs)
4876 while (gimple_assign_single_p (op1_def)
4877 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
4879 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
4880 if (TREE_CODE (op1) != SSA_NAME)
4881 break;
4882 op1_def = SSA_NAME_DEF_STMT (op1);
4886 /* Now look at the defining statement of OP1 to see if it adds
4887 or subtracts a nonzero constant from another operand. */
4888 if (op1_def
4889 && is_gimple_assign (op1_def)
4890 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
4891 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
4892 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
4894 tree target = gimple_assign_rhs1 (op1_def);
4896 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
4897 for one where TARGET appears on the RHS. */
4898 if (follow_assert_exprs)
4900 /* Now see if that "other operand" is op0, following the chain
4901 of ASSERT_EXPRs if necessary. */
4902 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
4903 while (op0 != target
4904 && gimple_assign_single_p (op0_def)
4905 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
4907 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
4908 if (TREE_CODE (op0) != SSA_NAME)
4909 break;
4910 op0_def = SSA_NAME_DEF_STMT (op0);
4914 /* If we did not find our target SSA_NAME, then this is not
4915 an overflow test. */
4916 if (op0 != target)
4917 return false;
4919 tree type = TREE_TYPE (op0);
4920 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
4921 tree inc = gimple_assign_rhs2 (op1_def);
4922 if (reversed)
4923 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
4924 else
4925 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
4926 return true;
4929 return false;
4932 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
4933 OP1's defining statement to see if it ultimately has the form
4934 OP0 CODE (OP0 PLUS INTEGER_CST)
4936 If so, return TRUE indicating this is an overflow test and store into
4937 *NEW_CST an updated constant that can be used in a narrowed range test.
4939 These statements are left as-is in the IL to facilitate discovery of
4940 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
4941 the alternate range representation is often useful within VRP. */
4943 static bool
4944 overflow_comparison_p (tree_code code, tree name, tree val,
4945 bool use_equiv_p, tree *new_cst)
4947 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
4948 return true;
4949 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
4950 use_equiv_p, true, new_cst);
4954 /* Try to register an edge assertion for SSA name NAME on edge E for
4955 the condition COND contributing to the conditional jump pointed to by BSI.
4956 Invert the condition COND if INVERT is true. */
4958 static void
4959 register_edge_assert_for_2 (tree name, edge e,
4960 enum tree_code cond_code,
4961 tree cond_op0, tree cond_op1, bool invert,
4962 vec<assert_info> &asserts)
4964 tree val;
4965 enum tree_code comp_code;
4967 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
4968 cond_op0,
4969 cond_op1,
4970 invert, &comp_code, &val))
4971 return;
4973 /* Queue the assert. */
4974 tree x;
4975 if (overflow_comparison_p (comp_code, name, val, false, &x))
4977 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
4978 ? GT_EXPR : LE_EXPR);
4979 add_assert_info (asserts, name, name, new_code, x);
4981 add_assert_info (asserts, name, name, comp_code, val);
4983 /* In the case of NAME <= CST and NAME being defined as
4984 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
4985 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
4986 This catches range and anti-range tests. */
4987 if ((comp_code == LE_EXPR
4988 || comp_code == GT_EXPR)
4989 && TREE_CODE (val) == INTEGER_CST
4990 && TYPE_UNSIGNED (TREE_TYPE (val)))
4992 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
4993 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
4995 /* Extract CST2 from the (optional) addition. */
4996 if (is_gimple_assign (def_stmt)
4997 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
4999 name2 = gimple_assign_rhs1 (def_stmt);
5000 cst2 = gimple_assign_rhs2 (def_stmt);
5001 if (TREE_CODE (name2) == SSA_NAME
5002 && TREE_CODE (cst2) == INTEGER_CST)
5003 def_stmt = SSA_NAME_DEF_STMT (name2);
5006 /* Extract NAME2 from the (optional) sign-changing cast. */
5007 if (gimple_assign_cast_p (def_stmt))
5009 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
5010 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5011 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
5012 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
5013 name3 = gimple_assign_rhs1 (def_stmt);
5016 /* If name3 is used later, create an ASSERT_EXPR for it. */
5017 if (name3 != NULL_TREE
5018 && TREE_CODE (name3) == SSA_NAME
5019 && (cst2 == NULL_TREE
5020 || TREE_CODE (cst2) == INTEGER_CST)
5021 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
5023 tree tmp;
5025 /* Build an expression for the range test. */
5026 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
5027 if (cst2 != NULL_TREE)
5028 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5030 if (dump_file)
5032 fprintf (dump_file, "Adding assert for ");
5033 print_generic_expr (dump_file, name3);
5034 fprintf (dump_file, " from ");
5035 print_generic_expr (dump_file, tmp);
5036 fprintf (dump_file, "\n");
5039 add_assert_info (asserts, name3, tmp, comp_code, val);
5042 /* If name2 is used later, create an ASSERT_EXPR for it. */
5043 if (name2 != NULL_TREE
5044 && TREE_CODE (name2) == SSA_NAME
5045 && TREE_CODE (cst2) == INTEGER_CST
5046 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
5048 tree tmp;
5050 /* Build an expression for the range test. */
5051 tmp = name2;
5052 if (TREE_TYPE (name) != TREE_TYPE (name2))
5053 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
5054 if (cst2 != NULL_TREE)
5055 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5057 if (dump_file)
5059 fprintf (dump_file, "Adding assert for ");
5060 print_generic_expr (dump_file, name2);
5061 fprintf (dump_file, " from ");
5062 print_generic_expr (dump_file, tmp);
5063 fprintf (dump_file, "\n");
5066 add_assert_info (asserts, name2, tmp, comp_code, val);
5070 /* In the case of post-in/decrement tests like if (i++) ... and uses
5071 of the in/decremented value on the edge the extra name we want to
5072 assert for is not on the def chain of the name compared. Instead
5073 it is in the set of use stmts.
5074 Similar cases happen for conversions that were simplified through
5075 fold_{sign_changed,widened}_comparison. */
5076 if ((comp_code == NE_EXPR
5077 || comp_code == EQ_EXPR)
5078 && TREE_CODE (val) == INTEGER_CST)
5080 imm_use_iterator ui;
5081 gimple *use_stmt;
5082 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
5084 if (!is_gimple_assign (use_stmt))
5085 continue;
5087 /* Cut off to use-stmts that are dominating the predecessor. */
5088 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
5089 continue;
5091 tree name2 = gimple_assign_lhs (use_stmt);
5092 if (TREE_CODE (name2) != SSA_NAME)
5093 continue;
5095 enum tree_code code = gimple_assign_rhs_code (use_stmt);
5096 tree cst;
5097 if (code == PLUS_EXPR
5098 || code == MINUS_EXPR)
5100 cst = gimple_assign_rhs2 (use_stmt);
5101 if (TREE_CODE (cst) != INTEGER_CST)
5102 continue;
5103 cst = int_const_binop (code, val, cst);
5105 else if (CONVERT_EXPR_CODE_P (code))
5107 /* For truncating conversions we cannot record
5108 an inequality. */
5109 if (comp_code == NE_EXPR
5110 && (TYPE_PRECISION (TREE_TYPE (name2))
5111 < TYPE_PRECISION (TREE_TYPE (name))))
5112 continue;
5113 cst = fold_convert (TREE_TYPE (name2), val);
5115 else
5116 continue;
5118 if (TREE_OVERFLOW_P (cst))
5119 cst = drop_tree_overflow (cst);
5120 add_assert_info (asserts, name2, name2, comp_code, cst);
5124 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
5125 && TREE_CODE (val) == INTEGER_CST)
5127 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5128 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
5129 tree val2 = NULL_TREE;
5130 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
5131 wide_int mask = wi::zero (prec);
5132 unsigned int nprec = prec;
5133 enum tree_code rhs_code = ERROR_MARK;
5135 if (is_gimple_assign (def_stmt))
5136 rhs_code = gimple_assign_rhs_code (def_stmt);
5138 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
5139 assert that A != CST1 -+ CST2. */
5140 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5141 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
5143 tree op0 = gimple_assign_rhs1 (def_stmt);
5144 tree op1 = gimple_assign_rhs2 (def_stmt);
5145 if (TREE_CODE (op0) == SSA_NAME
5146 && TREE_CODE (op1) == INTEGER_CST)
5148 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
5149 ? MINUS_EXPR : PLUS_EXPR);
5150 op1 = int_const_binop (reverse_op, val, op1);
5151 if (TREE_OVERFLOW (op1))
5152 op1 = drop_tree_overflow (op1);
5153 add_assert_info (asserts, op0, op0, comp_code, op1);
5157 /* Add asserts for NAME cmp CST and NAME being defined
5158 as NAME = (int) NAME2. */
5159 if (!TYPE_UNSIGNED (TREE_TYPE (val))
5160 && (comp_code == LE_EXPR || comp_code == LT_EXPR
5161 || comp_code == GT_EXPR || comp_code == GE_EXPR)
5162 && gimple_assign_cast_p (def_stmt))
5164 name2 = gimple_assign_rhs1 (def_stmt);
5165 if (CONVERT_EXPR_CODE_P (rhs_code)
5166 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5167 && TYPE_UNSIGNED (TREE_TYPE (name2))
5168 && prec == TYPE_PRECISION (TREE_TYPE (name2))
5169 && (comp_code == LE_EXPR || comp_code == GT_EXPR
5170 || !tree_int_cst_equal (val,
5171 TYPE_MIN_VALUE (TREE_TYPE (val)))))
5173 tree tmp, cst;
5174 enum tree_code new_comp_code = comp_code;
5176 cst = fold_convert (TREE_TYPE (name2),
5177 TYPE_MIN_VALUE (TREE_TYPE (val)));
5178 /* Build an expression for the range test. */
5179 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
5180 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
5181 fold_convert (TREE_TYPE (name2), val));
5182 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5184 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
5185 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
5186 build_int_cst (TREE_TYPE (name2), 1));
5189 if (dump_file)
5191 fprintf (dump_file, "Adding assert for ");
5192 print_generic_expr (dump_file, name2);
5193 fprintf (dump_file, " from ");
5194 print_generic_expr (dump_file, tmp);
5195 fprintf (dump_file, "\n");
5198 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
5202 /* Add asserts for NAME cmp CST and NAME being defined as
5203 NAME = NAME2 >> CST2.
5205 Extract CST2 from the right shift. */
5206 if (rhs_code == RSHIFT_EXPR)
5208 name2 = gimple_assign_rhs1 (def_stmt);
5209 cst2 = gimple_assign_rhs2 (def_stmt);
5210 if (TREE_CODE (name2) == SSA_NAME
5211 && tree_fits_uhwi_p (cst2)
5212 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5213 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
5214 && type_has_mode_precision_p (TREE_TYPE (val)))
5216 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
5217 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
5220 if (val2 != NULL_TREE
5221 && TREE_CODE (val2) == INTEGER_CST
5222 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
5223 TREE_TYPE (val),
5224 val2, cst2), val))
5226 enum tree_code new_comp_code = comp_code;
5227 tree tmp, new_val;
5229 tmp = name2;
5230 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
5232 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
5234 tree type = build_nonstandard_integer_type (prec, 1);
5235 tmp = build1 (NOP_EXPR, type, name2);
5236 val2 = fold_convert (type, val2);
5238 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
5239 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
5240 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
5242 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5244 wide_int minval
5245 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5246 new_val = val2;
5247 if (minval == wi::to_wide (new_val))
5248 new_val = NULL_TREE;
5250 else
5252 wide_int maxval
5253 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5254 mask |= wi::to_wide (val2);
5255 if (wi::eq_p (mask, maxval))
5256 new_val = NULL_TREE;
5257 else
5258 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
5261 if (new_val)
5263 if (dump_file)
5265 fprintf (dump_file, "Adding assert for ");
5266 print_generic_expr (dump_file, name2);
5267 fprintf (dump_file, " from ");
5268 print_generic_expr (dump_file, tmp);
5269 fprintf (dump_file, "\n");
5272 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
5276 /* Add asserts for NAME cmp CST and NAME being defined as
5277 NAME = NAME2 & CST2.
5279 Extract CST2 from the and.
5281 Also handle
5282 NAME = (unsigned) NAME2;
5283 casts where NAME's type is unsigned and has smaller precision
5284 than NAME2's type as if it was NAME = NAME2 & MASK. */
5285 names[0] = NULL_TREE;
5286 names[1] = NULL_TREE;
5287 cst2 = NULL_TREE;
5288 if (rhs_code == BIT_AND_EXPR
5289 || (CONVERT_EXPR_CODE_P (rhs_code)
5290 && INTEGRAL_TYPE_P (TREE_TYPE (val))
5291 && TYPE_UNSIGNED (TREE_TYPE (val))
5292 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5293 > prec))
5295 name2 = gimple_assign_rhs1 (def_stmt);
5296 if (rhs_code == BIT_AND_EXPR)
5297 cst2 = gimple_assign_rhs2 (def_stmt);
5298 else
5300 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
5301 nprec = TYPE_PRECISION (TREE_TYPE (name2));
5303 if (TREE_CODE (name2) == SSA_NAME
5304 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5305 && TREE_CODE (cst2) == INTEGER_CST
5306 && !integer_zerop (cst2)
5307 && (nprec > 1
5308 || TYPE_UNSIGNED (TREE_TYPE (val))))
5310 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
5311 if (gimple_assign_cast_p (def_stmt2))
5313 names[1] = gimple_assign_rhs1 (def_stmt2);
5314 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
5315 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
5316 || (TYPE_PRECISION (TREE_TYPE (name2))
5317 != TYPE_PRECISION (TREE_TYPE (names[1]))))
5318 names[1] = NULL_TREE;
5320 names[0] = name2;
5323 if (names[0] || names[1])
5325 wide_int minv, maxv, valv, cst2v;
5326 wide_int tem, sgnbit;
5327 bool valid_p = false, valn, cst2n;
5328 enum tree_code ccode = comp_code;
5330 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
5331 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
5332 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
5333 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
5334 /* If CST2 doesn't have most significant bit set,
5335 but VAL is negative, we have comparison like
5336 if ((x & 0x123) > -4) (always true). Just give up. */
5337 if (!cst2n && valn)
5338 ccode = ERROR_MARK;
5339 if (cst2n)
5340 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5341 else
5342 sgnbit = wi::zero (nprec);
5343 minv = valv & cst2v;
5344 switch (ccode)
5346 case EQ_EXPR:
5347 /* Minimum unsigned value for equality is VAL & CST2
5348 (should be equal to VAL, otherwise we probably should
5349 have folded the comparison into false) and
5350 maximum unsigned value is VAL | ~CST2. */
5351 maxv = valv | ~cst2v;
5352 valid_p = true;
5353 break;
5355 case NE_EXPR:
5356 tem = valv | ~cst2v;
5357 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
5358 if (valv == 0)
5360 cst2n = false;
5361 sgnbit = wi::zero (nprec);
5362 goto gt_expr;
5364 /* If (VAL | ~CST2) is all ones, handle it as
5365 (X & CST2) < VAL. */
5366 if (tem == -1)
5368 cst2n = false;
5369 valn = false;
5370 sgnbit = wi::zero (nprec);
5371 goto lt_expr;
5373 if (!cst2n && wi::neg_p (cst2v))
5374 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5375 if (sgnbit != 0)
5377 if (valv == sgnbit)
5379 cst2n = true;
5380 valn = true;
5381 goto gt_expr;
5383 if (tem == wi::mask (nprec - 1, false, nprec))
5385 cst2n = true;
5386 goto lt_expr;
5388 if (!cst2n)
5389 sgnbit = wi::zero (nprec);
5391 break;
5393 case GE_EXPR:
5394 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
5395 is VAL and maximum unsigned value is ~0. For signed
5396 comparison, if CST2 doesn't have most significant bit
5397 set, handle it similarly. If CST2 has MSB set,
5398 the minimum is the same, and maximum is ~0U/2. */
5399 if (minv != valv)
5401 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
5402 VAL. */
5403 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5404 if (minv == valv)
5405 break;
5407 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5408 valid_p = true;
5409 break;
5411 case GT_EXPR:
5412 gt_expr:
5413 /* Find out smallest MINV where MINV > VAL
5414 && (MINV & CST2) == MINV, if any. If VAL is signed and
5415 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
5416 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5417 if (minv == valv)
5418 break;
5419 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5420 valid_p = true;
5421 break;
5423 case LE_EXPR:
5424 /* Minimum unsigned value for <= is 0 and maximum
5425 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
5426 Otherwise, find smallest VAL2 where VAL2 > VAL
5427 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5428 as maximum.
5429 For signed comparison, if CST2 doesn't have most
5430 significant bit set, handle it similarly. If CST2 has
5431 MSB set, the maximum is the same and minimum is INT_MIN. */
5432 if (minv == valv)
5433 maxv = valv;
5434 else
5436 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5437 if (maxv == valv)
5438 break;
5439 maxv -= 1;
5441 maxv |= ~cst2v;
5442 minv = sgnbit;
5443 valid_p = true;
5444 break;
5446 case LT_EXPR:
5447 lt_expr:
5448 /* Minimum unsigned value for < is 0 and maximum
5449 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
5450 Otherwise, find smallest VAL2 where VAL2 > VAL
5451 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5452 as maximum.
5453 For signed comparison, if CST2 doesn't have most
5454 significant bit set, handle it similarly. If CST2 has
5455 MSB set, the maximum is the same and minimum is INT_MIN. */
5456 if (minv == valv)
5458 if (valv == sgnbit)
5459 break;
5460 maxv = valv;
5462 else
5464 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5465 if (maxv == valv)
5466 break;
5468 maxv -= 1;
5469 maxv |= ~cst2v;
5470 minv = sgnbit;
5471 valid_p = true;
5472 break;
5474 default:
5475 break;
5477 if (valid_p
5478 && (maxv - minv) != -1)
5480 tree tmp, new_val, type;
5481 int i;
5483 for (i = 0; i < 2; i++)
5484 if (names[i])
5486 wide_int maxv2 = maxv;
5487 tmp = names[i];
5488 type = TREE_TYPE (names[i]);
5489 if (!TYPE_UNSIGNED (type))
5491 type = build_nonstandard_integer_type (nprec, 1);
5492 tmp = build1 (NOP_EXPR, type, names[i]);
5494 if (minv != 0)
5496 tmp = build2 (PLUS_EXPR, type, tmp,
5497 wide_int_to_tree (type, -minv));
5498 maxv2 = maxv - minv;
5500 new_val = wide_int_to_tree (type, maxv2);
5502 if (dump_file)
5504 fprintf (dump_file, "Adding assert for ");
5505 print_generic_expr (dump_file, names[i]);
5506 fprintf (dump_file, " from ");
5507 print_generic_expr (dump_file, tmp);
5508 fprintf (dump_file, "\n");
5511 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
5518 /* OP is an operand of a truth value expression which is known to have
5519 a particular value. Register any asserts for OP and for any
5520 operands in OP's defining statement.
5522 If CODE is EQ_EXPR, then we want to register OP is zero (false),
5523 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
5525 static void
5526 register_edge_assert_for_1 (tree op, enum tree_code code,
5527 edge e, vec<assert_info> &asserts)
5529 gimple *op_def;
5530 tree val;
5531 enum tree_code rhs_code;
5533 /* We only care about SSA_NAMEs. */
5534 if (TREE_CODE (op) != SSA_NAME)
5535 return;
5537 /* We know that OP will have a zero or nonzero value. */
5538 val = build_int_cst (TREE_TYPE (op), 0);
5539 add_assert_info (asserts, op, op, code, val);
5541 /* Now look at how OP is set. If it's set from a comparison,
5542 a truth operation or some bit operations, then we may be able
5543 to register information about the operands of that assignment. */
5544 op_def = SSA_NAME_DEF_STMT (op);
5545 if (gimple_code (op_def) != GIMPLE_ASSIGN)
5546 return;
5548 rhs_code = gimple_assign_rhs_code (op_def);
5550 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
5552 bool invert = (code == EQ_EXPR ? true : false);
5553 tree op0 = gimple_assign_rhs1 (op_def);
5554 tree op1 = gimple_assign_rhs2 (op_def);
5556 if (TREE_CODE (op0) == SSA_NAME)
5557 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
5558 if (TREE_CODE (op1) == SSA_NAME)
5559 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
5561 else if ((code == NE_EXPR
5562 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
5563 || (code == EQ_EXPR
5564 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
5566 /* Recurse on each operand. */
5567 tree op0 = gimple_assign_rhs1 (op_def);
5568 tree op1 = gimple_assign_rhs2 (op_def);
5569 if (TREE_CODE (op0) == SSA_NAME
5570 && has_single_use (op0))
5571 register_edge_assert_for_1 (op0, code, e, asserts);
5572 if (TREE_CODE (op1) == SSA_NAME
5573 && has_single_use (op1))
5574 register_edge_assert_for_1 (op1, code, e, asserts);
5576 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
5577 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
5579 /* Recurse, flipping CODE. */
5580 code = invert_tree_comparison (code, false);
5581 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
5583 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
5585 /* Recurse through the copy. */
5586 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
5588 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
5590 /* Recurse through the type conversion, unless it is a narrowing
5591 conversion or conversion from non-integral type. */
5592 tree rhs = gimple_assign_rhs1 (op_def);
5593 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
5594 && (TYPE_PRECISION (TREE_TYPE (rhs))
5595 <= TYPE_PRECISION (TREE_TYPE (op))))
5596 register_edge_assert_for_1 (rhs, code, e, asserts);
5600 /* Check if comparison
5601 NAME COND_OP INTEGER_CST
5602 has a form of
5603 (X & 11...100..0) COND_OP XX...X00...0
5604 Such comparison can yield assertions like
5605 X >= XX...X00...0
5606 X <= XX...X11...1
5607 in case of COND_OP being NE_EXPR or
5608 X < XX...X00...0
5609 X > XX...X11...1
5610 in case of EQ_EXPR. */
5612 static bool
5613 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
5614 tree *new_name, tree *low, enum tree_code *low_code,
5615 tree *high, enum tree_code *high_code)
5617 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5619 if (!is_gimple_assign (def_stmt)
5620 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
5621 return false;
5623 tree t = gimple_assign_rhs1 (def_stmt);
5624 tree maskt = gimple_assign_rhs2 (def_stmt);
5625 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
5626 return false;
5628 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
5629 wide_int inv_mask = ~mask;
5630 /* Assume VALT is INTEGER_CST. */
5631 wi::tree_to_wide_ref val = wi::to_wide (valt);
5633 if ((inv_mask & (inv_mask + 1)) != 0
5634 || (val & mask) != val)
5635 return false;
5637 bool is_range = cond_code == EQ_EXPR;
5639 tree type = TREE_TYPE (t);
5640 wide_int min = wi::min_value (type),
5641 max = wi::max_value (type);
5643 if (is_range)
5645 *low_code = val == min ? ERROR_MARK : GE_EXPR;
5646 *high_code = val == max ? ERROR_MARK : LE_EXPR;
5648 else
5650 /* We can still generate assertion if one of alternatives
5651 is known to always be false. */
5652 if (val == min)
5654 *low_code = (enum tree_code) 0;
5655 *high_code = GT_EXPR;
5657 else if ((val | inv_mask) == max)
5659 *low_code = LT_EXPR;
5660 *high_code = (enum tree_code) 0;
5662 else
5663 return false;
5666 *new_name = t;
5667 *low = wide_int_to_tree (type, val);
5668 *high = wide_int_to_tree (type, val | inv_mask);
5670 if (wi::neg_p (val, TYPE_SIGN (type)))
5671 std::swap (*low, *high);
5673 return true;
5676 /* Try to register an edge assertion for SSA name NAME on edge E for
5677 the condition COND contributing to the conditional jump pointed to by
5678 SI. */
5680 void
5681 register_edge_assert_for (tree name, edge e,
5682 enum tree_code cond_code, tree cond_op0,
5683 tree cond_op1, vec<assert_info> &asserts)
5685 tree val;
5686 enum tree_code comp_code;
5687 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
5689 /* Do not attempt to infer anything in names that flow through
5690 abnormal edges. */
5691 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
5692 return;
5694 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5695 cond_op0, cond_op1,
5696 is_else_edge,
5697 &comp_code, &val))
5698 return;
5700 /* Register ASSERT_EXPRs for name. */
5701 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
5702 cond_op1, is_else_edge, asserts);
5705 /* If COND is effectively an equality test of an SSA_NAME against
5706 the value zero or one, then we may be able to assert values
5707 for SSA_NAMEs which flow into COND. */
5709 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
5710 statement of NAME we can assert both operands of the BIT_AND_EXPR
5711 have nonzero value. */
5712 if (((comp_code == EQ_EXPR && integer_onep (val))
5713 || (comp_code == NE_EXPR && integer_zerop (val))))
5715 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5717 if (is_gimple_assign (def_stmt)
5718 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
5720 tree op0 = gimple_assign_rhs1 (def_stmt);
5721 tree op1 = gimple_assign_rhs2 (def_stmt);
5722 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
5723 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
5727 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
5728 statement of NAME we can assert both operands of the BIT_IOR_EXPR
5729 have zero value. */
5730 if (((comp_code == EQ_EXPR && integer_zerop (val))
5731 || (comp_code == NE_EXPR && integer_onep (val))))
5733 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5735 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
5736 necessarily zero value, or if type-precision is one. */
5737 if (is_gimple_assign (def_stmt)
5738 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
5739 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
5740 || comp_code == EQ_EXPR)))
5742 tree op0 = gimple_assign_rhs1 (def_stmt);
5743 tree op1 = gimple_assign_rhs2 (def_stmt);
5744 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
5745 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
5749 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
5750 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5751 && TREE_CODE (val) == INTEGER_CST)
5753 enum tree_code low_code, high_code;
5754 tree low, high;
5755 if (is_masked_range_test (name, val, comp_code, &name, &low,
5756 &low_code, &high, &high_code))
5758 if (low_code != ERROR_MARK)
5759 register_edge_assert_for_2 (name, e, low_code, name,
5760 low, /*invert*/false, asserts);
5761 if (high_code != ERROR_MARK)
5762 register_edge_assert_for_2 (name, e, high_code, name,
5763 high, /*invert*/false, asserts);
5768 /* Finish found ASSERTS for E and register them at GSI. */
5770 static void
5771 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
5772 vec<assert_info> &asserts)
5774 for (unsigned i = 0; i < asserts.length (); ++i)
5775 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
5776 reachable from E. */
5777 if (live_on_edge (e, asserts[i].name))
5778 register_new_assert_for (asserts[i].name, asserts[i].expr,
5779 asserts[i].comp_code, asserts[i].val,
5780 NULL, e, gsi);
5785 /* Determine whether the outgoing edges of BB should receive an
5786 ASSERT_EXPR for each of the operands of BB's LAST statement.
5787 The last statement of BB must be a COND_EXPR.
5789 If any of the sub-graphs rooted at BB have an interesting use of
5790 the predicate operands, an assert location node is added to the
5791 list of assertions for the corresponding operands. */
5793 static void
5794 find_conditional_asserts (basic_block bb, gcond *last)
5796 gimple_stmt_iterator bsi;
5797 tree op;
5798 edge_iterator ei;
5799 edge e;
5800 ssa_op_iter iter;
5802 bsi = gsi_for_stmt (last);
5804 /* Look for uses of the operands in each of the sub-graphs
5805 rooted at BB. We need to check each of the outgoing edges
5806 separately, so that we know what kind of ASSERT_EXPR to
5807 insert. */
5808 FOR_EACH_EDGE (e, ei, bb->succs)
5810 if (e->dest == bb)
5811 continue;
5813 /* Register the necessary assertions for each operand in the
5814 conditional predicate. */
5815 auto_vec<assert_info, 8> asserts;
5816 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
5817 register_edge_assert_for (op, e,
5818 gimple_cond_code (last),
5819 gimple_cond_lhs (last),
5820 gimple_cond_rhs (last), asserts);
5821 finish_register_edge_assert_for (e, bsi, asserts);
5825 struct case_info
5827 tree expr;
5828 basic_block bb;
5831 /* Compare two case labels sorting first by the destination bb index
5832 and then by the case value. */
5834 static int
5835 compare_case_labels (const void *p1, const void *p2)
5837 const struct case_info *ci1 = (const struct case_info *) p1;
5838 const struct case_info *ci2 = (const struct case_info *) p2;
5839 int idx1 = ci1->bb->index;
5840 int idx2 = ci2->bb->index;
5842 if (idx1 < idx2)
5843 return -1;
5844 else if (idx1 == idx2)
5846 /* Make sure the default label is first in a group. */
5847 if (!CASE_LOW (ci1->expr))
5848 return -1;
5849 else if (!CASE_LOW (ci2->expr))
5850 return 1;
5851 else
5852 return tree_int_cst_compare (CASE_LOW (ci1->expr),
5853 CASE_LOW (ci2->expr));
5855 else
5856 return 1;
5859 /* Determine whether the outgoing edges of BB should receive an
5860 ASSERT_EXPR for each of the operands of BB's LAST statement.
5861 The last statement of BB must be a SWITCH_EXPR.
5863 If any of the sub-graphs rooted at BB have an interesting use of
5864 the predicate operands, an assert location node is added to the
5865 list of assertions for the corresponding operands. */
5867 static void
5868 find_switch_asserts (basic_block bb, gswitch *last)
5870 gimple_stmt_iterator bsi;
5871 tree op;
5872 edge e;
5873 struct case_info *ci;
5874 size_t n = gimple_switch_num_labels (last);
5875 #if GCC_VERSION >= 4000
5876 unsigned int idx;
5877 #else
5878 /* Work around GCC 3.4 bug (PR 37086). */
5879 volatile unsigned int idx;
5880 #endif
5882 bsi = gsi_for_stmt (last);
5883 op = gimple_switch_index (last);
5884 if (TREE_CODE (op) != SSA_NAME)
5885 return;
5887 /* Build a vector of case labels sorted by destination label. */
5888 ci = XNEWVEC (struct case_info, n);
5889 for (idx = 0; idx < n; ++idx)
5891 ci[idx].expr = gimple_switch_label (last, idx);
5892 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
5894 edge default_edge = find_edge (bb, ci[0].bb);
5895 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
5897 for (idx = 0; idx < n; ++idx)
5899 tree min, max;
5900 tree cl = ci[idx].expr;
5901 basic_block cbb = ci[idx].bb;
5903 min = CASE_LOW (cl);
5904 max = CASE_HIGH (cl);
5906 /* If there are multiple case labels with the same destination
5907 we need to combine them to a single value range for the edge. */
5908 if (idx + 1 < n && cbb == ci[idx + 1].bb)
5910 /* Skip labels until the last of the group. */
5911 do {
5912 ++idx;
5913 } while (idx < n && cbb == ci[idx].bb);
5914 --idx;
5916 /* Pick up the maximum of the case label range. */
5917 if (CASE_HIGH (ci[idx].expr))
5918 max = CASE_HIGH (ci[idx].expr);
5919 else
5920 max = CASE_LOW (ci[idx].expr);
5923 /* Can't extract a useful assertion out of a range that includes the
5924 default label. */
5925 if (min == NULL_TREE)
5926 continue;
5928 /* Find the edge to register the assert expr on. */
5929 e = find_edge (bb, cbb);
5931 /* Register the necessary assertions for the operand in the
5932 SWITCH_EXPR. */
5933 auto_vec<assert_info, 8> asserts;
5934 register_edge_assert_for (op, e,
5935 max ? GE_EXPR : EQ_EXPR,
5936 op, fold_convert (TREE_TYPE (op), min),
5937 asserts);
5938 if (max)
5939 register_edge_assert_for (op, e, LE_EXPR, op,
5940 fold_convert (TREE_TYPE (op), max),
5941 asserts);
5942 finish_register_edge_assert_for (e, bsi, asserts);
5945 XDELETEVEC (ci);
5947 if (!live_on_edge (default_edge, op))
5948 return;
5950 /* Now register along the default label assertions that correspond to the
5951 anti-range of each label. */
5952 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
5953 if (insertion_limit == 0)
5954 return;
5956 /* We can't do this if the default case shares a label with another case. */
5957 tree default_cl = gimple_switch_default_label (last);
5958 for (idx = 1; idx < n; idx++)
5960 tree min, max;
5961 tree cl = gimple_switch_label (last, idx);
5962 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
5963 continue;
5965 min = CASE_LOW (cl);
5966 max = CASE_HIGH (cl);
5968 /* Combine contiguous case ranges to reduce the number of assertions
5969 to insert. */
5970 for (idx = idx + 1; idx < n; idx++)
5972 tree next_min, next_max;
5973 tree next_cl = gimple_switch_label (last, idx);
5974 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
5975 break;
5977 next_min = CASE_LOW (next_cl);
5978 next_max = CASE_HIGH (next_cl);
5980 wide_int difference = (wi::to_wide (next_min)
5981 - wi::to_wide (max ? max : min));
5982 if (wi::eq_p (difference, 1))
5983 max = next_max ? next_max : next_min;
5984 else
5985 break;
5987 idx--;
5989 if (max == NULL_TREE)
5991 /* Register the assertion OP != MIN. */
5992 auto_vec<assert_info, 8> asserts;
5993 min = fold_convert (TREE_TYPE (op), min);
5994 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
5995 asserts);
5996 finish_register_edge_assert_for (default_edge, bsi, asserts);
5998 else
6000 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
6001 which will give OP the anti-range ~[MIN,MAX]. */
6002 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
6003 min = fold_convert (TREE_TYPE (uop), min);
6004 max = fold_convert (TREE_TYPE (uop), max);
6006 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
6007 tree rhs = int_const_binop (MINUS_EXPR, max, min);
6008 register_new_assert_for (op, lhs, GT_EXPR, rhs,
6009 NULL, default_edge, bsi);
6012 if (--insertion_limit == 0)
6013 break;
6018 /* Traverse all the statements in block BB looking for statements that
6019 may generate useful assertions for the SSA names in their operand.
6020 If a statement produces a useful assertion A for name N_i, then the
6021 list of assertions already generated for N_i is scanned to
6022 determine if A is actually needed.
6024 If N_i already had the assertion A at a location dominating the
6025 current location, then nothing needs to be done. Otherwise, the
6026 new location for A is recorded instead.
6028 1- For every statement S in BB, all the variables used by S are
6029 added to bitmap FOUND_IN_SUBGRAPH.
6031 2- If statement S uses an operand N in a way that exposes a known
6032 value range for N, then if N was not already generated by an
6033 ASSERT_EXPR, create a new assert location for N. For instance,
6034 if N is a pointer and the statement dereferences it, we can
6035 assume that N is not NULL.
6037 3- COND_EXPRs are a special case of #2. We can derive range
6038 information from the predicate but need to insert different
6039 ASSERT_EXPRs for each of the sub-graphs rooted at the
6040 conditional block. If the last statement of BB is a conditional
6041 expression of the form 'X op Y', then
6043 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
6045 b) If the conditional is the only entry point to the sub-graph
6046 corresponding to the THEN_CLAUSE, recurse into it. On
6047 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
6048 an ASSERT_EXPR is added for the corresponding variable.
6050 c) Repeat step (b) on the ELSE_CLAUSE.
6052 d) Mark X and Y in FOUND_IN_SUBGRAPH.
6054 For instance,
6056 if (a == 9)
6057 b = a;
6058 else
6059 b = c + 1;
6061 In this case, an assertion on the THEN clause is useful to
6062 determine that 'a' is always 9 on that edge. However, an assertion
6063 on the ELSE clause would be unnecessary.
6065 4- If BB does not end in a conditional expression, then we recurse
6066 into BB's dominator children.
6068 At the end of the recursive traversal, every SSA name will have a
6069 list of locations where ASSERT_EXPRs should be added. When a new
6070 location for name N is found, it is registered by calling
6071 register_new_assert_for. That function keeps track of all the
6072 registered assertions to prevent adding unnecessary assertions.
6073 For instance, if a pointer P_4 is dereferenced more than once in a
6074 dominator tree, only the location dominating all the dereference of
6075 P_4 will receive an ASSERT_EXPR. */
6077 static void
6078 find_assert_locations_1 (basic_block bb, sbitmap live)
6080 gimple *last;
6082 last = last_stmt (bb);
6084 /* If BB's last statement is a conditional statement involving integer
6085 operands, determine if we need to add ASSERT_EXPRs. */
6086 if (last
6087 && gimple_code (last) == GIMPLE_COND
6088 && !fp_predicate (last)
6089 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6090 find_conditional_asserts (bb, as_a <gcond *> (last));
6092 /* If BB's last statement is a switch statement involving integer
6093 operands, determine if we need to add ASSERT_EXPRs. */
6094 if (last
6095 && gimple_code (last) == GIMPLE_SWITCH
6096 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6097 find_switch_asserts (bb, as_a <gswitch *> (last));
6099 /* Traverse all the statements in BB marking used names and looking
6100 for statements that may infer assertions for their used operands. */
6101 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
6102 gsi_prev (&si))
6104 gimple *stmt;
6105 tree op;
6106 ssa_op_iter i;
6108 stmt = gsi_stmt (si);
6110 if (is_gimple_debug (stmt))
6111 continue;
6113 /* See if we can derive an assertion for any of STMT's operands. */
6114 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6116 tree value;
6117 enum tree_code comp_code;
6119 /* If op is not live beyond this stmt, do not bother to insert
6120 asserts for it. */
6121 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
6122 continue;
6124 /* If OP is used in such a way that we can infer a value
6125 range for it, and we don't find a previous assertion for
6126 it, create a new assertion location node for OP. */
6127 if (infer_value_range (stmt, op, &comp_code, &value))
6129 /* If we are able to infer a nonzero value range for OP,
6130 then walk backwards through the use-def chain to see if OP
6131 was set via a typecast.
6133 If so, then we can also infer a nonzero value range
6134 for the operand of the NOP_EXPR. */
6135 if (comp_code == NE_EXPR && integer_zerop (value))
6137 tree t = op;
6138 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
6140 while (is_gimple_assign (def_stmt)
6141 && CONVERT_EXPR_CODE_P
6142 (gimple_assign_rhs_code (def_stmt))
6143 && TREE_CODE
6144 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
6145 && POINTER_TYPE_P
6146 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
6148 t = gimple_assign_rhs1 (def_stmt);
6149 def_stmt = SSA_NAME_DEF_STMT (t);
6151 /* Note we want to register the assert for the
6152 operand of the NOP_EXPR after SI, not after the
6153 conversion. */
6154 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
6155 register_new_assert_for (t, t, comp_code, value,
6156 bb, NULL, si);
6160 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
6164 /* Update live. */
6165 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6166 bitmap_set_bit (live, SSA_NAME_VERSION (op));
6167 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
6168 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
6171 /* Traverse all PHI nodes in BB, updating live. */
6172 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6173 gsi_next (&si))
6175 use_operand_p arg_p;
6176 ssa_op_iter i;
6177 gphi *phi = si.phi ();
6178 tree res = gimple_phi_result (phi);
6180 if (virtual_operand_p (res))
6181 continue;
6183 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
6185 tree arg = USE_FROM_PTR (arg_p);
6186 if (TREE_CODE (arg) == SSA_NAME)
6187 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
6190 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
6194 /* Do an RPO walk over the function computing SSA name liveness
6195 on-the-fly and deciding on assert expressions to insert. */
6197 static void
6198 find_assert_locations (void)
6200 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6201 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6202 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
6203 int rpo_cnt, i;
6205 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
6206 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
6207 for (i = 0; i < rpo_cnt; ++i)
6208 bb_rpo[rpo[i]] = i;
6210 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
6211 the order we compute liveness and insert asserts we otherwise
6212 fail to insert asserts into the loop latch. */
6213 loop_p loop;
6214 FOR_EACH_LOOP (loop, 0)
6216 i = loop->latch->index;
6217 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
6218 for (gphi_iterator gsi = gsi_start_phis (loop->header);
6219 !gsi_end_p (gsi); gsi_next (&gsi))
6221 gphi *phi = gsi.phi ();
6222 if (virtual_operand_p (gimple_phi_result (phi)))
6223 continue;
6224 tree arg = gimple_phi_arg_def (phi, j);
6225 if (TREE_CODE (arg) == SSA_NAME)
6227 if (live[i] == NULL)
6229 live[i] = sbitmap_alloc (num_ssa_names);
6230 bitmap_clear (live[i]);
6232 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
6237 for (i = rpo_cnt - 1; i >= 0; --i)
6239 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
6240 edge e;
6241 edge_iterator ei;
6243 if (!live[rpo[i]])
6245 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
6246 bitmap_clear (live[rpo[i]]);
6249 /* Process BB and update the live information with uses in
6250 this block. */
6251 find_assert_locations_1 (bb, live[rpo[i]]);
6253 /* Merge liveness into the predecessor blocks and free it. */
6254 if (!bitmap_empty_p (live[rpo[i]]))
6256 int pred_rpo = i;
6257 FOR_EACH_EDGE (e, ei, bb->preds)
6259 int pred = e->src->index;
6260 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
6261 continue;
6263 if (!live[pred])
6265 live[pred] = sbitmap_alloc (num_ssa_names);
6266 bitmap_clear (live[pred]);
6268 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
6270 if (bb_rpo[pred] < pred_rpo)
6271 pred_rpo = bb_rpo[pred];
6274 /* Record the RPO number of the last visited block that needs
6275 live information from this block. */
6276 last_rpo[rpo[i]] = pred_rpo;
6278 else
6280 sbitmap_free (live[rpo[i]]);
6281 live[rpo[i]] = NULL;
6284 /* We can free all successors live bitmaps if all their
6285 predecessors have been visited already. */
6286 FOR_EACH_EDGE (e, ei, bb->succs)
6287 if (last_rpo[e->dest->index] == i
6288 && live[e->dest->index])
6290 sbitmap_free (live[e->dest->index]);
6291 live[e->dest->index] = NULL;
6295 XDELETEVEC (rpo);
6296 XDELETEVEC (bb_rpo);
6297 XDELETEVEC (last_rpo);
6298 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
6299 if (live[i])
6300 sbitmap_free (live[i]);
6301 XDELETEVEC (live);
6304 /* Create an ASSERT_EXPR for NAME and insert it in the location
6305 indicated by LOC. Return true if we made any edge insertions. */
6307 static bool
6308 process_assert_insertions_for (tree name, assert_locus *loc)
6310 /* Build the comparison expression NAME_i COMP_CODE VAL. */
6311 gimple *stmt;
6312 tree cond;
6313 gimple *assert_stmt;
6314 edge_iterator ei;
6315 edge e;
6317 /* If we have X <=> X do not insert an assert expr for that. */
6318 if (loc->expr == loc->val)
6319 return false;
6321 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
6322 assert_stmt = build_assert_expr_for (cond, name);
6323 if (loc->e)
6325 /* We have been asked to insert the assertion on an edge. This
6326 is used only by COND_EXPR and SWITCH_EXPR assertions. */
6327 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
6328 || (gimple_code (gsi_stmt (loc->si))
6329 == GIMPLE_SWITCH));
6331 gsi_insert_on_edge (loc->e, assert_stmt);
6332 return true;
6335 /* If the stmt iterator points at the end then this is an insertion
6336 at the beginning of a block. */
6337 if (gsi_end_p (loc->si))
6339 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
6340 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
6341 return false;
6344 /* Otherwise, we can insert right after LOC->SI iff the
6345 statement must not be the last statement in the block. */
6346 stmt = gsi_stmt (loc->si);
6347 if (!stmt_ends_bb_p (stmt))
6349 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
6350 return false;
6353 /* If STMT must be the last statement in BB, we can only insert new
6354 assertions on the non-abnormal edge out of BB. Note that since
6355 STMT is not control flow, there may only be one non-abnormal/eh edge
6356 out of BB. */
6357 FOR_EACH_EDGE (e, ei, loc->bb->succs)
6358 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
6360 gsi_insert_on_edge (e, assert_stmt);
6361 return true;
6364 gcc_unreachable ();
6367 /* Qsort helper for sorting assert locations. If stable is true, don't
6368 use iterative_hash_expr because it can be unstable for -fcompare-debug,
6369 on the other side some pointers might be NULL. */
6371 template <bool stable>
6372 static int
6373 compare_assert_loc (const void *pa, const void *pb)
6375 assert_locus * const a = *(assert_locus * const *)pa;
6376 assert_locus * const b = *(assert_locus * const *)pb;
6378 /* If stable, some asserts might be optimized away already, sort
6379 them last. */
6380 if (stable)
6382 if (a == NULL)
6383 return b != NULL;
6384 else if (b == NULL)
6385 return -1;
6388 if (a->e == NULL && b->e != NULL)
6389 return 1;
6390 else if (a->e != NULL && b->e == NULL)
6391 return -1;
6393 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
6394 no need to test both a->e and b->e. */
6396 /* Sort after destination index. */
6397 if (a->e == NULL)
6399 else if (a->e->dest->index > b->e->dest->index)
6400 return 1;
6401 else if (a->e->dest->index < b->e->dest->index)
6402 return -1;
6404 /* Sort after comp_code. */
6405 if (a->comp_code > b->comp_code)
6406 return 1;
6407 else if (a->comp_code < b->comp_code)
6408 return -1;
6410 hashval_t ha, hb;
6412 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
6413 uses DECL_UID of the VAR_DECL, so sorting might differ between
6414 -g and -g0. When doing the removal of redundant assert exprs
6415 and commonization to successors, this does not matter, but for
6416 the final sort needs to be stable. */
6417 if (stable)
6419 ha = 0;
6420 hb = 0;
6422 else
6424 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
6425 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
6428 /* Break the tie using hashing and source/bb index. */
6429 if (ha == hb)
6430 return (a->e != NULL
6431 ? a->e->src->index - b->e->src->index
6432 : a->bb->index - b->bb->index);
6433 return ha > hb ? 1 : -1;
6436 /* Process all the insertions registered for every name N_i registered
6437 in NEED_ASSERT_FOR. The list of assertions to be inserted are
6438 found in ASSERTS_FOR[i]. */
6440 static void
6441 process_assert_insertions (void)
6443 unsigned i;
6444 bitmap_iterator bi;
6445 bool update_edges_p = false;
6446 int num_asserts = 0;
6448 if (dump_file && (dump_flags & TDF_DETAILS))
6449 dump_all_asserts (dump_file);
6451 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
6453 assert_locus *loc = asserts_for[i];
6454 gcc_assert (loc);
6456 auto_vec<assert_locus *, 16> asserts;
6457 for (; loc; loc = loc->next)
6458 asserts.safe_push (loc);
6459 asserts.qsort (compare_assert_loc<false>);
6461 /* Push down common asserts to successors and remove redundant ones. */
6462 unsigned ecnt = 0;
6463 assert_locus *common = NULL;
6464 unsigned commonj = 0;
6465 for (unsigned j = 0; j < asserts.length (); ++j)
6467 loc = asserts[j];
6468 if (! loc->e)
6469 common = NULL;
6470 else if (! common
6471 || loc->e->dest != common->e->dest
6472 || loc->comp_code != common->comp_code
6473 || ! operand_equal_p (loc->val, common->val, 0)
6474 || ! operand_equal_p (loc->expr, common->expr, 0))
6476 commonj = j;
6477 common = loc;
6478 ecnt = 1;
6480 else if (loc->e == asserts[j-1]->e)
6482 /* Remove duplicate asserts. */
6483 if (commonj == j - 1)
6485 commonj = j;
6486 common = loc;
6488 free (asserts[j-1]);
6489 asserts[j-1] = NULL;
6491 else
6493 ecnt++;
6494 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
6496 /* We have the same assertion on all incoming edges of a BB.
6497 Insert it at the beginning of that block. */
6498 loc->bb = loc->e->dest;
6499 loc->e = NULL;
6500 loc->si = gsi_none ();
6501 common = NULL;
6502 /* Clear asserts commoned. */
6503 for (; commonj != j; ++commonj)
6504 if (asserts[commonj])
6506 free (asserts[commonj]);
6507 asserts[commonj] = NULL;
6513 /* The asserts vector sorting above might be unstable for
6514 -fcompare-debug, sort again to ensure a stable sort. */
6515 asserts.qsort (compare_assert_loc<true>);
6516 for (unsigned j = 0; j < asserts.length (); ++j)
6518 loc = asserts[j];
6519 if (! loc)
6520 break;
6521 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
6522 num_asserts++;
6523 free (loc);
6527 if (update_edges_p)
6528 gsi_commit_edge_inserts ();
6530 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
6531 num_asserts);
6535 /* Traverse the flowgraph looking for conditional jumps to insert range
6536 expressions. These range expressions are meant to provide information
6537 to optimizations that need to reason in terms of value ranges. They
6538 will not be expanded into RTL. For instance, given:
6540 x = ...
6541 y = ...
6542 if (x < y)
6543 y = x - 2;
6544 else
6545 x = y + 3;
6547 this pass will transform the code into:
6549 x = ...
6550 y = ...
6551 if (x < y)
6553 x = ASSERT_EXPR <x, x < y>
6554 y = x - 2
6556 else
6558 y = ASSERT_EXPR <y, x >= y>
6559 x = y + 3
6562 The idea is that once copy and constant propagation have run, other
6563 optimizations will be able to determine what ranges of values can 'x'
6564 take in different paths of the code, simply by checking the reaching
6565 definition of 'x'. */
6567 static void
6568 insert_range_assertions (void)
6570 need_assert_for = BITMAP_ALLOC (NULL);
6571 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
6573 calculate_dominance_info (CDI_DOMINATORS);
6575 find_assert_locations ();
6576 if (!bitmap_empty_p (need_assert_for))
6578 process_assert_insertions ();
6579 update_ssa (TODO_update_ssa_no_phi);
6582 if (dump_file && (dump_flags & TDF_DETAILS))
6584 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
6585 dump_function_to_file (current_function_decl, dump_file, dump_flags);
6588 free (asserts_for);
6589 BITMAP_FREE (need_assert_for);
6592 class vrp_prop : public ssa_propagation_engine
6594 public:
6595 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
6596 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
6598 void vrp_initialize (void);
6599 void vrp_finalize (bool);
6600 void check_all_array_refs (void);
6601 void check_array_ref (location_t, tree, bool);
6602 void search_for_addr_array (tree, location_t);
6604 class vr_values vr_values;
6605 /* Temporary delegator to minimize code churn. */
6606 value_range *get_value_range (const_tree op)
6607 { return vr_values.get_value_range (op); }
6608 void set_defs_to_varying (gimple *stmt)
6609 { return vr_values.set_defs_to_varying (stmt); }
6610 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
6611 tree *output_p, value_range *vr)
6612 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
6613 bool update_value_range (const_tree op, value_range *vr)
6614 { return vr_values.update_value_range (op, vr); }
6615 void extract_range_basic (value_range *vr, gimple *stmt)
6616 { vr_values.extract_range_basic (vr, stmt); }
6617 void extract_range_from_phi_node (gphi *phi, value_range *vr)
6618 { vr_values.extract_range_from_phi_node (phi, vr); }
6621 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
6622 and "struct" hacks. If VRP can determine that the
6623 array subscript is a constant, check if it is outside valid
6624 range. If the array subscript is a RANGE, warn if it is
6625 non-overlapping with valid range.
6626 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
6628 void
6629 vrp_prop::check_array_ref (location_t location, tree ref,
6630 bool ignore_off_by_one)
6632 value_range *vr = NULL;
6633 tree low_sub, up_sub;
6634 tree low_bound, up_bound, up_bound_p1;
6636 if (TREE_NO_WARNING (ref))
6637 return;
6639 low_sub = up_sub = TREE_OPERAND (ref, 1);
6640 up_bound = array_ref_up_bound (ref);
6642 /* Can not check flexible arrays. */
6643 if (!up_bound
6644 || TREE_CODE (up_bound) != INTEGER_CST)
6645 return;
6647 /* Accesses to trailing arrays via pointers may access storage
6648 beyond the types array bounds. */
6649 if (warn_array_bounds < 2
6650 && array_at_struct_end_p (ref))
6651 return;
6653 low_bound = array_ref_low_bound (ref);
6654 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
6655 build_int_cst (TREE_TYPE (up_bound), 1));
6657 /* Empty array. */
6658 if (tree_int_cst_equal (low_bound, up_bound_p1))
6660 warning_at (location, OPT_Warray_bounds,
6661 "array subscript is above array bounds");
6662 TREE_NO_WARNING (ref) = 1;
6665 if (TREE_CODE (low_sub) == SSA_NAME)
6667 vr = get_value_range (low_sub);
6668 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
6670 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
6671 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
6675 if (vr && vr->type == VR_ANTI_RANGE)
6677 if (TREE_CODE (up_sub) == INTEGER_CST
6678 && (ignore_off_by_one
6679 ? tree_int_cst_lt (up_bound, up_sub)
6680 : tree_int_cst_le (up_bound, up_sub))
6681 && TREE_CODE (low_sub) == INTEGER_CST
6682 && tree_int_cst_le (low_sub, low_bound))
6684 warning_at (location, OPT_Warray_bounds,
6685 "array subscript is outside array bounds");
6686 TREE_NO_WARNING (ref) = 1;
6689 else if (TREE_CODE (up_sub) == INTEGER_CST
6690 && (ignore_off_by_one
6691 ? !tree_int_cst_le (up_sub, up_bound_p1)
6692 : !tree_int_cst_le (up_sub, up_bound)))
6694 if (dump_file && (dump_flags & TDF_DETAILS))
6696 fprintf (dump_file, "Array bound warning for ");
6697 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6698 fprintf (dump_file, "\n");
6700 warning_at (location, OPT_Warray_bounds,
6701 "array subscript is above array bounds");
6702 TREE_NO_WARNING (ref) = 1;
6704 else if (TREE_CODE (low_sub) == INTEGER_CST
6705 && tree_int_cst_lt (low_sub, low_bound))
6707 if (dump_file && (dump_flags & TDF_DETAILS))
6709 fprintf (dump_file, "Array bound warning for ");
6710 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6711 fprintf (dump_file, "\n");
6713 warning_at (location, OPT_Warray_bounds,
6714 "array subscript is below array bounds");
6715 TREE_NO_WARNING (ref) = 1;
6719 /* Searches if the expr T, located at LOCATION computes
6720 address of an ARRAY_REF, and call check_array_ref on it. */
6722 void
6723 vrp_prop::search_for_addr_array (tree t, location_t location)
6725 /* Check each ARRAY_REFs in the reference chain. */
6728 if (TREE_CODE (t) == ARRAY_REF)
6729 check_array_ref (location, t, true /*ignore_off_by_one*/);
6731 t = TREE_OPERAND (t, 0);
6733 while (handled_component_p (t));
6735 if (TREE_CODE (t) == MEM_REF
6736 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
6737 && !TREE_NO_WARNING (t))
6739 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
6740 tree low_bound, up_bound, el_sz;
6741 offset_int idx;
6742 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
6743 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
6744 || !TYPE_DOMAIN (TREE_TYPE (tem)))
6745 return;
6747 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6748 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6749 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
6750 if (!low_bound
6751 || TREE_CODE (low_bound) != INTEGER_CST
6752 || !up_bound
6753 || TREE_CODE (up_bound) != INTEGER_CST
6754 || !el_sz
6755 || TREE_CODE (el_sz) != INTEGER_CST)
6756 return;
6758 idx = mem_ref_offset (t);
6759 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
6760 if (idx < 0)
6762 if (dump_file && (dump_flags & TDF_DETAILS))
6764 fprintf (dump_file, "Array bound warning for ");
6765 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6766 fprintf (dump_file, "\n");
6768 warning_at (location, OPT_Warray_bounds,
6769 "array subscript is below array bounds");
6770 TREE_NO_WARNING (t) = 1;
6772 else if (idx > (wi::to_offset (up_bound)
6773 - wi::to_offset (low_bound) + 1))
6775 if (dump_file && (dump_flags & TDF_DETAILS))
6777 fprintf (dump_file, "Array bound warning for ");
6778 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6779 fprintf (dump_file, "\n");
6781 warning_at (location, OPT_Warray_bounds,
6782 "array subscript is above array bounds");
6783 TREE_NO_WARNING (t) = 1;
6788 /* walk_tree() callback that checks if *TP is
6789 an ARRAY_REF inside an ADDR_EXPR (in which an array
6790 subscript one outside the valid range is allowed). Call
6791 check_array_ref for each ARRAY_REF found. The location is
6792 passed in DATA. */
6794 static tree
6795 check_array_bounds (tree *tp, int *walk_subtree, void *data)
6797 tree t = *tp;
6798 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
6799 location_t location;
6801 if (EXPR_HAS_LOCATION (t))
6802 location = EXPR_LOCATION (t);
6803 else
6804 location = gimple_location (wi->stmt);
6806 *walk_subtree = TRUE;
6808 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
6809 if (TREE_CODE (t) == ARRAY_REF)
6810 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
6812 else if (TREE_CODE (t) == ADDR_EXPR)
6814 vrp_prop->search_for_addr_array (t, location);
6815 *walk_subtree = FALSE;
6818 return NULL_TREE;
6821 /* Walk over all statements of all reachable BBs and call check_array_bounds
6822 on them. */
6824 void
6825 vrp_prop::check_all_array_refs ()
6827 basic_block bb;
6828 gimple_stmt_iterator si;
6830 FOR_EACH_BB_FN (bb, cfun)
6832 edge_iterator ei;
6833 edge e;
6834 bool executable = false;
6836 /* Skip blocks that were found to be unreachable. */
6837 FOR_EACH_EDGE (e, ei, bb->preds)
6838 executable |= !!(e->flags & EDGE_EXECUTABLE);
6839 if (!executable)
6840 continue;
6842 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
6844 gimple *stmt = gsi_stmt (si);
6845 struct walk_stmt_info wi;
6846 if (!gimple_has_location (stmt)
6847 || is_gimple_debug (stmt))
6848 continue;
6850 memset (&wi, 0, sizeof (wi));
6852 wi.info = this;
6854 walk_gimple_op (gsi_stmt (si),
6855 check_array_bounds,
6856 &wi);
6861 /* Return true if all imm uses of VAR are either in STMT, or
6862 feed (optionally through a chain of single imm uses) GIMPLE_COND
6863 in basic block COND_BB. */
6865 static bool
6866 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
6868 use_operand_p use_p, use2_p;
6869 imm_use_iterator iter;
6871 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
6872 if (USE_STMT (use_p) != stmt)
6874 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
6875 if (is_gimple_debug (use_stmt))
6876 continue;
6877 while (is_gimple_assign (use_stmt)
6878 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
6879 && single_imm_use (gimple_assign_lhs (use_stmt),
6880 &use2_p, &use_stmt2))
6881 use_stmt = use_stmt2;
6882 if (gimple_code (use_stmt) != GIMPLE_COND
6883 || gimple_bb (use_stmt) != cond_bb)
6884 return false;
6886 return true;
6889 /* Handle
6890 _4 = x_3 & 31;
6891 if (_4 != 0)
6892 goto <bb 6>;
6893 else
6894 goto <bb 7>;
6895 <bb 6>:
6896 __builtin_unreachable ();
6897 <bb 7>:
6898 x_5 = ASSERT_EXPR <x_3, ...>;
6899 If x_3 has no other immediate uses (checked by caller),
6900 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
6901 from the non-zero bitmask. */
6903 static void
6904 maybe_set_nonzero_bits (basic_block bb, tree var)
6906 edge e = single_pred_edge (bb);
6907 basic_block cond_bb = e->src;
6908 gimple *stmt = last_stmt (cond_bb);
6909 tree cst;
6911 if (stmt == NULL
6912 || gimple_code (stmt) != GIMPLE_COND
6913 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
6914 ? EQ_EXPR : NE_EXPR)
6915 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
6916 || !integer_zerop (gimple_cond_rhs (stmt)))
6917 return;
6919 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
6920 if (!is_gimple_assign (stmt)
6921 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
6922 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
6923 return;
6924 if (gimple_assign_rhs1 (stmt) != var)
6926 gimple *stmt2;
6928 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
6929 return;
6930 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
6931 if (!gimple_assign_cast_p (stmt2)
6932 || gimple_assign_rhs1 (stmt2) != var
6933 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
6934 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
6935 != TYPE_PRECISION (TREE_TYPE (var))))
6936 return;
6938 cst = gimple_assign_rhs2 (stmt);
6939 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
6940 wi::to_wide (cst)));
6943 /* Convert range assertion expressions into the implied copies and
6944 copy propagate away the copies. Doing the trivial copy propagation
6945 here avoids the need to run the full copy propagation pass after
6946 VRP.
6948 FIXME, this will eventually lead to copy propagation removing the
6949 names that had useful range information attached to them. For
6950 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
6951 then N_i will have the range [3, +INF].
6953 However, by converting the assertion into the implied copy
6954 operation N_i = N_j, we will then copy-propagate N_j into the uses
6955 of N_i and lose the range information. We may want to hold on to
6956 ASSERT_EXPRs a little while longer as the ranges could be used in
6957 things like jump threading.
6959 The problem with keeping ASSERT_EXPRs around is that passes after
6960 VRP need to handle them appropriately.
6962 Another approach would be to make the range information a first
6963 class property of the SSA_NAME so that it can be queried from
6964 any pass. This is made somewhat more complex by the need for
6965 multiple ranges to be associated with one SSA_NAME. */
6967 static void
6968 remove_range_assertions (void)
6970 basic_block bb;
6971 gimple_stmt_iterator si;
6972 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
6973 a basic block preceeded by GIMPLE_COND branching to it and
6974 __builtin_trap, -1 if not yet checked, 0 otherwise. */
6975 int is_unreachable;
6977 /* Note that the BSI iterator bump happens at the bottom of the
6978 loop and no bump is necessary if we're removing the statement
6979 referenced by the current BSI. */
6980 FOR_EACH_BB_FN (bb, cfun)
6981 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
6983 gimple *stmt = gsi_stmt (si);
6985 if (is_gimple_assign (stmt)
6986 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
6988 tree lhs = gimple_assign_lhs (stmt);
6989 tree rhs = gimple_assign_rhs1 (stmt);
6990 tree var;
6992 var = ASSERT_EXPR_VAR (rhs);
6994 if (TREE_CODE (var) == SSA_NAME
6995 && !POINTER_TYPE_P (TREE_TYPE (lhs))
6996 && SSA_NAME_RANGE_INFO (lhs))
6998 if (is_unreachable == -1)
7000 is_unreachable = 0;
7001 if (single_pred_p (bb)
7002 && assert_unreachable_fallthru_edge_p
7003 (single_pred_edge (bb)))
7004 is_unreachable = 1;
7006 /* Handle
7007 if (x_7 >= 10 && x_7 < 20)
7008 __builtin_unreachable ();
7009 x_8 = ASSERT_EXPR <x_7, ...>;
7010 if the only uses of x_7 are in the ASSERT_EXPR and
7011 in the condition. In that case, we can copy the
7012 range info from x_8 computed in this pass also
7013 for x_7. */
7014 if (is_unreachable
7015 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
7016 single_pred (bb)))
7018 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
7019 SSA_NAME_RANGE_INFO (lhs)->get_min (),
7020 SSA_NAME_RANGE_INFO (lhs)->get_max ());
7021 maybe_set_nonzero_bits (bb, var);
7025 /* Propagate the RHS into every use of the LHS. For SSA names
7026 also propagate abnormals as it merely restores the original
7027 IL in this case (an replace_uses_by would assert). */
7028 if (TREE_CODE (var) == SSA_NAME)
7030 imm_use_iterator iter;
7031 use_operand_p use_p;
7032 gimple *use_stmt;
7033 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
7034 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
7035 SET_USE (use_p, var);
7037 else
7038 replace_uses_by (lhs, var);
7040 /* And finally, remove the copy, it is not needed. */
7041 gsi_remove (&si, true);
7042 release_defs (stmt);
7044 else
7046 if (!is_gimple_debug (gsi_stmt (si)))
7047 is_unreachable = 0;
7048 gsi_next (&si);
7054 /* Return true if STMT is interesting for VRP. */
7056 bool
7057 stmt_interesting_for_vrp (gimple *stmt)
7059 if (gimple_code (stmt) == GIMPLE_PHI)
7061 tree res = gimple_phi_result (stmt);
7062 return (!virtual_operand_p (res)
7063 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
7064 || POINTER_TYPE_P (TREE_TYPE (res))));
7066 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
7068 tree lhs = gimple_get_lhs (stmt);
7070 /* In general, assignments with virtual operands are not useful
7071 for deriving ranges, with the obvious exception of calls to
7072 builtin functions. */
7073 if (lhs && TREE_CODE (lhs) == SSA_NAME
7074 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7075 || POINTER_TYPE_P (TREE_TYPE (lhs)))
7076 && (is_gimple_call (stmt)
7077 || !gimple_vuse (stmt)))
7078 return true;
7079 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
7080 switch (gimple_call_internal_fn (stmt))
7082 case IFN_ADD_OVERFLOW:
7083 case IFN_SUB_OVERFLOW:
7084 case IFN_MUL_OVERFLOW:
7085 case IFN_ATOMIC_COMPARE_EXCHANGE:
7086 /* These internal calls return _Complex integer type,
7087 but are interesting to VRP nevertheless. */
7088 if (lhs && TREE_CODE (lhs) == SSA_NAME)
7089 return true;
7090 break;
7091 default:
7092 break;
7095 else if (gimple_code (stmt) == GIMPLE_COND
7096 || gimple_code (stmt) == GIMPLE_SWITCH)
7097 return true;
7099 return false;
7102 /* Initialize VRP lattice. */
7104 vr_values::vr_values () : vrp_value_range_pool ("Tree VRP value ranges")
7106 values_propagated = false;
7107 num_vr_values = num_ssa_names;
7108 vr_value = XCNEWVEC (value_range *, num_vr_values);
7109 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
7110 bitmap_obstack_initialize (&vrp_equiv_obstack);
7113 /* Initialization required by ssa_propagate engine. */
7115 void
7116 vrp_prop::vrp_initialize ()
7118 basic_block bb;
7120 FOR_EACH_BB_FN (bb, cfun)
7122 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
7123 gsi_next (&si))
7125 gphi *phi = si.phi ();
7126 if (!stmt_interesting_for_vrp (phi))
7128 tree lhs = PHI_RESULT (phi);
7129 set_value_range_to_varying (get_value_range (lhs));
7130 prop_set_simulate_again (phi, false);
7132 else
7133 prop_set_simulate_again (phi, true);
7136 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
7137 gsi_next (&si))
7139 gimple *stmt = gsi_stmt (si);
7141 /* If the statement is a control insn, then we do not
7142 want to avoid simulating the statement once. Failure
7143 to do so means that those edges will never get added. */
7144 if (stmt_ends_bb_p (stmt))
7145 prop_set_simulate_again (stmt, true);
7146 else if (!stmt_interesting_for_vrp (stmt))
7148 set_defs_to_varying (stmt);
7149 prop_set_simulate_again (stmt, false);
7151 else
7152 prop_set_simulate_again (stmt, true);
7157 /* A hack. */
7158 static class vr_values *x_vr_values;
7160 /* Return the singleton value-range for NAME or NAME. */
7162 static inline tree
7163 vrp_valueize (tree name)
7165 if (TREE_CODE (name) == SSA_NAME)
7167 value_range *vr = x_vr_values->get_value_range (name);
7168 if (vr->type == VR_RANGE
7169 && (TREE_CODE (vr->min) == SSA_NAME
7170 || is_gimple_min_invariant (vr->min))
7171 && vrp_operand_equal_p (vr->min, vr->max))
7172 return vr->min;
7174 return name;
7177 /* Return the singleton value-range for NAME if that is a constant
7178 but signal to not follow SSA edges. */
7180 static inline tree
7181 vrp_valueize_1 (tree name)
7183 if (TREE_CODE (name) == SSA_NAME)
7185 /* If the definition may be simulated again we cannot follow
7186 this SSA edge as the SSA propagator does not necessarily
7187 re-visit the use. */
7188 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
7189 if (!gimple_nop_p (def_stmt)
7190 && prop_simulate_again_p (def_stmt))
7191 return NULL_TREE;
7192 value_range *vr = x_vr_values->get_value_range (name);
7193 if (range_int_cst_singleton_p (vr))
7194 return vr->min;
7196 return name;
7199 /* Visit assignment STMT. If it produces an interesting range, record
7200 the range in VR and set LHS to OUTPUT_P. */
7202 void
7203 vr_values::vrp_visit_assignment_or_call (gimple *stmt, tree *output_p,
7204 value_range *vr)
7206 tree lhs;
7207 enum gimple_code code = gimple_code (stmt);
7208 lhs = gimple_get_lhs (stmt);
7209 *output_p = NULL_TREE;
7211 /* We only keep track of ranges in integral and pointer types. */
7212 if (TREE_CODE (lhs) == SSA_NAME
7213 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7214 /* It is valid to have NULL MIN/MAX values on a type. See
7215 build_range_type. */
7216 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
7217 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
7218 || POINTER_TYPE_P (TREE_TYPE (lhs))))
7220 *output_p = lhs;
7222 /* Try folding the statement to a constant first. */
7223 x_vr_values = this;
7224 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
7225 vrp_valueize_1);
7226 x_vr_values = NULL;
7227 if (tem)
7229 if (TREE_CODE (tem) == SSA_NAME
7230 && (SSA_NAME_IS_DEFAULT_DEF (tem)
7231 || ! prop_simulate_again_p (SSA_NAME_DEF_STMT (tem))))
7233 extract_range_from_ssa_name (vr, tem);
7234 return;
7236 else if (is_gimple_min_invariant (tem))
7238 set_value_range_to_value (vr, tem, NULL);
7239 return;
7242 /* Then dispatch to value-range extracting functions. */
7243 if (code == GIMPLE_CALL)
7244 extract_range_basic (vr, stmt);
7245 else
7246 extract_range_from_assignment (vr, as_a <gassign *> (stmt));
7250 /* Helper that gets the value range of the SSA_NAME with version I
7251 or a symbolic range containing the SSA_NAME only if the value range
7252 is varying or undefined. */
7254 value_range
7255 vr_values::get_vr_for_comparison (int i)
7257 value_range vr = *get_value_range (ssa_name (i));
7259 /* If name N_i does not have a valid range, use N_i as its own
7260 range. This allows us to compare against names that may
7261 have N_i in their ranges. */
7262 if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
7264 vr.type = VR_RANGE;
7265 vr.min = ssa_name (i);
7266 vr.max = ssa_name (i);
7269 return vr;
7272 /* Compare all the value ranges for names equivalent to VAR with VAL
7273 using comparison code COMP. Return the same value returned by
7274 compare_range_with_value, including the setting of
7275 *STRICT_OVERFLOW_P. */
7277 tree
7278 vr_values::compare_name_with_value (enum tree_code comp, tree var, tree val,
7279 bool *strict_overflow_p, bool use_equiv_p)
7281 bitmap_iterator bi;
7282 unsigned i;
7283 bitmap e;
7284 tree retval, t;
7285 int used_strict_overflow;
7286 bool sop;
7287 value_range equiv_vr;
7289 /* Get the set of equivalences for VAR. */
7290 e = get_value_range (var)->equiv;
7292 /* Start at -1. Set it to 0 if we do a comparison without relying
7293 on overflow, or 1 if all comparisons rely on overflow. */
7294 used_strict_overflow = -1;
7296 /* Compare vars' value range with val. */
7297 equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
7298 sop = false;
7299 retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
7300 if (retval)
7301 used_strict_overflow = sop ? 1 : 0;
7303 /* If the equiv set is empty we have done all work we need to do. */
7304 if (e == NULL)
7306 if (retval
7307 && used_strict_overflow > 0)
7308 *strict_overflow_p = true;
7309 return retval;
7312 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
7314 tree name = ssa_name (i);
7315 if (! name)
7316 continue;
7318 if (! use_equiv_p
7319 && ! SSA_NAME_IS_DEFAULT_DEF (name)
7320 && prop_simulate_again_p (SSA_NAME_DEF_STMT (name)))
7321 continue;
7323 equiv_vr = get_vr_for_comparison (i);
7324 sop = false;
7325 t = compare_range_with_value (comp, &equiv_vr, val, &sop);
7326 if (t)
7328 /* If we get different answers from different members
7329 of the equivalence set this check must be in a dead
7330 code region. Folding it to a trap representation
7331 would be correct here. For now just return don't-know. */
7332 if (retval != NULL
7333 && t != retval)
7335 retval = NULL_TREE;
7336 break;
7338 retval = t;
7340 if (!sop)
7341 used_strict_overflow = 0;
7342 else if (used_strict_overflow < 0)
7343 used_strict_overflow = 1;
7347 if (retval
7348 && used_strict_overflow > 0)
7349 *strict_overflow_p = true;
7351 return retval;
7355 /* Given a comparison code COMP and names N1 and N2, compare all the
7356 ranges equivalent to N1 against all the ranges equivalent to N2
7357 to determine the value of N1 COMP N2. Return the same value
7358 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
7359 whether we relied on undefined signed overflow in the comparison. */
7362 tree
7363 vr_values::compare_names (enum tree_code comp, tree n1, tree n2,
7364 bool *strict_overflow_p)
7366 tree t, retval;
7367 bitmap e1, e2;
7368 bitmap_iterator bi1, bi2;
7369 unsigned i1, i2;
7370 int used_strict_overflow;
7371 static bitmap_obstack *s_obstack = NULL;
7372 static bitmap s_e1 = NULL, s_e2 = NULL;
7374 /* Compare the ranges of every name equivalent to N1 against the
7375 ranges of every name equivalent to N2. */
7376 e1 = get_value_range (n1)->equiv;
7377 e2 = get_value_range (n2)->equiv;
7379 /* Use the fake bitmaps if e1 or e2 are not available. */
7380 if (s_obstack == NULL)
7382 s_obstack = XNEW (bitmap_obstack);
7383 bitmap_obstack_initialize (s_obstack);
7384 s_e1 = BITMAP_ALLOC (s_obstack);
7385 s_e2 = BITMAP_ALLOC (s_obstack);
7387 if (e1 == NULL)
7388 e1 = s_e1;
7389 if (e2 == NULL)
7390 e2 = s_e2;
7392 /* Add N1 and N2 to their own set of equivalences to avoid
7393 duplicating the body of the loop just to check N1 and N2
7394 ranges. */
7395 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
7396 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
7398 /* If the equivalence sets have a common intersection, then the two
7399 names can be compared without checking their ranges. */
7400 if (bitmap_intersect_p (e1, e2))
7402 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7403 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7405 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
7406 ? boolean_true_node
7407 : boolean_false_node;
7410 /* Start at -1. Set it to 0 if we do a comparison without relying
7411 on overflow, or 1 if all comparisons rely on overflow. */
7412 used_strict_overflow = -1;
7414 /* Otherwise, compare all the equivalent ranges. First, add N1 and
7415 N2 to their own set of equivalences to avoid duplicating the body
7416 of the loop just to check N1 and N2 ranges. */
7417 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
7419 if (! ssa_name (i1))
7420 continue;
7422 value_range vr1 = get_vr_for_comparison (i1);
7424 t = retval = NULL_TREE;
7425 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
7427 if (! ssa_name (i2))
7428 continue;
7430 bool sop = false;
7432 value_range vr2 = get_vr_for_comparison (i2);
7434 t = compare_ranges (comp, &vr1, &vr2, &sop);
7435 if (t)
7437 /* If we get different answers from different members
7438 of the equivalence set this check must be in a dead
7439 code region. Folding it to a trap representation
7440 would be correct here. For now just return don't-know. */
7441 if (retval != NULL
7442 && t != retval)
7444 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7445 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7446 return NULL_TREE;
7448 retval = t;
7450 if (!sop)
7451 used_strict_overflow = 0;
7452 else if (used_strict_overflow < 0)
7453 used_strict_overflow = 1;
7457 if (retval)
7459 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7460 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7461 if (used_strict_overflow > 0)
7462 *strict_overflow_p = true;
7463 return retval;
7467 /* None of the equivalent ranges are useful in computing this
7468 comparison. */
7469 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7470 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7471 return NULL_TREE;
7474 /* Helper function for vrp_evaluate_conditional_warnv & other
7475 optimizers. */
7477 tree
7478 vr_values::vrp_evaluate_conditional_warnv_with_ops_using_ranges
7479 (enum tree_code code, tree op0, tree op1, bool * strict_overflow_p)
7481 value_range *vr0, *vr1;
7483 vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
7484 vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
7486 tree res = NULL_TREE;
7487 if (vr0 && vr1)
7488 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
7489 if (!res && vr0)
7490 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
7491 if (!res && vr1)
7492 res = (compare_range_with_value
7493 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
7494 return res;
7497 /* Helper function for vrp_evaluate_conditional_warnv. */
7499 tree
7500 vr_values::vrp_evaluate_conditional_warnv_with_ops (enum tree_code code,
7501 tree op0, tree op1,
7502 bool use_equiv_p,
7503 bool *strict_overflow_p,
7504 bool *only_ranges)
7506 tree ret;
7507 if (only_ranges)
7508 *only_ranges = true;
7510 /* We only deal with integral and pointer types. */
7511 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
7512 && !POINTER_TYPE_P (TREE_TYPE (op0)))
7513 return NULL_TREE;
7515 /* If OP0 CODE OP1 is an overflow comparison, if it can be expressed
7516 as a simple equality test, then prefer that over its current form
7517 for evaluation.
7519 An overflow test which collapses to an equality test can always be
7520 expressed as a comparison of one argument against zero. Overflow
7521 occurs when the chosen argument is zero and does not occur if the
7522 chosen argument is not zero. */
7523 tree x;
7524 if (overflow_comparison_p (code, op0, op1, use_equiv_p, &x))
7526 wide_int max = wi::max_value (TYPE_PRECISION (TREE_TYPE (op0)), UNSIGNED);
7527 /* B = A - 1; if (A < B) -> B = A - 1; if (A == 0)
7528 B = A - 1; if (A > B) -> B = A - 1; if (A != 0)
7529 B = A + 1; if (B < A) -> B = A + 1; if (B == 0)
7530 B = A + 1; if (B > A) -> B = A + 1; if (B != 0) */
7531 if (integer_zerop (x))
7533 op1 = x;
7534 code = (code == LT_EXPR || code == LE_EXPR) ? EQ_EXPR : NE_EXPR;
7536 /* B = A + 1; if (A > B) -> B = A + 1; if (B == 0)
7537 B = A + 1; if (A < B) -> B = A + 1; if (B != 0)
7538 B = A - 1; if (B > A) -> B = A - 1; if (A == 0)
7539 B = A - 1; if (B < A) -> B = A - 1; if (A != 0) */
7540 else if (wi::to_wide (x) == max - 1)
7542 op0 = op1;
7543 op1 = wide_int_to_tree (TREE_TYPE (op0), 0);
7544 code = (code == GT_EXPR || code == GE_EXPR) ? EQ_EXPR : NE_EXPR;
7548 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
7549 (code, op0, op1, strict_overflow_p)))
7550 return ret;
7551 if (only_ranges)
7552 *only_ranges = false;
7553 /* Do not use compare_names during propagation, it's quadratic. */
7554 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
7555 && use_equiv_p)
7556 return compare_names (code, op0, op1, strict_overflow_p);
7557 else if (TREE_CODE (op0) == SSA_NAME)
7558 return compare_name_with_value (code, op0, op1,
7559 strict_overflow_p, use_equiv_p);
7560 else if (TREE_CODE (op1) == SSA_NAME)
7561 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
7562 strict_overflow_p, use_equiv_p);
7563 return NULL_TREE;
7566 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
7567 information. Return NULL if the conditional can not be evaluated.
7568 The ranges of all the names equivalent with the operands in COND
7569 will be used when trying to compute the value. If the result is
7570 based on undefined signed overflow, issue a warning if
7571 appropriate. */
7573 tree
7574 vr_values::vrp_evaluate_conditional (tree_code code, tree op0,
7575 tree op1, gimple *stmt)
7577 bool sop;
7578 tree ret;
7579 bool only_ranges;
7581 /* Some passes and foldings leak constants with overflow flag set
7582 into the IL. Avoid doing wrong things with these and bail out. */
7583 if ((TREE_CODE (op0) == INTEGER_CST
7584 && TREE_OVERFLOW (op0))
7585 || (TREE_CODE (op1) == INTEGER_CST
7586 && TREE_OVERFLOW (op1)))
7587 return NULL_TREE;
7589 sop = false;
7590 ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
7591 &only_ranges);
7593 if (ret && sop)
7595 enum warn_strict_overflow_code wc;
7596 const char* warnmsg;
7598 if (is_gimple_min_invariant (ret))
7600 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
7601 warnmsg = G_("assuming signed overflow does not occur when "
7602 "simplifying conditional to constant");
7604 else
7606 wc = WARN_STRICT_OVERFLOW_COMPARISON;
7607 warnmsg = G_("assuming signed overflow does not occur when "
7608 "simplifying conditional");
7611 if (issue_strict_overflow_warning (wc))
7613 location_t location;
7615 if (!gimple_has_location (stmt))
7616 location = input_location;
7617 else
7618 location = gimple_location (stmt);
7619 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
7623 if (warn_type_limits
7624 && ret && only_ranges
7625 && TREE_CODE_CLASS (code) == tcc_comparison
7626 && TREE_CODE (op0) == SSA_NAME)
7628 /* If the comparison is being folded and the operand on the LHS
7629 is being compared against a constant value that is outside of
7630 the natural range of OP0's type, then the predicate will
7631 always fold regardless of the value of OP0. If -Wtype-limits
7632 was specified, emit a warning. */
7633 tree type = TREE_TYPE (op0);
7634 value_range *vr0 = get_value_range (op0);
7636 if (vr0->type == VR_RANGE
7637 && INTEGRAL_TYPE_P (type)
7638 && vrp_val_is_min (vr0->min)
7639 && vrp_val_is_max (vr0->max)
7640 && is_gimple_min_invariant (op1))
7642 location_t location;
7644 if (!gimple_has_location (stmt))
7645 location = input_location;
7646 else
7647 location = gimple_location (stmt);
7649 warning_at (location, OPT_Wtype_limits,
7650 integer_zerop (ret)
7651 ? G_("comparison always false "
7652 "due to limited range of data type")
7653 : G_("comparison always true "
7654 "due to limited range of data type"));
7658 return ret;
7662 /* Visit conditional statement STMT. If we can determine which edge
7663 will be taken out of STMT's basic block, record it in
7664 *TAKEN_EDGE_P. Otherwise, set *TAKEN_EDGE_P to NULL. */
7666 void
7667 vr_values::vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
7669 tree val;
7671 *taken_edge_p = NULL;
7673 if (dump_file && (dump_flags & TDF_DETAILS))
7675 tree use;
7676 ssa_op_iter i;
7678 fprintf (dump_file, "\nVisiting conditional with predicate: ");
7679 print_gimple_stmt (dump_file, stmt, 0);
7680 fprintf (dump_file, "\nWith known ranges\n");
7682 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
7684 fprintf (dump_file, "\t");
7685 print_generic_expr (dump_file, use);
7686 fprintf (dump_file, ": ");
7687 dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
7690 fprintf (dump_file, "\n");
7693 /* Compute the value of the predicate COND by checking the known
7694 ranges of each of its operands.
7696 Note that we cannot evaluate all the equivalent ranges here
7697 because those ranges may not yet be final and with the current
7698 propagation strategy, we cannot determine when the value ranges
7699 of the names in the equivalence set have changed.
7701 For instance, given the following code fragment
7703 i_5 = PHI <8, i_13>
7705 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
7706 if (i_14 == 1)
7709 Assume that on the first visit to i_14, i_5 has the temporary
7710 range [8, 8] because the second argument to the PHI function is
7711 not yet executable. We derive the range ~[0, 0] for i_14 and the
7712 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
7713 the first time, since i_14 is equivalent to the range [8, 8], we
7714 determine that the predicate is always false.
7716 On the next round of propagation, i_13 is determined to be
7717 VARYING, which causes i_5 to drop down to VARYING. So, another
7718 visit to i_14 is scheduled. In this second visit, we compute the
7719 exact same range and equivalence set for i_14, namely ~[0, 0] and
7720 { i_5 }. But we did not have the previous range for i_5
7721 registered, so vrp_visit_assignment thinks that the range for
7722 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
7723 is not visited again, which stops propagation from visiting
7724 statements in the THEN clause of that if().
7726 To properly fix this we would need to keep the previous range
7727 value for the names in the equivalence set. This way we would've
7728 discovered that from one visit to the other i_5 changed from
7729 range [8, 8] to VR_VARYING.
7731 However, fixing this apparent limitation may not be worth the
7732 additional checking. Testing on several code bases (GCC, DLV,
7733 MICO, TRAMP3D and SPEC2000) showed that doing this results in
7734 4 more predicates folded in SPEC. */
7736 bool sop;
7737 val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
7738 gimple_cond_lhs (stmt),
7739 gimple_cond_rhs (stmt),
7740 false, &sop, NULL);
7741 if (val)
7742 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
7744 if (dump_file && (dump_flags & TDF_DETAILS))
7746 fprintf (dump_file, "\nPredicate evaluates to: ");
7747 if (val == NULL_TREE)
7748 fprintf (dump_file, "DON'T KNOW\n");
7749 else
7750 print_generic_stmt (dump_file, val);
7754 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
7755 that includes the value VAL. The search is restricted to the range
7756 [START_IDX, n - 1] where n is the size of VEC.
7758 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
7759 returned.
7761 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
7762 it is placed in IDX and false is returned.
7764 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
7765 returned. */
7767 static bool
7768 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
7770 size_t n = gimple_switch_num_labels (stmt);
7771 size_t low, high;
7773 /* Find case label for minimum of the value range or the next one.
7774 At each iteration we are searching in [low, high - 1]. */
7776 for (low = start_idx, high = n; high != low; )
7778 tree t;
7779 int cmp;
7780 /* Note that i != high, so we never ask for n. */
7781 size_t i = (high + low) / 2;
7782 t = gimple_switch_label (stmt, i);
7784 /* Cache the result of comparing CASE_LOW and val. */
7785 cmp = tree_int_cst_compare (CASE_LOW (t), val);
7787 if (cmp == 0)
7789 /* Ranges cannot be empty. */
7790 *idx = i;
7791 return true;
7793 else if (cmp > 0)
7794 high = i;
7795 else
7797 low = i + 1;
7798 if (CASE_HIGH (t) != NULL
7799 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
7801 *idx = i;
7802 return true;
7807 *idx = high;
7808 return false;
7811 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
7812 for values between MIN and MAX. The first index is placed in MIN_IDX. The
7813 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
7814 then MAX_IDX < MIN_IDX.
7815 Returns true if the default label is not needed. */
7817 static bool
7818 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
7819 size_t *max_idx)
7821 size_t i, j;
7822 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
7823 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
7825 if (i == j
7826 && min_take_default
7827 && max_take_default)
7829 /* Only the default case label reached.
7830 Return an empty range. */
7831 *min_idx = 1;
7832 *max_idx = 0;
7833 return false;
7835 else
7837 bool take_default = min_take_default || max_take_default;
7838 tree low, high;
7839 size_t k;
7841 if (max_take_default)
7842 j--;
7844 /* If the case label range is continuous, we do not need
7845 the default case label. Verify that. */
7846 high = CASE_LOW (gimple_switch_label (stmt, i));
7847 if (CASE_HIGH (gimple_switch_label (stmt, i)))
7848 high = CASE_HIGH (gimple_switch_label (stmt, i));
7849 for (k = i + 1; k <= j; ++k)
7851 low = CASE_LOW (gimple_switch_label (stmt, k));
7852 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
7854 take_default = true;
7855 break;
7857 high = low;
7858 if (CASE_HIGH (gimple_switch_label (stmt, k)))
7859 high = CASE_HIGH (gimple_switch_label (stmt, k));
7862 *min_idx = i;
7863 *max_idx = j;
7864 return !take_default;
7868 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
7869 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
7870 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
7871 Returns true if the default label is not needed. */
7873 static bool
7874 find_case_label_ranges (gswitch *stmt, value_range *vr, size_t *min_idx1,
7875 size_t *max_idx1, size_t *min_idx2,
7876 size_t *max_idx2)
7878 size_t i, j, k, l;
7879 unsigned int n = gimple_switch_num_labels (stmt);
7880 bool take_default;
7881 tree case_low, case_high;
7882 tree min = vr->min, max = vr->max;
7884 gcc_checking_assert (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE);
7886 take_default = !find_case_label_range (stmt, min, max, &i, &j);
7888 /* Set second range to emtpy. */
7889 *min_idx2 = 1;
7890 *max_idx2 = 0;
7892 if (vr->type == VR_RANGE)
7894 *min_idx1 = i;
7895 *max_idx1 = j;
7896 return !take_default;
7899 /* Set first range to all case labels. */
7900 *min_idx1 = 1;
7901 *max_idx1 = n - 1;
7903 if (i > j)
7904 return false;
7906 /* Make sure all the values of case labels [i , j] are contained in
7907 range [MIN, MAX]. */
7908 case_low = CASE_LOW (gimple_switch_label (stmt, i));
7909 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
7910 if (tree_int_cst_compare (case_low, min) < 0)
7911 i += 1;
7912 if (case_high != NULL_TREE
7913 && tree_int_cst_compare (max, case_high) < 0)
7914 j -= 1;
7916 if (i > j)
7917 return false;
7919 /* If the range spans case labels [i, j], the corresponding anti-range spans
7920 the labels [1, i - 1] and [j + 1, n - 1]. */
7921 k = j + 1;
7922 l = n - 1;
7923 if (k > l)
7925 k = 1;
7926 l = 0;
7929 j = i - 1;
7930 i = 1;
7931 if (i > j)
7933 i = k;
7934 j = l;
7935 k = 1;
7936 l = 0;
7939 *min_idx1 = i;
7940 *max_idx1 = j;
7941 *min_idx2 = k;
7942 *max_idx2 = l;
7943 return false;
7946 /* Visit switch statement STMT. If we can determine which edge
7947 will be taken out of STMT's basic block, record it in
7948 *TAKEN_EDGE_P. Otherwise, *TAKEN_EDGE_P set to NULL. */
7950 void
7951 vr_values::vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
7953 tree op, val;
7954 value_range *vr;
7955 size_t i = 0, j = 0, k, l;
7956 bool take_default;
7958 *taken_edge_p = NULL;
7959 op = gimple_switch_index (stmt);
7960 if (TREE_CODE (op) != SSA_NAME)
7961 return;
7963 vr = get_value_range (op);
7964 if (dump_file && (dump_flags & TDF_DETAILS))
7966 fprintf (dump_file, "\nVisiting switch expression with operand ");
7967 print_generic_expr (dump_file, op);
7968 fprintf (dump_file, " with known range ");
7969 dump_value_range (dump_file, vr);
7970 fprintf (dump_file, "\n");
7973 if ((vr->type != VR_RANGE
7974 && vr->type != VR_ANTI_RANGE)
7975 || symbolic_range_p (vr))
7976 return;
7978 /* Find the single edge that is taken from the switch expression. */
7979 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
7981 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
7982 label */
7983 if (j < i)
7985 gcc_assert (take_default);
7986 val = gimple_switch_default_label (stmt);
7988 else
7990 /* Check if labels with index i to j and maybe the default label
7991 are all reaching the same label. */
7993 val = gimple_switch_label (stmt, i);
7994 if (take_default
7995 && CASE_LABEL (gimple_switch_default_label (stmt))
7996 != CASE_LABEL (val))
7998 if (dump_file && (dump_flags & TDF_DETAILS))
7999 fprintf (dump_file, " not a single destination for this "
8000 "range\n");
8001 return;
8003 for (++i; i <= j; ++i)
8005 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
8007 if (dump_file && (dump_flags & TDF_DETAILS))
8008 fprintf (dump_file, " not a single destination for this "
8009 "range\n");
8010 return;
8013 for (; k <= l; ++k)
8015 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
8017 if (dump_file && (dump_flags & TDF_DETAILS))
8018 fprintf (dump_file, " not a single destination for this "
8019 "range\n");
8020 return;
8025 *taken_edge_p = find_edge (gimple_bb (stmt),
8026 label_to_block (CASE_LABEL (val)));
8028 if (dump_file && (dump_flags & TDF_DETAILS))
8030 fprintf (dump_file, " will take edge to ");
8031 print_generic_stmt (dump_file, CASE_LABEL (val));
8036 /* Evaluate statement STMT. If the statement produces a useful range,
8037 set VR and corepsponding OUTPUT_P.
8039 If STMT is a conditional branch and we can determine its truth
8040 value, the taken edge is recorded in *TAKEN_EDGE_P. */
8042 void
8043 vr_values::extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
8044 tree *output_p, value_range *vr)
8047 if (dump_file && (dump_flags & TDF_DETAILS))
8049 fprintf (dump_file, "\nVisiting statement:\n");
8050 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
8053 if (!stmt_interesting_for_vrp (stmt))
8054 gcc_assert (stmt_ends_bb_p (stmt));
8055 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
8056 vrp_visit_assignment_or_call (stmt, output_p, vr);
8057 else if (gimple_code (stmt) == GIMPLE_COND)
8058 vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
8059 else if (gimple_code (stmt) == GIMPLE_SWITCH)
8060 vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
8063 /* Evaluate statement STMT. If the statement produces a useful range,
8064 return SSA_PROP_INTERESTING and record the SSA name with the
8065 interesting range into *OUTPUT_P.
8067 If STMT is a conditional branch and we can determine its truth
8068 value, the taken edge is recorded in *TAKEN_EDGE_P.
8070 If STMT produces a varying value, return SSA_PROP_VARYING. */
8072 enum ssa_prop_result
8073 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
8075 value_range vr = VR_INITIALIZER;
8076 tree lhs = gimple_get_lhs (stmt);
8077 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
8079 if (*output_p)
8081 if (update_value_range (*output_p, &vr))
8083 if (dump_file && (dump_flags & TDF_DETAILS))
8085 fprintf (dump_file, "Found new range for ");
8086 print_generic_expr (dump_file, *output_p);
8087 fprintf (dump_file, ": ");
8088 dump_value_range (dump_file, &vr);
8089 fprintf (dump_file, "\n");
8092 if (vr.type == VR_VARYING)
8093 return SSA_PROP_VARYING;
8095 return SSA_PROP_INTERESTING;
8097 return SSA_PROP_NOT_INTERESTING;
8100 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
8101 switch (gimple_call_internal_fn (stmt))
8103 case IFN_ADD_OVERFLOW:
8104 case IFN_SUB_OVERFLOW:
8105 case IFN_MUL_OVERFLOW:
8106 case IFN_ATOMIC_COMPARE_EXCHANGE:
8107 /* These internal calls return _Complex integer type,
8108 which VRP does not track, but the immediate uses
8109 thereof might be interesting. */
8110 if (lhs && TREE_CODE (lhs) == SSA_NAME)
8112 imm_use_iterator iter;
8113 use_operand_p use_p;
8114 enum ssa_prop_result res = SSA_PROP_VARYING;
8116 set_value_range_to_varying (get_value_range (lhs));
8118 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
8120 gimple *use_stmt = USE_STMT (use_p);
8121 if (!is_gimple_assign (use_stmt))
8122 continue;
8123 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
8124 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
8125 continue;
8126 tree rhs1 = gimple_assign_rhs1 (use_stmt);
8127 tree use_lhs = gimple_assign_lhs (use_stmt);
8128 if (TREE_CODE (rhs1) != rhs_code
8129 || TREE_OPERAND (rhs1, 0) != lhs
8130 || TREE_CODE (use_lhs) != SSA_NAME
8131 || !stmt_interesting_for_vrp (use_stmt)
8132 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
8133 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
8134 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
8135 continue;
8137 /* If there is a change in the value range for any of the
8138 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
8139 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
8140 or IMAGPART_EXPR immediate uses, but none of them have
8141 a change in their value ranges, return
8142 SSA_PROP_NOT_INTERESTING. If there are no
8143 {REAL,IMAG}PART_EXPR uses at all,
8144 return SSA_PROP_VARYING. */
8145 value_range new_vr = VR_INITIALIZER;
8146 extract_range_basic (&new_vr, use_stmt);
8147 value_range *old_vr = get_value_range (use_lhs);
8148 if (old_vr->type != new_vr.type
8149 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
8150 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
8151 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
8152 res = SSA_PROP_INTERESTING;
8153 else
8154 res = SSA_PROP_NOT_INTERESTING;
8155 BITMAP_FREE (new_vr.equiv);
8156 if (res == SSA_PROP_INTERESTING)
8158 *output_p = lhs;
8159 return res;
8163 return res;
8165 break;
8166 default:
8167 break;
8170 /* All other statements produce nothing of interest for VRP, so mark
8171 their outputs varying and prevent further simulation. */
8172 set_defs_to_varying (stmt);
8174 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
8177 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8178 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8179 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8180 possible such range. The resulting range is not canonicalized. */
8182 static void
8183 union_ranges (enum value_range_type *vr0type,
8184 tree *vr0min, tree *vr0max,
8185 enum value_range_type vr1type,
8186 tree vr1min, tree vr1max)
8188 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8189 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8191 /* [] is vr0, () is vr1 in the following classification comments. */
8192 if (mineq && maxeq)
8194 /* [( )] */
8195 if (*vr0type == vr1type)
8196 /* Nothing to do for equal ranges. */
8198 else if ((*vr0type == VR_RANGE
8199 && vr1type == VR_ANTI_RANGE)
8200 || (*vr0type == VR_ANTI_RANGE
8201 && vr1type == VR_RANGE))
8203 /* For anti-range with range union the result is varying. */
8204 goto give_up;
8206 else
8207 gcc_unreachable ();
8209 else if (operand_less_p (*vr0max, vr1min) == 1
8210 || operand_less_p (vr1max, *vr0min) == 1)
8212 /* [ ] ( ) or ( ) [ ]
8213 If the ranges have an empty intersection, result of the union
8214 operation is the anti-range or if both are anti-ranges
8215 it covers all. */
8216 if (*vr0type == VR_ANTI_RANGE
8217 && vr1type == VR_ANTI_RANGE)
8218 goto give_up;
8219 else if (*vr0type == VR_ANTI_RANGE
8220 && vr1type == VR_RANGE)
8222 else if (*vr0type == VR_RANGE
8223 && vr1type == VR_ANTI_RANGE)
8225 *vr0type = vr1type;
8226 *vr0min = vr1min;
8227 *vr0max = vr1max;
8229 else if (*vr0type == VR_RANGE
8230 && vr1type == VR_RANGE)
8232 /* The result is the convex hull of both ranges. */
8233 if (operand_less_p (*vr0max, vr1min) == 1)
8235 /* If the result can be an anti-range, create one. */
8236 if (TREE_CODE (*vr0max) == INTEGER_CST
8237 && TREE_CODE (vr1min) == INTEGER_CST
8238 && vrp_val_is_min (*vr0min)
8239 && vrp_val_is_max (vr1max))
8241 tree min = int_const_binop (PLUS_EXPR,
8242 *vr0max,
8243 build_int_cst (TREE_TYPE (*vr0max), 1));
8244 tree max = int_const_binop (MINUS_EXPR,
8245 vr1min,
8246 build_int_cst (TREE_TYPE (vr1min), 1));
8247 if (!operand_less_p (max, min))
8249 *vr0type = VR_ANTI_RANGE;
8250 *vr0min = min;
8251 *vr0max = max;
8253 else
8254 *vr0max = vr1max;
8256 else
8257 *vr0max = vr1max;
8259 else
8261 /* If the result can be an anti-range, create one. */
8262 if (TREE_CODE (vr1max) == INTEGER_CST
8263 && TREE_CODE (*vr0min) == INTEGER_CST
8264 && vrp_val_is_min (vr1min)
8265 && vrp_val_is_max (*vr0max))
8267 tree min = int_const_binop (PLUS_EXPR,
8268 vr1max,
8269 build_int_cst (TREE_TYPE (vr1max), 1));
8270 tree max = int_const_binop (MINUS_EXPR,
8271 *vr0min,
8272 build_int_cst (TREE_TYPE (*vr0min), 1));
8273 if (!operand_less_p (max, min))
8275 *vr0type = VR_ANTI_RANGE;
8276 *vr0min = min;
8277 *vr0max = max;
8279 else
8280 *vr0min = vr1min;
8282 else
8283 *vr0min = vr1min;
8286 else
8287 gcc_unreachable ();
8289 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8290 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8292 /* [ ( ) ] or [( ) ] or [ ( )] */
8293 if (*vr0type == VR_RANGE
8294 && vr1type == VR_RANGE)
8296 else if (*vr0type == VR_ANTI_RANGE
8297 && vr1type == VR_ANTI_RANGE)
8299 *vr0type = vr1type;
8300 *vr0min = vr1min;
8301 *vr0max = vr1max;
8303 else if (*vr0type == VR_ANTI_RANGE
8304 && vr1type == VR_RANGE)
8306 /* Arbitrarily choose the right or left gap. */
8307 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
8308 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8309 build_int_cst (TREE_TYPE (vr1min), 1));
8310 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
8311 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8312 build_int_cst (TREE_TYPE (vr1max), 1));
8313 else
8314 goto give_up;
8316 else if (*vr0type == VR_RANGE
8317 && vr1type == VR_ANTI_RANGE)
8318 /* The result covers everything. */
8319 goto give_up;
8320 else
8321 gcc_unreachable ();
8323 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8324 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8326 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8327 if (*vr0type == VR_RANGE
8328 && vr1type == VR_RANGE)
8330 *vr0type = vr1type;
8331 *vr0min = vr1min;
8332 *vr0max = vr1max;
8334 else if (*vr0type == VR_ANTI_RANGE
8335 && vr1type == VR_ANTI_RANGE)
8337 else if (*vr0type == VR_RANGE
8338 && vr1type == VR_ANTI_RANGE)
8340 *vr0type = VR_ANTI_RANGE;
8341 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
8343 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8344 build_int_cst (TREE_TYPE (*vr0min), 1));
8345 *vr0min = vr1min;
8347 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
8349 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8350 build_int_cst (TREE_TYPE (*vr0max), 1));
8351 *vr0max = vr1max;
8353 else
8354 goto give_up;
8356 else if (*vr0type == VR_ANTI_RANGE
8357 && vr1type == VR_RANGE)
8358 /* The result covers everything. */
8359 goto give_up;
8360 else
8361 gcc_unreachable ();
8363 else if ((operand_less_p (vr1min, *vr0max) == 1
8364 || operand_equal_p (vr1min, *vr0max, 0))
8365 && operand_less_p (*vr0min, vr1min) == 1
8366 && operand_less_p (*vr0max, vr1max) == 1)
8368 /* [ ( ] ) or [ ]( ) */
8369 if (*vr0type == VR_RANGE
8370 && vr1type == VR_RANGE)
8371 *vr0max = vr1max;
8372 else if (*vr0type == VR_ANTI_RANGE
8373 && vr1type == VR_ANTI_RANGE)
8374 *vr0min = vr1min;
8375 else if (*vr0type == VR_ANTI_RANGE
8376 && vr1type == VR_RANGE)
8378 if (TREE_CODE (vr1min) == INTEGER_CST)
8379 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8380 build_int_cst (TREE_TYPE (vr1min), 1));
8381 else
8382 goto give_up;
8384 else if (*vr0type == VR_RANGE
8385 && vr1type == VR_ANTI_RANGE)
8387 if (TREE_CODE (*vr0max) == INTEGER_CST)
8389 *vr0type = vr1type;
8390 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8391 build_int_cst (TREE_TYPE (*vr0max), 1));
8392 *vr0max = vr1max;
8394 else
8395 goto give_up;
8397 else
8398 gcc_unreachable ();
8400 else if ((operand_less_p (*vr0min, vr1max) == 1
8401 || operand_equal_p (*vr0min, vr1max, 0))
8402 && operand_less_p (vr1min, *vr0min) == 1
8403 && operand_less_p (vr1max, *vr0max) == 1)
8405 /* ( [ ) ] or ( )[ ] */
8406 if (*vr0type == VR_RANGE
8407 && vr1type == VR_RANGE)
8408 *vr0min = vr1min;
8409 else if (*vr0type == VR_ANTI_RANGE
8410 && vr1type == VR_ANTI_RANGE)
8411 *vr0max = vr1max;
8412 else if (*vr0type == VR_ANTI_RANGE
8413 && vr1type == VR_RANGE)
8415 if (TREE_CODE (vr1max) == INTEGER_CST)
8416 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8417 build_int_cst (TREE_TYPE (vr1max), 1));
8418 else
8419 goto give_up;
8421 else if (*vr0type == VR_RANGE
8422 && vr1type == VR_ANTI_RANGE)
8424 if (TREE_CODE (*vr0min) == INTEGER_CST)
8426 *vr0type = vr1type;
8427 *vr0min = vr1min;
8428 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8429 build_int_cst (TREE_TYPE (*vr0min), 1));
8431 else
8432 goto give_up;
8434 else
8435 gcc_unreachable ();
8437 else
8438 goto give_up;
8440 return;
8442 give_up:
8443 *vr0type = VR_VARYING;
8444 *vr0min = NULL_TREE;
8445 *vr0max = NULL_TREE;
8448 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8449 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8450 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8451 possible such range. The resulting range is not canonicalized. */
8453 static void
8454 intersect_ranges (enum value_range_type *vr0type,
8455 tree *vr0min, tree *vr0max,
8456 enum value_range_type vr1type,
8457 tree vr1min, tree vr1max)
8459 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8460 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8462 /* [] is vr0, () is vr1 in the following classification comments. */
8463 if (mineq && maxeq)
8465 /* [( )] */
8466 if (*vr0type == vr1type)
8467 /* Nothing to do for equal ranges. */
8469 else if ((*vr0type == VR_RANGE
8470 && vr1type == VR_ANTI_RANGE)
8471 || (*vr0type == VR_ANTI_RANGE
8472 && vr1type == VR_RANGE))
8474 /* For anti-range with range intersection the result is empty. */
8475 *vr0type = VR_UNDEFINED;
8476 *vr0min = NULL_TREE;
8477 *vr0max = NULL_TREE;
8479 else
8480 gcc_unreachable ();
8482 else if (operand_less_p (*vr0max, vr1min) == 1
8483 || operand_less_p (vr1max, *vr0min) == 1)
8485 /* [ ] ( ) or ( ) [ ]
8486 If the ranges have an empty intersection, the result of the
8487 intersect operation is the range for intersecting an
8488 anti-range with a range or empty when intersecting two ranges. */
8489 if (*vr0type == VR_RANGE
8490 && vr1type == VR_ANTI_RANGE)
8492 else if (*vr0type == VR_ANTI_RANGE
8493 && vr1type == VR_RANGE)
8495 *vr0type = vr1type;
8496 *vr0min = vr1min;
8497 *vr0max = vr1max;
8499 else if (*vr0type == VR_RANGE
8500 && vr1type == VR_RANGE)
8502 *vr0type = VR_UNDEFINED;
8503 *vr0min = NULL_TREE;
8504 *vr0max = NULL_TREE;
8506 else if (*vr0type == VR_ANTI_RANGE
8507 && vr1type == VR_ANTI_RANGE)
8509 /* If the anti-ranges are adjacent to each other merge them. */
8510 if (TREE_CODE (*vr0max) == INTEGER_CST
8511 && TREE_CODE (vr1min) == INTEGER_CST
8512 && operand_less_p (*vr0max, vr1min) == 1
8513 && integer_onep (int_const_binop (MINUS_EXPR,
8514 vr1min, *vr0max)))
8515 *vr0max = vr1max;
8516 else if (TREE_CODE (vr1max) == INTEGER_CST
8517 && TREE_CODE (*vr0min) == INTEGER_CST
8518 && operand_less_p (vr1max, *vr0min) == 1
8519 && integer_onep (int_const_binop (MINUS_EXPR,
8520 *vr0min, vr1max)))
8521 *vr0min = vr1min;
8522 /* Else arbitrarily take VR0. */
8525 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8526 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8528 /* [ ( ) ] or [( ) ] or [ ( )] */
8529 if (*vr0type == VR_RANGE
8530 && vr1type == VR_RANGE)
8532 /* If both are ranges the result is the inner one. */
8533 *vr0type = vr1type;
8534 *vr0min = vr1min;
8535 *vr0max = vr1max;
8537 else if (*vr0type == VR_RANGE
8538 && vr1type == VR_ANTI_RANGE)
8540 /* Choose the right gap if the left one is empty. */
8541 if (mineq)
8543 if (TREE_CODE (vr1max) != INTEGER_CST)
8544 *vr0min = vr1max;
8545 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
8546 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
8547 *vr0min
8548 = int_const_binop (MINUS_EXPR, vr1max,
8549 build_int_cst (TREE_TYPE (vr1max), -1));
8550 else
8551 *vr0min
8552 = int_const_binop (PLUS_EXPR, vr1max,
8553 build_int_cst (TREE_TYPE (vr1max), 1));
8555 /* Choose the left gap if the right one is empty. */
8556 else if (maxeq)
8558 if (TREE_CODE (vr1min) != INTEGER_CST)
8559 *vr0max = vr1min;
8560 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
8561 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
8562 *vr0max
8563 = int_const_binop (PLUS_EXPR, vr1min,
8564 build_int_cst (TREE_TYPE (vr1min), -1));
8565 else
8566 *vr0max
8567 = int_const_binop (MINUS_EXPR, vr1min,
8568 build_int_cst (TREE_TYPE (vr1min), 1));
8570 /* Choose the anti-range if the range is effectively varying. */
8571 else if (vrp_val_is_min (*vr0min)
8572 && vrp_val_is_max (*vr0max))
8574 *vr0type = vr1type;
8575 *vr0min = vr1min;
8576 *vr0max = vr1max;
8578 /* Else choose the range. */
8580 else if (*vr0type == VR_ANTI_RANGE
8581 && vr1type == VR_ANTI_RANGE)
8582 /* If both are anti-ranges the result is the outer one. */
8584 else if (*vr0type == VR_ANTI_RANGE
8585 && vr1type == VR_RANGE)
8587 /* The intersection is empty. */
8588 *vr0type = VR_UNDEFINED;
8589 *vr0min = NULL_TREE;
8590 *vr0max = NULL_TREE;
8592 else
8593 gcc_unreachable ();
8595 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8596 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8598 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8599 if (*vr0type == VR_RANGE
8600 && vr1type == VR_RANGE)
8601 /* Choose the inner range. */
8603 else if (*vr0type == VR_ANTI_RANGE
8604 && vr1type == VR_RANGE)
8606 /* Choose the right gap if the left is empty. */
8607 if (mineq)
8609 *vr0type = VR_RANGE;
8610 if (TREE_CODE (*vr0max) != INTEGER_CST)
8611 *vr0min = *vr0max;
8612 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
8613 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
8614 *vr0min
8615 = int_const_binop (MINUS_EXPR, *vr0max,
8616 build_int_cst (TREE_TYPE (*vr0max), -1));
8617 else
8618 *vr0min
8619 = int_const_binop (PLUS_EXPR, *vr0max,
8620 build_int_cst (TREE_TYPE (*vr0max), 1));
8621 *vr0max = vr1max;
8623 /* Choose the left gap if the right is empty. */
8624 else if (maxeq)
8626 *vr0type = VR_RANGE;
8627 if (TREE_CODE (*vr0min) != INTEGER_CST)
8628 *vr0max = *vr0min;
8629 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
8630 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
8631 *vr0max
8632 = int_const_binop (PLUS_EXPR, *vr0min,
8633 build_int_cst (TREE_TYPE (*vr0min), -1));
8634 else
8635 *vr0max
8636 = int_const_binop (MINUS_EXPR, *vr0min,
8637 build_int_cst (TREE_TYPE (*vr0min), 1));
8638 *vr0min = vr1min;
8640 /* Choose the anti-range if the range is effectively varying. */
8641 else if (vrp_val_is_min (vr1min)
8642 && vrp_val_is_max (vr1max))
8644 /* Choose the anti-range if it is ~[0,0], that range is special
8645 enough to special case when vr1's range is relatively wide. */
8646 else if (*vr0min == *vr0max
8647 && integer_zerop (*vr0min)
8648 && (TYPE_PRECISION (TREE_TYPE (*vr0min))
8649 == TYPE_PRECISION (ptr_type_node))
8650 && TREE_CODE (vr1max) == INTEGER_CST
8651 && TREE_CODE (vr1min) == INTEGER_CST
8652 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
8653 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
8655 /* Else choose the range. */
8656 else
8658 *vr0type = vr1type;
8659 *vr0min = vr1min;
8660 *vr0max = vr1max;
8663 else if (*vr0type == VR_ANTI_RANGE
8664 && vr1type == VR_ANTI_RANGE)
8666 /* If both are anti-ranges the result is the outer one. */
8667 *vr0type = vr1type;
8668 *vr0min = vr1min;
8669 *vr0max = vr1max;
8671 else if (vr1type == VR_ANTI_RANGE
8672 && *vr0type == VR_RANGE)
8674 /* The intersection is empty. */
8675 *vr0type = VR_UNDEFINED;
8676 *vr0min = NULL_TREE;
8677 *vr0max = NULL_TREE;
8679 else
8680 gcc_unreachable ();
8682 else if ((operand_less_p (vr1min, *vr0max) == 1
8683 || operand_equal_p (vr1min, *vr0max, 0))
8684 && operand_less_p (*vr0min, vr1min) == 1)
8686 /* [ ( ] ) or [ ]( ) */
8687 if (*vr0type == VR_ANTI_RANGE
8688 && vr1type == VR_ANTI_RANGE)
8689 *vr0max = vr1max;
8690 else if (*vr0type == VR_RANGE
8691 && vr1type == VR_RANGE)
8692 *vr0min = vr1min;
8693 else if (*vr0type == VR_RANGE
8694 && vr1type == VR_ANTI_RANGE)
8696 if (TREE_CODE (vr1min) == INTEGER_CST)
8697 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8698 build_int_cst (TREE_TYPE (vr1min), 1));
8699 else
8700 *vr0max = vr1min;
8702 else if (*vr0type == VR_ANTI_RANGE
8703 && vr1type == VR_RANGE)
8705 *vr0type = VR_RANGE;
8706 if (TREE_CODE (*vr0max) == INTEGER_CST)
8707 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8708 build_int_cst (TREE_TYPE (*vr0max), 1));
8709 else
8710 *vr0min = *vr0max;
8711 *vr0max = vr1max;
8713 else
8714 gcc_unreachable ();
8716 else if ((operand_less_p (*vr0min, vr1max) == 1
8717 || operand_equal_p (*vr0min, vr1max, 0))
8718 && operand_less_p (vr1min, *vr0min) == 1)
8720 /* ( [ ) ] or ( )[ ] */
8721 if (*vr0type == VR_ANTI_RANGE
8722 && vr1type == VR_ANTI_RANGE)
8723 *vr0min = vr1min;
8724 else if (*vr0type == VR_RANGE
8725 && vr1type == VR_RANGE)
8726 *vr0max = vr1max;
8727 else if (*vr0type == VR_RANGE
8728 && vr1type == VR_ANTI_RANGE)
8730 if (TREE_CODE (vr1max) == INTEGER_CST)
8731 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8732 build_int_cst (TREE_TYPE (vr1max), 1));
8733 else
8734 *vr0min = vr1max;
8736 else if (*vr0type == VR_ANTI_RANGE
8737 && vr1type == VR_RANGE)
8739 *vr0type = VR_RANGE;
8740 if (TREE_CODE (*vr0min) == INTEGER_CST)
8741 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8742 build_int_cst (TREE_TYPE (*vr0min), 1));
8743 else
8744 *vr0max = *vr0min;
8745 *vr0min = vr1min;
8747 else
8748 gcc_unreachable ();
8751 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
8752 result for the intersection. That's always a conservative
8753 correct estimate unless VR1 is a constant singleton range
8754 in which case we choose that. */
8755 if (vr1type == VR_RANGE
8756 && is_gimple_min_invariant (vr1min)
8757 && vrp_operand_equal_p (vr1min, vr1max))
8759 *vr0type = vr1type;
8760 *vr0min = vr1min;
8761 *vr0max = vr1max;
8764 return;
8768 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
8769 in *VR0. This may not be the smallest possible such range. */
8771 static void
8772 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
8774 value_range saved;
8776 /* If either range is VR_VARYING the other one wins. */
8777 if (vr1->type == VR_VARYING)
8778 return;
8779 if (vr0->type == VR_VARYING)
8781 copy_value_range (vr0, vr1);
8782 return;
8785 /* When either range is VR_UNDEFINED the resulting range is
8786 VR_UNDEFINED, too. */
8787 if (vr0->type == VR_UNDEFINED)
8788 return;
8789 if (vr1->type == VR_UNDEFINED)
8791 set_value_range_to_undefined (vr0);
8792 return;
8795 /* Save the original vr0 so we can return it as conservative intersection
8796 result when our worker turns things to varying. */
8797 saved = *vr0;
8798 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
8799 vr1->type, vr1->min, vr1->max);
8800 /* Make sure to canonicalize the result though as the inversion of a
8801 VR_RANGE can still be a VR_RANGE. */
8802 set_and_canonicalize_value_range (vr0, vr0->type,
8803 vr0->min, vr0->max, vr0->equiv);
8804 /* If that failed, use the saved original VR0. */
8805 if (vr0->type == VR_VARYING)
8807 *vr0 = saved;
8808 return;
8810 /* If the result is VR_UNDEFINED there is no need to mess with
8811 the equivalencies. */
8812 if (vr0->type == VR_UNDEFINED)
8813 return;
8815 /* The resulting set of equivalences for range intersection is the union of
8816 the two sets. */
8817 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8818 bitmap_ior_into (vr0->equiv, vr1->equiv);
8819 else if (vr1->equiv && !vr0->equiv)
8821 /* All equivalence bitmaps are allocated from the same obstack. So
8822 we can use the obstack associated with VR to allocate vr0->equiv. */
8823 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
8824 bitmap_copy (vr0->equiv, vr1->equiv);
8828 void
8829 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
8831 if (dump_file && (dump_flags & TDF_DETAILS))
8833 fprintf (dump_file, "Intersecting\n ");
8834 dump_value_range (dump_file, vr0);
8835 fprintf (dump_file, "\nand\n ");
8836 dump_value_range (dump_file, vr1);
8837 fprintf (dump_file, "\n");
8839 vrp_intersect_ranges_1 (vr0, vr1);
8840 if (dump_file && (dump_flags & TDF_DETAILS))
8842 fprintf (dump_file, "to\n ");
8843 dump_value_range (dump_file, vr0);
8844 fprintf (dump_file, "\n");
8848 /* Meet operation for value ranges. Given two value ranges VR0 and
8849 VR1, store in VR0 a range that contains both VR0 and VR1. This
8850 may not be the smallest possible such range. */
8852 static void
8853 vrp_meet_1 (value_range *vr0, const value_range *vr1)
8855 value_range saved;
8857 if (vr0->type == VR_UNDEFINED)
8859 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
8860 return;
8863 if (vr1->type == VR_UNDEFINED)
8865 /* VR0 already has the resulting range. */
8866 return;
8869 if (vr0->type == VR_VARYING)
8871 /* Nothing to do. VR0 already has the resulting range. */
8872 return;
8875 if (vr1->type == VR_VARYING)
8877 set_value_range_to_varying (vr0);
8878 return;
8881 saved = *vr0;
8882 union_ranges (&vr0->type, &vr0->min, &vr0->max,
8883 vr1->type, vr1->min, vr1->max);
8884 if (vr0->type == VR_VARYING)
8886 /* Failed to find an efficient meet. Before giving up and setting
8887 the result to VARYING, see if we can at least derive a useful
8888 anti-range. FIXME, all this nonsense about distinguishing
8889 anti-ranges from ranges is necessary because of the odd
8890 semantics of range_includes_zero_p and friends. */
8891 if (((saved.type == VR_RANGE
8892 && range_includes_zero_p (saved.min, saved.max) == 0)
8893 || (saved.type == VR_ANTI_RANGE
8894 && range_includes_zero_p (saved.min, saved.max) == 1))
8895 && ((vr1->type == VR_RANGE
8896 && range_includes_zero_p (vr1->min, vr1->max) == 0)
8897 || (vr1->type == VR_ANTI_RANGE
8898 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
8900 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
8902 /* Since this meet operation did not result from the meeting of
8903 two equivalent names, VR0 cannot have any equivalences. */
8904 if (vr0->equiv)
8905 bitmap_clear (vr0->equiv);
8906 return;
8909 set_value_range_to_varying (vr0);
8910 return;
8912 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
8913 vr0->equiv);
8914 if (vr0->type == VR_VARYING)
8915 return;
8917 /* The resulting set of equivalences is always the intersection of
8918 the two sets. */
8919 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8920 bitmap_and_into (vr0->equiv, vr1->equiv);
8921 else if (vr0->equiv && !vr1->equiv)
8922 bitmap_clear (vr0->equiv);
8925 void
8926 vrp_meet (value_range *vr0, const value_range *vr1)
8928 if (dump_file && (dump_flags & TDF_DETAILS))
8930 fprintf (dump_file, "Meeting\n ");
8931 dump_value_range (dump_file, vr0);
8932 fprintf (dump_file, "\nand\n ");
8933 dump_value_range (dump_file, vr1);
8934 fprintf (dump_file, "\n");
8936 vrp_meet_1 (vr0, vr1);
8937 if (dump_file && (dump_flags & TDF_DETAILS))
8939 fprintf (dump_file, "to\n ");
8940 dump_value_range (dump_file, vr0);
8941 fprintf (dump_file, "\n");
8946 /* Visit all arguments for PHI node PHI that flow through executable
8947 edges. If a valid value range can be derived from all the incoming
8948 value ranges, set a new range in VR_RESULT. */
8950 void
8951 vr_values::extract_range_from_phi_node (gphi *phi, value_range *vr_result)
8953 size_t i;
8954 tree lhs = PHI_RESULT (phi);
8955 value_range *lhs_vr = get_value_range (lhs);
8956 bool first = true;
8957 int edges, old_edges;
8958 struct loop *l;
8960 if (dump_file && (dump_flags & TDF_DETAILS))
8962 fprintf (dump_file, "\nVisiting PHI node: ");
8963 print_gimple_stmt (dump_file, phi, 0, dump_flags);
8966 bool may_simulate_backedge_again = false;
8967 edges = 0;
8968 for (i = 0; i < gimple_phi_num_args (phi); i++)
8970 edge e = gimple_phi_arg_edge (phi, i);
8972 if (dump_file && (dump_flags & TDF_DETAILS))
8974 fprintf (dump_file,
8975 " Argument #%d (%d -> %d %sexecutable)\n",
8976 (int) i, e->src->index, e->dest->index,
8977 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
8980 if (e->flags & EDGE_EXECUTABLE)
8982 tree arg = PHI_ARG_DEF (phi, i);
8983 value_range vr_arg;
8985 ++edges;
8987 if (TREE_CODE (arg) == SSA_NAME)
8989 /* See if we are eventually going to change one of the args. */
8990 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
8991 if (! gimple_nop_p (def_stmt)
8992 && prop_simulate_again_p (def_stmt)
8993 && e->flags & EDGE_DFS_BACK)
8994 may_simulate_backedge_again = true;
8996 vr_arg = *(get_value_range (arg));
8997 /* Do not allow equivalences or symbolic ranges to leak in from
8998 backedges. That creates invalid equivalencies.
8999 See PR53465 and PR54767. */
9000 if (e->flags & EDGE_DFS_BACK)
9002 if (vr_arg.type == VR_RANGE
9003 || vr_arg.type == VR_ANTI_RANGE)
9005 vr_arg.equiv = NULL;
9006 if (symbolic_range_p (&vr_arg))
9008 vr_arg.type = VR_VARYING;
9009 vr_arg.min = NULL_TREE;
9010 vr_arg.max = NULL_TREE;
9014 else
9016 /* If the non-backedge arguments range is VR_VARYING then
9017 we can still try recording a simple equivalence. */
9018 if (vr_arg.type == VR_VARYING)
9020 vr_arg.type = VR_RANGE;
9021 vr_arg.min = arg;
9022 vr_arg.max = arg;
9023 vr_arg.equiv = NULL;
9027 else
9029 if (TREE_OVERFLOW_P (arg))
9030 arg = drop_tree_overflow (arg);
9032 vr_arg.type = VR_RANGE;
9033 vr_arg.min = arg;
9034 vr_arg.max = arg;
9035 vr_arg.equiv = NULL;
9038 if (dump_file && (dump_flags & TDF_DETAILS))
9040 fprintf (dump_file, "\t");
9041 print_generic_expr (dump_file, arg, dump_flags);
9042 fprintf (dump_file, ": ");
9043 dump_value_range (dump_file, &vr_arg);
9044 fprintf (dump_file, "\n");
9047 if (first)
9048 copy_value_range (vr_result, &vr_arg);
9049 else
9050 vrp_meet (vr_result, &vr_arg);
9051 first = false;
9053 if (vr_result->type == VR_VARYING)
9054 break;
9058 if (vr_result->type == VR_VARYING)
9059 goto varying;
9060 else if (vr_result->type == VR_UNDEFINED)
9061 goto update_range;
9063 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
9064 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
9066 /* To prevent infinite iterations in the algorithm, derive ranges
9067 when the new value is slightly bigger or smaller than the
9068 previous one. We don't do this if we have seen a new executable
9069 edge; this helps us avoid an infinity for conditionals
9070 which are not in a loop. If the old value-range was VR_UNDEFINED
9071 use the updated range and iterate one more time. If we will not
9072 simulate this PHI again via the backedge allow us to iterate. */
9073 if (edges > 0
9074 && gimple_phi_num_args (phi) > 1
9075 && edges == old_edges
9076 && lhs_vr->type != VR_UNDEFINED
9077 && may_simulate_backedge_again)
9079 /* Compare old and new ranges, fall back to varying if the
9080 values are not comparable. */
9081 int cmp_min = compare_values (lhs_vr->min, vr_result->min);
9082 if (cmp_min == -2)
9083 goto varying;
9084 int cmp_max = compare_values (lhs_vr->max, vr_result->max);
9085 if (cmp_max == -2)
9086 goto varying;
9088 /* For non VR_RANGE or for pointers fall back to varying if
9089 the range changed. */
9090 if ((lhs_vr->type != VR_RANGE || vr_result->type != VR_RANGE
9091 || POINTER_TYPE_P (TREE_TYPE (lhs)))
9092 && (cmp_min != 0 || cmp_max != 0))
9093 goto varying;
9095 /* If the new minimum is larger than the previous one
9096 retain the old value. If the new minimum value is smaller
9097 than the previous one and not -INF go all the way to -INF + 1.
9098 In the first case, to avoid infinite bouncing between different
9099 minimums, and in the other case to avoid iterating millions of
9100 times to reach -INF. Going to -INF + 1 also lets the following
9101 iteration compute whether there will be any overflow, at the
9102 expense of one additional iteration. */
9103 if (cmp_min < 0)
9104 vr_result->min = lhs_vr->min;
9105 else if (cmp_min > 0
9106 && !vrp_val_is_min (vr_result->min))
9107 vr_result->min
9108 = int_const_binop (PLUS_EXPR,
9109 vrp_val_min (TREE_TYPE (vr_result->min)),
9110 build_int_cst (TREE_TYPE (vr_result->min), 1));
9112 /* Similarly for the maximum value. */
9113 if (cmp_max > 0)
9114 vr_result->max = lhs_vr->max;
9115 else if (cmp_max < 0
9116 && !vrp_val_is_max (vr_result->max))
9117 vr_result->max
9118 = int_const_binop (MINUS_EXPR,
9119 vrp_val_max (TREE_TYPE (vr_result->min)),
9120 build_int_cst (TREE_TYPE (vr_result->min), 1));
9122 /* If we dropped either bound to +-INF then if this is a loop
9123 PHI node SCEV may known more about its value-range. */
9124 if (cmp_min > 0 || cmp_min < 0
9125 || cmp_max < 0 || cmp_max > 0)
9126 goto scev_check;
9128 goto infinite_check;
9131 goto update_range;
9133 varying:
9134 set_value_range_to_varying (vr_result);
9136 scev_check:
9137 /* If this is a loop PHI node SCEV may known more about its value-range.
9138 scev_check can be reached from two paths, one is a fall through from above
9139 "varying" label, the other is direct goto from code block which tries to
9140 avoid infinite simulation. */
9141 if ((l = loop_containing_stmt (phi))
9142 && l->header == gimple_bb (phi))
9143 adjust_range_with_scev (vr_result, l, phi, lhs);
9145 infinite_check:
9146 /* If we will end up with a (-INF, +INF) range, set it to
9147 VARYING. Same if the previous max value was invalid for
9148 the type and we end up with vr_result.min > vr_result.max. */
9149 if ((vr_result->type == VR_RANGE || vr_result->type == VR_ANTI_RANGE)
9150 && !((vrp_val_is_max (vr_result->max) && vrp_val_is_min (vr_result->min))
9151 || compare_values (vr_result->min, vr_result->max) > 0))
9153 else
9154 set_value_range_to_varying (vr_result);
9156 /* If the new range is different than the previous value, keep
9157 iterating. */
9158 update_range:
9159 return;
9162 /* Visit all arguments for PHI node PHI that flow through executable
9163 edges. If a valid value range can be derived from all the incoming
9164 value ranges, set a new range for the LHS of PHI. */
9166 enum ssa_prop_result
9167 vrp_prop::visit_phi (gphi *phi)
9169 tree lhs = PHI_RESULT (phi);
9170 value_range vr_result = VR_INITIALIZER;
9171 extract_range_from_phi_node (phi, &vr_result);
9172 if (update_value_range (lhs, &vr_result))
9174 if (dump_file && (dump_flags & TDF_DETAILS))
9176 fprintf (dump_file, "Found new range for ");
9177 print_generic_expr (dump_file, lhs);
9178 fprintf (dump_file, ": ");
9179 dump_value_range (dump_file, &vr_result);
9180 fprintf (dump_file, "\n");
9183 if (vr_result.type == VR_VARYING)
9184 return SSA_PROP_VARYING;
9186 return SSA_PROP_INTERESTING;
9189 /* Nothing changed, don't add outgoing edges. */
9190 return SSA_PROP_NOT_INTERESTING;
9193 /* Simplify boolean operations if the source is known
9194 to be already a boolean. */
9195 bool
9196 vr_values::simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi,
9197 gimple *stmt)
9199 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9200 tree lhs, op0, op1;
9201 bool need_conversion;
9203 /* We handle only !=/== case here. */
9204 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
9206 op0 = gimple_assign_rhs1 (stmt);
9207 if (!op_with_boolean_value_range_p (op0))
9208 return false;
9210 op1 = gimple_assign_rhs2 (stmt);
9211 if (!op_with_boolean_value_range_p (op1))
9212 return false;
9214 /* Reduce number of cases to handle to NE_EXPR. As there is no
9215 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
9216 if (rhs_code == EQ_EXPR)
9218 if (TREE_CODE (op1) == INTEGER_CST)
9219 op1 = int_const_binop (BIT_XOR_EXPR, op1,
9220 build_int_cst (TREE_TYPE (op1), 1));
9221 else
9222 return false;
9225 lhs = gimple_assign_lhs (stmt);
9226 need_conversion
9227 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
9229 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
9230 if (need_conversion
9231 && !TYPE_UNSIGNED (TREE_TYPE (op0))
9232 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
9233 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
9234 return false;
9236 /* For A != 0 we can substitute A itself. */
9237 if (integer_zerop (op1))
9238 gimple_assign_set_rhs_with_ops (gsi,
9239 need_conversion
9240 ? NOP_EXPR : TREE_CODE (op0), op0);
9241 /* For A != B we substitute A ^ B. Either with conversion. */
9242 else if (need_conversion)
9244 tree tem = make_ssa_name (TREE_TYPE (op0));
9245 gassign *newop
9246 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
9247 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
9248 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
9249 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
9250 set_range_info (tem, VR_RANGE,
9251 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
9252 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
9253 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
9255 /* Or without. */
9256 else
9257 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
9258 update_stmt (gsi_stmt (*gsi));
9259 fold_stmt (gsi, follow_single_use_edges);
9261 return true;
9264 /* Simplify a division or modulo operator to a right shift or bitwise and
9265 if the first operand is unsigned or is greater than zero and the second
9266 operand is an exact power of two. For TRUNC_MOD_EXPR op0 % op1 with
9267 constant op1 (op1min = op1) or with op1 in [op1min, op1max] range,
9268 optimize it into just op0 if op0's range is known to be a subset of
9269 [-op1min + 1, op1min - 1] for signed and [0, op1min - 1] for unsigned
9270 modulo. */
9272 bool
9273 vr_values::simplify_div_or_mod_using_ranges (gimple_stmt_iterator *gsi,
9274 gimple *stmt)
9276 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9277 tree val = NULL;
9278 tree op0 = gimple_assign_rhs1 (stmt);
9279 tree op1 = gimple_assign_rhs2 (stmt);
9280 tree op0min = NULL_TREE, op0max = NULL_TREE;
9281 tree op1min = op1;
9282 value_range *vr = NULL;
9284 if (TREE_CODE (op0) == INTEGER_CST)
9286 op0min = op0;
9287 op0max = op0;
9289 else
9291 vr = get_value_range (op0);
9292 if (range_int_cst_p (vr))
9294 op0min = vr->min;
9295 op0max = vr->max;
9299 if (rhs_code == TRUNC_MOD_EXPR
9300 && TREE_CODE (op1) == SSA_NAME)
9302 value_range *vr1 = get_value_range (op1);
9303 if (range_int_cst_p (vr1))
9304 op1min = vr1->min;
9306 if (rhs_code == TRUNC_MOD_EXPR
9307 && TREE_CODE (op1min) == INTEGER_CST
9308 && tree_int_cst_sgn (op1min) == 1
9309 && op0max
9310 && tree_int_cst_lt (op0max, op1min))
9312 if (TYPE_UNSIGNED (TREE_TYPE (op0))
9313 || tree_int_cst_sgn (op0min) >= 0
9314 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1min), op1min),
9315 op0min))
9317 /* If op0 already has the range op0 % op1 has,
9318 then TRUNC_MOD_EXPR won't change anything. */
9319 gimple_assign_set_rhs_from_tree (gsi, op0);
9320 return true;
9324 if (TREE_CODE (op0) != SSA_NAME)
9325 return false;
9327 if (!integer_pow2p (op1))
9329 /* X % -Y can be only optimized into X % Y either if
9330 X is not INT_MIN, or Y is not -1. Fold it now, as after
9331 remove_range_assertions the range info might be not available
9332 anymore. */
9333 if (rhs_code == TRUNC_MOD_EXPR
9334 && fold_stmt (gsi, follow_single_use_edges))
9335 return true;
9336 return false;
9339 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
9340 val = integer_one_node;
9341 else
9343 bool sop = false;
9345 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
9347 if (val
9348 && sop
9349 && integer_onep (val)
9350 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9352 location_t location;
9354 if (!gimple_has_location (stmt))
9355 location = input_location;
9356 else
9357 location = gimple_location (stmt);
9358 warning_at (location, OPT_Wstrict_overflow,
9359 "assuming signed overflow does not occur when "
9360 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
9364 if (val && integer_onep (val))
9366 tree t;
9368 if (rhs_code == TRUNC_DIV_EXPR)
9370 t = build_int_cst (integer_type_node, tree_log2 (op1));
9371 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
9372 gimple_assign_set_rhs1 (stmt, op0);
9373 gimple_assign_set_rhs2 (stmt, t);
9375 else
9377 t = build_int_cst (TREE_TYPE (op1), 1);
9378 t = int_const_binop (MINUS_EXPR, op1, t);
9379 t = fold_convert (TREE_TYPE (op0), t);
9381 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
9382 gimple_assign_set_rhs1 (stmt, op0);
9383 gimple_assign_set_rhs2 (stmt, t);
9386 update_stmt (stmt);
9387 fold_stmt (gsi, follow_single_use_edges);
9388 return true;
9391 return false;
9394 /* Simplify a min or max if the ranges of the two operands are
9395 disjoint. Return true if we do simplify. */
9397 bool
9398 vr_values::simplify_min_or_max_using_ranges (gimple_stmt_iterator *gsi,
9399 gimple *stmt)
9401 tree op0 = gimple_assign_rhs1 (stmt);
9402 tree op1 = gimple_assign_rhs2 (stmt);
9403 bool sop = false;
9404 tree val;
9406 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9407 (LE_EXPR, op0, op1, &sop));
9408 if (!val)
9410 sop = false;
9411 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9412 (LT_EXPR, op0, op1, &sop));
9415 if (val)
9417 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9419 location_t location;
9421 if (!gimple_has_location (stmt))
9422 location = input_location;
9423 else
9424 location = gimple_location (stmt);
9425 warning_at (location, OPT_Wstrict_overflow,
9426 "assuming signed overflow does not occur when "
9427 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
9430 /* VAL == TRUE -> OP0 < or <= op1
9431 VAL == FALSE -> OP0 > or >= op1. */
9432 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
9433 == integer_zerop (val)) ? op0 : op1;
9434 gimple_assign_set_rhs_from_tree (gsi, res);
9435 return true;
9438 return false;
9441 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
9442 ABS_EXPR. If the operand is <= 0, then simplify the
9443 ABS_EXPR into a NEGATE_EXPR. */
9445 bool
9446 vr_values::simplify_abs_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9448 tree op = gimple_assign_rhs1 (stmt);
9449 value_range *vr = get_value_range (op);
9451 if (vr)
9453 tree val = NULL;
9454 bool sop = false;
9456 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
9457 if (!val)
9459 /* The range is neither <= 0 nor > 0. Now see if it is
9460 either < 0 or >= 0. */
9461 sop = false;
9462 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
9463 &sop);
9466 if (val)
9468 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9470 location_t location;
9472 if (!gimple_has_location (stmt))
9473 location = input_location;
9474 else
9475 location = gimple_location (stmt);
9476 warning_at (location, OPT_Wstrict_overflow,
9477 "assuming signed overflow does not occur when "
9478 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
9481 gimple_assign_set_rhs1 (stmt, op);
9482 if (integer_zerop (val))
9483 gimple_assign_set_rhs_code (stmt, SSA_NAME);
9484 else
9485 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
9486 update_stmt (stmt);
9487 fold_stmt (gsi, follow_single_use_edges);
9488 return true;
9492 return false;
9495 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
9496 If all the bits that are being cleared by & are already
9497 known to be zero from VR, or all the bits that are being
9498 set by | are already known to be one from VR, the bit
9499 operation is redundant. */
9501 bool
9502 vr_values::simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi,
9503 gimple *stmt)
9505 tree op0 = gimple_assign_rhs1 (stmt);
9506 tree op1 = gimple_assign_rhs2 (stmt);
9507 tree op = NULL_TREE;
9508 value_range vr0 = VR_INITIALIZER;
9509 value_range vr1 = VR_INITIALIZER;
9510 wide_int may_be_nonzero0, may_be_nonzero1;
9511 wide_int must_be_nonzero0, must_be_nonzero1;
9512 wide_int mask;
9514 if (TREE_CODE (op0) == SSA_NAME)
9515 vr0 = *(get_value_range (op0));
9516 else if (is_gimple_min_invariant (op0))
9517 set_value_range_to_value (&vr0, op0, NULL);
9518 else
9519 return false;
9521 if (TREE_CODE (op1) == SSA_NAME)
9522 vr1 = *(get_value_range (op1));
9523 else if (is_gimple_min_invariant (op1))
9524 set_value_range_to_value (&vr1, op1, NULL);
9525 else
9526 return false;
9528 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
9529 &must_be_nonzero0))
9530 return false;
9531 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
9532 &must_be_nonzero1))
9533 return false;
9535 switch (gimple_assign_rhs_code (stmt))
9537 case BIT_AND_EXPR:
9538 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
9539 if (mask == 0)
9541 op = op0;
9542 break;
9544 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
9545 if (mask == 0)
9547 op = op1;
9548 break;
9550 break;
9551 case BIT_IOR_EXPR:
9552 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
9553 if (mask == 0)
9555 op = op1;
9556 break;
9558 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
9559 if (mask == 0)
9561 op = op0;
9562 break;
9564 break;
9565 default:
9566 gcc_unreachable ();
9569 if (op == NULL_TREE)
9570 return false;
9572 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
9573 update_stmt (gsi_stmt (*gsi));
9574 return true;
9577 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
9578 a known value range VR.
9580 If there is one and only one value which will satisfy the
9581 conditional, then return that value. Else return NULL.
9583 If signed overflow must be undefined for the value to satisfy
9584 the conditional, then set *STRICT_OVERFLOW_P to true. */
9586 static tree
9587 test_for_singularity (enum tree_code cond_code, tree op0,
9588 tree op1, value_range *vr)
9590 tree min = NULL;
9591 tree max = NULL;
9593 /* Extract minimum/maximum values which satisfy the conditional as it was
9594 written. */
9595 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
9597 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
9599 max = op1;
9600 if (cond_code == LT_EXPR)
9602 tree one = build_int_cst (TREE_TYPE (op0), 1);
9603 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
9604 /* Signal to compare_values_warnv this expr doesn't overflow. */
9605 if (EXPR_P (max))
9606 TREE_NO_WARNING (max) = 1;
9609 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
9611 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
9613 min = op1;
9614 if (cond_code == GT_EXPR)
9616 tree one = build_int_cst (TREE_TYPE (op0), 1);
9617 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
9618 /* Signal to compare_values_warnv this expr doesn't overflow. */
9619 if (EXPR_P (min))
9620 TREE_NO_WARNING (min) = 1;
9624 /* Now refine the minimum and maximum values using any
9625 value range information we have for op0. */
9626 if (min && max)
9628 if (compare_values (vr->min, min) == 1)
9629 min = vr->min;
9630 if (compare_values (vr->max, max) == -1)
9631 max = vr->max;
9633 /* If the new min/max values have converged to a single value,
9634 then there is only one value which can satisfy the condition,
9635 return that value. */
9636 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
9637 return min;
9639 return NULL;
9642 /* Return whether the value range *VR fits in an integer type specified
9643 by PRECISION and UNSIGNED_P. */
9645 static bool
9646 range_fits_type_p (value_range *vr, unsigned dest_precision, signop dest_sgn)
9648 tree src_type;
9649 unsigned src_precision;
9650 widest_int tem;
9651 signop src_sgn;
9653 /* We can only handle integral and pointer types. */
9654 src_type = TREE_TYPE (vr->min);
9655 if (!INTEGRAL_TYPE_P (src_type)
9656 && !POINTER_TYPE_P (src_type))
9657 return false;
9659 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
9660 and so is an identity transform. */
9661 src_precision = TYPE_PRECISION (TREE_TYPE (vr->min));
9662 src_sgn = TYPE_SIGN (src_type);
9663 if ((src_precision < dest_precision
9664 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
9665 || (src_precision == dest_precision && src_sgn == dest_sgn))
9666 return true;
9668 /* Now we can only handle ranges with constant bounds. */
9669 if (vr->type != VR_RANGE
9670 || TREE_CODE (vr->min) != INTEGER_CST
9671 || TREE_CODE (vr->max) != INTEGER_CST)
9672 return false;
9674 /* For sign changes, the MSB of the wide_int has to be clear.
9675 An unsigned value with its MSB set cannot be represented by
9676 a signed wide_int, while a negative value cannot be represented
9677 by an unsigned wide_int. */
9678 if (src_sgn != dest_sgn
9679 && (wi::lts_p (wi::to_wide (vr->min), 0)
9680 || wi::lts_p (wi::to_wide (vr->max), 0)))
9681 return false;
9683 /* Then we can perform the conversion on both ends and compare
9684 the result for equality. */
9685 tem = wi::ext (wi::to_widest (vr->min), dest_precision, dest_sgn);
9686 if (tem != wi::to_widest (vr->min))
9687 return false;
9688 tem = wi::ext (wi::to_widest (vr->max), dest_precision, dest_sgn);
9689 if (tem != wi::to_widest (vr->max))
9690 return false;
9692 return true;
9695 /* Simplify a conditional using a relational operator to an equality
9696 test if the range information indicates only one value can satisfy
9697 the original conditional. */
9699 bool
9700 vr_values::simplify_cond_using_ranges_1 (gcond *stmt)
9702 tree op0 = gimple_cond_lhs (stmt);
9703 tree op1 = gimple_cond_rhs (stmt);
9704 enum tree_code cond_code = gimple_cond_code (stmt);
9706 if (cond_code != NE_EXPR
9707 && cond_code != EQ_EXPR
9708 && TREE_CODE (op0) == SSA_NAME
9709 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9710 && is_gimple_min_invariant (op1))
9712 value_range *vr = get_value_range (op0);
9714 /* If we have range information for OP0, then we might be
9715 able to simplify this conditional. */
9716 if (vr->type == VR_RANGE)
9718 tree new_tree = test_for_singularity (cond_code, op0, op1, vr);
9719 if (new_tree)
9721 if (dump_file)
9723 fprintf (dump_file, "Simplified relational ");
9724 print_gimple_stmt (dump_file, stmt, 0);
9725 fprintf (dump_file, " into ");
9728 gimple_cond_set_code (stmt, EQ_EXPR);
9729 gimple_cond_set_lhs (stmt, op0);
9730 gimple_cond_set_rhs (stmt, new_tree);
9732 update_stmt (stmt);
9734 if (dump_file)
9736 print_gimple_stmt (dump_file, stmt, 0);
9737 fprintf (dump_file, "\n");
9740 return true;
9743 /* Try again after inverting the condition. We only deal
9744 with integral types here, so no need to worry about
9745 issues with inverting FP comparisons. */
9746 new_tree = test_for_singularity
9747 (invert_tree_comparison (cond_code, false),
9748 op0, op1, vr);
9749 if (new_tree)
9751 if (dump_file)
9753 fprintf (dump_file, "Simplified relational ");
9754 print_gimple_stmt (dump_file, stmt, 0);
9755 fprintf (dump_file, " into ");
9758 gimple_cond_set_code (stmt, NE_EXPR);
9759 gimple_cond_set_lhs (stmt, op0);
9760 gimple_cond_set_rhs (stmt, new_tree);
9762 update_stmt (stmt);
9764 if (dump_file)
9766 print_gimple_stmt (dump_file, stmt, 0);
9767 fprintf (dump_file, "\n");
9770 return true;
9774 return false;
9777 /* STMT is a conditional at the end of a basic block.
9779 If the conditional is of the form SSA_NAME op constant and the SSA_NAME
9780 was set via a type conversion, try to replace the SSA_NAME with the RHS
9781 of the type conversion. Doing so makes the conversion dead which helps
9782 subsequent passes. */
9784 void
9785 vr_values::simplify_cond_using_ranges_2 (gcond *stmt)
9787 tree op0 = gimple_cond_lhs (stmt);
9788 tree op1 = gimple_cond_rhs (stmt);
9790 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
9791 see if OP0 was set by a type conversion where the source of
9792 the conversion is another SSA_NAME with a range that fits
9793 into the range of OP0's type.
9795 If so, the conversion is redundant as the earlier SSA_NAME can be
9796 used for the comparison directly if we just massage the constant in the
9797 comparison. */
9798 if (TREE_CODE (op0) == SSA_NAME
9799 && TREE_CODE (op1) == INTEGER_CST)
9801 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
9802 tree innerop;
9804 if (!is_gimple_assign (def_stmt)
9805 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
9806 return;
9808 innerop = gimple_assign_rhs1 (def_stmt);
9810 if (TREE_CODE (innerop) == SSA_NAME
9811 && !POINTER_TYPE_P (TREE_TYPE (innerop))
9812 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
9813 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
9815 value_range *vr = get_value_range (innerop);
9817 if (range_int_cst_p (vr)
9818 && range_fits_type_p (vr,
9819 TYPE_PRECISION (TREE_TYPE (op0)),
9820 TYPE_SIGN (TREE_TYPE (op0)))
9821 && int_fits_type_p (op1, TREE_TYPE (innerop)))
9823 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
9824 gimple_cond_set_lhs (stmt, innerop);
9825 gimple_cond_set_rhs (stmt, newconst);
9826 update_stmt (stmt);
9827 if (dump_file && (dump_flags & TDF_DETAILS))
9829 fprintf (dump_file, "Folded into: ");
9830 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
9831 fprintf (dump_file, "\n");
9838 /* Simplify a switch statement using the value range of the switch
9839 argument. */
9841 bool
9842 vr_values::simplify_switch_using_ranges (gswitch *stmt)
9844 tree op = gimple_switch_index (stmt);
9845 value_range *vr = NULL;
9846 bool take_default;
9847 edge e;
9848 edge_iterator ei;
9849 size_t i = 0, j = 0, n, n2;
9850 tree vec2;
9851 switch_update su;
9852 size_t k = 1, l = 0;
9854 if (TREE_CODE (op) == SSA_NAME)
9856 vr = get_value_range (op);
9858 /* We can only handle integer ranges. */
9859 if ((vr->type != VR_RANGE
9860 && vr->type != VR_ANTI_RANGE)
9861 || symbolic_range_p (vr))
9862 return false;
9864 /* Find case label for min/max of the value range. */
9865 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
9867 else if (TREE_CODE (op) == INTEGER_CST)
9869 take_default = !find_case_label_index (stmt, 1, op, &i);
9870 if (take_default)
9872 i = 1;
9873 j = 0;
9875 else
9877 j = i;
9880 else
9881 return false;
9883 n = gimple_switch_num_labels (stmt);
9885 /* We can truncate the case label ranges that partially overlap with OP's
9886 value range. */
9887 size_t min_idx = 1, max_idx = 0;
9888 if (vr != NULL)
9889 find_case_label_range (stmt, vr->min, vr->max, &min_idx, &max_idx);
9890 if (min_idx <= max_idx)
9892 tree min_label = gimple_switch_label (stmt, min_idx);
9893 tree max_label = gimple_switch_label (stmt, max_idx);
9895 /* Avoid changing the type of the case labels when truncating. */
9896 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
9897 tree vr_min = fold_convert (case_label_type, vr->min);
9898 tree vr_max = fold_convert (case_label_type, vr->max);
9900 if (vr->type == VR_RANGE)
9902 /* If OP's value range is [2,8] and the low label range is
9903 0 ... 3, truncate the label's range to 2 .. 3. */
9904 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9905 && CASE_HIGH (min_label) != NULL_TREE
9906 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9907 CASE_LOW (min_label) = vr_min;
9909 /* If OP's value range is [2,8] and the high label range is
9910 7 ... 10, truncate the label's range to 7 .. 8. */
9911 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9912 && CASE_HIGH (max_label) != NULL_TREE
9913 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9914 CASE_HIGH (max_label) = vr_max;
9916 else if (vr->type == VR_ANTI_RANGE)
9918 tree one_cst = build_one_cst (case_label_type);
9920 if (min_label == max_label)
9922 /* If OP's value range is ~[7,8] and the label's range is
9923 7 ... 10, truncate the label's range to 9 ... 10. */
9924 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
9925 && CASE_HIGH (min_label) != NULL_TREE
9926 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
9927 CASE_LOW (min_label)
9928 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9930 /* If OP's value range is ~[7,8] and the label's range is
9931 5 ... 8, truncate the label's range to 5 ... 6. */
9932 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9933 && CASE_HIGH (min_label) != NULL_TREE
9934 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
9935 CASE_HIGH (min_label)
9936 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9938 else
9940 /* If OP's value range is ~[2,8] and the low label range is
9941 0 ... 3, truncate the label's range to 0 ... 1. */
9942 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9943 && CASE_HIGH (min_label) != NULL_TREE
9944 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9945 CASE_HIGH (min_label)
9946 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9948 /* If OP's value range is ~[2,8] and the high label range is
9949 7 ... 10, truncate the label's range to 9 ... 10. */
9950 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9951 && CASE_HIGH (max_label) != NULL_TREE
9952 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9953 CASE_LOW (max_label)
9954 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9958 /* Canonicalize singleton case ranges. */
9959 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
9960 CASE_HIGH (min_label) = NULL_TREE;
9961 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
9962 CASE_HIGH (max_label) = NULL_TREE;
9965 /* We can also eliminate case labels that lie completely outside OP's value
9966 range. */
9968 /* Bail out if this is just all edges taken. */
9969 if (i == 1
9970 && j == n - 1
9971 && take_default)
9972 return false;
9974 /* Build a new vector of taken case labels. */
9975 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
9976 n2 = 0;
9978 /* Add the default edge, if necessary. */
9979 if (take_default)
9980 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
9982 for (; i <= j; ++i, ++n2)
9983 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
9985 for (; k <= l; ++k, ++n2)
9986 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
9988 /* Mark needed edges. */
9989 for (i = 0; i < n2; ++i)
9991 e = find_edge (gimple_bb (stmt),
9992 label_to_block (CASE_LABEL (TREE_VEC_ELT (vec2, i))));
9993 e->aux = (void *)-1;
9996 /* Queue not needed edges for later removal. */
9997 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
9999 if (e->aux == (void *)-1)
10001 e->aux = NULL;
10002 continue;
10005 if (dump_file && (dump_flags & TDF_DETAILS))
10007 fprintf (dump_file, "removing unreachable case label\n");
10009 to_remove_edges.safe_push (e);
10010 e->flags &= ~EDGE_EXECUTABLE;
10013 /* And queue an update for the stmt. */
10014 su.stmt = stmt;
10015 su.vec = vec2;
10016 to_update_switch_stmts.safe_push (su);
10017 return false;
10020 /* Simplify an integral conversion from an SSA name in STMT. */
10022 static bool
10023 simplify_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10025 tree innerop, middleop, finaltype;
10026 gimple *def_stmt;
10027 signop inner_sgn, middle_sgn, final_sgn;
10028 unsigned inner_prec, middle_prec, final_prec;
10029 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
10031 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
10032 if (!INTEGRAL_TYPE_P (finaltype))
10033 return false;
10034 middleop = gimple_assign_rhs1 (stmt);
10035 def_stmt = SSA_NAME_DEF_STMT (middleop);
10036 if (!is_gimple_assign (def_stmt)
10037 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
10038 return false;
10039 innerop = gimple_assign_rhs1 (def_stmt);
10040 if (TREE_CODE (innerop) != SSA_NAME
10041 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
10042 return false;
10044 /* Get the value-range of the inner operand. Use get_range_info in
10045 case innerop was created during substitute-and-fold. */
10046 wide_int imin, imax;
10047 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop))
10048 || get_range_info (innerop, &imin, &imax) != VR_RANGE)
10049 return false;
10050 innermin = widest_int::from (imin, TYPE_SIGN (TREE_TYPE (innerop)));
10051 innermax = widest_int::from (imax, TYPE_SIGN (TREE_TYPE (innerop)));
10053 /* Simulate the conversion chain to check if the result is equal if
10054 the middle conversion is removed. */
10055 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
10056 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
10057 final_prec = TYPE_PRECISION (finaltype);
10059 /* If the first conversion is not injective, the second must not
10060 be widening. */
10061 if (wi::gtu_p (innermax - innermin,
10062 wi::mask <widest_int> (middle_prec, false))
10063 && middle_prec < final_prec)
10064 return false;
10065 /* We also want a medium value so that we can track the effect that
10066 narrowing conversions with sign change have. */
10067 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
10068 if (inner_sgn == UNSIGNED)
10069 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
10070 else
10071 innermed = 0;
10072 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
10073 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
10074 innermed = innermin;
10076 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
10077 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
10078 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
10079 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
10081 /* Require that the final conversion applied to both the original
10082 and the intermediate range produces the same result. */
10083 final_sgn = TYPE_SIGN (finaltype);
10084 if (wi::ext (middlemin, final_prec, final_sgn)
10085 != wi::ext (innermin, final_prec, final_sgn)
10086 || wi::ext (middlemed, final_prec, final_sgn)
10087 != wi::ext (innermed, final_prec, final_sgn)
10088 || wi::ext (middlemax, final_prec, final_sgn)
10089 != wi::ext (innermax, final_prec, final_sgn))
10090 return false;
10092 gimple_assign_set_rhs1 (stmt, innerop);
10093 fold_stmt (gsi, follow_single_use_edges);
10094 return true;
10097 /* Simplify a conversion from integral SSA name to float in STMT. */
10099 bool
10100 vr_values::simplify_float_conversion_using_ranges (gimple_stmt_iterator *gsi,
10101 gimple *stmt)
10103 tree rhs1 = gimple_assign_rhs1 (stmt);
10104 value_range *vr = get_value_range (rhs1);
10105 scalar_float_mode fltmode
10106 = SCALAR_FLOAT_TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
10107 scalar_int_mode mode;
10108 tree tem;
10109 gassign *conv;
10111 /* We can only handle constant ranges. */
10112 if (vr->type != VR_RANGE
10113 || TREE_CODE (vr->min) != INTEGER_CST
10114 || TREE_CODE (vr->max) != INTEGER_CST)
10115 return false;
10117 /* First check if we can use a signed type in place of an unsigned. */
10118 scalar_int_mode rhs_mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (rhs1));
10119 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
10120 && can_float_p (fltmode, rhs_mode, 0) != CODE_FOR_nothing
10121 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
10122 mode = rhs_mode;
10123 /* If we can do the conversion in the current input mode do nothing. */
10124 else if (can_float_p (fltmode, rhs_mode,
10125 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
10126 return false;
10127 /* Otherwise search for a mode we can use, starting from the narrowest
10128 integer mode available. */
10129 else
10131 mode = NARROWEST_INT_MODE;
10132 for (;;)
10134 /* If we cannot do a signed conversion to float from mode
10135 or if the value-range does not fit in the signed type
10136 try with a wider mode. */
10137 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
10138 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
10139 break;
10141 /* But do not widen the input. Instead leave that to the
10142 optabs expansion code. */
10143 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
10144 || GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
10145 return false;
10149 /* It works, insert a truncation or sign-change before the
10150 float conversion. */
10151 tem = make_ssa_name (build_nonstandard_integer_type
10152 (GET_MODE_PRECISION (mode), 0));
10153 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
10154 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
10155 gimple_assign_set_rhs1 (stmt, tem);
10156 fold_stmt (gsi, follow_single_use_edges);
10158 return true;
10161 /* Simplify an internal fn call using ranges if possible. */
10163 bool
10164 vr_values::simplify_internal_call_using_ranges (gimple_stmt_iterator *gsi,
10165 gimple *stmt)
10167 enum tree_code subcode;
10168 bool is_ubsan = false;
10169 bool ovf = false;
10170 switch (gimple_call_internal_fn (stmt))
10172 case IFN_UBSAN_CHECK_ADD:
10173 subcode = PLUS_EXPR;
10174 is_ubsan = true;
10175 break;
10176 case IFN_UBSAN_CHECK_SUB:
10177 subcode = MINUS_EXPR;
10178 is_ubsan = true;
10179 break;
10180 case IFN_UBSAN_CHECK_MUL:
10181 subcode = MULT_EXPR;
10182 is_ubsan = true;
10183 break;
10184 case IFN_ADD_OVERFLOW:
10185 subcode = PLUS_EXPR;
10186 break;
10187 case IFN_SUB_OVERFLOW:
10188 subcode = MINUS_EXPR;
10189 break;
10190 case IFN_MUL_OVERFLOW:
10191 subcode = MULT_EXPR;
10192 break;
10193 default:
10194 return false;
10197 tree op0 = gimple_call_arg (stmt, 0);
10198 tree op1 = gimple_call_arg (stmt, 1);
10199 tree type;
10200 if (is_ubsan)
10202 type = TREE_TYPE (op0);
10203 if (VECTOR_TYPE_P (type))
10204 return false;
10206 else if (gimple_call_lhs (stmt) == NULL_TREE)
10207 return false;
10208 else
10209 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
10210 if (!check_for_binary_op_overflow (subcode, type, op0, op1, &ovf)
10211 || (is_ubsan && ovf))
10212 return false;
10214 gimple *g;
10215 location_t loc = gimple_location (stmt);
10216 if (is_ubsan)
10217 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
10218 else
10220 int prec = TYPE_PRECISION (type);
10221 tree utype = type;
10222 if (ovf
10223 || !useless_type_conversion_p (type, TREE_TYPE (op0))
10224 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
10225 utype = build_nonstandard_integer_type (prec, 1);
10226 if (TREE_CODE (op0) == INTEGER_CST)
10227 op0 = fold_convert (utype, op0);
10228 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
10230 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
10231 gimple_set_location (g, loc);
10232 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10233 op0 = gimple_assign_lhs (g);
10235 if (TREE_CODE (op1) == INTEGER_CST)
10236 op1 = fold_convert (utype, op1);
10237 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
10239 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
10240 gimple_set_location (g, loc);
10241 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10242 op1 = gimple_assign_lhs (g);
10244 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
10245 gimple_set_location (g, loc);
10246 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10247 if (utype != type)
10249 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
10250 gimple_assign_lhs (g));
10251 gimple_set_location (g, loc);
10252 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10254 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
10255 gimple_assign_lhs (g),
10256 build_int_cst (type, ovf));
10258 gimple_set_location (g, loc);
10259 gsi_replace (gsi, g, false);
10260 return true;
10263 /* Return true if VAR is a two-valued variable. Set a and b with the
10264 two-values when it is true. Return false otherwise. */
10266 bool
10267 vr_values::two_valued_val_range_p (tree var, tree *a, tree *b)
10269 value_range *vr = get_value_range (var);
10270 if ((vr->type != VR_RANGE
10271 && vr->type != VR_ANTI_RANGE)
10272 || TREE_CODE (vr->min) != INTEGER_CST
10273 || TREE_CODE (vr->max) != INTEGER_CST)
10274 return false;
10276 if (vr->type == VR_RANGE
10277 && wi::to_wide (vr->max) - wi::to_wide (vr->min) == 1)
10279 *a = vr->min;
10280 *b = vr->max;
10281 return true;
10284 /* ~[TYPE_MIN + 1, TYPE_MAX - 1] */
10285 if (vr->type == VR_ANTI_RANGE
10286 && (wi::to_wide (vr->min)
10287 - wi::to_wide (vrp_val_min (TREE_TYPE (var)))) == 1
10288 && (wi::to_wide (vrp_val_max (TREE_TYPE (var)))
10289 - wi::to_wide (vr->max)) == 1)
10291 *a = vrp_val_min (TREE_TYPE (var));
10292 *b = vrp_val_max (TREE_TYPE (var));
10293 return true;
10296 return false;
10299 /* Simplify STMT using ranges if possible. */
10301 bool
10302 vr_values::simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
10304 gimple *stmt = gsi_stmt (*gsi);
10305 if (is_gimple_assign (stmt))
10307 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
10308 tree rhs1 = gimple_assign_rhs1 (stmt);
10309 tree rhs2 = gimple_assign_rhs2 (stmt);
10310 tree lhs = gimple_assign_lhs (stmt);
10311 tree val1 = NULL_TREE, val2 = NULL_TREE;
10312 use_operand_p use_p;
10313 gimple *use_stmt;
10315 /* Convert:
10316 LHS = CST BINOP VAR
10317 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10319 LHS = VAR == VAL1 ? (CST BINOP VAL1) : (CST BINOP VAL2)
10321 Also handles:
10322 LHS = VAR BINOP CST
10323 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10325 LHS = VAR == VAL1 ? (VAL1 BINOP CST) : (VAL2 BINOP CST) */
10327 if (TREE_CODE_CLASS (rhs_code) == tcc_binary
10328 && INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10329 && ((TREE_CODE (rhs1) == INTEGER_CST
10330 && TREE_CODE (rhs2) == SSA_NAME)
10331 || (TREE_CODE (rhs2) == INTEGER_CST
10332 && TREE_CODE (rhs1) == SSA_NAME))
10333 && single_imm_use (lhs, &use_p, &use_stmt)
10334 && gimple_code (use_stmt) == GIMPLE_COND)
10337 tree new_rhs1 = NULL_TREE;
10338 tree new_rhs2 = NULL_TREE;
10339 tree cmp_var = NULL_TREE;
10341 if (TREE_CODE (rhs2) == SSA_NAME
10342 && two_valued_val_range_p (rhs2, &val1, &val2))
10344 /* Optimize RHS1 OP [VAL1, VAL2]. */
10345 new_rhs1 = int_const_binop (rhs_code, rhs1, val1);
10346 new_rhs2 = int_const_binop (rhs_code, rhs1, val2);
10347 cmp_var = rhs2;
10349 else if (TREE_CODE (rhs1) == SSA_NAME
10350 && two_valued_val_range_p (rhs1, &val1, &val2))
10352 /* Optimize [VAL1, VAL2] OP RHS2. */
10353 new_rhs1 = int_const_binop (rhs_code, val1, rhs2);
10354 new_rhs2 = int_const_binop (rhs_code, val2, rhs2);
10355 cmp_var = rhs1;
10358 /* If we could not find two-vals or the optimzation is invalid as
10359 in divide by zero, new_rhs1 / new_rhs will be NULL_TREE. */
10360 if (new_rhs1 && new_rhs2)
10362 tree cond = build2 (EQ_EXPR, boolean_type_node, cmp_var, val1);
10363 gimple_assign_set_rhs_with_ops (gsi,
10364 COND_EXPR, cond,
10365 new_rhs1,
10366 new_rhs2);
10367 update_stmt (gsi_stmt (*gsi));
10368 fold_stmt (gsi, follow_single_use_edges);
10369 return true;
10373 switch (rhs_code)
10375 case EQ_EXPR:
10376 case NE_EXPR:
10377 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
10378 if the RHS is zero or one, and the LHS are known to be boolean
10379 values. */
10380 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10381 return simplify_truth_ops_using_ranges (gsi, stmt);
10382 break;
10384 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
10385 and BIT_AND_EXPR respectively if the first operand is greater
10386 than zero and the second operand is an exact power of two.
10387 Also optimize TRUNC_MOD_EXPR away if the second operand is
10388 constant and the first operand already has the right value
10389 range. */
10390 case TRUNC_DIV_EXPR:
10391 case TRUNC_MOD_EXPR:
10392 if ((TREE_CODE (rhs1) == SSA_NAME
10393 || TREE_CODE (rhs1) == INTEGER_CST)
10394 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10395 return simplify_div_or_mod_using_ranges (gsi, stmt);
10396 break;
10398 /* Transform ABS (X) into X or -X as appropriate. */
10399 case ABS_EXPR:
10400 if (TREE_CODE (rhs1) == SSA_NAME
10401 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10402 return simplify_abs_using_ranges (gsi, stmt);
10403 break;
10405 case BIT_AND_EXPR:
10406 case BIT_IOR_EXPR:
10407 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
10408 if all the bits being cleared are already cleared or
10409 all the bits being set are already set. */
10410 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10411 return simplify_bit_ops_using_ranges (gsi, stmt);
10412 break;
10414 CASE_CONVERT:
10415 if (TREE_CODE (rhs1) == SSA_NAME
10416 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10417 return simplify_conversion_using_ranges (gsi, stmt);
10418 break;
10420 case FLOAT_EXPR:
10421 if (TREE_CODE (rhs1) == SSA_NAME
10422 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10423 return simplify_float_conversion_using_ranges (gsi, stmt);
10424 break;
10426 case MIN_EXPR:
10427 case MAX_EXPR:
10428 return simplify_min_or_max_using_ranges (gsi, stmt);
10430 default:
10431 break;
10434 else if (gimple_code (stmt) == GIMPLE_COND)
10435 return simplify_cond_using_ranges_1 (as_a <gcond *> (stmt));
10436 else if (gimple_code (stmt) == GIMPLE_SWITCH)
10437 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
10438 else if (is_gimple_call (stmt)
10439 && gimple_call_internal_p (stmt))
10440 return simplify_internal_call_using_ranges (gsi, stmt);
10442 return false;
10445 class vrp_folder : public substitute_and_fold_engine
10447 public:
10448 tree get_value (tree) FINAL OVERRIDE;
10449 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
10450 bool fold_predicate_in (gimple_stmt_iterator *);
10452 class vr_values *vr_values;
10454 /* Delegators. */
10455 tree vrp_evaluate_conditional (tree_code code, tree op0,
10456 tree op1, gimple *stmt)
10457 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
10458 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
10459 { return vr_values->simplify_stmt_using_ranges (gsi); }
10460 tree op_with_constant_singleton_value_range (tree op)
10461 { return vr_values->op_with_constant_singleton_value_range (op); }
10464 /* If the statement pointed by SI has a predicate whose value can be
10465 computed using the value range information computed by VRP, compute
10466 its value and return true. Otherwise, return false. */
10468 bool
10469 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
10471 bool assignment_p = false;
10472 tree val;
10473 gimple *stmt = gsi_stmt (*si);
10475 if (is_gimple_assign (stmt)
10476 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
10478 assignment_p = true;
10479 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
10480 gimple_assign_rhs1 (stmt),
10481 gimple_assign_rhs2 (stmt),
10482 stmt);
10484 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10485 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10486 gimple_cond_lhs (cond_stmt),
10487 gimple_cond_rhs (cond_stmt),
10488 stmt);
10489 else
10490 return false;
10492 if (val)
10494 if (assignment_p)
10495 val = fold_convert (gimple_expr_type (stmt), val);
10497 if (dump_file)
10499 fprintf (dump_file, "Folding predicate ");
10500 print_gimple_expr (dump_file, stmt, 0);
10501 fprintf (dump_file, " to ");
10502 print_generic_expr (dump_file, val);
10503 fprintf (dump_file, "\n");
10506 if (is_gimple_assign (stmt))
10507 gimple_assign_set_rhs_from_tree (si, val);
10508 else
10510 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
10511 gcond *cond_stmt = as_a <gcond *> (stmt);
10512 if (integer_zerop (val))
10513 gimple_cond_make_false (cond_stmt);
10514 else if (integer_onep (val))
10515 gimple_cond_make_true (cond_stmt);
10516 else
10517 gcc_unreachable ();
10520 return true;
10523 return false;
10526 /* Callback for substitute_and_fold folding the stmt at *SI. */
10528 bool
10529 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
10531 if (fold_predicate_in (si))
10532 return true;
10534 return simplify_stmt_using_ranges (si);
10537 /* If OP has a value range with a single constant value return that,
10538 otherwise return NULL_TREE. This returns OP itself if OP is a
10539 constant.
10541 Implemented as a pure wrapper right now, but this will change. */
10543 tree
10544 vrp_folder::get_value (tree op)
10546 return op_with_constant_singleton_value_range (op);
10549 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
10550 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
10551 BB. If no such ASSERT_EXPR is found, return OP. */
10553 static tree
10554 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
10556 imm_use_iterator imm_iter;
10557 gimple *use_stmt;
10558 use_operand_p use_p;
10560 if (TREE_CODE (op) == SSA_NAME)
10562 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
10564 use_stmt = USE_STMT (use_p);
10565 if (use_stmt != stmt
10566 && gimple_assign_single_p (use_stmt)
10567 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
10568 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
10569 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
10570 return gimple_assign_lhs (use_stmt);
10573 return op;
10576 /* A trivial wrapper so that we can present the generic jump threading
10577 code with a simple API for simplifying statements. STMT is the
10578 statement we want to simplify, WITHIN_STMT provides the location
10579 for any overflow warnings. */
10581 static tree
10582 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
10583 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
10584 basic_block bb)
10586 /* First see if the conditional is in the hash table. */
10587 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
10588 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
10589 return cached_lhs;
10591 vr_values *vr_values = x_vr_values;
10592 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10594 tree op0 = gimple_cond_lhs (cond_stmt);
10595 op0 = lhs_of_dominating_assert (op0, bb, stmt);
10597 tree op1 = gimple_cond_rhs (cond_stmt);
10598 op1 = lhs_of_dominating_assert (op1, bb, stmt);
10600 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10601 op0, op1, within_stmt);
10604 /* We simplify a switch statement by trying to determine which case label
10605 will be taken. If we are successful then we return the corresponding
10606 CASE_LABEL_EXPR. */
10607 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
10609 tree op = gimple_switch_index (switch_stmt);
10610 if (TREE_CODE (op) != SSA_NAME)
10611 return NULL_TREE;
10613 op = lhs_of_dominating_assert (op, bb, stmt);
10615 value_range *vr = vr_values->get_value_range (op);
10616 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
10617 || symbolic_range_p (vr))
10618 return NULL_TREE;
10620 if (vr->type == VR_RANGE)
10622 size_t i, j;
10623 /* Get the range of labels that contain a part of the operand's
10624 value range. */
10625 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
10627 /* Is there only one such label? */
10628 if (i == j)
10630 tree label = gimple_switch_label (switch_stmt, i);
10632 /* The i'th label will be taken only if the value range of the
10633 operand is entirely within the bounds of this label. */
10634 if (CASE_HIGH (label) != NULL_TREE
10635 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
10636 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
10637 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
10638 && tree_int_cst_equal (vr->min, vr->max)))
10639 return label;
10642 /* If there are no such labels then the default label will be
10643 taken. */
10644 if (i > j)
10645 return gimple_switch_label (switch_stmt, 0);
10648 if (vr->type == VR_ANTI_RANGE)
10650 unsigned n = gimple_switch_num_labels (switch_stmt);
10651 tree min_label = gimple_switch_label (switch_stmt, 1);
10652 tree max_label = gimple_switch_label (switch_stmt, n - 1);
10654 /* The default label will be taken only if the anti-range of the
10655 operand is entirely outside the bounds of all the (non-default)
10656 case labels. */
10657 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
10658 && (CASE_HIGH (max_label) != NULL_TREE
10659 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
10660 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
10661 return gimple_switch_label (switch_stmt, 0);
10664 return NULL_TREE;
10667 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
10669 value_range new_vr = VR_INITIALIZER;
10670 tree lhs = gimple_assign_lhs (assign_stmt);
10672 if (TREE_CODE (lhs) == SSA_NAME
10673 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10674 || POINTER_TYPE_P (TREE_TYPE (lhs))))
10676 vr_values->extract_range_from_assignment (&new_vr, assign_stmt);
10677 if (range_int_cst_singleton_p (&new_vr))
10678 return new_vr.min;
10682 return NULL_TREE;
10685 class vrp_dom_walker : public dom_walker
10687 public:
10688 vrp_dom_walker (cdi_direction direction,
10689 class const_and_copies *const_and_copies,
10690 class avail_exprs_stack *avail_exprs_stack)
10691 : dom_walker (direction, true),
10692 m_const_and_copies (const_and_copies),
10693 m_avail_exprs_stack (avail_exprs_stack),
10694 m_dummy_cond (NULL) {}
10696 virtual edge before_dom_children (basic_block);
10697 virtual void after_dom_children (basic_block);
10699 class vr_values *vr_values;
10701 private:
10702 class const_and_copies *m_const_and_copies;
10703 class avail_exprs_stack *m_avail_exprs_stack;
10705 gcond *m_dummy_cond;
10709 /* Called before processing dominator children of BB. We want to look
10710 at ASSERT_EXPRs and record information from them in the appropriate
10711 tables.
10713 We could look at other statements here. It's not seen as likely
10714 to significantly increase the jump threads we discover. */
10716 edge
10717 vrp_dom_walker::before_dom_children (basic_block bb)
10719 gimple_stmt_iterator gsi;
10721 m_avail_exprs_stack->push_marker ();
10722 m_const_and_copies->push_marker ();
10723 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
10725 gimple *stmt = gsi_stmt (gsi);
10726 if (gimple_assign_single_p (stmt)
10727 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
10729 tree rhs1 = gimple_assign_rhs1 (stmt);
10730 tree cond = TREE_OPERAND (rhs1, 1);
10731 tree inverted = invert_truthvalue (cond);
10732 vec<cond_equivalence> p;
10733 p.create (3);
10734 record_conditions (&p, cond, inverted);
10735 for (unsigned int i = 0; i < p.length (); i++)
10736 m_avail_exprs_stack->record_cond (&p[i]);
10738 tree lhs = gimple_assign_lhs (stmt);
10739 m_const_and_copies->record_const_or_copy (lhs,
10740 TREE_OPERAND (rhs1, 0));
10741 p.release ();
10742 continue;
10744 break;
10746 return NULL;
10749 /* Called after processing dominator children of BB. This is where we
10750 actually call into the threader. */
10751 void
10752 vrp_dom_walker::after_dom_children (basic_block bb)
10754 if (!m_dummy_cond)
10755 m_dummy_cond = gimple_build_cond (NE_EXPR,
10756 integer_zero_node, integer_zero_node,
10757 NULL, NULL);
10759 x_vr_values = vr_values;
10760 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
10761 m_avail_exprs_stack,
10762 simplify_stmt_for_jump_threading);
10763 x_vr_values = NULL;
10765 m_avail_exprs_stack->pop_to_marker ();
10766 m_const_and_copies->pop_to_marker ();
10769 /* Blocks which have more than one predecessor and more than
10770 one successor present jump threading opportunities, i.e.,
10771 when the block is reached from a specific predecessor, we
10772 may be able to determine which of the outgoing edges will
10773 be traversed. When this optimization applies, we are able
10774 to avoid conditionals at runtime and we may expose secondary
10775 optimization opportunities.
10777 This routine is effectively a driver for the generic jump
10778 threading code. It basically just presents the generic code
10779 with edges that may be suitable for jump threading.
10781 Unlike DOM, we do not iterate VRP if jump threading was successful.
10782 While iterating may expose new opportunities for VRP, it is expected
10783 those opportunities would be very limited and the compile time cost
10784 to expose those opportunities would be significant.
10786 As jump threading opportunities are discovered, they are registered
10787 for later realization. */
10789 static void
10790 identify_jump_threads (class vr_values *vr_values)
10792 int i;
10793 edge e;
10795 /* Ugh. When substituting values earlier in this pass we can
10796 wipe the dominance information. So rebuild the dominator
10797 information as we need it within the jump threading code. */
10798 calculate_dominance_info (CDI_DOMINATORS);
10800 /* We do not allow VRP information to be used for jump threading
10801 across a back edge in the CFG. Otherwise it becomes too
10802 difficult to avoid eliminating loop exit tests. Of course
10803 EDGE_DFS_BACK is not accurate at this time so we have to
10804 recompute it. */
10805 mark_dfs_back_edges ();
10807 /* Do not thread across edges we are about to remove. Just marking
10808 them as EDGE_IGNORE will do. */
10809 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10810 e->flags |= EDGE_IGNORE;
10812 /* Allocate our unwinder stack to unwind any temporary equivalences
10813 that might be recorded. */
10814 const_and_copies *equiv_stack = new const_and_copies ();
10816 hash_table<expr_elt_hasher> *avail_exprs
10817 = new hash_table<expr_elt_hasher> (1024);
10818 avail_exprs_stack *avail_exprs_stack
10819 = new class avail_exprs_stack (avail_exprs);
10821 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
10822 walker.vr_values = vr_values;
10823 walker.walk (cfun->cfg->x_entry_block_ptr);
10825 /* Clear EDGE_IGNORE. */
10826 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10827 e->flags &= ~EDGE_IGNORE;
10829 /* We do not actually update the CFG or SSA graphs at this point as
10830 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
10831 handle ASSERT_EXPRs gracefully. */
10832 delete equiv_stack;
10833 delete avail_exprs;
10834 delete avail_exprs_stack;
10837 /* Free VRP lattice. */
10839 vr_values::~vr_values ()
10841 /* Free allocated memory. */
10842 free (vr_value);
10843 free (vr_phi_edge_counts);
10844 bitmap_obstack_release (&vrp_equiv_obstack);
10845 vrp_value_range_pool.release ();
10847 /* So that we can distinguish between VRP data being available
10848 and not available. */
10849 vr_value = NULL;
10850 vr_phi_edge_counts = NULL;
10853 /* Traverse all the blocks folding conditionals with known ranges. */
10855 void
10856 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
10858 size_t i;
10860 vr_values.values_propagated = true;
10862 if (dump_file)
10864 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
10865 vr_values.dump_all_value_ranges (dump_file);
10866 fprintf (dump_file, "\n");
10869 /* Set value range to non pointer SSA_NAMEs. */
10870 for (i = 0; i < num_ssa_names; i++)
10872 tree name = ssa_name (i);
10873 if (!name)
10874 continue;
10876 value_range *vr = get_value_range (name);
10877 if (!name
10878 || (vr->type == VR_VARYING)
10879 || (vr->type == VR_UNDEFINED)
10880 || (TREE_CODE (vr->min) != INTEGER_CST)
10881 || (TREE_CODE (vr->max) != INTEGER_CST))
10882 continue;
10884 if (POINTER_TYPE_P (TREE_TYPE (name))
10885 && ((vr->type == VR_RANGE
10886 && range_includes_zero_p (vr->min, vr->max) == 0)
10887 || (vr->type == VR_ANTI_RANGE
10888 && range_includes_zero_p (vr->min, vr->max) == 1)))
10889 set_ptr_nonnull (name);
10890 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
10891 set_range_info (name, vr->type,
10892 wi::to_wide (vr->min),
10893 wi::to_wide (vr->max));
10896 class vrp_folder vrp_folder;
10897 vrp_folder.vr_values = &vr_values;
10898 vrp_folder.substitute_and_fold ();
10900 if (warn_array_bounds && warn_array_bounds_p)
10901 check_all_array_refs ();
10904 void
10905 vr_values::set_vr_value (tree var, value_range *vr)
10907 if (SSA_NAME_VERSION (var) >= num_vr_values)
10908 return;
10909 vr_value[SSA_NAME_VERSION (var)] = vr;
10912 /* Main entry point to VRP (Value Range Propagation). This pass is
10913 loosely based on J. R. C. Patterson, ``Accurate Static Branch
10914 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
10915 Programming Language Design and Implementation, pp. 67-78, 1995.
10916 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
10918 This is essentially an SSA-CCP pass modified to deal with ranges
10919 instead of constants.
10921 While propagating ranges, we may find that two or more SSA name
10922 have equivalent, though distinct ranges. For instance,
10924 1 x_9 = p_3->a;
10925 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
10926 3 if (p_4 == q_2)
10927 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
10928 5 endif
10929 6 if (q_2)
10931 In the code above, pointer p_5 has range [q_2, q_2], but from the
10932 code we can also determine that p_5 cannot be NULL and, if q_2 had
10933 a non-varying range, p_5's range should also be compatible with it.
10935 These equivalences are created by two expressions: ASSERT_EXPR and
10936 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
10937 result of another assertion, then we can use the fact that p_5 and
10938 p_4 are equivalent when evaluating p_5's range.
10940 Together with value ranges, we also propagate these equivalences
10941 between names so that we can take advantage of information from
10942 multiple ranges when doing final replacement. Note that this
10943 equivalency relation is transitive but not symmetric.
10945 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
10946 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
10947 in contexts where that assertion does not hold (e.g., in line 6).
10949 TODO, the main difference between this pass and Patterson's is that
10950 we do not propagate edge probabilities. We only compute whether
10951 edges can be taken or not. That is, instead of having a spectrum
10952 of jump probabilities between 0 and 1, we only deal with 0, 1 and
10953 DON'T KNOW. In the future, it may be worthwhile to propagate
10954 probabilities to aid branch prediction. */
10956 static unsigned int
10957 execute_vrp (bool warn_array_bounds_p)
10959 int i;
10960 edge e;
10961 switch_update *su;
10963 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
10964 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
10965 scev_initialize ();
10967 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
10968 Inserting assertions may split edges which will invalidate
10969 EDGE_DFS_BACK. */
10970 insert_range_assertions ();
10972 to_remove_edges.create (10);
10973 to_update_switch_stmts.create (5);
10974 threadedge_initialize_values ();
10976 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
10977 mark_dfs_back_edges ();
10979 class vrp_prop vrp_prop;
10980 vrp_prop.vrp_initialize ();
10981 vrp_prop.ssa_propagate ();
10982 vrp_prop.vrp_finalize (warn_array_bounds_p);
10984 /* We must identify jump threading opportunities before we release
10985 the datastructures built by VRP. */
10986 identify_jump_threads (&vrp_prop.vr_values);
10988 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
10989 was set by a type conversion can often be rewritten to use the
10990 RHS of the type conversion.
10992 However, doing so inhibits jump threading through the comparison.
10993 So that transformation is not performed until after jump threading
10994 is complete. */
10995 basic_block bb;
10996 FOR_EACH_BB_FN (bb, cfun)
10998 gimple *last = last_stmt (bb);
10999 if (last && gimple_code (last) == GIMPLE_COND)
11000 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
11003 free_numbers_of_iterations_estimates (cfun);
11005 /* ASSERT_EXPRs must be removed before finalizing jump threads
11006 as finalizing jump threads calls the CFG cleanup code which
11007 does not properly handle ASSERT_EXPRs. */
11008 remove_range_assertions ();
11010 /* If we exposed any new variables, go ahead and put them into
11011 SSA form now, before we handle jump threading. This simplifies
11012 interactions between rewriting of _DECL nodes into SSA form
11013 and rewriting SSA_NAME nodes into SSA form after block
11014 duplication and CFG manipulation. */
11015 update_ssa (TODO_update_ssa);
11017 /* We identified all the jump threading opportunities earlier, but could
11018 not transform the CFG at that time. This routine transforms the
11019 CFG and arranges for the dominator tree to be rebuilt if necessary.
11021 Note the SSA graph update will occur during the normal TODO
11022 processing by the pass manager. */
11023 thread_through_all_blocks (false);
11025 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
11026 CFG in a broken state and requires a cfg_cleanup run. */
11027 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
11028 remove_edge (e);
11029 /* Update SWITCH_EXPR case label vector. */
11030 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
11032 size_t j;
11033 size_t n = TREE_VEC_LENGTH (su->vec);
11034 tree label;
11035 gimple_switch_set_num_labels (su->stmt, n);
11036 for (j = 0; j < n; j++)
11037 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
11038 /* As we may have replaced the default label with a regular one
11039 make sure to make it a real default label again. This ensures
11040 optimal expansion. */
11041 label = gimple_switch_label (su->stmt, 0);
11042 CASE_LOW (label) = NULL_TREE;
11043 CASE_HIGH (label) = NULL_TREE;
11046 if (to_remove_edges.length () > 0)
11048 free_dominance_info (CDI_DOMINATORS);
11049 loops_state_set (LOOPS_NEED_FIXUP);
11052 to_remove_edges.release ();
11053 to_update_switch_stmts.release ();
11054 threadedge_finalize_values ();
11056 scev_finalize ();
11057 loop_optimizer_finalize ();
11058 return 0;
11061 namespace {
11063 const pass_data pass_data_vrp =
11065 GIMPLE_PASS, /* type */
11066 "vrp", /* name */
11067 OPTGROUP_NONE, /* optinfo_flags */
11068 TV_TREE_VRP, /* tv_id */
11069 PROP_ssa, /* properties_required */
11070 0, /* properties_provided */
11071 0, /* properties_destroyed */
11072 0, /* todo_flags_start */
11073 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
11076 class pass_vrp : public gimple_opt_pass
11078 public:
11079 pass_vrp (gcc::context *ctxt)
11080 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
11083 /* opt_pass methods: */
11084 opt_pass * clone () { return new pass_vrp (m_ctxt); }
11085 void set_pass_param (unsigned int n, bool param)
11087 gcc_assert (n == 0);
11088 warn_array_bounds_p = param;
11090 virtual bool gate (function *) { return flag_tree_vrp != 0; }
11091 virtual unsigned int execute (function *)
11092 { return execute_vrp (warn_array_bounds_p); }
11094 private:
11095 bool warn_array_bounds_p;
11096 }; // class pass_vrp
11098 } // anon namespace
11100 gimple_opt_pass *
11101 make_pass_vrp (gcc::context *ctxt)
11103 return new pass_vrp (ctxt);