PR rtl-optimization/82913
[official-gcc.git] / gcc / tree-vrp.c
blob7173ab22478cd3512fd031f5534e2dfb2760fb5a
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 #define VR_INITIALIZER { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL }
71 /* Set of SSA names found live during the RPO traversal of the function
72 for still active basic-blocks. */
73 static sbitmap *live;
75 /* Return true if the SSA name NAME is live on the edge E. */
77 static bool
78 live_on_edge (edge e, tree name)
80 return (live[e->dest->index]
81 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
84 /* Local functions. */
85 static int compare_values (tree val1, tree val2);
86 static int compare_values_warnv (tree val1, tree val2, bool *);
88 struct assert_info
90 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
91 enum tree_code comp_code;
93 /* Name to register the assert for. */
94 tree name;
96 /* Value being compared against. */
97 tree val;
99 /* Expression to compare. */
100 tree expr;
103 /* Location information for ASSERT_EXPRs. Each instance of this
104 structure describes an ASSERT_EXPR for an SSA name. Since a single
105 SSA name may have more than one assertion associated with it, these
106 locations are kept in a linked list attached to the corresponding
107 SSA name. */
108 struct assert_locus
110 /* Basic block where the assertion would be inserted. */
111 basic_block bb;
113 /* Some assertions need to be inserted on an edge (e.g., assertions
114 generated by COND_EXPRs). In those cases, BB will be NULL. */
115 edge e;
117 /* Pointer to the statement that generated this assertion. */
118 gimple_stmt_iterator si;
120 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
121 enum tree_code comp_code;
123 /* Value being compared against. */
124 tree val;
126 /* Expression to compare. */
127 tree expr;
129 /* Next node in the linked list. */
130 assert_locus *next;
133 /* If bit I is present, it means that SSA name N_i has a list of
134 assertions that should be inserted in the IL. */
135 static bitmap need_assert_for;
137 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
138 holds a list of ASSERT_LOCUS_T nodes that describe where
139 ASSERT_EXPRs for SSA name N_I should be inserted. */
140 static assert_locus **asserts_for;
142 struct switch_update {
143 gswitch *stmt;
144 tree vec;
147 static vec<edge> to_remove_edges;
148 static vec<switch_update> to_update_switch_stmts;
151 /* Return the maximum value for TYPE. */
153 static inline tree
154 vrp_val_max (const_tree type)
156 if (!INTEGRAL_TYPE_P (type))
157 return NULL_TREE;
159 return TYPE_MAX_VALUE (type);
162 /* Return the minimum value for TYPE. */
164 static inline tree
165 vrp_val_min (const_tree type)
167 if (!INTEGRAL_TYPE_P (type))
168 return NULL_TREE;
170 return TYPE_MIN_VALUE (type);
173 /* Return whether VAL is equal to the maximum value of its type.
174 We can't do a simple equality comparison with TYPE_MAX_VALUE because
175 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
176 is not == to the integer constant with the same value in the type. */
178 static inline bool
179 vrp_val_is_max (const_tree val)
181 tree type_max = vrp_val_max (TREE_TYPE (val));
182 return (val == type_max
183 || (type_max != NULL_TREE
184 && operand_equal_p (val, type_max, 0)));
187 /* Return whether VAL is equal to the minimum value of its type. */
189 static inline bool
190 vrp_val_is_min (const_tree val)
192 tree type_min = vrp_val_min (TREE_TYPE (val));
193 return (val == type_min
194 || (type_min != NULL_TREE
195 && operand_equal_p (val, type_min, 0)));
199 /* Set value range VR to VR_UNDEFINED. */
201 static inline void
202 set_value_range_to_undefined (value_range *vr)
204 vr->type = VR_UNDEFINED;
205 vr->min = vr->max = NULL_TREE;
206 if (vr->equiv)
207 bitmap_clear (vr->equiv);
211 /* Set value range VR to VR_VARYING. */
213 static inline void
214 set_value_range_to_varying (value_range *vr)
216 vr->type = VR_VARYING;
217 vr->min = vr->max = NULL_TREE;
218 if (vr->equiv)
219 bitmap_clear (vr->equiv);
223 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
225 static void
226 set_value_range (value_range *vr, enum value_range_type t, tree min,
227 tree max, bitmap equiv)
229 /* Check the validity of the range. */
230 if (flag_checking
231 && (t == VR_RANGE || t == VR_ANTI_RANGE))
233 int cmp;
235 gcc_assert (min && max);
237 gcc_assert (!TREE_OVERFLOW_P (min) && !TREE_OVERFLOW_P (max));
239 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
240 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
242 cmp = compare_values (min, max);
243 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
246 if (flag_checking
247 && (t == VR_UNDEFINED || t == VR_VARYING))
249 gcc_assert (min == NULL_TREE && max == NULL_TREE);
250 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
253 vr->type = t;
254 vr->min = min;
255 vr->max = max;
257 /* Since updating the equivalence set involves deep copying the
258 bitmaps, only do it if absolutely necessary.
260 All equivalence bitmaps are allocated from the same obstack. So
261 we can use the obstack associated with EQUIV to allocate vr->equiv. */
262 if (vr->equiv == NULL
263 && equiv != NULL)
264 vr->equiv = BITMAP_ALLOC (equiv->obstack);
266 if (equiv != vr->equiv)
268 if (equiv && !bitmap_empty_p (equiv))
269 bitmap_copy (vr->equiv, equiv);
270 else
271 bitmap_clear (vr->equiv);
276 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
277 This means adjusting T, MIN and MAX representing the case of a
278 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
279 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
280 In corner cases where MAX+1 or MIN-1 wraps this will fall back
281 to varying.
282 This routine exists to ease canonicalization in the case where we
283 extract ranges from var + CST op limit. */
285 static void
286 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
287 tree min, tree max, bitmap equiv)
289 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
290 if (t == VR_UNDEFINED)
292 set_value_range_to_undefined (vr);
293 return;
295 else if (t == VR_VARYING)
297 set_value_range_to_varying (vr);
298 return;
301 /* Nothing to canonicalize for symbolic ranges. */
302 if (TREE_CODE (min) != INTEGER_CST
303 || TREE_CODE (max) != INTEGER_CST)
305 set_value_range (vr, t, min, max, equiv);
306 return;
309 /* Wrong order for min and max, to swap them and the VR type we need
310 to adjust them. */
311 if (tree_int_cst_lt (max, min))
313 tree one, tmp;
315 /* For one bit precision if max < min, then the swapped
316 range covers all values, so for VR_RANGE it is varying and
317 for VR_ANTI_RANGE empty range, so drop to varying as well. */
318 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
320 set_value_range_to_varying (vr);
321 return;
324 one = build_int_cst (TREE_TYPE (min), 1);
325 tmp = int_const_binop (PLUS_EXPR, max, one);
326 max = int_const_binop (MINUS_EXPR, min, one);
327 min = tmp;
329 /* There's one corner case, if we had [C+1, C] before we now have
330 that again. But this represents an empty value range, so drop
331 to varying in this case. */
332 if (tree_int_cst_lt (max, min))
334 set_value_range_to_varying (vr);
335 return;
338 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
341 /* Anti-ranges that can be represented as ranges should be so. */
342 if (t == VR_ANTI_RANGE)
344 bool is_min = vrp_val_is_min (min);
345 bool is_max = vrp_val_is_max (max);
347 if (is_min && is_max)
349 /* We cannot deal with empty ranges, drop to varying.
350 ??? This could be VR_UNDEFINED instead. */
351 set_value_range_to_varying (vr);
352 return;
354 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
355 && (is_min || is_max))
357 /* Non-empty boolean ranges can always be represented
358 as a singleton range. */
359 if (is_min)
360 min = max = vrp_val_max (TREE_TYPE (min));
361 else
362 min = max = vrp_val_min (TREE_TYPE (min));
363 t = VR_RANGE;
365 else if (is_min
366 /* As a special exception preserve non-null ranges. */
367 && !(TYPE_UNSIGNED (TREE_TYPE (min))
368 && integer_zerop (max)))
370 tree one = build_int_cst (TREE_TYPE (max), 1);
371 min = int_const_binop (PLUS_EXPR, max, one);
372 max = vrp_val_max (TREE_TYPE (max));
373 t = VR_RANGE;
375 else if (is_max)
377 tree one = build_int_cst (TREE_TYPE (min), 1);
378 max = int_const_binop (MINUS_EXPR, min, one);
379 min = vrp_val_min (TREE_TYPE (min));
380 t = VR_RANGE;
384 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
385 to make sure VRP iteration terminates, otherwise we can get into
386 oscillations. */
388 set_value_range (vr, t, min, max, equiv);
391 /* Copy value range FROM into value range TO. */
393 static inline void
394 copy_value_range (value_range *to, value_range *from)
396 set_value_range (to, from->type, from->min, from->max, from->equiv);
399 /* Set value range VR to a single value. This function is only called
400 with values we get from statements, and exists to clear the
401 TREE_OVERFLOW flag. */
403 static inline void
404 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
406 gcc_assert (is_gimple_min_invariant (val));
407 if (TREE_OVERFLOW_P (val))
408 val = drop_tree_overflow (val);
409 set_value_range (vr, VR_RANGE, val, val, equiv);
412 /* Set value range VR to a non-negative range of type TYPE. */
414 static inline void
415 set_value_range_to_nonnegative (value_range *vr, tree type)
417 tree zero = build_int_cst (type, 0);
418 set_value_range (vr, VR_RANGE, zero, vrp_val_max (type), vr->equiv);
421 /* Set value range VR to a non-NULL range of type TYPE. */
423 static inline void
424 set_value_range_to_nonnull (value_range *vr, tree type)
426 tree zero = build_int_cst (type, 0);
427 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
431 /* Set value range VR to a NULL range of type TYPE. */
433 static inline void
434 set_value_range_to_null (value_range *vr, tree type)
436 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
440 /* Set value range VR to a range of a truthvalue of type TYPE. */
442 static inline void
443 set_value_range_to_truthvalue (value_range *vr, tree type)
445 if (TYPE_PRECISION (type) == 1)
446 set_value_range_to_varying (vr);
447 else
448 set_value_range (vr, VR_RANGE,
449 build_int_cst (type, 0), build_int_cst (type, 1),
450 vr->equiv);
454 /* If abs (min) < abs (max), set VR to [-max, max], if
455 abs (min) >= abs (max), set VR to [-min, min]. */
457 static void
458 abs_extent_range (value_range *vr, tree min, tree max)
460 int cmp;
462 gcc_assert (TREE_CODE (min) == INTEGER_CST);
463 gcc_assert (TREE_CODE (max) == INTEGER_CST);
464 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
465 gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
466 min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
467 max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
468 if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
470 set_value_range_to_varying (vr);
471 return;
473 cmp = compare_values (min, max);
474 if (cmp == -1)
475 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
476 else if (cmp == 0 || cmp == 1)
478 max = min;
479 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
481 else
483 set_value_range_to_varying (vr);
484 return;
486 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
490 /* Return value range information for VAR.
492 If we have no values ranges recorded (ie, VRP is not running), then
493 return NULL. Otherwise create an empty range if none existed for VAR. */
495 value_range *
496 vr_values::get_value_range (const_tree var)
498 static const value_range vr_const_varying
499 = { VR_VARYING, NULL_TREE, NULL_TREE, NULL };
500 value_range *vr;
501 tree sym;
502 unsigned ver = SSA_NAME_VERSION (var);
504 /* If we have no recorded ranges, then return NULL. */
505 if (! vr_value)
506 return NULL;
508 /* If we query the range for a new SSA name return an unmodifiable VARYING.
509 We should get here at most from the substitute-and-fold stage which
510 will never try to change values. */
511 if (ver >= num_vr_values)
512 return CONST_CAST (value_range *, &vr_const_varying);
514 vr = vr_value[ver];
515 if (vr)
516 return vr;
518 /* After propagation finished do not allocate new value-ranges. */
519 if (values_propagated)
520 return CONST_CAST (value_range *, &vr_const_varying);
522 /* Create a default value range. */
523 vr_value[ver] = vr = vrp_value_range_pool.allocate ();
524 memset (vr, 0, sizeof (*vr));
526 /* Defer allocating the equivalence set. */
527 vr->equiv = NULL;
529 /* If VAR is a default definition of a parameter, the variable can
530 take any value in VAR's type. */
531 if (SSA_NAME_IS_DEFAULT_DEF (var))
533 sym = SSA_NAME_VAR (var);
534 if (TREE_CODE (sym) == PARM_DECL)
536 /* Try to use the "nonnull" attribute to create ~[0, 0]
537 anti-ranges for pointers. Note that this is only valid with
538 default definitions of PARM_DECLs. */
539 if (POINTER_TYPE_P (TREE_TYPE (sym))
540 && (nonnull_arg_p (sym)
541 || get_ptr_nonnull (var)))
542 set_value_range_to_nonnull (vr, TREE_TYPE (sym));
543 else if (INTEGRAL_TYPE_P (TREE_TYPE (sym)))
545 wide_int min, max;
546 value_range_type rtype = get_range_info (var, &min, &max);
547 if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
548 set_value_range (vr, rtype,
549 wide_int_to_tree (TREE_TYPE (var), min),
550 wide_int_to_tree (TREE_TYPE (var), max),
551 NULL);
552 else
553 set_value_range_to_varying (vr);
555 else
556 set_value_range_to_varying (vr);
558 else if (TREE_CODE (sym) == RESULT_DECL
559 && DECL_BY_REFERENCE (sym))
560 set_value_range_to_nonnull (vr, TREE_TYPE (sym));
563 return vr;
566 /* Set value-ranges of all SSA names defined by STMT to varying. */
568 void
569 vr_values::set_defs_to_varying (gimple *stmt)
571 ssa_op_iter i;
572 tree def;
573 FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
575 value_range *vr = get_value_range (def);
576 /* Avoid writing to vr_const_varying get_value_range may return. */
577 if (vr->type != VR_VARYING)
578 set_value_range_to_varying (vr);
583 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
585 static inline bool
586 vrp_operand_equal_p (const_tree val1, const_tree val2)
588 if (val1 == val2)
589 return true;
590 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
591 return false;
592 return true;
595 /* Return true, if the bitmaps B1 and B2 are equal. */
597 static inline bool
598 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
600 return (b1 == b2
601 || ((!b1 || bitmap_empty_p (b1))
602 && (!b2 || bitmap_empty_p (b2)))
603 || (b1 && b2
604 && bitmap_equal_p (b1, b2)));
607 /* Update the value range and equivalence set for variable VAR to
608 NEW_VR. Return true if NEW_VR is different from VAR's previous
609 value.
611 NOTE: This function assumes that NEW_VR is a temporary value range
612 object created for the sole purpose of updating VAR's range. The
613 storage used by the equivalence set from NEW_VR will be freed by
614 this function. Do not call update_value_range when NEW_VR
615 is the range object associated with another SSA name. */
617 bool
618 vr_values::update_value_range (const_tree var, value_range *new_vr)
620 value_range *old_vr;
621 bool is_new;
623 /* If there is a value-range on the SSA name from earlier analysis
624 factor that in. */
625 if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
627 wide_int min, max;
628 value_range_type rtype = get_range_info (var, &min, &max);
629 if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
631 tree nr_min, nr_max;
632 nr_min = wide_int_to_tree (TREE_TYPE (var), min);
633 nr_max = wide_int_to_tree (TREE_TYPE (var), max);
634 value_range nr = VR_INITIALIZER;
635 set_and_canonicalize_value_range (&nr, rtype, nr_min, nr_max, NULL);
636 vrp_intersect_ranges (new_vr, &nr);
640 /* Update the value range, if necessary. */
641 old_vr = get_value_range (var);
642 is_new = old_vr->type != new_vr->type
643 || !vrp_operand_equal_p (old_vr->min, new_vr->min)
644 || !vrp_operand_equal_p (old_vr->max, new_vr->max)
645 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr->equiv);
647 if (is_new)
649 /* Do not allow transitions up the lattice. The following
650 is slightly more awkward than just new_vr->type < old_vr->type
651 because VR_RANGE and VR_ANTI_RANGE need to be considered
652 the same. We may not have is_new when transitioning to
653 UNDEFINED. If old_vr->type is VARYING, we shouldn't be
654 called. */
655 if (new_vr->type == VR_UNDEFINED)
657 BITMAP_FREE (new_vr->equiv);
658 set_value_range_to_varying (old_vr);
659 set_value_range_to_varying (new_vr);
660 return true;
662 else
663 set_value_range (old_vr, new_vr->type, new_vr->min, new_vr->max,
664 new_vr->equiv);
667 BITMAP_FREE (new_vr->equiv);
669 return is_new;
673 /* Add VAR and VAR's equivalence set to EQUIV. This is the central
674 point where equivalence processing can be turned on/off. */
676 void
677 vr_values::add_equivalence (bitmap *equiv, const_tree var)
679 unsigned ver = SSA_NAME_VERSION (var);
680 value_range *vr = get_value_range (var);
682 if (*equiv == NULL)
683 *equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
684 bitmap_set_bit (*equiv, ver);
685 if (vr && vr->equiv)
686 bitmap_ior_into (*equiv, vr->equiv);
690 /* Return true if VR is ~[0, 0]. */
692 static inline bool
693 range_is_nonnull (value_range *vr)
695 return vr->type == VR_ANTI_RANGE
696 && integer_zerop (vr->min)
697 && integer_zerop (vr->max);
701 /* Return true if VR is [0, 0]. */
703 static inline bool
704 range_is_null (value_range *vr)
706 return vr->type == VR_RANGE
707 && integer_zerop (vr->min)
708 && integer_zerop (vr->max);
711 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
712 a singleton. */
714 static inline bool
715 range_int_cst_p (value_range *vr)
717 return (vr->type == VR_RANGE
718 && TREE_CODE (vr->max) == INTEGER_CST
719 && TREE_CODE (vr->min) == INTEGER_CST);
722 /* Return true if VR is a INTEGER_CST singleton. */
724 static inline bool
725 range_int_cst_singleton_p (value_range *vr)
727 return (range_int_cst_p (vr)
728 && tree_int_cst_equal (vr->min, vr->max));
731 /* Return true if value range VR involves at least one symbol. */
733 static inline bool
734 symbolic_range_p (value_range *vr)
736 return (!is_gimple_min_invariant (vr->min)
737 || !is_gimple_min_invariant (vr->max));
740 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
741 otherwise. We only handle additive operations and set NEG to true if the
742 symbol is negated and INV to the invariant part, if any. */
744 static tree
745 get_single_symbol (tree t, bool *neg, tree *inv)
747 bool neg_;
748 tree inv_;
750 *inv = NULL_TREE;
751 *neg = false;
753 if (TREE_CODE (t) == PLUS_EXPR
754 || TREE_CODE (t) == POINTER_PLUS_EXPR
755 || TREE_CODE (t) == MINUS_EXPR)
757 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
759 neg_ = (TREE_CODE (t) == MINUS_EXPR);
760 inv_ = TREE_OPERAND (t, 0);
761 t = TREE_OPERAND (t, 1);
763 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
765 neg_ = false;
766 inv_ = TREE_OPERAND (t, 1);
767 t = TREE_OPERAND (t, 0);
769 else
770 return NULL_TREE;
772 else
774 neg_ = false;
775 inv_ = NULL_TREE;
778 if (TREE_CODE (t) == NEGATE_EXPR)
780 t = TREE_OPERAND (t, 0);
781 neg_ = !neg_;
784 if (TREE_CODE (t) != SSA_NAME)
785 return NULL_TREE;
787 if (inv_ && TREE_OVERFLOW_P (inv_))
788 inv_ = drop_tree_overflow (inv_);
790 *neg = neg_;
791 *inv = inv_;
792 return t;
795 /* The reverse operation: build a symbolic expression with TYPE
796 from symbol SYM, negated according to NEG, and invariant INV. */
798 static tree
799 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
801 const bool pointer_p = POINTER_TYPE_P (type);
802 tree t = sym;
804 if (neg)
805 t = build1 (NEGATE_EXPR, type, t);
807 if (integer_zerop (inv))
808 return t;
810 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
813 /* Return true if value range VR involves exactly one symbol SYM. */
815 static bool
816 symbolic_range_based_on_p (value_range *vr, const_tree sym)
818 bool neg, min_has_symbol, max_has_symbol;
819 tree inv;
821 if (is_gimple_min_invariant (vr->min))
822 min_has_symbol = false;
823 else if (get_single_symbol (vr->min, &neg, &inv) == sym)
824 min_has_symbol = true;
825 else
826 return false;
828 if (is_gimple_min_invariant (vr->max))
829 max_has_symbol = false;
830 else if (get_single_symbol (vr->max, &neg, &inv) == sym)
831 max_has_symbol = true;
832 else
833 return false;
835 return (min_has_symbol || max_has_symbol);
838 /* Return true if the result of assignment STMT is know to be non-zero. */
840 static bool
841 gimple_assign_nonzero_p (gimple *stmt)
843 enum tree_code code = gimple_assign_rhs_code (stmt);
844 bool strict_overflow_p;
845 switch (get_gimple_rhs_class (code))
847 case GIMPLE_UNARY_RHS:
848 return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
849 gimple_expr_type (stmt),
850 gimple_assign_rhs1 (stmt),
851 &strict_overflow_p);
852 case GIMPLE_BINARY_RHS:
853 return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
854 gimple_expr_type (stmt),
855 gimple_assign_rhs1 (stmt),
856 gimple_assign_rhs2 (stmt),
857 &strict_overflow_p);
858 case GIMPLE_TERNARY_RHS:
859 return false;
860 case GIMPLE_SINGLE_RHS:
861 return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
862 &strict_overflow_p);
863 case GIMPLE_INVALID_RHS:
864 gcc_unreachable ();
865 default:
866 gcc_unreachable ();
870 /* Return true if STMT is known to compute a non-zero value. */
872 static bool
873 gimple_stmt_nonzero_p (gimple *stmt)
875 switch (gimple_code (stmt))
877 case GIMPLE_ASSIGN:
878 return gimple_assign_nonzero_p (stmt);
879 case GIMPLE_CALL:
881 tree fndecl = gimple_call_fndecl (stmt);
882 if (!fndecl) return false;
883 if (flag_delete_null_pointer_checks && !flag_check_new
884 && DECL_IS_OPERATOR_NEW (fndecl)
885 && !TREE_NOTHROW (fndecl))
886 return true;
887 /* References are always non-NULL. */
888 if (flag_delete_null_pointer_checks
889 && TREE_CODE (TREE_TYPE (fndecl)) == REFERENCE_TYPE)
890 return true;
891 if (flag_delete_null_pointer_checks &&
892 lookup_attribute ("returns_nonnull",
893 TYPE_ATTRIBUTES (gimple_call_fntype (stmt))))
894 return true;
896 gcall *call_stmt = as_a<gcall *> (stmt);
897 unsigned rf = gimple_call_return_flags (call_stmt);
898 if (rf & ERF_RETURNS_ARG)
900 unsigned argnum = rf & ERF_RETURN_ARG_MASK;
901 if (argnum < gimple_call_num_args (call_stmt))
903 tree arg = gimple_call_arg (call_stmt, argnum);
904 if (SSA_VAR_P (arg)
905 && infer_nonnull_range_by_attribute (stmt, arg))
906 return true;
909 return gimple_alloca_call_p (stmt);
911 default:
912 gcc_unreachable ();
916 /* Like tree_expr_nonzero_p, but this function uses value ranges
917 obtained so far. */
919 bool
920 vr_values::vrp_stmt_computes_nonzero (gimple *stmt)
922 if (gimple_stmt_nonzero_p (stmt))
923 return true;
925 /* If we have an expression of the form &X->a, then the expression
926 is nonnull if X is nonnull. */
927 if (is_gimple_assign (stmt)
928 && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
930 tree expr = gimple_assign_rhs1 (stmt);
931 tree base = get_base_address (TREE_OPERAND (expr, 0));
933 if (base != NULL_TREE
934 && TREE_CODE (base) == MEM_REF
935 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
937 value_range *vr = get_value_range (TREE_OPERAND (base, 0));
938 if (range_is_nonnull (vr))
939 return true;
943 return false;
946 /* Returns true if EXPR is a valid value (as expected by compare_values) --
947 a gimple invariant, or SSA_NAME +- CST. */
949 static bool
950 valid_value_p (tree expr)
952 if (TREE_CODE (expr) == SSA_NAME)
953 return true;
955 if (TREE_CODE (expr) == PLUS_EXPR
956 || TREE_CODE (expr) == MINUS_EXPR)
957 return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
958 && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
960 return is_gimple_min_invariant (expr);
963 /* Return
964 1 if VAL < VAL2
965 0 if !(VAL < VAL2)
966 -2 if those are incomparable. */
967 static inline int
968 operand_less_p (tree val, tree val2)
970 /* LT is folded faster than GE and others. Inline the common case. */
971 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
972 return tree_int_cst_lt (val, val2);
973 else
975 tree tcmp;
977 fold_defer_overflow_warnings ();
979 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
981 fold_undefer_and_ignore_overflow_warnings ();
983 if (!tcmp
984 || TREE_CODE (tcmp) != INTEGER_CST)
985 return -2;
987 if (!integer_zerop (tcmp))
988 return 1;
991 return 0;
994 /* Compare two values VAL1 and VAL2. Return
996 -2 if VAL1 and VAL2 cannot be compared at compile-time,
997 -1 if VAL1 < VAL2,
998 0 if VAL1 == VAL2,
999 +1 if VAL1 > VAL2, and
1000 +2 if VAL1 != VAL2
1002 This is similar to tree_int_cst_compare but supports pointer values
1003 and values that cannot be compared at compile time.
1005 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
1006 true if the return value is only valid if we assume that signed
1007 overflow is undefined. */
1009 static int
1010 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
1012 if (val1 == val2)
1013 return 0;
1015 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
1016 both integers. */
1017 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
1018 == POINTER_TYPE_P (TREE_TYPE (val2)));
1020 /* Convert the two values into the same type. This is needed because
1021 sizetype causes sign extension even for unsigned types. */
1022 val2 = fold_convert (TREE_TYPE (val1), val2);
1023 STRIP_USELESS_TYPE_CONVERSION (val2);
1025 const bool overflow_undefined
1026 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
1027 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
1028 tree inv1, inv2;
1029 bool neg1, neg2;
1030 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
1031 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
1033 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
1034 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
1035 if (sym1 && sym2)
1037 /* Both values must use the same name with the same sign. */
1038 if (sym1 != sym2 || neg1 != neg2)
1039 return -2;
1041 /* [-]NAME + CST == [-]NAME + CST. */
1042 if (inv1 == inv2)
1043 return 0;
1045 /* If overflow is defined we cannot simplify more. */
1046 if (!overflow_undefined)
1047 return -2;
1049 if (strict_overflow_p != NULL
1050 /* Symbolic range building sets TREE_NO_WARNING to declare
1051 that overflow doesn't happen. */
1052 && (!inv1 || !TREE_NO_WARNING (val1))
1053 && (!inv2 || !TREE_NO_WARNING (val2)))
1054 *strict_overflow_p = true;
1056 if (!inv1)
1057 inv1 = build_int_cst (TREE_TYPE (val1), 0);
1058 if (!inv2)
1059 inv2 = build_int_cst (TREE_TYPE (val2), 0);
1061 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
1062 TYPE_SIGN (TREE_TYPE (val1)));
1065 const bool cst1 = is_gimple_min_invariant (val1);
1066 const bool cst2 = is_gimple_min_invariant (val2);
1068 /* If one is of the form '[-]NAME + CST' and the other is constant, then
1069 it might be possible to say something depending on the constants. */
1070 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
1072 if (!overflow_undefined)
1073 return -2;
1075 if (strict_overflow_p != NULL
1076 /* Symbolic range building sets TREE_NO_WARNING to declare
1077 that overflow doesn't happen. */
1078 && (!sym1 || !TREE_NO_WARNING (val1))
1079 && (!sym2 || !TREE_NO_WARNING (val2)))
1080 *strict_overflow_p = true;
1082 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
1083 tree cst = cst1 ? val1 : val2;
1084 tree inv = cst1 ? inv2 : inv1;
1086 /* Compute the difference between the constants. If it overflows or
1087 underflows, this means that we can trivially compare the NAME with
1088 it and, consequently, the two values with each other. */
1089 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
1090 if (wi::cmp (0, wi::to_wide (inv), sgn)
1091 != wi::cmp (diff, wi::to_wide (cst), sgn))
1093 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
1094 return cst1 ? res : -res;
1097 return -2;
1100 /* We cannot say anything more for non-constants. */
1101 if (!cst1 || !cst2)
1102 return -2;
1104 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1106 /* We cannot compare overflowed values. */
1107 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1108 return -2;
1110 return tree_int_cst_compare (val1, val2);
1112 else
1114 tree t;
1116 /* First see if VAL1 and VAL2 are not the same. */
1117 if (val1 == val2 || operand_equal_p (val1, val2, 0))
1118 return 0;
1120 /* If VAL1 is a lower address than VAL2, return -1. */
1121 if (operand_less_p (val1, val2) == 1)
1122 return -1;
1124 /* If VAL1 is a higher address than VAL2, return +1. */
1125 if (operand_less_p (val2, val1) == 1)
1126 return 1;
1128 /* If VAL1 is different than VAL2, return +2.
1129 For integer constants we either have already returned -1 or 1
1130 or they are equivalent. We still might succeed in proving
1131 something about non-trivial operands. */
1132 if (TREE_CODE (val1) != INTEGER_CST
1133 || TREE_CODE (val2) != INTEGER_CST)
1135 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1136 if (t && integer_onep (t))
1137 return 2;
1140 return -2;
1144 /* Compare values like compare_values_warnv. */
1146 static int
1147 compare_values (tree val1, tree val2)
1149 bool sop;
1150 return compare_values_warnv (val1, val2, &sop);
1154 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
1155 0 if VAL is not inside [MIN, MAX],
1156 -2 if we cannot tell either way.
1158 Benchmark compile/20001226-1.c compilation time after changing this
1159 function. */
1161 static inline int
1162 value_inside_range (tree val, tree min, tree max)
1164 int cmp1, cmp2;
1166 cmp1 = operand_less_p (val, min);
1167 if (cmp1 == -2)
1168 return -2;
1169 if (cmp1 == 1)
1170 return 0;
1172 cmp2 = operand_less_p (max, val);
1173 if (cmp2 == -2)
1174 return -2;
1176 return !cmp2;
1180 /* Return true if value ranges VR0 and VR1 have a non-empty
1181 intersection.
1183 Benchmark compile/20001226-1.c compilation time after changing this
1184 function.
1187 static inline bool
1188 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
1190 /* The value ranges do not intersect if the maximum of the first range is
1191 less than the minimum of the second range or vice versa.
1192 When those relations are unknown, we can't do any better. */
1193 if (operand_less_p (vr0->max, vr1->min) != 0)
1194 return false;
1195 if (operand_less_p (vr1->max, vr0->min) != 0)
1196 return false;
1197 return true;
1201 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
1202 include the value zero, -2 if we cannot tell. */
1204 static inline int
1205 range_includes_zero_p (tree min, tree max)
1207 tree zero = build_int_cst (TREE_TYPE (min), 0);
1208 return value_inside_range (zero, min, max);
1211 /* Return true if *VR is know to only contain nonnegative values. */
1213 static inline bool
1214 value_range_nonnegative_p (value_range *vr)
1216 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
1217 which would return a useful value should be encoded as a
1218 VR_RANGE. */
1219 if (vr->type == VR_RANGE)
1221 int result = compare_values (vr->min, integer_zero_node);
1222 return (result == 0 || result == 1);
1225 return false;
1228 /* If *VR has a value rante that is a single constant value return that,
1229 otherwise return NULL_TREE. */
1231 static tree
1232 value_range_constant_singleton (value_range *vr)
1234 if (vr->type == VR_RANGE
1235 && vrp_operand_equal_p (vr->min, vr->max)
1236 && is_gimple_min_invariant (vr->min))
1237 return vr->min;
1239 return NULL_TREE;
1242 /* If OP has a value range with a single constant value return that,
1243 otherwise return NULL_TREE. This returns OP itself if OP is a
1244 constant. */
1246 tree
1247 vr_values::op_with_constant_singleton_value_range (tree op)
1249 if (is_gimple_min_invariant (op))
1250 return op;
1252 if (TREE_CODE (op) != SSA_NAME)
1253 return NULL_TREE;
1255 return value_range_constant_singleton (get_value_range (op));
1258 /* Return true if op is in a boolean [0, 1] value-range. */
1260 bool
1261 vr_values::op_with_boolean_value_range_p (tree op)
1263 value_range *vr;
1265 if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
1266 return true;
1268 if (integer_zerop (op)
1269 || integer_onep (op))
1270 return true;
1272 if (TREE_CODE (op) != SSA_NAME)
1273 return false;
1275 vr = get_value_range (op);
1276 return (vr->type == VR_RANGE
1277 && integer_zerop (vr->min)
1278 && integer_onep (vr->max));
1281 /* Extract value range information for VAR when (OP COND_CODE LIMIT) is
1282 true and store it in *VR_P. */
1284 void
1285 vr_values::extract_range_for_var_from_comparison_expr (tree var,
1286 enum tree_code cond_code,
1287 tree op, tree limit,
1288 value_range *vr_p)
1290 tree min, max, type;
1291 value_range *limit_vr;
1292 type = TREE_TYPE (var);
1293 gcc_assert (limit != var);
1295 /* For pointer arithmetic, we only keep track of pointer equality
1296 and inequality. */
1297 if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
1299 set_value_range_to_varying (vr_p);
1300 return;
1303 /* If LIMIT is another SSA name and LIMIT has a range of its own,
1304 try to use LIMIT's range to avoid creating symbolic ranges
1305 unnecessarily. */
1306 limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
1308 /* LIMIT's range is only interesting if it has any useful information. */
1309 if (! limit_vr
1310 || limit_vr->type == VR_UNDEFINED
1311 || limit_vr->type == VR_VARYING
1312 || (symbolic_range_p (limit_vr)
1313 && ! (limit_vr->type == VR_RANGE
1314 && (limit_vr->min == limit_vr->max
1315 || operand_equal_p (limit_vr->min, limit_vr->max, 0)))))
1316 limit_vr = NULL;
1318 /* Initially, the new range has the same set of equivalences of
1319 VAR's range. This will be revised before returning the final
1320 value. Since assertions may be chained via mutually exclusive
1321 predicates, we will need to trim the set of equivalences before
1322 we are done. */
1323 gcc_assert (vr_p->equiv == NULL);
1324 add_equivalence (&vr_p->equiv, var);
1326 /* Extract a new range based on the asserted comparison for VAR and
1327 LIMIT's value range. Notice that if LIMIT has an anti-range, we
1328 will only use it for equality comparisons (EQ_EXPR). For any
1329 other kind of assertion, we cannot derive a range from LIMIT's
1330 anti-range that can be used to describe the new range. For
1331 instance, ASSERT_EXPR <x_2, x_2 <= b_4>. If b_4 is ~[2, 10],
1332 then b_4 takes on the ranges [-INF, 1] and [11, +INF]. There is
1333 no single range for x_2 that could describe LE_EXPR, so we might
1334 as well build the range [b_4, +INF] for it.
1335 One special case we handle is extracting a range from a
1336 range test encoded as (unsigned)var + CST <= limit. */
1337 if (TREE_CODE (op) == NOP_EXPR
1338 || TREE_CODE (op) == PLUS_EXPR)
1340 if (TREE_CODE (op) == PLUS_EXPR)
1342 min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (op, 1)),
1343 TREE_OPERAND (op, 1));
1344 max = int_const_binop (PLUS_EXPR, limit, min);
1345 op = TREE_OPERAND (op, 0);
1347 else
1349 min = build_int_cst (TREE_TYPE (var), 0);
1350 max = limit;
1353 /* Make sure to not set TREE_OVERFLOW on the final type
1354 conversion. We are willingly interpreting large positive
1355 unsigned values as negative signed values here. */
1356 min = force_fit_type (TREE_TYPE (var), wi::to_widest (min), 0, false);
1357 max = force_fit_type (TREE_TYPE (var), wi::to_widest (max), 0, false);
1359 /* We can transform a max, min range to an anti-range or
1360 vice-versa. Use set_and_canonicalize_value_range which does
1361 this for us. */
1362 if (cond_code == LE_EXPR)
1363 set_and_canonicalize_value_range (vr_p, VR_RANGE,
1364 min, max, vr_p->equiv);
1365 else if (cond_code == GT_EXPR)
1366 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1367 min, max, vr_p->equiv);
1368 else
1369 gcc_unreachable ();
1371 else if (cond_code == EQ_EXPR)
1373 enum value_range_type range_type;
1375 if (limit_vr)
1377 range_type = limit_vr->type;
1378 min = limit_vr->min;
1379 max = limit_vr->max;
1381 else
1383 range_type = VR_RANGE;
1384 min = limit;
1385 max = limit;
1388 set_value_range (vr_p, range_type, min, max, vr_p->equiv);
1390 /* When asserting the equality VAR == LIMIT and LIMIT is another
1391 SSA name, the new range will also inherit the equivalence set
1392 from LIMIT. */
1393 if (TREE_CODE (limit) == SSA_NAME)
1394 add_equivalence (&vr_p->equiv, limit);
1396 else if (cond_code == NE_EXPR)
1398 /* As described above, when LIMIT's range is an anti-range and
1399 this assertion is an inequality (NE_EXPR), then we cannot
1400 derive anything from the anti-range. For instance, if
1401 LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
1402 not imply that VAR's range is [0, 0]. So, in the case of
1403 anti-ranges, we just assert the inequality using LIMIT and
1404 not its anti-range.
1406 If LIMIT_VR is a range, we can only use it to build a new
1407 anti-range if LIMIT_VR is a single-valued range. For
1408 instance, if LIMIT_VR is [0, 1], the predicate
1409 VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
1410 Rather, it means that for value 0 VAR should be ~[0, 0]
1411 and for value 1, VAR should be ~[1, 1]. We cannot
1412 represent these ranges.
1414 The only situation in which we can build a valid
1415 anti-range is when LIMIT_VR is a single-valued range
1416 (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX). In that case,
1417 build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX]. */
1418 if (limit_vr
1419 && limit_vr->type == VR_RANGE
1420 && compare_values (limit_vr->min, limit_vr->max) == 0)
1422 min = limit_vr->min;
1423 max = limit_vr->max;
1425 else
1427 /* In any other case, we cannot use LIMIT's range to build a
1428 valid anti-range. */
1429 min = max = limit;
1432 /* If MIN and MAX cover the whole range for their type, then
1433 just use the original LIMIT. */
1434 if (INTEGRAL_TYPE_P (type)
1435 && vrp_val_is_min (min)
1436 && vrp_val_is_max (max))
1437 min = max = limit;
1439 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1440 min, max, vr_p->equiv);
1442 else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
1444 min = TYPE_MIN_VALUE (type);
1446 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1447 max = limit;
1448 else
1450 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1451 range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
1452 LT_EXPR. */
1453 max = limit_vr->max;
1456 /* If the maximum value forces us to be out of bounds, simply punt.
1457 It would be pointless to try and do anything more since this
1458 all should be optimized away above us. */
1459 if (cond_code == LT_EXPR
1460 && compare_values (max, min) == 0)
1461 set_value_range_to_varying (vr_p);
1462 else
1464 /* For LT_EXPR, we create the range [MIN, MAX - 1]. */
1465 if (cond_code == LT_EXPR)
1467 if (TYPE_PRECISION (TREE_TYPE (max)) == 1
1468 && !TYPE_UNSIGNED (TREE_TYPE (max)))
1469 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
1470 build_int_cst (TREE_TYPE (max), -1));
1471 else
1472 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
1473 build_int_cst (TREE_TYPE (max), 1));
1474 /* Signal to compare_values_warnv this expr doesn't overflow. */
1475 if (EXPR_P (max))
1476 TREE_NO_WARNING (max) = 1;
1479 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1482 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
1484 max = TYPE_MAX_VALUE (type);
1486 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1487 min = limit;
1488 else
1490 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1491 range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
1492 GT_EXPR. */
1493 min = limit_vr->min;
1496 /* If the minimum value forces us to be out of bounds, simply punt.
1497 It would be pointless to try and do anything more since this
1498 all should be optimized away above us. */
1499 if (cond_code == GT_EXPR
1500 && compare_values (min, max) == 0)
1501 set_value_range_to_varying (vr_p);
1502 else
1504 /* For GT_EXPR, we create the range [MIN + 1, MAX]. */
1505 if (cond_code == GT_EXPR)
1507 if (TYPE_PRECISION (TREE_TYPE (min)) == 1
1508 && !TYPE_UNSIGNED (TREE_TYPE (min)))
1509 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
1510 build_int_cst (TREE_TYPE (min), -1));
1511 else
1512 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
1513 build_int_cst (TREE_TYPE (min), 1));
1514 /* Signal to compare_values_warnv this expr doesn't overflow. */
1515 if (EXPR_P (min))
1516 TREE_NO_WARNING (min) = 1;
1519 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1522 else
1523 gcc_unreachable ();
1525 /* Finally intersect the new range with what we already know about var. */
1526 vrp_intersect_ranges (vr_p, get_value_range (var));
1529 /* Extract value range information from an ASSERT_EXPR EXPR and store
1530 it in *VR_P. */
1532 void
1533 vr_values::extract_range_from_assert (value_range *vr_p, tree expr)
1535 tree var = ASSERT_EXPR_VAR (expr);
1536 tree cond = ASSERT_EXPR_COND (expr);
1537 tree limit, op;
1538 enum tree_code cond_code;
1539 gcc_assert (COMPARISON_CLASS_P (cond));
1541 /* Find VAR in the ASSERT_EXPR conditional. */
1542 if (var == TREE_OPERAND (cond, 0)
1543 || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
1544 || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
1546 /* If the predicate is of the form VAR COMP LIMIT, then we just
1547 take LIMIT from the RHS and use the same comparison code. */
1548 cond_code = TREE_CODE (cond);
1549 limit = TREE_OPERAND (cond, 1);
1550 op = TREE_OPERAND (cond, 0);
1552 else
1554 /* If the predicate is of the form LIMIT COMP VAR, then we need
1555 to flip around the comparison code to create the proper range
1556 for VAR. */
1557 cond_code = swap_tree_comparison (TREE_CODE (cond));
1558 limit = TREE_OPERAND (cond, 0);
1559 op = TREE_OPERAND (cond, 1);
1561 extract_range_for_var_from_comparison_expr (var, cond_code, op,
1562 limit, vr_p);
1565 /* Extract range information from SSA name VAR and store it in VR. If
1566 VAR has an interesting range, use it. Otherwise, create the
1567 range [VAR, VAR] and return it. This is useful in situations where
1568 we may have conditionals testing values of VARYING names. For
1569 instance,
1571 x_3 = y_5;
1572 if (x_3 > y_5)
1575 Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
1576 always false. */
1578 void
1579 vr_values::extract_range_from_ssa_name (value_range *vr, tree var)
1581 value_range *var_vr = get_value_range (var);
1583 if (var_vr->type != VR_VARYING)
1584 copy_value_range (vr, var_vr);
1585 else
1586 set_value_range (vr, VR_RANGE, var, var, NULL);
1588 add_equivalence (&vr->equiv, var);
1592 /* Wrapper around int_const_binop. Return true if we can compute the
1593 result; i.e. if the operation doesn't overflow or if the overflow is
1594 undefined. In the latter case (if the operation overflows and
1595 overflow is undefined), then adjust the result to be -INF or +INF
1596 depending on CODE, VAL1 and VAL2. Return the value in *RES.
1598 Return false for division by zero, for which the result is
1599 indeterminate. */
1601 static bool
1602 vrp_int_const_binop (enum tree_code code, tree val1, tree val2, wide_int *res)
1604 bool overflow = false;
1605 signop sign = TYPE_SIGN (TREE_TYPE (val1));
1607 switch (code)
1609 case RSHIFT_EXPR:
1610 case LSHIFT_EXPR:
1612 wide_int wval2 = wi::to_wide (val2, TYPE_PRECISION (TREE_TYPE (val1)));
1613 if (wi::neg_p (wval2))
1615 wval2 = -wval2;
1616 if (code == RSHIFT_EXPR)
1617 code = LSHIFT_EXPR;
1618 else
1619 code = RSHIFT_EXPR;
1622 if (code == RSHIFT_EXPR)
1623 /* It's unclear from the C standard whether shifts can overflow.
1624 The following code ignores overflow; perhaps a C standard
1625 interpretation ruling is needed. */
1626 *res = wi::rshift (wi::to_wide (val1), wval2, sign);
1627 else
1628 *res = wi::lshift (wi::to_wide (val1), wval2);
1629 break;
1632 case MULT_EXPR:
1633 *res = wi::mul (wi::to_wide (val1),
1634 wi::to_wide (val2), sign, &overflow);
1635 break;
1637 case TRUNC_DIV_EXPR:
1638 case EXACT_DIV_EXPR:
1639 if (val2 == 0)
1640 return false;
1641 else
1642 *res = wi::div_trunc (wi::to_wide (val1),
1643 wi::to_wide (val2), sign, &overflow);
1644 break;
1646 case FLOOR_DIV_EXPR:
1647 if (val2 == 0)
1648 return false;
1649 *res = wi::div_floor (wi::to_wide (val1),
1650 wi::to_wide (val2), sign, &overflow);
1651 break;
1653 case CEIL_DIV_EXPR:
1654 if (val2 == 0)
1655 return false;
1656 *res = wi::div_ceil (wi::to_wide (val1),
1657 wi::to_wide (val2), sign, &overflow);
1658 break;
1660 case ROUND_DIV_EXPR:
1661 if (val2 == 0)
1662 return false;
1663 *res = wi::div_round (wi::to_wide (val1),
1664 wi::to_wide (val2), sign, &overflow);
1665 break;
1667 default:
1668 gcc_unreachable ();
1671 if (overflow
1672 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1)))
1674 /* If the operation overflowed return -INF or +INF depending
1675 on the operation and the combination of signs of the operands. */
1676 int sgn1 = tree_int_cst_sgn (val1);
1677 int sgn2 = tree_int_cst_sgn (val2);
1679 /* Notice that we only need to handle the restricted set of
1680 operations handled by extract_range_from_binary_expr.
1681 Among them, only multiplication, addition and subtraction
1682 can yield overflow without overflown operands because we
1683 are working with integral types only... except in the
1684 case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1685 for division too. */
1687 /* For multiplication, the sign of the overflow is given
1688 by the comparison of the signs of the operands. */
1689 if ((code == MULT_EXPR && sgn1 == sgn2)
1690 /* For addition, the operands must be of the same sign
1691 to yield an overflow. Its sign is therefore that
1692 of one of the operands, for example the first. */
1693 || (code == PLUS_EXPR && sgn1 >= 0)
1694 /* For subtraction, operands must be of
1695 different signs to yield an overflow. Its sign is
1696 therefore that of the first operand or the opposite of
1697 that of the second operand. A first operand of 0 counts
1698 as positive here, for the corner case 0 - (-INF), which
1699 overflows, but must yield +INF. */
1700 || (code == MINUS_EXPR && sgn1 >= 0)
1701 /* For division, the only case is -INF / -1 = +INF. */
1702 || code == TRUNC_DIV_EXPR
1703 || code == FLOOR_DIV_EXPR
1704 || code == CEIL_DIV_EXPR
1705 || code == EXACT_DIV_EXPR
1706 || code == ROUND_DIV_EXPR)
1707 *res = wi::max_value (TYPE_PRECISION (TREE_TYPE (val1)),
1708 TYPE_SIGN (TREE_TYPE (val1)));
1709 else
1710 *res = wi::min_value (TYPE_PRECISION (TREE_TYPE (val1)),
1711 TYPE_SIGN (TREE_TYPE (val1)));
1712 return true;
1715 return !overflow;
1719 /* For range VR compute two wide_int bitmasks. In *MAY_BE_NONZERO
1720 bitmask if some bit is unset, it means for all numbers in the range
1721 the bit is 0, otherwise it might be 0 or 1. In *MUST_BE_NONZERO
1722 bitmask if some bit is set, it means for all numbers in the range
1723 the bit is 1, otherwise it might be 0 or 1. */
1725 static bool
1726 zero_nonzero_bits_from_vr (const tree expr_type,
1727 value_range *vr,
1728 wide_int *may_be_nonzero,
1729 wide_int *must_be_nonzero)
1731 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1732 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1733 if (!range_int_cst_p (vr))
1734 return false;
1736 if (range_int_cst_singleton_p (vr))
1738 *may_be_nonzero = wi::to_wide (vr->min);
1739 *must_be_nonzero = *may_be_nonzero;
1741 else if (tree_int_cst_sgn (vr->min) >= 0
1742 || tree_int_cst_sgn (vr->max) < 0)
1744 wide_int xor_mask = wi::to_wide (vr->min) ^ wi::to_wide (vr->max);
1745 *may_be_nonzero = wi::to_wide (vr->min) | wi::to_wide (vr->max);
1746 *must_be_nonzero = wi::to_wide (vr->min) & wi::to_wide (vr->max);
1747 if (xor_mask != 0)
1749 wide_int mask = wi::mask (wi::floor_log2 (xor_mask), false,
1750 may_be_nonzero->get_precision ());
1751 *may_be_nonzero = *may_be_nonzero | mask;
1752 *must_be_nonzero = wi::bit_and_not (*must_be_nonzero, mask);
1756 return true;
1759 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
1760 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
1761 false otherwise. If *AR can be represented with a single range
1762 *VR1 will be VR_UNDEFINED. */
1764 static bool
1765 ranges_from_anti_range (value_range *ar,
1766 value_range *vr0, value_range *vr1)
1768 tree type = TREE_TYPE (ar->min);
1770 vr0->type = VR_UNDEFINED;
1771 vr1->type = VR_UNDEFINED;
1773 if (ar->type != VR_ANTI_RANGE
1774 || TREE_CODE (ar->min) != INTEGER_CST
1775 || TREE_CODE (ar->max) != INTEGER_CST
1776 || !vrp_val_min (type)
1777 || !vrp_val_max (type))
1778 return false;
1780 if (!vrp_val_is_min (ar->min))
1782 vr0->type = VR_RANGE;
1783 vr0->min = vrp_val_min (type);
1784 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
1786 if (!vrp_val_is_max (ar->max))
1788 vr1->type = VR_RANGE;
1789 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
1790 vr1->max = vrp_val_max (type);
1792 if (vr0->type == VR_UNDEFINED)
1794 *vr0 = *vr1;
1795 vr1->type = VR_UNDEFINED;
1798 return vr0->type != VR_UNDEFINED;
1801 /* Helper to extract a value-range *VR for a multiplicative operation
1802 *VR0 CODE *VR1. */
1804 static void
1805 extract_range_from_multiplicative_op_1 (value_range *vr,
1806 enum tree_code code,
1807 value_range *vr0, value_range *vr1)
1809 enum value_range_type rtype;
1810 wide_int val, min, max;
1811 tree type;
1813 /* Multiplications, divisions and shifts are a bit tricky to handle,
1814 depending on the mix of signs we have in the two ranges, we
1815 need to operate on different values to get the minimum and
1816 maximum values for the new range. One approach is to figure
1817 out all the variations of range combinations and do the
1818 operations.
1820 However, this involves several calls to compare_values and it
1821 is pretty convoluted. It's simpler to do the 4 operations
1822 (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
1823 MAX1) and then figure the smallest and largest values to form
1824 the new range. */
1825 gcc_assert (code == MULT_EXPR
1826 || code == TRUNC_DIV_EXPR
1827 || code == FLOOR_DIV_EXPR
1828 || code == CEIL_DIV_EXPR
1829 || code == EXACT_DIV_EXPR
1830 || code == ROUND_DIV_EXPR
1831 || code == RSHIFT_EXPR
1832 || code == LSHIFT_EXPR);
1833 gcc_assert (vr0->type == VR_RANGE
1834 && vr0->type == vr1->type);
1836 rtype = vr0->type;
1837 type = TREE_TYPE (vr0->min);
1838 signop sgn = TYPE_SIGN (type);
1840 /* Compute the 4 cross operations and their minimum and maximum value. */
1841 if (!vrp_int_const_binop (code, vr0->min, vr1->min, &val))
1843 set_value_range_to_varying (vr);
1844 return;
1846 min = max = val;
1848 if (vr1->max != vr1->min)
1850 if (!vrp_int_const_binop (code, vr0->min, vr1->max, &val))
1852 set_value_range_to_varying (vr);
1853 return;
1855 if (wi::lt_p (val, min, sgn))
1856 min = val;
1857 else if (wi::gt_p (val, max, sgn))
1858 max = val;
1861 if (vr0->max != vr0->min)
1863 if (!vrp_int_const_binop (code, vr0->max, vr1->min, &val))
1865 set_value_range_to_varying (vr);
1866 return;
1868 if (wi::lt_p (val, min, sgn))
1869 min = val;
1870 else if (wi::gt_p (val, max, sgn))
1871 max = val;
1874 if (vr0->min != vr0->max && vr1->min != vr1->max)
1876 if (!vrp_int_const_binop (code, vr0->max, vr1->max, &val))
1878 set_value_range_to_varying (vr);
1879 return;
1881 if (wi::lt_p (val, min, sgn))
1882 min = val;
1883 else if (wi::gt_p (val, max, sgn))
1884 max = val;
1887 /* If the new range has its limits swapped around (MIN > MAX),
1888 then the operation caused one of them to wrap around, mark
1889 the new range VARYING. */
1890 if (wi::gt_p (min, max, sgn))
1892 set_value_range_to_varying (vr);
1893 return;
1896 /* We punt for [-INF, +INF].
1897 We learn nothing when we have INF on both sides.
1898 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1899 if (wi::eq_p (min, wi::min_value (TYPE_PRECISION (type), sgn))
1900 && wi::eq_p (max, wi::max_value (TYPE_PRECISION (type), sgn)))
1902 set_value_range_to_varying (vr);
1903 return;
1906 set_value_range (vr, rtype,
1907 wide_int_to_tree (type, min),
1908 wide_int_to_tree (type, max), NULL);
1911 /* Extract range information from a binary operation CODE based on
1912 the ranges of each of its operands *VR0 and *VR1 with resulting
1913 type EXPR_TYPE. The resulting range is stored in *VR. */
1915 static void
1916 extract_range_from_binary_expr_1 (value_range *vr,
1917 enum tree_code code, tree expr_type,
1918 value_range *vr0_, value_range *vr1_)
1920 value_range vr0 = *vr0_, vr1 = *vr1_;
1921 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1922 enum value_range_type type;
1923 tree min = NULL_TREE, max = NULL_TREE;
1924 int cmp;
1926 if (!INTEGRAL_TYPE_P (expr_type)
1927 && !POINTER_TYPE_P (expr_type))
1929 set_value_range_to_varying (vr);
1930 return;
1933 /* Not all binary expressions can be applied to ranges in a
1934 meaningful way. Handle only arithmetic operations. */
1935 if (code != PLUS_EXPR
1936 && code != MINUS_EXPR
1937 && code != POINTER_PLUS_EXPR
1938 && code != MULT_EXPR
1939 && code != TRUNC_DIV_EXPR
1940 && code != FLOOR_DIV_EXPR
1941 && code != CEIL_DIV_EXPR
1942 && code != EXACT_DIV_EXPR
1943 && code != ROUND_DIV_EXPR
1944 && code != TRUNC_MOD_EXPR
1945 && code != RSHIFT_EXPR
1946 && code != LSHIFT_EXPR
1947 && code != MIN_EXPR
1948 && code != MAX_EXPR
1949 && code != BIT_AND_EXPR
1950 && code != BIT_IOR_EXPR
1951 && code != BIT_XOR_EXPR)
1953 set_value_range_to_varying (vr);
1954 return;
1957 /* If both ranges are UNDEFINED, so is the result. */
1958 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1960 set_value_range_to_undefined (vr);
1961 return;
1963 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1964 code. At some point we may want to special-case operations that
1965 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1966 operand. */
1967 else if (vr0.type == VR_UNDEFINED)
1968 set_value_range_to_varying (&vr0);
1969 else if (vr1.type == VR_UNDEFINED)
1970 set_value_range_to_varying (&vr1);
1972 /* We get imprecise results from ranges_from_anti_range when
1973 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1974 range, but then we also need to hack up vrp_meet. It's just
1975 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1976 if (code == EXACT_DIV_EXPR
1977 && vr0.type == VR_ANTI_RANGE
1978 && vr0.min == vr0.max
1979 && integer_zerop (vr0.min))
1981 set_value_range_to_nonnull (vr, expr_type);
1982 return;
1985 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1986 and express ~[] op X as ([]' op X) U ([]'' op X). */
1987 if (vr0.type == VR_ANTI_RANGE
1988 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1990 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1991 if (vrtem1.type != VR_UNDEFINED)
1993 value_range vrres = VR_INITIALIZER;
1994 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1995 &vrtem1, vr1_);
1996 vrp_meet (vr, &vrres);
1998 return;
2000 /* Likewise for X op ~[]. */
2001 if (vr1.type == VR_ANTI_RANGE
2002 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
2004 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
2005 if (vrtem1.type != VR_UNDEFINED)
2007 value_range vrres = VR_INITIALIZER;
2008 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2009 vr0_, &vrtem1);
2010 vrp_meet (vr, &vrres);
2012 return;
2015 /* The type of the resulting value range defaults to VR0.TYPE. */
2016 type = vr0.type;
2018 /* Refuse to operate on VARYING ranges, ranges of different kinds
2019 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
2020 because we may be able to derive a useful range even if one of
2021 the operands is VR_VARYING or symbolic range. Similarly for
2022 divisions, MIN/MAX and PLUS/MINUS.
2024 TODO, we may be able to derive anti-ranges in some cases. */
2025 if (code != BIT_AND_EXPR
2026 && code != BIT_IOR_EXPR
2027 && code != TRUNC_DIV_EXPR
2028 && code != FLOOR_DIV_EXPR
2029 && code != CEIL_DIV_EXPR
2030 && code != EXACT_DIV_EXPR
2031 && code != ROUND_DIV_EXPR
2032 && code != TRUNC_MOD_EXPR
2033 && code != MIN_EXPR
2034 && code != MAX_EXPR
2035 && code != PLUS_EXPR
2036 && code != MINUS_EXPR
2037 && code != RSHIFT_EXPR
2038 && (vr0.type == VR_VARYING
2039 || vr1.type == VR_VARYING
2040 || vr0.type != vr1.type
2041 || symbolic_range_p (&vr0)
2042 || symbolic_range_p (&vr1)))
2044 set_value_range_to_varying (vr);
2045 return;
2048 /* Now evaluate the expression to determine the new range. */
2049 if (POINTER_TYPE_P (expr_type))
2051 if (code == MIN_EXPR || code == MAX_EXPR)
2053 /* For MIN/MAX expressions with pointers, we only care about
2054 nullness, if both are non null, then the result is nonnull.
2055 If both are null, then the result is null. Otherwise they
2056 are varying. */
2057 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2058 set_value_range_to_nonnull (vr, expr_type);
2059 else if (range_is_null (&vr0) && range_is_null (&vr1))
2060 set_value_range_to_null (vr, expr_type);
2061 else
2062 set_value_range_to_varying (vr);
2064 else if (code == POINTER_PLUS_EXPR)
2066 /* For pointer types, we are really only interested in asserting
2067 whether the expression evaluates to non-NULL. */
2068 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
2069 set_value_range_to_nonnull (vr, expr_type);
2070 else if (range_is_null (&vr0) && range_is_null (&vr1))
2071 set_value_range_to_null (vr, expr_type);
2072 else
2073 set_value_range_to_varying (vr);
2075 else if (code == BIT_AND_EXPR)
2077 /* For pointer types, we are really only interested in asserting
2078 whether the expression evaluates to non-NULL. */
2079 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2080 set_value_range_to_nonnull (vr, expr_type);
2081 else if (range_is_null (&vr0) || range_is_null (&vr1))
2082 set_value_range_to_null (vr, expr_type);
2083 else
2084 set_value_range_to_varying (vr);
2086 else
2087 set_value_range_to_varying (vr);
2089 return;
2092 /* For integer ranges, apply the operation to each end of the
2093 range and see what we end up with. */
2094 if (code == PLUS_EXPR || code == MINUS_EXPR)
2096 const bool minus_p = (code == MINUS_EXPR);
2097 tree min_op0 = vr0.min;
2098 tree min_op1 = minus_p ? vr1.max : vr1.min;
2099 tree max_op0 = vr0.max;
2100 tree max_op1 = minus_p ? vr1.min : vr1.max;
2101 tree sym_min_op0 = NULL_TREE;
2102 tree sym_min_op1 = NULL_TREE;
2103 tree sym_max_op0 = NULL_TREE;
2104 tree sym_max_op1 = NULL_TREE;
2105 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
2107 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
2108 single-symbolic ranges, try to compute the precise resulting range,
2109 but only if we know that this resulting range will also be constant
2110 or single-symbolic. */
2111 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
2112 && (TREE_CODE (min_op0) == INTEGER_CST
2113 || (sym_min_op0
2114 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
2115 && (TREE_CODE (min_op1) == INTEGER_CST
2116 || (sym_min_op1
2117 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
2118 && (!(sym_min_op0 && sym_min_op1)
2119 || (sym_min_op0 == sym_min_op1
2120 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
2121 && (TREE_CODE (max_op0) == INTEGER_CST
2122 || (sym_max_op0
2123 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
2124 && (TREE_CODE (max_op1) == INTEGER_CST
2125 || (sym_max_op1
2126 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
2127 && (!(sym_max_op0 && sym_max_op1)
2128 || (sym_max_op0 == sym_max_op1
2129 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
2131 const signop sgn = TYPE_SIGN (expr_type);
2132 const unsigned int prec = TYPE_PRECISION (expr_type);
2133 wide_int type_min, type_max, wmin, wmax;
2134 int min_ovf = 0;
2135 int max_ovf = 0;
2137 /* Get the lower and upper bounds of the type. */
2138 if (TYPE_OVERFLOW_WRAPS (expr_type))
2140 type_min = wi::min_value (prec, sgn);
2141 type_max = wi::max_value (prec, sgn);
2143 else
2145 type_min = wi::to_wide (vrp_val_min (expr_type));
2146 type_max = wi::to_wide (vrp_val_max (expr_type));
2149 /* Combine the lower bounds, if any. */
2150 if (min_op0 && min_op1)
2152 if (minus_p)
2154 wmin = wi::to_wide (min_op0) - wi::to_wide (min_op1);
2156 /* Check for overflow. */
2157 if (wi::cmp (0, wi::to_wide (min_op1), sgn)
2158 != wi::cmp (wmin, wi::to_wide (min_op0), sgn))
2159 min_ovf = wi::cmp (wi::to_wide (min_op0),
2160 wi::to_wide (min_op1), sgn);
2162 else
2164 wmin = wi::to_wide (min_op0) + wi::to_wide (min_op1);
2166 /* Check for overflow. */
2167 if (wi::cmp (wi::to_wide (min_op1), 0, sgn)
2168 != wi::cmp (wmin, wi::to_wide (min_op0), sgn))
2169 min_ovf = wi::cmp (wi::to_wide (min_op0), wmin, sgn);
2172 else if (min_op0)
2173 wmin = wi::to_wide (min_op0);
2174 else if (min_op1)
2176 if (minus_p)
2178 wmin = -wi::to_wide (min_op1);
2180 /* Check for overflow. */
2181 if (sgn == SIGNED
2182 && wi::neg_p (wi::to_wide (min_op1))
2183 && wi::neg_p (wmin))
2184 min_ovf = 1;
2185 else if (sgn == UNSIGNED && wi::to_wide (min_op1) != 0)
2186 min_ovf = -1;
2188 else
2189 wmin = wi::to_wide (min_op1);
2191 else
2192 wmin = wi::shwi (0, prec);
2194 /* Combine the upper bounds, if any. */
2195 if (max_op0 && max_op1)
2197 if (minus_p)
2199 wmax = wi::to_wide (max_op0) - wi::to_wide (max_op1);
2201 /* Check for overflow. */
2202 if (wi::cmp (0, wi::to_wide (max_op1), sgn)
2203 != wi::cmp (wmax, wi::to_wide (max_op0), sgn))
2204 max_ovf = wi::cmp (wi::to_wide (max_op0),
2205 wi::to_wide (max_op1), sgn);
2207 else
2209 wmax = wi::to_wide (max_op0) + wi::to_wide (max_op1);
2211 if (wi::cmp (wi::to_wide (max_op1), 0, sgn)
2212 != wi::cmp (wmax, wi::to_wide (max_op0), sgn))
2213 max_ovf = wi::cmp (wi::to_wide (max_op0), wmax, sgn);
2216 else if (max_op0)
2217 wmax = wi::to_wide (max_op0);
2218 else if (max_op1)
2220 if (minus_p)
2222 wmax = -wi::to_wide (max_op1);
2224 /* Check for overflow. */
2225 if (sgn == SIGNED
2226 && wi::neg_p (wi::to_wide (max_op1))
2227 && wi::neg_p (wmax))
2228 max_ovf = 1;
2229 else if (sgn == UNSIGNED && wi::to_wide (max_op1) != 0)
2230 max_ovf = -1;
2232 else
2233 wmax = wi::to_wide (max_op1);
2235 else
2236 wmax = wi::shwi (0, prec);
2238 /* Check for type overflow. */
2239 if (min_ovf == 0)
2241 if (wi::cmp (wmin, type_min, sgn) == -1)
2242 min_ovf = -1;
2243 else if (wi::cmp (wmin, type_max, sgn) == 1)
2244 min_ovf = 1;
2246 if (max_ovf == 0)
2248 if (wi::cmp (wmax, type_min, sgn) == -1)
2249 max_ovf = -1;
2250 else if (wi::cmp (wmax, type_max, sgn) == 1)
2251 max_ovf = 1;
2254 /* If we have overflow for the constant part and the resulting
2255 range will be symbolic, drop to VR_VARYING. */
2256 if ((min_ovf && sym_min_op0 != sym_min_op1)
2257 || (max_ovf && sym_max_op0 != sym_max_op1))
2259 set_value_range_to_varying (vr);
2260 return;
2263 if (TYPE_OVERFLOW_WRAPS (expr_type))
2265 /* If overflow wraps, truncate the values and adjust the
2266 range kind and bounds appropriately. */
2267 wide_int tmin = wide_int::from (wmin, prec, sgn);
2268 wide_int tmax = wide_int::from (wmax, prec, sgn);
2269 if (min_ovf == max_ovf)
2271 /* No overflow or both overflow or underflow. The
2272 range kind stays VR_RANGE. */
2273 min = wide_int_to_tree (expr_type, tmin);
2274 max = wide_int_to_tree (expr_type, tmax);
2276 else if ((min_ovf == -1 && max_ovf == 0)
2277 || (max_ovf == 1 && min_ovf == 0))
2279 /* Min underflow or max overflow. The range kind
2280 changes to VR_ANTI_RANGE. */
2281 bool covers = false;
2282 wide_int tem = tmin;
2283 type = VR_ANTI_RANGE;
2284 tmin = tmax + 1;
2285 if (wi::cmp (tmin, tmax, sgn) < 0)
2286 covers = true;
2287 tmax = tem - 1;
2288 if (wi::cmp (tmax, tem, sgn) > 0)
2289 covers = true;
2290 /* If the anti-range would cover nothing, drop to varying.
2291 Likewise if the anti-range bounds are outside of the
2292 types values. */
2293 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
2295 set_value_range_to_varying (vr);
2296 return;
2298 min = wide_int_to_tree (expr_type, tmin);
2299 max = wide_int_to_tree (expr_type, tmax);
2301 else
2303 /* Other underflow and/or overflow, drop to VR_VARYING. */
2304 set_value_range_to_varying (vr);
2305 return;
2308 else
2310 /* If overflow does not wrap, saturate to the types min/max
2311 value. */
2312 if (min_ovf == -1)
2313 min = wide_int_to_tree (expr_type, type_min);
2314 else if (min_ovf == 1)
2315 min = wide_int_to_tree (expr_type, type_max);
2316 else
2317 min = wide_int_to_tree (expr_type, wmin);
2319 if (max_ovf == -1)
2320 max = wide_int_to_tree (expr_type, type_min);
2321 else if (max_ovf == 1)
2322 max = wide_int_to_tree (expr_type, type_max);
2323 else
2324 max = wide_int_to_tree (expr_type, wmax);
2327 /* If the result lower bound is constant, we're done;
2328 otherwise, build the symbolic lower bound. */
2329 if (sym_min_op0 == sym_min_op1)
2331 else if (sym_min_op0)
2332 min = build_symbolic_expr (expr_type, sym_min_op0,
2333 neg_min_op0, min);
2334 else if (sym_min_op1)
2336 /* We may not negate if that might introduce
2337 undefined overflow. */
2338 if (! minus_p
2339 || neg_min_op1
2340 || TYPE_OVERFLOW_WRAPS (expr_type))
2341 min = build_symbolic_expr (expr_type, sym_min_op1,
2342 neg_min_op1 ^ minus_p, min);
2343 else
2344 min = NULL_TREE;
2347 /* Likewise for the upper bound. */
2348 if (sym_max_op0 == sym_max_op1)
2350 else if (sym_max_op0)
2351 max = build_symbolic_expr (expr_type, sym_max_op0,
2352 neg_max_op0, max);
2353 else if (sym_max_op1)
2355 /* We may not negate if that might introduce
2356 undefined overflow. */
2357 if (! minus_p
2358 || neg_max_op1
2359 || TYPE_OVERFLOW_WRAPS (expr_type))
2360 max = build_symbolic_expr (expr_type, sym_max_op1,
2361 neg_max_op1 ^ minus_p, max);
2362 else
2363 max = NULL_TREE;
2366 else
2368 /* For other cases, for example if we have a PLUS_EXPR with two
2369 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
2370 to compute a precise range for such a case.
2371 ??? General even mixed range kind operations can be expressed
2372 by for example transforming ~[3, 5] + [1, 2] to range-only
2373 operations and a union primitive:
2374 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
2375 [-INF+1, 4] U [6, +INF(OVF)]
2376 though usually the union is not exactly representable with
2377 a single range or anti-range as the above is
2378 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
2379 but one could use a scheme similar to equivalences for this. */
2380 set_value_range_to_varying (vr);
2381 return;
2384 else if (code == MIN_EXPR
2385 || code == MAX_EXPR)
2387 if (vr0.type == VR_RANGE
2388 && !symbolic_range_p (&vr0))
2390 type = VR_RANGE;
2391 if (vr1.type == VR_RANGE
2392 && !symbolic_range_p (&vr1))
2394 /* For operations that make the resulting range directly
2395 proportional to the original ranges, apply the operation to
2396 the same end of each range. */
2397 min = int_const_binop (code, vr0.min, vr1.min);
2398 max = int_const_binop (code, vr0.max, vr1.max);
2400 else if (code == MIN_EXPR)
2402 min = vrp_val_min (expr_type);
2403 max = vr0.max;
2405 else if (code == MAX_EXPR)
2407 min = vr0.min;
2408 max = vrp_val_max (expr_type);
2411 else if (vr1.type == VR_RANGE
2412 && !symbolic_range_p (&vr1))
2414 type = VR_RANGE;
2415 if (code == MIN_EXPR)
2417 min = vrp_val_min (expr_type);
2418 max = vr1.max;
2420 else if (code == MAX_EXPR)
2422 min = vr1.min;
2423 max = vrp_val_max (expr_type);
2426 else
2428 set_value_range_to_varying (vr);
2429 return;
2432 else if (code == MULT_EXPR)
2434 /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
2435 drop to varying. This test requires 2*prec bits if both
2436 operands are signed and 2*prec + 2 bits if either is not. */
2438 signop sign = TYPE_SIGN (expr_type);
2439 unsigned int prec = TYPE_PRECISION (expr_type);
2441 if (!range_int_cst_p (&vr0)
2442 || !range_int_cst_p (&vr1))
2444 set_value_range_to_varying (vr);
2445 return;
2448 if (TYPE_OVERFLOW_WRAPS (expr_type))
2450 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) vrp_int;
2451 typedef generic_wide_int
2452 <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> > vrp_int_cst;
2453 vrp_int sizem1 = wi::mask <vrp_int> (prec, false);
2454 vrp_int size = sizem1 + 1;
2456 /* Extend the values using the sign of the result to PREC2.
2457 From here on out, everthing is just signed math no matter
2458 what the input types were. */
2459 vrp_int min0 = vrp_int_cst (vr0.min);
2460 vrp_int max0 = vrp_int_cst (vr0.max);
2461 vrp_int min1 = vrp_int_cst (vr1.min);
2462 vrp_int max1 = vrp_int_cst (vr1.max);
2463 /* Canonicalize the intervals. */
2464 if (sign == UNSIGNED)
2466 if (wi::ltu_p (size, min0 + max0))
2468 min0 -= size;
2469 max0 -= size;
2472 if (wi::ltu_p (size, min1 + max1))
2474 min1 -= size;
2475 max1 -= size;
2479 vrp_int prod0 = min0 * min1;
2480 vrp_int prod1 = min0 * max1;
2481 vrp_int prod2 = max0 * min1;
2482 vrp_int prod3 = max0 * max1;
2484 /* Sort the 4 products so that min is in prod0 and max is in
2485 prod3. */
2486 /* min0min1 > max0max1 */
2487 if (prod0 > prod3)
2488 std::swap (prod0, prod3);
2490 /* min0max1 > max0min1 */
2491 if (prod1 > prod2)
2492 std::swap (prod1, prod2);
2494 if (prod0 > prod1)
2495 std::swap (prod0, prod1);
2497 if (prod2 > prod3)
2498 std::swap (prod2, prod3);
2500 /* diff = max - min. */
2501 prod2 = prod3 - prod0;
2502 if (wi::geu_p (prod2, sizem1))
2504 /* the range covers all values. */
2505 set_value_range_to_varying (vr);
2506 return;
2509 /* The following should handle the wrapping and selecting
2510 VR_ANTI_RANGE for us. */
2511 min = wide_int_to_tree (expr_type, prod0);
2512 max = wide_int_to_tree (expr_type, prod3);
2513 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
2514 return;
2517 /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
2518 drop to VR_VARYING. It would take more effort to compute a
2519 precise range for such a case. For example, if we have
2520 op0 == 65536 and op1 == 65536 with their ranges both being
2521 ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
2522 we cannot claim that the product is in ~[0,0]. Note that we
2523 are guaranteed to have vr0.type == vr1.type at this
2524 point. */
2525 if (vr0.type == VR_ANTI_RANGE
2526 && !TYPE_OVERFLOW_UNDEFINED (expr_type))
2528 set_value_range_to_varying (vr);
2529 return;
2532 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2533 return;
2535 else if (code == RSHIFT_EXPR
2536 || code == LSHIFT_EXPR)
2538 /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
2539 then drop to VR_VARYING. Outside of this range we get undefined
2540 behavior from the shift operation. We cannot even trust
2541 SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
2542 shifts, and the operation at the tree level may be widened. */
2543 if (range_int_cst_p (&vr1)
2544 && compare_tree_int (vr1.min, 0) >= 0
2545 && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
2547 if (code == RSHIFT_EXPR)
2549 /* Even if vr0 is VARYING or otherwise not usable, we can derive
2550 useful ranges just from the shift count. E.g.
2551 x >> 63 for signed 64-bit x is always [-1, 0]. */
2552 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2554 vr0.type = type = VR_RANGE;
2555 vr0.min = vrp_val_min (expr_type);
2556 vr0.max = vrp_val_max (expr_type);
2558 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2559 return;
2561 /* We can map lshifts by constants to MULT_EXPR handling. */
2562 else if (code == LSHIFT_EXPR
2563 && range_int_cst_singleton_p (&vr1))
2565 bool saved_flag_wrapv;
2566 value_range vr1p = VR_INITIALIZER;
2567 vr1p.type = VR_RANGE;
2568 vr1p.min = (wide_int_to_tree
2569 (expr_type,
2570 wi::set_bit_in_zero (tree_to_shwi (vr1.min),
2571 TYPE_PRECISION (expr_type))));
2572 vr1p.max = vr1p.min;
2573 /* We have to use a wrapping multiply though as signed overflow
2574 on lshifts is implementation defined in C89. */
2575 saved_flag_wrapv = flag_wrapv;
2576 flag_wrapv = 1;
2577 extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
2578 &vr0, &vr1p);
2579 flag_wrapv = saved_flag_wrapv;
2580 return;
2582 else if (code == LSHIFT_EXPR
2583 && range_int_cst_p (&vr0))
2585 int prec = TYPE_PRECISION (expr_type);
2586 int overflow_pos = prec;
2587 int bound_shift;
2588 wide_int low_bound, high_bound;
2589 bool uns = TYPE_UNSIGNED (expr_type);
2590 bool in_bounds = false;
2592 if (!uns)
2593 overflow_pos -= 1;
2595 bound_shift = overflow_pos - tree_to_shwi (vr1.max);
2596 /* If bound_shift == HOST_BITS_PER_WIDE_INT, the llshift can
2597 overflow. However, for that to happen, vr1.max needs to be
2598 zero, which means vr1 is a singleton range of zero, which
2599 means it should be handled by the previous LSHIFT_EXPR
2600 if-clause. */
2601 wide_int bound = wi::set_bit_in_zero (bound_shift, prec);
2602 wide_int complement = ~(bound - 1);
2604 if (uns)
2606 low_bound = bound;
2607 high_bound = complement;
2608 if (wi::ltu_p (wi::to_wide (vr0.max), low_bound))
2610 /* [5, 6] << [1, 2] == [10, 24]. */
2611 /* We're shifting out only zeroes, the value increases
2612 monotonically. */
2613 in_bounds = true;
2615 else if (wi::ltu_p (high_bound, wi::to_wide (vr0.min)))
2617 /* [0xffffff00, 0xffffffff] << [1, 2]
2618 == [0xfffffc00, 0xfffffffe]. */
2619 /* We're shifting out only ones, the value decreases
2620 monotonically. */
2621 in_bounds = true;
2624 else
2626 /* [-1, 1] << [1, 2] == [-4, 4]. */
2627 low_bound = complement;
2628 high_bound = bound;
2629 if (wi::lts_p (wi::to_wide (vr0.max), high_bound)
2630 && wi::lts_p (low_bound, wi::to_wide (vr0.min)))
2632 /* For non-negative numbers, we're shifting out only
2633 zeroes, the value increases monotonically.
2634 For negative numbers, we're shifting out only ones, the
2635 value decreases monotomically. */
2636 in_bounds = true;
2640 if (in_bounds)
2642 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2643 return;
2647 set_value_range_to_varying (vr);
2648 return;
2650 else if (code == TRUNC_DIV_EXPR
2651 || code == FLOOR_DIV_EXPR
2652 || code == CEIL_DIV_EXPR
2653 || code == EXACT_DIV_EXPR
2654 || code == ROUND_DIV_EXPR)
2656 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2658 /* For division, if op1 has VR_RANGE but op0 does not, something
2659 can be deduced just from that range. Say [min, max] / [4, max]
2660 gives [min / 4, max / 4] range. */
2661 if (vr1.type == VR_RANGE
2662 && !symbolic_range_p (&vr1)
2663 && range_includes_zero_p (vr1.min, vr1.max) == 0)
2665 vr0.type = type = VR_RANGE;
2666 vr0.min = vrp_val_min (expr_type);
2667 vr0.max = vrp_val_max (expr_type);
2669 else
2671 set_value_range_to_varying (vr);
2672 return;
2676 /* For divisions, if flag_non_call_exceptions is true, we must
2677 not eliminate a division by zero. */
2678 if (cfun->can_throw_non_call_exceptions
2679 && (vr1.type != VR_RANGE
2680 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2682 set_value_range_to_varying (vr);
2683 return;
2686 /* For divisions, if op0 is VR_RANGE, we can deduce a range
2687 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
2688 include 0. */
2689 if (vr0.type == VR_RANGE
2690 && (vr1.type != VR_RANGE
2691 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2693 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
2694 int cmp;
2696 min = NULL_TREE;
2697 max = NULL_TREE;
2698 if (TYPE_UNSIGNED (expr_type)
2699 || value_range_nonnegative_p (&vr1))
2701 /* For unsigned division or when divisor is known
2702 to be non-negative, the range has to cover
2703 all numbers from 0 to max for positive max
2704 and all numbers from min to 0 for negative min. */
2705 cmp = compare_values (vr0.max, zero);
2706 if (cmp == -1)
2708 /* When vr0.max < 0, vr1.min != 0 and value
2709 ranges for dividend and divisor are available. */
2710 if (vr1.type == VR_RANGE
2711 && !symbolic_range_p (&vr0)
2712 && !symbolic_range_p (&vr1)
2713 && compare_values (vr1.min, zero) != 0)
2714 max = int_const_binop (code, vr0.max, vr1.min);
2715 else
2716 max = zero;
2718 else if (cmp == 0 || cmp == 1)
2719 max = vr0.max;
2720 else
2721 type = VR_VARYING;
2722 cmp = compare_values (vr0.min, zero);
2723 if (cmp == 1)
2725 /* For unsigned division when value ranges for dividend
2726 and divisor are available. */
2727 if (vr1.type == VR_RANGE
2728 && !symbolic_range_p (&vr0)
2729 && !symbolic_range_p (&vr1)
2730 && compare_values (vr1.max, zero) != 0)
2731 min = int_const_binop (code, vr0.min, vr1.max);
2732 else
2733 min = zero;
2735 else if (cmp == 0 || cmp == -1)
2736 min = vr0.min;
2737 else
2738 type = VR_VARYING;
2740 else
2742 /* Otherwise the range is -max .. max or min .. -min
2743 depending on which bound is bigger in absolute value,
2744 as the division can change the sign. */
2745 abs_extent_range (vr, vr0.min, vr0.max);
2746 return;
2748 if (type == VR_VARYING)
2750 set_value_range_to_varying (vr);
2751 return;
2754 else if (!symbolic_range_p (&vr0) && !symbolic_range_p (&vr1))
2756 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2757 return;
2760 else if (code == TRUNC_MOD_EXPR)
2762 if (range_is_null (&vr1))
2764 set_value_range_to_undefined (vr);
2765 return;
2767 /* ABS (A % B) < ABS (B) and either
2768 0 <= A % B <= A or A <= A % B <= 0. */
2769 type = VR_RANGE;
2770 signop sgn = TYPE_SIGN (expr_type);
2771 unsigned int prec = TYPE_PRECISION (expr_type);
2772 wide_int wmin, wmax, tmp;
2773 if (vr1.type == VR_RANGE && !symbolic_range_p (&vr1))
2775 wmax = wi::to_wide (vr1.max) - 1;
2776 if (sgn == SIGNED)
2778 tmp = -1 - wi::to_wide (vr1.min);
2779 wmax = wi::smax (wmax, tmp);
2782 else
2784 wmax = wi::max_value (prec, sgn);
2785 /* X % INT_MIN may be INT_MAX. */
2786 if (sgn == UNSIGNED)
2787 wmax = wmax - 1;
2790 if (sgn == UNSIGNED)
2791 wmin = wi::zero (prec);
2792 else
2794 wmin = -wmax;
2795 if (vr0.type == VR_RANGE && TREE_CODE (vr0.min) == INTEGER_CST)
2797 tmp = wi::to_wide (vr0.min);
2798 if (wi::gts_p (tmp, 0))
2799 tmp = wi::zero (prec);
2800 wmin = wi::smax (wmin, tmp);
2804 if (vr0.type == VR_RANGE && TREE_CODE (vr0.max) == INTEGER_CST)
2806 tmp = wi::to_wide (vr0.max);
2807 if (sgn == SIGNED && wi::neg_p (tmp))
2808 tmp = wi::zero (prec);
2809 wmax = wi::min (wmax, tmp, sgn);
2812 min = wide_int_to_tree (expr_type, wmin);
2813 max = wide_int_to_tree (expr_type, wmax);
2815 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
2817 bool int_cst_range0, int_cst_range1;
2818 wide_int may_be_nonzero0, may_be_nonzero1;
2819 wide_int must_be_nonzero0, must_be_nonzero1;
2821 int_cst_range0 = zero_nonzero_bits_from_vr (expr_type, &vr0,
2822 &may_be_nonzero0,
2823 &must_be_nonzero0);
2824 int_cst_range1 = zero_nonzero_bits_from_vr (expr_type, &vr1,
2825 &may_be_nonzero1,
2826 &must_be_nonzero1);
2828 if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR)
2830 value_range *vr0p = NULL, *vr1p = NULL;
2831 if (range_int_cst_singleton_p (&vr1))
2833 vr0p = &vr0;
2834 vr1p = &vr1;
2836 else if (range_int_cst_singleton_p (&vr0))
2838 vr0p = &vr1;
2839 vr1p = &vr0;
2841 /* For op & or | attempt to optimize:
2842 [x, y] op z into [x op z, y op z]
2843 if z is a constant which (for op | its bitwise not) has n
2844 consecutive least significant bits cleared followed by m 1
2845 consecutive bits set immediately above it and either
2846 m + n == precision, or (x >> (m + n)) == (y >> (m + n)).
2847 The least significant n bits of all the values in the range are
2848 cleared or set, the m bits above it are preserved and any bits
2849 above these are required to be the same for all values in the
2850 range. */
2851 if (vr0p && range_int_cst_p (vr0p))
2853 wide_int w = wi::to_wide (vr1p->min);
2854 int m = 0, n = 0;
2855 if (code == BIT_IOR_EXPR)
2856 w = ~w;
2857 if (wi::eq_p (w, 0))
2858 n = TYPE_PRECISION (expr_type);
2859 else
2861 n = wi::ctz (w);
2862 w = ~(w | wi::mask (n, false, w.get_precision ()));
2863 if (wi::eq_p (w, 0))
2864 m = TYPE_PRECISION (expr_type) - n;
2865 else
2866 m = wi::ctz (w) - n;
2868 wide_int mask = wi::mask (m + n, true, w.get_precision ());
2869 if ((mask & wi::to_wide (vr0p->min))
2870 == (mask & wi::to_wide (vr0p->max)))
2872 min = int_const_binop (code, vr0p->min, vr1p->min);
2873 max = int_const_binop (code, vr0p->max, vr1p->min);
2878 type = VR_RANGE;
2879 if (min && max)
2880 /* Optimized above already. */;
2881 else if (code == BIT_AND_EXPR)
2883 min = wide_int_to_tree (expr_type,
2884 must_be_nonzero0 & must_be_nonzero1);
2885 wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
2886 /* If both input ranges contain only negative values we can
2887 truncate the result range maximum to the minimum of the
2888 input range maxima. */
2889 if (int_cst_range0 && int_cst_range1
2890 && tree_int_cst_sgn (vr0.max) < 0
2891 && tree_int_cst_sgn (vr1.max) < 0)
2893 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2894 TYPE_SIGN (expr_type));
2895 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2896 TYPE_SIGN (expr_type));
2898 /* If either input range contains only non-negative values
2899 we can truncate the result range maximum to the respective
2900 maximum of the input range. */
2901 if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
2902 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2903 TYPE_SIGN (expr_type));
2904 if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
2905 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2906 TYPE_SIGN (expr_type));
2907 max = wide_int_to_tree (expr_type, wmax);
2908 cmp = compare_values (min, max);
2909 /* PR68217: In case of signed & sign-bit-CST should
2910 result in [-INF, 0] instead of [-INF, INF]. */
2911 if (cmp == -2 || cmp == 1)
2913 wide_int sign_bit
2914 = wi::set_bit_in_zero (TYPE_PRECISION (expr_type) - 1,
2915 TYPE_PRECISION (expr_type));
2916 if (!TYPE_UNSIGNED (expr_type)
2917 && ((int_cst_range0
2918 && value_range_constant_singleton (&vr0)
2919 && !wi::cmps (wi::to_wide (vr0.min), sign_bit))
2920 || (int_cst_range1
2921 && value_range_constant_singleton (&vr1)
2922 && !wi::cmps (wi::to_wide (vr1.min), sign_bit))))
2924 min = TYPE_MIN_VALUE (expr_type);
2925 max = build_int_cst (expr_type, 0);
2929 else if (code == BIT_IOR_EXPR)
2931 max = wide_int_to_tree (expr_type,
2932 may_be_nonzero0 | may_be_nonzero1);
2933 wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
2934 /* If the input ranges contain only positive values we can
2935 truncate the minimum of the result range to the maximum
2936 of the input range minima. */
2937 if (int_cst_range0 && int_cst_range1
2938 && tree_int_cst_sgn (vr0.min) >= 0
2939 && tree_int_cst_sgn (vr1.min) >= 0)
2941 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2942 TYPE_SIGN (expr_type));
2943 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2944 TYPE_SIGN (expr_type));
2946 /* If either input range contains only negative values
2947 we can truncate the minimum of the result range to the
2948 respective minimum range. */
2949 if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
2950 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2951 TYPE_SIGN (expr_type));
2952 if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
2953 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2954 TYPE_SIGN (expr_type));
2955 min = wide_int_to_tree (expr_type, wmin);
2957 else if (code == BIT_XOR_EXPR)
2959 wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
2960 | ~(may_be_nonzero0 | may_be_nonzero1));
2961 wide_int result_one_bits
2962 = (wi::bit_and_not (must_be_nonzero0, may_be_nonzero1)
2963 | wi::bit_and_not (must_be_nonzero1, may_be_nonzero0));
2964 max = wide_int_to_tree (expr_type, ~result_zero_bits);
2965 min = wide_int_to_tree (expr_type, result_one_bits);
2966 /* If the range has all positive or all negative values the
2967 result is better than VARYING. */
2968 if (tree_int_cst_sgn (min) < 0
2969 || tree_int_cst_sgn (max) >= 0)
2971 else
2972 max = min = NULL_TREE;
2975 else
2976 gcc_unreachable ();
2978 /* If either MIN or MAX overflowed, then set the resulting range to
2979 VARYING. */
2980 if (min == NULL_TREE
2981 || TREE_OVERFLOW_P (min)
2982 || max == NULL_TREE
2983 || TREE_OVERFLOW_P (max))
2985 set_value_range_to_varying (vr);
2986 return;
2989 /* We punt for [-INF, +INF].
2990 We learn nothing when we have INF on both sides.
2991 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
2992 if (vrp_val_is_min (min) && vrp_val_is_max (max))
2994 set_value_range_to_varying (vr);
2995 return;
2998 cmp = compare_values (min, max);
2999 if (cmp == -2 || cmp == 1)
3001 /* If the new range has its limits swapped around (MIN > MAX),
3002 then the operation caused one of them to wrap around, mark
3003 the new range VARYING. */
3004 set_value_range_to_varying (vr);
3006 else
3007 set_value_range (vr, type, min, max, NULL);
3010 /* Extract range information from a binary expression OP0 CODE OP1 based on
3011 the ranges of each of its operands with resulting type EXPR_TYPE.
3012 The resulting range is stored in *VR. */
3014 void
3015 vr_values::extract_range_from_binary_expr (value_range *vr,
3016 enum tree_code code,
3017 tree expr_type, tree op0, tree op1)
3019 value_range vr0 = VR_INITIALIZER;
3020 value_range vr1 = VR_INITIALIZER;
3022 /* Get value ranges for each operand. For constant operands, create
3023 a new value range with the operand to simplify processing. */
3024 if (TREE_CODE (op0) == SSA_NAME)
3025 vr0 = *(get_value_range (op0));
3026 else if (is_gimple_min_invariant (op0))
3027 set_value_range_to_value (&vr0, op0, NULL);
3028 else
3029 set_value_range_to_varying (&vr0);
3031 if (TREE_CODE (op1) == SSA_NAME)
3032 vr1 = *(get_value_range (op1));
3033 else if (is_gimple_min_invariant (op1))
3034 set_value_range_to_value (&vr1, op1, NULL);
3035 else
3036 set_value_range_to_varying (&vr1);
3038 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &vr1);
3040 /* Try harder for PLUS and MINUS if the range of one operand is symbolic
3041 and based on the other operand, for example if it was deduced from a
3042 symbolic comparison. When a bound of the range of the first operand
3043 is invariant, we set the corresponding bound of the new range to INF
3044 in order to avoid recursing on the range of the second operand. */
3045 if (vr->type == VR_VARYING
3046 && (code == PLUS_EXPR || code == MINUS_EXPR)
3047 && TREE_CODE (op1) == SSA_NAME
3048 && vr0.type == VR_RANGE
3049 && symbolic_range_based_on_p (&vr0, op1))
3051 const bool minus_p = (code == MINUS_EXPR);
3052 value_range n_vr1 = VR_INITIALIZER;
3054 /* Try with VR0 and [-INF, OP1]. */
3055 if (is_gimple_min_invariant (minus_p ? vr0.max : vr0.min))
3056 set_value_range (&n_vr1, VR_RANGE, vrp_val_min (expr_type), op1, NULL);
3058 /* Try with VR0 and [OP1, +INF]. */
3059 else if (is_gimple_min_invariant (minus_p ? vr0.min : vr0.max))
3060 set_value_range (&n_vr1, VR_RANGE, op1, vrp_val_max (expr_type), NULL);
3062 /* Try with VR0 and [OP1, OP1]. */
3063 else
3064 set_value_range (&n_vr1, VR_RANGE, op1, op1, NULL);
3066 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &n_vr1);
3069 if (vr->type == VR_VARYING
3070 && (code == PLUS_EXPR || code == MINUS_EXPR)
3071 && TREE_CODE (op0) == SSA_NAME
3072 && vr1.type == VR_RANGE
3073 && symbolic_range_based_on_p (&vr1, op0))
3075 const bool minus_p = (code == MINUS_EXPR);
3076 value_range n_vr0 = VR_INITIALIZER;
3078 /* Try with [-INF, OP0] and VR1. */
3079 if (is_gimple_min_invariant (minus_p ? vr1.max : vr1.min))
3080 set_value_range (&n_vr0, VR_RANGE, vrp_val_min (expr_type), op0, NULL);
3082 /* Try with [OP0, +INF] and VR1. */
3083 else if (is_gimple_min_invariant (minus_p ? vr1.min : vr1.max))
3084 set_value_range (&n_vr0, VR_RANGE, op0, vrp_val_max (expr_type), NULL);
3086 /* Try with [OP0, OP0] and VR1. */
3087 else
3088 set_value_range (&n_vr0, VR_RANGE, op0, op0, NULL);
3090 extract_range_from_binary_expr_1 (vr, code, expr_type, &n_vr0, &vr1);
3093 /* If we didn't derive a range for MINUS_EXPR, and
3094 op1's range is ~[op0,op0] or vice-versa, then we
3095 can derive a non-null range. This happens often for
3096 pointer subtraction. */
3097 if (vr->type == VR_VARYING
3098 && code == MINUS_EXPR
3099 && TREE_CODE (op0) == SSA_NAME
3100 && ((vr0.type == VR_ANTI_RANGE
3101 && vr0.min == op1
3102 && vr0.min == vr0.max)
3103 || (vr1.type == VR_ANTI_RANGE
3104 && vr1.min == op0
3105 && vr1.min == vr1.max)))
3106 set_value_range_to_nonnull (vr, TREE_TYPE (op0));
3109 /* Extract range information from a unary operation CODE based on
3110 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
3111 The resulting range is stored in *VR. */
3113 void
3114 extract_range_from_unary_expr (value_range *vr,
3115 enum tree_code code, tree type,
3116 value_range *vr0_, tree op0_type)
3118 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
3120 /* VRP only operates on integral and pointer types. */
3121 if (!(INTEGRAL_TYPE_P (op0_type)
3122 || POINTER_TYPE_P (op0_type))
3123 || !(INTEGRAL_TYPE_P (type)
3124 || POINTER_TYPE_P (type)))
3126 set_value_range_to_varying (vr);
3127 return;
3130 /* If VR0 is UNDEFINED, so is the result. */
3131 if (vr0.type == VR_UNDEFINED)
3133 set_value_range_to_undefined (vr);
3134 return;
3137 /* Handle operations that we express in terms of others. */
3138 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
3140 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
3141 copy_value_range (vr, &vr0);
3142 return;
3144 else if (code == NEGATE_EXPR)
3146 /* -X is simply 0 - X, so re-use existing code that also handles
3147 anti-ranges fine. */
3148 value_range zero = VR_INITIALIZER;
3149 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
3150 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
3151 return;
3153 else if (code == BIT_NOT_EXPR)
3155 /* ~X is simply -1 - X, so re-use existing code that also handles
3156 anti-ranges fine. */
3157 value_range minusone = VR_INITIALIZER;
3158 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
3159 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
3160 type, &minusone, &vr0);
3161 return;
3164 /* Now canonicalize anti-ranges to ranges when they are not symbolic
3165 and express op ~[] as (op []') U (op []''). */
3166 if (vr0.type == VR_ANTI_RANGE
3167 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
3169 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
3170 if (vrtem1.type != VR_UNDEFINED)
3172 value_range vrres = VR_INITIALIZER;
3173 extract_range_from_unary_expr (&vrres, code, type,
3174 &vrtem1, op0_type);
3175 vrp_meet (vr, &vrres);
3177 return;
3180 if (CONVERT_EXPR_CODE_P (code))
3182 tree inner_type = op0_type;
3183 tree outer_type = type;
3185 /* If the expression evaluates to a pointer, we are only interested in
3186 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
3187 if (POINTER_TYPE_P (type))
3189 if (range_is_nonnull (&vr0))
3190 set_value_range_to_nonnull (vr, type);
3191 else if (range_is_null (&vr0))
3192 set_value_range_to_null (vr, type);
3193 else
3194 set_value_range_to_varying (vr);
3195 return;
3198 /* If VR0 is varying and we increase the type precision, assume
3199 a full range for the following transformation. */
3200 if (vr0.type == VR_VARYING
3201 && INTEGRAL_TYPE_P (inner_type)
3202 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
3204 vr0.type = VR_RANGE;
3205 vr0.min = TYPE_MIN_VALUE (inner_type);
3206 vr0.max = TYPE_MAX_VALUE (inner_type);
3209 /* If VR0 is a constant range or anti-range and the conversion is
3210 not truncating we can convert the min and max values and
3211 canonicalize the resulting range. Otherwise we can do the
3212 conversion if the size of the range is less than what the
3213 precision of the target type can represent and the range is
3214 not an anti-range. */
3215 if ((vr0.type == VR_RANGE
3216 || vr0.type == VR_ANTI_RANGE)
3217 && TREE_CODE (vr0.min) == INTEGER_CST
3218 && TREE_CODE (vr0.max) == INTEGER_CST
3219 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
3220 || (vr0.type == VR_RANGE
3221 && integer_zerop (int_const_binop (RSHIFT_EXPR,
3222 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
3223 size_int (TYPE_PRECISION (outer_type)))))))
3225 tree new_min, new_max;
3226 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
3227 0, false);
3228 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
3229 0, false);
3230 set_and_canonicalize_value_range (vr, vr0.type,
3231 new_min, new_max, NULL);
3232 return;
3235 set_value_range_to_varying (vr);
3236 return;
3238 else if (code == ABS_EXPR)
3240 tree min, max;
3241 int cmp;
3243 /* Pass through vr0 in the easy cases. */
3244 if (TYPE_UNSIGNED (type)
3245 || value_range_nonnegative_p (&vr0))
3247 copy_value_range (vr, &vr0);
3248 return;
3251 /* For the remaining varying or symbolic ranges we can't do anything
3252 useful. */
3253 if (vr0.type == VR_VARYING
3254 || symbolic_range_p (&vr0))
3256 set_value_range_to_varying (vr);
3257 return;
3260 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
3261 useful range. */
3262 if (!TYPE_OVERFLOW_UNDEFINED (type)
3263 && ((vr0.type == VR_RANGE
3264 && vrp_val_is_min (vr0.min))
3265 || (vr0.type == VR_ANTI_RANGE
3266 && !vrp_val_is_min (vr0.min))))
3268 set_value_range_to_varying (vr);
3269 return;
3272 /* ABS_EXPR may flip the range around, if the original range
3273 included negative values. */
3274 if (!vrp_val_is_min (vr0.min))
3275 min = fold_unary_to_constant (code, type, vr0.min);
3276 else
3277 min = TYPE_MAX_VALUE (type);
3279 if (!vrp_val_is_min (vr0.max))
3280 max = fold_unary_to_constant (code, type, vr0.max);
3281 else
3282 max = TYPE_MAX_VALUE (type);
3284 cmp = compare_values (min, max);
3286 /* If a VR_ANTI_RANGEs contains zero, then we have
3287 ~[-INF, min(MIN, MAX)]. */
3288 if (vr0.type == VR_ANTI_RANGE)
3290 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3292 /* Take the lower of the two values. */
3293 if (cmp != 1)
3294 max = min;
3296 /* Create ~[-INF, min (abs(MIN), abs(MAX))]
3297 or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
3298 flag_wrapv is set and the original anti-range doesn't include
3299 TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE. */
3300 if (TYPE_OVERFLOW_WRAPS (type))
3302 tree type_min_value = TYPE_MIN_VALUE (type);
3304 min = (vr0.min != type_min_value
3305 ? int_const_binop (PLUS_EXPR, type_min_value,
3306 build_int_cst (TREE_TYPE (type_min_value), 1))
3307 : type_min_value);
3309 else
3310 min = TYPE_MIN_VALUE (type);
3312 else
3314 /* All else has failed, so create the range [0, INF], even for
3315 flag_wrapv since TYPE_MIN_VALUE is in the original
3316 anti-range. */
3317 vr0.type = VR_RANGE;
3318 min = build_int_cst (type, 0);
3319 max = TYPE_MAX_VALUE (type);
3323 /* If the range contains zero then we know that the minimum value in the
3324 range will be zero. */
3325 else if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3327 if (cmp == 1)
3328 max = min;
3329 min = build_int_cst (type, 0);
3331 else
3333 /* If the range was reversed, swap MIN and MAX. */
3334 if (cmp == 1)
3335 std::swap (min, max);
3338 cmp = compare_values (min, max);
3339 if (cmp == -2 || cmp == 1)
3341 /* If the new range has its limits swapped around (MIN > MAX),
3342 then the operation caused one of them to wrap around, mark
3343 the new range VARYING. */
3344 set_value_range_to_varying (vr);
3346 else
3347 set_value_range (vr, vr0.type, min, max, NULL);
3348 return;
3351 /* For unhandled operations fall back to varying. */
3352 set_value_range_to_varying (vr);
3353 return;
3357 /* Extract range information from a unary expression CODE OP0 based on
3358 the range of its operand with resulting type TYPE.
3359 The resulting range is stored in *VR. */
3361 void
3362 vr_values::extract_range_from_unary_expr (value_range *vr, enum tree_code code,
3363 tree type, tree op0)
3365 value_range vr0 = VR_INITIALIZER;
3367 /* Get value ranges for the operand. For constant operands, create
3368 a new value range with the operand to simplify processing. */
3369 if (TREE_CODE (op0) == SSA_NAME)
3370 vr0 = *(get_value_range (op0));
3371 else if (is_gimple_min_invariant (op0))
3372 set_value_range_to_value (&vr0, op0, NULL);
3373 else
3374 set_value_range_to_varying (&vr0);
3376 ::extract_range_from_unary_expr (vr, code, type, &vr0, TREE_TYPE (op0));
3380 /* Extract range information from a conditional expression STMT based on
3381 the ranges of each of its operands and the expression code. */
3383 void
3384 vr_values::extract_range_from_cond_expr (value_range *vr, gassign *stmt)
3386 tree op0, op1;
3387 value_range vr0 = VR_INITIALIZER;
3388 value_range vr1 = VR_INITIALIZER;
3390 /* Get value ranges for each operand. For constant operands, create
3391 a new value range with the operand to simplify processing. */
3392 op0 = gimple_assign_rhs2 (stmt);
3393 if (TREE_CODE (op0) == SSA_NAME)
3394 vr0 = *(get_value_range (op0));
3395 else if (is_gimple_min_invariant (op0))
3396 set_value_range_to_value (&vr0, op0, NULL);
3397 else
3398 set_value_range_to_varying (&vr0);
3400 op1 = gimple_assign_rhs3 (stmt);
3401 if (TREE_CODE (op1) == SSA_NAME)
3402 vr1 = *(get_value_range (op1));
3403 else if (is_gimple_min_invariant (op1))
3404 set_value_range_to_value (&vr1, op1, NULL);
3405 else
3406 set_value_range_to_varying (&vr1);
3408 /* The resulting value range is the union of the operand ranges */
3409 copy_value_range (vr, &vr0);
3410 vrp_meet (vr, &vr1);
3414 /* Extract range information from a comparison expression EXPR based
3415 on the range of its operand and the expression code. */
3417 void
3418 vr_values::extract_range_from_comparison (value_range *vr, enum tree_code code,
3419 tree type, tree op0, tree op1)
3421 bool sop;
3422 tree val;
3424 val = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, false, &sop,
3425 NULL);
3426 if (val)
3428 /* Since this expression was found on the RHS of an assignment,
3429 its type may be different from _Bool. Convert VAL to EXPR's
3430 type. */
3431 val = fold_convert (type, val);
3432 if (is_gimple_min_invariant (val))
3433 set_value_range_to_value (vr, val, vr->equiv);
3434 else
3435 set_value_range (vr, VR_RANGE, val, val, vr->equiv);
3437 else
3438 /* The result of a comparison is always true or false. */
3439 set_value_range_to_truthvalue (vr, type);
3442 /* Helper function for simplify_internal_call_using_ranges and
3443 extract_range_basic. Return true if OP0 SUBCODE OP1 for
3444 SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
3445 always overflow. Set *OVF to true if it is known to always
3446 overflow. */
3448 bool
3449 vr_values::check_for_binary_op_overflow (enum tree_code subcode, tree type,
3450 tree op0, tree op1, bool *ovf)
3452 value_range vr0 = VR_INITIALIZER;
3453 value_range vr1 = VR_INITIALIZER;
3454 if (TREE_CODE (op0) == SSA_NAME)
3455 vr0 = *get_value_range (op0);
3456 else if (TREE_CODE (op0) == INTEGER_CST)
3457 set_value_range_to_value (&vr0, op0, NULL);
3458 else
3459 set_value_range_to_varying (&vr0);
3461 if (TREE_CODE (op1) == SSA_NAME)
3462 vr1 = *get_value_range (op1);
3463 else if (TREE_CODE (op1) == INTEGER_CST)
3464 set_value_range_to_value (&vr1, op1, NULL);
3465 else
3466 set_value_range_to_varying (&vr1);
3468 if (!range_int_cst_p (&vr0)
3469 || TREE_OVERFLOW (vr0.min)
3470 || TREE_OVERFLOW (vr0.max))
3472 vr0.min = vrp_val_min (TREE_TYPE (op0));
3473 vr0.max = vrp_val_max (TREE_TYPE (op0));
3475 if (!range_int_cst_p (&vr1)
3476 || TREE_OVERFLOW (vr1.min)
3477 || TREE_OVERFLOW (vr1.max))
3479 vr1.min = vrp_val_min (TREE_TYPE (op1));
3480 vr1.max = vrp_val_max (TREE_TYPE (op1));
3482 *ovf = arith_overflowed_p (subcode, type, vr0.min,
3483 subcode == MINUS_EXPR ? vr1.max : vr1.min);
3484 if (arith_overflowed_p (subcode, type, vr0.max,
3485 subcode == MINUS_EXPR ? vr1.min : vr1.max) != *ovf)
3486 return false;
3487 if (subcode == MULT_EXPR)
3489 if (arith_overflowed_p (subcode, type, vr0.min, vr1.max) != *ovf
3490 || arith_overflowed_p (subcode, type, vr0.max, vr1.min) != *ovf)
3491 return false;
3493 if (*ovf)
3495 /* So far we found that there is an overflow on the boundaries.
3496 That doesn't prove that there is an overflow even for all values
3497 in between the boundaries. For that compute widest_int range
3498 of the result and see if it doesn't overlap the range of
3499 type. */
3500 widest_int wmin, wmax;
3501 widest_int w[4];
3502 int i;
3503 w[0] = wi::to_widest (vr0.min);
3504 w[1] = wi::to_widest (vr0.max);
3505 w[2] = wi::to_widest (vr1.min);
3506 w[3] = wi::to_widest (vr1.max);
3507 for (i = 0; i < 4; i++)
3509 widest_int wt;
3510 switch (subcode)
3512 case PLUS_EXPR:
3513 wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
3514 break;
3515 case MINUS_EXPR:
3516 wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
3517 break;
3518 case MULT_EXPR:
3519 wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
3520 break;
3521 default:
3522 gcc_unreachable ();
3524 if (i == 0)
3526 wmin = wt;
3527 wmax = wt;
3529 else
3531 wmin = wi::smin (wmin, wt);
3532 wmax = wi::smax (wmax, wt);
3535 /* The result of op0 CODE op1 is known to be in range
3536 [wmin, wmax]. */
3537 widest_int wtmin = wi::to_widest (vrp_val_min (type));
3538 widest_int wtmax = wi::to_widest (vrp_val_max (type));
3539 /* If all values in [wmin, wmax] are smaller than
3540 [wtmin, wtmax] or all are larger than [wtmin, wtmax],
3541 the arithmetic operation will always overflow. */
3542 if (wmax < wtmin || wmin > wtmax)
3543 return true;
3544 return false;
3546 return true;
3549 /* Try to derive a nonnegative or nonzero range out of STMT relying
3550 primarily on generic routines in fold in conjunction with range data.
3551 Store the result in *VR */
3553 void
3554 vr_values::extract_range_basic (value_range *vr, gimple *stmt)
3556 bool sop;
3557 tree type = gimple_expr_type (stmt);
3559 if (is_gimple_call (stmt))
3561 tree arg;
3562 int mini, maxi, zerov = 0, prec;
3563 enum tree_code subcode = ERROR_MARK;
3564 combined_fn cfn = gimple_call_combined_fn (stmt);
3565 scalar_int_mode mode;
3567 switch (cfn)
3569 case CFN_BUILT_IN_CONSTANT_P:
3570 /* If the call is __builtin_constant_p and the argument is a
3571 function parameter resolve it to false. This avoids bogus
3572 array bound warnings.
3573 ??? We could do this as early as inlining is finished. */
3574 arg = gimple_call_arg (stmt, 0);
3575 if (TREE_CODE (arg) == SSA_NAME
3576 && SSA_NAME_IS_DEFAULT_DEF (arg)
3577 && TREE_CODE (SSA_NAME_VAR (arg)) == PARM_DECL
3578 && cfun->after_inlining)
3580 set_value_range_to_null (vr, type);
3581 return;
3583 break;
3584 /* Both __builtin_ffs* and __builtin_popcount return
3585 [0, prec]. */
3586 CASE_CFN_FFS:
3587 CASE_CFN_POPCOUNT:
3588 arg = gimple_call_arg (stmt, 0);
3589 prec = TYPE_PRECISION (TREE_TYPE (arg));
3590 mini = 0;
3591 maxi = prec;
3592 if (TREE_CODE (arg) == SSA_NAME)
3594 value_range *vr0 = get_value_range (arg);
3595 /* If arg is non-zero, then ffs or popcount
3596 are non-zero. */
3597 if ((vr0->type == VR_RANGE
3598 && range_includes_zero_p (vr0->min, vr0->max) == 0)
3599 || (vr0->type == VR_ANTI_RANGE
3600 && range_includes_zero_p (vr0->min, vr0->max) == 1))
3601 mini = 1;
3602 /* If some high bits are known to be zero,
3603 we can decrease the maximum. */
3604 if (vr0->type == VR_RANGE
3605 && TREE_CODE (vr0->max) == INTEGER_CST
3606 && !operand_less_p (vr0->min,
3607 build_zero_cst (TREE_TYPE (vr0->min))))
3608 maxi = tree_floor_log2 (vr0->max) + 1;
3610 goto bitop_builtin;
3611 /* __builtin_parity* returns [0, 1]. */
3612 CASE_CFN_PARITY:
3613 mini = 0;
3614 maxi = 1;
3615 goto bitop_builtin;
3616 /* __builtin_c[lt]z* return [0, prec-1], except for
3617 when the argument is 0, but that is undefined behavior.
3618 On many targets where the CLZ RTL or optab value is defined
3619 for 0 the value is prec, so include that in the range
3620 by default. */
3621 CASE_CFN_CLZ:
3622 arg = gimple_call_arg (stmt, 0);
3623 prec = TYPE_PRECISION (TREE_TYPE (arg));
3624 mini = 0;
3625 maxi = prec;
3626 mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (arg));
3627 if (optab_handler (clz_optab, mode) != CODE_FOR_nothing
3628 && CLZ_DEFINED_VALUE_AT_ZERO (mode, zerov)
3629 /* Handle only the single common value. */
3630 && zerov != prec)
3631 /* Magic value to give up, unless vr0 proves
3632 arg is non-zero. */
3633 mini = -2;
3634 if (TREE_CODE (arg) == SSA_NAME)
3636 value_range *vr0 = get_value_range (arg);
3637 /* From clz of VR_RANGE minimum we can compute
3638 result maximum. */
3639 if (vr0->type == VR_RANGE
3640 && TREE_CODE (vr0->min) == INTEGER_CST)
3642 maxi = prec - 1 - tree_floor_log2 (vr0->min);
3643 if (maxi != prec)
3644 mini = 0;
3646 else if (vr0->type == VR_ANTI_RANGE
3647 && integer_zerop (vr0->min))
3649 maxi = prec - 1;
3650 mini = 0;
3652 if (mini == -2)
3653 break;
3654 /* From clz of VR_RANGE maximum we can compute
3655 result minimum. */
3656 if (vr0->type == VR_RANGE
3657 && TREE_CODE (vr0->max) == INTEGER_CST)
3659 mini = prec - 1 - tree_floor_log2 (vr0->max);
3660 if (mini == prec)
3661 break;
3664 if (mini == -2)
3665 break;
3666 goto bitop_builtin;
3667 /* __builtin_ctz* return [0, prec-1], except for
3668 when the argument is 0, but that is undefined behavior.
3669 If there is a ctz optab for this mode and
3670 CTZ_DEFINED_VALUE_AT_ZERO, include that in the range,
3671 otherwise just assume 0 won't be seen. */
3672 CASE_CFN_CTZ:
3673 arg = gimple_call_arg (stmt, 0);
3674 prec = TYPE_PRECISION (TREE_TYPE (arg));
3675 mini = 0;
3676 maxi = prec - 1;
3677 mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (arg));
3678 if (optab_handler (ctz_optab, mode) != CODE_FOR_nothing
3679 && CTZ_DEFINED_VALUE_AT_ZERO (mode, zerov))
3681 /* Handle only the two common values. */
3682 if (zerov == -1)
3683 mini = -1;
3684 else if (zerov == prec)
3685 maxi = prec;
3686 else
3687 /* Magic value to give up, unless vr0 proves
3688 arg is non-zero. */
3689 mini = -2;
3691 if (TREE_CODE (arg) == SSA_NAME)
3693 value_range *vr0 = get_value_range (arg);
3694 /* If arg is non-zero, then use [0, prec - 1]. */
3695 if ((vr0->type == VR_RANGE
3696 && integer_nonzerop (vr0->min))
3697 || (vr0->type == VR_ANTI_RANGE
3698 && integer_zerop (vr0->min)))
3700 mini = 0;
3701 maxi = prec - 1;
3703 /* If some high bits are known to be zero,
3704 we can decrease the result maximum. */
3705 if (vr0->type == VR_RANGE
3706 && TREE_CODE (vr0->max) == INTEGER_CST)
3708 maxi = tree_floor_log2 (vr0->max);
3709 /* For vr0 [0, 0] give up. */
3710 if (maxi == -1)
3711 break;
3714 if (mini == -2)
3715 break;
3716 goto bitop_builtin;
3717 /* __builtin_clrsb* returns [0, prec-1]. */
3718 CASE_CFN_CLRSB:
3719 arg = gimple_call_arg (stmt, 0);
3720 prec = TYPE_PRECISION (TREE_TYPE (arg));
3721 mini = 0;
3722 maxi = prec - 1;
3723 goto bitop_builtin;
3724 bitop_builtin:
3725 set_value_range (vr, VR_RANGE, build_int_cst (type, mini),
3726 build_int_cst (type, maxi), NULL);
3727 return;
3728 case CFN_UBSAN_CHECK_ADD:
3729 subcode = PLUS_EXPR;
3730 break;
3731 case CFN_UBSAN_CHECK_SUB:
3732 subcode = MINUS_EXPR;
3733 break;
3734 case CFN_UBSAN_CHECK_MUL:
3735 subcode = MULT_EXPR;
3736 break;
3737 case CFN_GOACC_DIM_SIZE:
3738 case CFN_GOACC_DIM_POS:
3739 /* Optimizing these two internal functions helps the loop
3740 optimizer eliminate outer comparisons. Size is [1,N]
3741 and pos is [0,N-1]. */
3743 bool is_pos = cfn == CFN_GOACC_DIM_POS;
3744 int axis = oacc_get_ifn_dim_arg (stmt);
3745 int size = oacc_get_fn_dim_size (current_function_decl, axis);
3747 if (!size)
3748 /* If it's dynamic, the backend might know a hardware
3749 limitation. */
3750 size = targetm.goacc.dim_limit (axis);
3752 tree type = TREE_TYPE (gimple_call_lhs (stmt));
3753 set_value_range (vr, VR_RANGE,
3754 build_int_cst (type, is_pos ? 0 : 1),
3755 size ? build_int_cst (type, size - is_pos)
3756 : vrp_val_max (type), NULL);
3758 return;
3759 case CFN_BUILT_IN_STRLEN:
3760 if (tree lhs = gimple_call_lhs (stmt))
3761 if (ptrdiff_type_node
3762 && (TYPE_PRECISION (ptrdiff_type_node)
3763 == TYPE_PRECISION (TREE_TYPE (lhs))))
3765 tree type = TREE_TYPE (lhs);
3766 tree max = vrp_val_max (ptrdiff_type_node);
3767 wide_int wmax = wi::to_wide (max, TYPE_PRECISION (TREE_TYPE (max)));
3768 tree range_min = build_zero_cst (type);
3769 tree range_max = wide_int_to_tree (type, wmax - 1);
3770 set_value_range (vr, VR_RANGE, range_min, range_max, NULL);
3771 return;
3773 break;
3774 default:
3775 break;
3777 if (subcode != ERROR_MARK)
3779 bool saved_flag_wrapv = flag_wrapv;
3780 /* Pretend the arithmetics is wrapping. If there is
3781 any overflow, we'll complain, but will actually do
3782 wrapping operation. */
3783 flag_wrapv = 1;
3784 extract_range_from_binary_expr (vr, subcode, type,
3785 gimple_call_arg (stmt, 0),
3786 gimple_call_arg (stmt, 1));
3787 flag_wrapv = saved_flag_wrapv;
3789 /* If for both arguments vrp_valueize returned non-NULL,
3790 this should have been already folded and if not, it
3791 wasn't folded because of overflow. Avoid removing the
3792 UBSAN_CHECK_* calls in that case. */
3793 if (vr->type == VR_RANGE
3794 && (vr->min == vr->max
3795 || operand_equal_p (vr->min, vr->max, 0)))
3796 set_value_range_to_varying (vr);
3797 return;
3800 /* Handle extraction of the two results (result of arithmetics and
3801 a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
3802 internal function. Similarly from ATOMIC_COMPARE_EXCHANGE. */
3803 else if (is_gimple_assign (stmt)
3804 && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
3805 || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
3806 && INTEGRAL_TYPE_P (type))
3808 enum tree_code code = gimple_assign_rhs_code (stmt);
3809 tree op = gimple_assign_rhs1 (stmt);
3810 if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
3812 gimple *g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
3813 if (is_gimple_call (g) && gimple_call_internal_p (g))
3815 enum tree_code subcode = ERROR_MARK;
3816 switch (gimple_call_internal_fn (g))
3818 case IFN_ADD_OVERFLOW:
3819 subcode = PLUS_EXPR;
3820 break;
3821 case IFN_SUB_OVERFLOW:
3822 subcode = MINUS_EXPR;
3823 break;
3824 case IFN_MUL_OVERFLOW:
3825 subcode = MULT_EXPR;
3826 break;
3827 case IFN_ATOMIC_COMPARE_EXCHANGE:
3828 if (code == IMAGPART_EXPR)
3830 /* This is the boolean return value whether compare and
3831 exchange changed anything or not. */
3832 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
3833 build_int_cst (type, 1), NULL);
3834 return;
3836 break;
3837 default:
3838 break;
3840 if (subcode != ERROR_MARK)
3842 tree op0 = gimple_call_arg (g, 0);
3843 tree op1 = gimple_call_arg (g, 1);
3844 if (code == IMAGPART_EXPR)
3846 bool ovf = false;
3847 if (check_for_binary_op_overflow (subcode, type,
3848 op0, op1, &ovf))
3849 set_value_range_to_value (vr,
3850 build_int_cst (type, ovf),
3851 NULL);
3852 else if (TYPE_PRECISION (type) == 1
3853 && !TYPE_UNSIGNED (type))
3854 set_value_range_to_varying (vr);
3855 else
3856 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
3857 build_int_cst (type, 1), NULL);
3859 else if (types_compatible_p (type, TREE_TYPE (op0))
3860 && types_compatible_p (type, TREE_TYPE (op1)))
3862 bool saved_flag_wrapv = flag_wrapv;
3863 /* Pretend the arithmetics is wrapping. If there is
3864 any overflow, IMAGPART_EXPR will be set. */
3865 flag_wrapv = 1;
3866 extract_range_from_binary_expr (vr, subcode, type,
3867 op0, op1);
3868 flag_wrapv = saved_flag_wrapv;
3870 else
3872 value_range vr0 = VR_INITIALIZER;
3873 value_range vr1 = VR_INITIALIZER;
3874 bool saved_flag_wrapv = flag_wrapv;
3875 /* Pretend the arithmetics is wrapping. If there is
3876 any overflow, IMAGPART_EXPR will be set. */
3877 flag_wrapv = 1;
3878 extract_range_from_unary_expr (&vr0, NOP_EXPR,
3879 type, op0);
3880 extract_range_from_unary_expr (&vr1, NOP_EXPR,
3881 type, op1);
3882 extract_range_from_binary_expr_1 (vr, subcode, type,
3883 &vr0, &vr1);
3884 flag_wrapv = saved_flag_wrapv;
3886 return;
3891 if (INTEGRAL_TYPE_P (type)
3892 && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
3893 set_value_range_to_nonnegative (vr, type);
3894 else if (vrp_stmt_computes_nonzero (stmt))
3895 set_value_range_to_nonnull (vr, type);
3896 else
3897 set_value_range_to_varying (vr);
3901 /* Try to compute a useful range out of assignment STMT and store it
3902 in *VR. */
3904 void
3905 vr_values::extract_range_from_assignment (value_range *vr, gassign *stmt)
3907 enum tree_code code = gimple_assign_rhs_code (stmt);
3909 if (code == ASSERT_EXPR)
3910 extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
3911 else if (code == SSA_NAME)
3912 extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
3913 else if (TREE_CODE_CLASS (code) == tcc_binary)
3914 extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
3915 gimple_expr_type (stmt),
3916 gimple_assign_rhs1 (stmt),
3917 gimple_assign_rhs2 (stmt));
3918 else if (TREE_CODE_CLASS (code) == tcc_unary)
3919 extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
3920 gimple_expr_type (stmt),
3921 gimple_assign_rhs1 (stmt));
3922 else if (code == COND_EXPR)
3923 extract_range_from_cond_expr (vr, stmt);
3924 else if (TREE_CODE_CLASS (code) == tcc_comparison)
3925 extract_range_from_comparison (vr, gimple_assign_rhs_code (stmt),
3926 gimple_expr_type (stmt),
3927 gimple_assign_rhs1 (stmt),
3928 gimple_assign_rhs2 (stmt));
3929 else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
3930 && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
3931 set_value_range_to_value (vr, gimple_assign_rhs1 (stmt), NULL);
3932 else
3933 set_value_range_to_varying (vr);
3935 if (vr->type == VR_VARYING)
3936 extract_range_basic (vr, stmt);
3939 /* Given a range VR, a LOOP and a variable VAR, determine whether it
3940 would be profitable to adjust VR using scalar evolution information
3941 for VAR. If so, update VR with the new limits. */
3943 void
3944 vr_values::adjust_range_with_scev (value_range *vr, struct loop *loop,
3945 gimple *stmt, tree var)
3947 tree init, step, chrec, tmin, tmax, min, max, type, tem;
3948 enum ev_direction dir;
3950 /* TODO. Don't adjust anti-ranges. An anti-range may provide
3951 better opportunities than a regular range, but I'm not sure. */
3952 if (vr->type == VR_ANTI_RANGE)
3953 return;
3955 chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
3957 /* Like in PR19590, scev can return a constant function. */
3958 if (is_gimple_min_invariant (chrec))
3960 set_value_range_to_value (vr, chrec, vr->equiv);
3961 return;
3964 if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
3965 return;
3967 init = initial_condition_in_loop_num (chrec, loop->num);
3968 tem = op_with_constant_singleton_value_range (init);
3969 if (tem)
3970 init = tem;
3971 step = evolution_part_in_loop_num (chrec, loop->num);
3972 tem = op_with_constant_singleton_value_range (step);
3973 if (tem)
3974 step = tem;
3976 /* If STEP is symbolic, we can't know whether INIT will be the
3977 minimum or maximum value in the range. Also, unless INIT is
3978 a simple expression, compare_values and possibly other functions
3979 in tree-vrp won't be able to handle it. */
3980 if (step == NULL_TREE
3981 || !is_gimple_min_invariant (step)
3982 || !valid_value_p (init))
3983 return;
3985 dir = scev_direction (chrec);
3986 if (/* Do not adjust ranges if we do not know whether the iv increases
3987 or decreases, ... */
3988 dir == EV_DIR_UNKNOWN
3989 /* ... or if it may wrap. */
3990 || scev_probably_wraps_p (NULL_TREE, init, step, stmt,
3991 get_chrec_loop (chrec), true))
3992 return;
3994 type = TREE_TYPE (var);
3995 if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
3996 tmin = lower_bound_in_type (type, type);
3997 else
3998 tmin = TYPE_MIN_VALUE (type);
3999 if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
4000 tmax = upper_bound_in_type (type, type);
4001 else
4002 tmax = TYPE_MAX_VALUE (type);
4004 /* Try to use estimated number of iterations for the loop to constrain the
4005 final value in the evolution. */
4006 if (TREE_CODE (step) == INTEGER_CST
4007 && is_gimple_val (init)
4008 && (TREE_CODE (init) != SSA_NAME
4009 || get_value_range (init)->type == VR_RANGE))
4011 widest_int nit;
4013 /* We are only entering here for loop header PHI nodes, so using
4014 the number of latch executions is the correct thing to use. */
4015 if (max_loop_iterations (loop, &nit))
4017 value_range maxvr = VR_INITIALIZER;
4018 signop sgn = TYPE_SIGN (TREE_TYPE (step));
4019 bool overflow;
4021 widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
4022 &overflow);
4023 /* If the multiplication overflowed we can't do a meaningful
4024 adjustment. Likewise if the result doesn't fit in the type
4025 of the induction variable. For a signed type we have to
4026 check whether the result has the expected signedness which
4027 is that of the step as number of iterations is unsigned. */
4028 if (!overflow
4029 && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
4030 && (sgn == UNSIGNED
4031 || wi::gts_p (wtmp, 0) == wi::gts_p (wi::to_wide (step), 0)))
4033 tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
4034 extract_range_from_binary_expr (&maxvr, PLUS_EXPR,
4035 TREE_TYPE (init), init, tem);
4036 /* Likewise if the addition did. */
4037 if (maxvr.type == VR_RANGE)
4039 value_range initvr = VR_INITIALIZER;
4041 if (TREE_CODE (init) == SSA_NAME)
4042 initvr = *(get_value_range (init));
4043 else if (is_gimple_min_invariant (init))
4044 set_value_range_to_value (&initvr, init, NULL);
4045 else
4046 return;
4048 /* Check if init + nit * step overflows. Though we checked
4049 scev {init, step}_loop doesn't wrap, it is not enough
4050 because the loop may exit immediately. Overflow could
4051 happen in the plus expression in this case. */
4052 if ((dir == EV_DIR_DECREASES
4053 && compare_values (maxvr.min, initvr.min) != -1)
4054 || (dir == EV_DIR_GROWS
4055 && compare_values (maxvr.max, initvr.max) != 1))
4056 return;
4058 tmin = maxvr.min;
4059 tmax = maxvr.max;
4065 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4067 min = tmin;
4068 max = tmax;
4070 /* For VARYING or UNDEFINED ranges, just about anything we get
4071 from scalar evolutions should be better. */
4073 if (dir == EV_DIR_DECREASES)
4074 max = init;
4075 else
4076 min = init;
4078 else if (vr->type == VR_RANGE)
4080 min = vr->min;
4081 max = vr->max;
4083 if (dir == EV_DIR_DECREASES)
4085 /* INIT is the maximum value. If INIT is lower than VR->MAX
4086 but no smaller than VR->MIN, set VR->MAX to INIT. */
4087 if (compare_values (init, max) == -1)
4088 max = init;
4090 /* According to the loop information, the variable does not
4091 overflow. */
4092 if (compare_values (min, tmin) == -1)
4093 min = tmin;
4096 else
4098 /* If INIT is bigger than VR->MIN, set VR->MIN to INIT. */
4099 if (compare_values (init, min) == 1)
4100 min = init;
4102 if (compare_values (tmax, max) == -1)
4103 max = tmax;
4106 else
4107 return;
4109 /* If we just created an invalid range with the minimum
4110 greater than the maximum, we fail conservatively.
4111 This should happen only in unreachable
4112 parts of code, or for invalid programs. */
4113 if (compare_values (min, max) == 1)
4114 return;
4116 /* Even for valid range info, sometimes overflow flag will leak in.
4117 As GIMPLE IL should have no constants with TREE_OVERFLOW set, we
4118 drop them. */
4119 if (TREE_OVERFLOW_P (min))
4120 min = drop_tree_overflow (min);
4121 if (TREE_OVERFLOW_P (max))
4122 max = drop_tree_overflow (max);
4124 set_value_range (vr, VR_RANGE, min, max, vr->equiv);
4128 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
4130 - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
4131 all the values in the ranges.
4133 - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
4135 - Return NULL_TREE if it is not always possible to determine the
4136 value of the comparison.
4138 Also set *STRICT_OVERFLOW_P to indicate whether comparision evaluation
4139 assumed signed overflow is undefined. */
4142 static tree
4143 compare_ranges (enum tree_code comp, value_range *vr0, value_range *vr1,
4144 bool *strict_overflow_p)
4146 /* VARYING or UNDEFINED ranges cannot be compared. */
4147 if (vr0->type == VR_VARYING
4148 || vr0->type == VR_UNDEFINED
4149 || vr1->type == VR_VARYING
4150 || vr1->type == VR_UNDEFINED)
4151 return NULL_TREE;
4153 /* Anti-ranges need to be handled separately. */
4154 if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
4156 /* If both are anti-ranges, then we cannot compute any
4157 comparison. */
4158 if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
4159 return NULL_TREE;
4161 /* These comparisons are never statically computable. */
4162 if (comp == GT_EXPR
4163 || comp == GE_EXPR
4164 || comp == LT_EXPR
4165 || comp == LE_EXPR)
4166 return NULL_TREE;
4168 /* Equality can be computed only between a range and an
4169 anti-range. ~[VAL1, VAL2] == [VAL1, VAL2] is always false. */
4170 if (vr0->type == VR_RANGE)
4172 /* To simplify processing, make VR0 the anti-range. */
4173 value_range *tmp = vr0;
4174 vr0 = vr1;
4175 vr1 = tmp;
4178 gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
4180 if (compare_values_warnv (vr0->min, vr1->min, strict_overflow_p) == 0
4181 && compare_values_warnv (vr0->max, vr1->max, strict_overflow_p) == 0)
4182 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4184 return NULL_TREE;
4187 /* Simplify processing. If COMP is GT_EXPR or GE_EXPR, switch the
4188 operands around and change the comparison code. */
4189 if (comp == GT_EXPR || comp == GE_EXPR)
4191 comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
4192 std::swap (vr0, vr1);
4195 if (comp == EQ_EXPR)
4197 /* Equality may only be computed if both ranges represent
4198 exactly one value. */
4199 if (compare_values_warnv (vr0->min, vr0->max, strict_overflow_p) == 0
4200 && compare_values_warnv (vr1->min, vr1->max, strict_overflow_p) == 0)
4202 int cmp_min = compare_values_warnv (vr0->min, vr1->min,
4203 strict_overflow_p);
4204 int cmp_max = compare_values_warnv (vr0->max, vr1->max,
4205 strict_overflow_p);
4206 if (cmp_min == 0 && cmp_max == 0)
4207 return boolean_true_node;
4208 else if (cmp_min != -2 && cmp_max != -2)
4209 return boolean_false_node;
4211 /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1. */
4212 else if (compare_values_warnv (vr0->min, vr1->max,
4213 strict_overflow_p) == 1
4214 || compare_values_warnv (vr1->min, vr0->max,
4215 strict_overflow_p) == 1)
4216 return boolean_false_node;
4218 return NULL_TREE;
4220 else if (comp == NE_EXPR)
4222 int cmp1, cmp2;
4224 /* If VR0 is completely to the left or completely to the right
4225 of VR1, they are always different. Notice that we need to
4226 make sure that both comparisons yield similar results to
4227 avoid comparing values that cannot be compared at
4228 compile-time. */
4229 cmp1 = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4230 cmp2 = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4231 if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
4232 return boolean_true_node;
4234 /* If VR0 and VR1 represent a single value and are identical,
4235 return false. */
4236 else if (compare_values_warnv (vr0->min, vr0->max,
4237 strict_overflow_p) == 0
4238 && compare_values_warnv (vr1->min, vr1->max,
4239 strict_overflow_p) == 0
4240 && compare_values_warnv (vr0->min, vr1->min,
4241 strict_overflow_p) == 0
4242 && compare_values_warnv (vr0->max, vr1->max,
4243 strict_overflow_p) == 0)
4244 return boolean_false_node;
4246 /* Otherwise, they may or may not be different. */
4247 else
4248 return NULL_TREE;
4250 else if (comp == LT_EXPR || comp == LE_EXPR)
4252 int tst;
4254 /* If VR0 is to the left of VR1, return true. */
4255 tst = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4256 if ((comp == LT_EXPR && tst == -1)
4257 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4258 return boolean_true_node;
4260 /* If VR0 is to the right of VR1, return false. */
4261 tst = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4262 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4263 || (comp == LE_EXPR && tst == 1))
4264 return boolean_false_node;
4266 /* Otherwise, we don't know. */
4267 return NULL_TREE;
4270 gcc_unreachable ();
4274 /* Given a value range VR, a value VAL and a comparison code COMP, return
4275 BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
4276 values in VR. Return BOOLEAN_FALSE_NODE if the comparison
4277 always returns false. Return NULL_TREE if it is not always
4278 possible to determine the value of the comparison. Also set
4279 *STRICT_OVERFLOW_P to indicate whether comparision evaluation
4280 assumed signed overflow is undefined. */
4282 static tree
4283 compare_range_with_value (enum tree_code comp, value_range *vr, tree val,
4284 bool *strict_overflow_p)
4286 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4287 return NULL_TREE;
4289 /* Anti-ranges need to be handled separately. */
4290 if (vr->type == VR_ANTI_RANGE)
4292 /* For anti-ranges, the only predicates that we can compute at
4293 compile time are equality and inequality. */
4294 if (comp == GT_EXPR
4295 || comp == GE_EXPR
4296 || comp == LT_EXPR
4297 || comp == LE_EXPR)
4298 return NULL_TREE;
4300 /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2. */
4301 if (value_inside_range (val, vr->min, vr->max) == 1)
4302 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4304 return NULL_TREE;
4307 if (comp == EQ_EXPR)
4309 /* EQ_EXPR may only be computed if VR represents exactly
4310 one value. */
4311 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0)
4313 int cmp = compare_values_warnv (vr->min, val, strict_overflow_p);
4314 if (cmp == 0)
4315 return boolean_true_node;
4316 else if (cmp == -1 || cmp == 1 || cmp == 2)
4317 return boolean_false_node;
4319 else if (compare_values_warnv (val, vr->min, strict_overflow_p) == -1
4320 || compare_values_warnv (vr->max, val, strict_overflow_p) == -1)
4321 return boolean_false_node;
4323 return NULL_TREE;
4325 else if (comp == NE_EXPR)
4327 /* If VAL is not inside VR, then they are always different. */
4328 if (compare_values_warnv (vr->max, val, strict_overflow_p) == -1
4329 || compare_values_warnv (vr->min, val, strict_overflow_p) == 1)
4330 return boolean_true_node;
4332 /* If VR represents exactly one value equal to VAL, then return
4333 false. */
4334 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0
4335 && compare_values_warnv (vr->min, val, strict_overflow_p) == 0)
4336 return boolean_false_node;
4338 /* Otherwise, they may or may not be different. */
4339 return NULL_TREE;
4341 else if (comp == LT_EXPR || comp == LE_EXPR)
4343 int tst;
4345 /* If VR is to the left of VAL, return true. */
4346 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4347 if ((comp == LT_EXPR && tst == -1)
4348 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4349 return boolean_true_node;
4351 /* If VR is to the right of VAL, return false. */
4352 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4353 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4354 || (comp == LE_EXPR && tst == 1))
4355 return boolean_false_node;
4357 /* Otherwise, we don't know. */
4358 return NULL_TREE;
4360 else if (comp == GT_EXPR || comp == GE_EXPR)
4362 int tst;
4364 /* If VR is to the right of VAL, return true. */
4365 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4366 if ((comp == GT_EXPR && tst == 1)
4367 || (comp == GE_EXPR && (tst == 0 || tst == 1)))
4368 return boolean_true_node;
4370 /* If VR is to the left of VAL, return false. */
4371 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4372 if ((comp == GT_EXPR && (tst == -1 || tst == 0))
4373 || (comp == GE_EXPR && tst == -1))
4374 return boolean_false_node;
4376 /* Otherwise, we don't know. */
4377 return NULL_TREE;
4380 gcc_unreachable ();
4384 /* Debugging dumps. */
4386 void dump_value_range (FILE *, const value_range *);
4387 void debug_value_range (value_range *);
4388 void dump_all_value_ranges (FILE *);
4389 void dump_vr_equiv (FILE *, bitmap);
4390 void debug_vr_equiv (bitmap);
4393 /* Dump value range VR to FILE. */
4395 void
4396 dump_value_range (FILE *file, const value_range *vr)
4398 if (vr == NULL)
4399 fprintf (file, "[]");
4400 else if (vr->type == VR_UNDEFINED)
4401 fprintf (file, "UNDEFINED");
4402 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4404 tree type = TREE_TYPE (vr->min);
4406 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
4408 if (INTEGRAL_TYPE_P (type)
4409 && !TYPE_UNSIGNED (type)
4410 && vrp_val_is_min (vr->min))
4411 fprintf (file, "-INF");
4412 else
4413 print_generic_expr (file, vr->min);
4415 fprintf (file, ", ");
4417 if (INTEGRAL_TYPE_P (type)
4418 && vrp_val_is_max (vr->max))
4419 fprintf (file, "+INF");
4420 else
4421 print_generic_expr (file, vr->max);
4423 fprintf (file, "]");
4425 if (vr->equiv)
4427 bitmap_iterator bi;
4428 unsigned i, c = 0;
4430 fprintf (file, " EQUIVALENCES: { ");
4432 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
4434 print_generic_expr (file, ssa_name (i));
4435 fprintf (file, " ");
4436 c++;
4439 fprintf (file, "} (%u elements)", c);
4442 else if (vr->type == VR_VARYING)
4443 fprintf (file, "VARYING");
4444 else
4445 fprintf (file, "INVALID RANGE");
4449 /* Dump value range VR to stderr. */
4451 DEBUG_FUNCTION void
4452 debug_value_range (value_range *vr)
4454 dump_value_range (stderr, vr);
4455 fprintf (stderr, "\n");
4459 /* Dump value ranges of all SSA_NAMEs to FILE. */
4461 void
4462 vr_values::dump_all_value_ranges (FILE *file)
4464 size_t i;
4466 for (i = 0; i < num_vr_values; i++)
4468 if (vr_value[i])
4470 print_generic_expr (file, ssa_name (i));
4471 fprintf (file, ": ");
4472 dump_value_range (file, vr_value[i]);
4473 fprintf (file, "\n");
4477 fprintf (file, "\n");
4480 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
4481 create a new SSA name N and return the assertion assignment
4482 'N = ASSERT_EXPR <V, V OP W>'. */
4484 static gimple *
4485 build_assert_expr_for (tree cond, tree v)
4487 tree a;
4488 gassign *assertion;
4490 gcc_assert (TREE_CODE (v) == SSA_NAME
4491 && COMPARISON_CLASS_P (cond));
4493 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
4494 assertion = gimple_build_assign (NULL_TREE, a);
4496 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
4497 operand of the ASSERT_EXPR. Create it so the new name and the old one
4498 are registered in the replacement table so that we can fix the SSA web
4499 after adding all the ASSERT_EXPRs. */
4500 tree new_def = create_new_def_for (v, assertion, NULL);
4501 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
4502 given we have to be able to fully propagate those out to re-create
4503 valid SSA when removing the asserts. */
4504 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
4505 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
4507 return assertion;
4511 /* Return false if EXPR is a predicate expression involving floating
4512 point values. */
4514 static inline bool
4515 fp_predicate (gimple *stmt)
4517 GIMPLE_CHECK (stmt, GIMPLE_COND);
4519 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
4522 /* If the range of values taken by OP can be inferred after STMT executes,
4523 return the comparison code (COMP_CODE_P) and value (VAL_P) that
4524 describes the inferred range. Return true if a range could be
4525 inferred. */
4527 static bool
4528 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
4530 *val_p = NULL_TREE;
4531 *comp_code_p = ERROR_MARK;
4533 /* Do not attempt to infer anything in names that flow through
4534 abnormal edges. */
4535 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
4536 return false;
4538 /* If STMT is the last statement of a basic block with no normal
4539 successors, there is no point inferring anything about any of its
4540 operands. We would not be able to find a proper insertion point
4541 for the assertion, anyway. */
4542 if (stmt_ends_bb_p (stmt))
4544 edge_iterator ei;
4545 edge e;
4547 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
4548 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4549 break;
4550 if (e == NULL)
4551 return false;
4554 if (infer_nonnull_range (stmt, op))
4556 *val_p = build_int_cst (TREE_TYPE (op), 0);
4557 *comp_code_p = NE_EXPR;
4558 return true;
4561 return false;
4565 void dump_asserts_for (FILE *, tree);
4566 void debug_asserts_for (tree);
4567 void dump_all_asserts (FILE *);
4568 void debug_all_asserts (void);
4570 /* Dump all the registered assertions for NAME to FILE. */
4572 void
4573 dump_asserts_for (FILE *file, tree name)
4575 assert_locus *loc;
4577 fprintf (file, "Assertions to be inserted for ");
4578 print_generic_expr (file, name);
4579 fprintf (file, "\n");
4581 loc = asserts_for[SSA_NAME_VERSION (name)];
4582 while (loc)
4584 fprintf (file, "\t");
4585 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
4586 fprintf (file, "\n\tBB #%d", loc->bb->index);
4587 if (loc->e)
4589 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
4590 loc->e->dest->index);
4591 dump_edge_info (file, loc->e, dump_flags, 0);
4593 fprintf (file, "\n\tPREDICATE: ");
4594 print_generic_expr (file, loc->expr);
4595 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
4596 print_generic_expr (file, loc->val);
4597 fprintf (file, "\n\n");
4598 loc = loc->next;
4601 fprintf (file, "\n");
4605 /* Dump all the registered assertions for NAME to stderr. */
4607 DEBUG_FUNCTION void
4608 debug_asserts_for (tree name)
4610 dump_asserts_for (stderr, name);
4614 /* Dump all the registered assertions for all the names to FILE. */
4616 void
4617 dump_all_asserts (FILE *file)
4619 unsigned i;
4620 bitmap_iterator bi;
4622 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
4623 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4624 dump_asserts_for (file, ssa_name (i));
4625 fprintf (file, "\n");
4629 /* Dump all the registered assertions for all the names to stderr. */
4631 DEBUG_FUNCTION void
4632 debug_all_asserts (void)
4634 dump_all_asserts (stderr);
4637 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
4639 static void
4640 add_assert_info (vec<assert_info> &asserts,
4641 tree name, tree expr, enum tree_code comp_code, tree val)
4643 assert_info info;
4644 info.comp_code = comp_code;
4645 info.name = name;
4646 info.val = val;
4647 info.expr = expr;
4648 asserts.safe_push (info);
4651 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
4652 'EXPR COMP_CODE VAL' at a location that dominates block BB or
4653 E->DEST, then register this location as a possible insertion point
4654 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
4656 BB, E and SI provide the exact insertion point for the new
4657 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
4658 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
4659 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
4660 must not be NULL. */
4662 static void
4663 register_new_assert_for (tree name, tree expr,
4664 enum tree_code comp_code,
4665 tree val,
4666 basic_block bb,
4667 edge e,
4668 gimple_stmt_iterator si)
4670 assert_locus *n, *loc, *last_loc;
4671 basic_block dest_bb;
4673 gcc_checking_assert (bb == NULL || e == NULL);
4675 if (e == NULL)
4676 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
4677 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
4679 /* Never build an assert comparing against an integer constant with
4680 TREE_OVERFLOW set. This confuses our undefined overflow warning
4681 machinery. */
4682 if (TREE_OVERFLOW_P (val))
4683 val = drop_tree_overflow (val);
4685 /* The new assertion A will be inserted at BB or E. We need to
4686 determine if the new location is dominated by a previously
4687 registered location for A. If we are doing an edge insertion,
4688 assume that A will be inserted at E->DEST. Note that this is not
4689 necessarily true.
4691 If E is a critical edge, it will be split. But even if E is
4692 split, the new block will dominate the same set of blocks that
4693 E->DEST dominates.
4695 The reverse, however, is not true, blocks dominated by E->DEST
4696 will not be dominated by the new block created to split E. So,
4697 if the insertion location is on a critical edge, we will not use
4698 the new location to move another assertion previously registered
4699 at a block dominated by E->DEST. */
4700 dest_bb = (bb) ? bb : e->dest;
4702 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
4703 VAL at a block dominating DEST_BB, then we don't need to insert a new
4704 one. Similarly, if the same assertion already exists at a block
4705 dominated by DEST_BB and the new location is not on a critical
4706 edge, then update the existing location for the assertion (i.e.,
4707 move the assertion up in the dominance tree).
4709 Note, this is implemented as a simple linked list because there
4710 should not be more than a handful of assertions registered per
4711 name. If this becomes a performance problem, a table hashed by
4712 COMP_CODE and VAL could be implemented. */
4713 loc = asserts_for[SSA_NAME_VERSION (name)];
4714 last_loc = loc;
4715 while (loc)
4717 if (loc->comp_code == comp_code
4718 && (loc->val == val
4719 || operand_equal_p (loc->val, val, 0))
4720 && (loc->expr == expr
4721 || operand_equal_p (loc->expr, expr, 0)))
4723 /* If E is not a critical edge and DEST_BB
4724 dominates the existing location for the assertion, move
4725 the assertion up in the dominance tree by updating its
4726 location information. */
4727 if ((e == NULL || !EDGE_CRITICAL_P (e))
4728 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
4730 loc->bb = dest_bb;
4731 loc->e = e;
4732 loc->si = si;
4733 return;
4737 /* Update the last node of the list and move to the next one. */
4738 last_loc = loc;
4739 loc = loc->next;
4742 /* If we didn't find an assertion already registered for
4743 NAME COMP_CODE VAL, add a new one at the end of the list of
4744 assertions associated with NAME. */
4745 n = XNEW (struct assert_locus);
4746 n->bb = dest_bb;
4747 n->e = e;
4748 n->si = si;
4749 n->comp_code = comp_code;
4750 n->val = val;
4751 n->expr = expr;
4752 n->next = NULL;
4754 if (last_loc)
4755 last_loc->next = n;
4756 else
4757 asserts_for[SSA_NAME_VERSION (name)] = n;
4759 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
4762 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
4763 Extract a suitable test code and value and store them into *CODE_P and
4764 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
4766 If no extraction was possible, return FALSE, otherwise return TRUE.
4768 If INVERT is true, then we invert the result stored into *CODE_P. */
4770 static bool
4771 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
4772 tree cond_op0, tree cond_op1,
4773 bool invert, enum tree_code *code_p,
4774 tree *val_p)
4776 enum tree_code comp_code;
4777 tree val;
4779 /* Otherwise, we have a comparison of the form NAME COMP VAL
4780 or VAL COMP NAME. */
4781 if (name == cond_op1)
4783 /* If the predicate is of the form VAL COMP NAME, flip
4784 COMP around because we need to register NAME as the
4785 first operand in the predicate. */
4786 comp_code = swap_tree_comparison (cond_code);
4787 val = cond_op0;
4789 else if (name == cond_op0)
4791 /* The comparison is of the form NAME COMP VAL, so the
4792 comparison code remains unchanged. */
4793 comp_code = cond_code;
4794 val = cond_op1;
4796 else
4797 gcc_unreachable ();
4799 /* Invert the comparison code as necessary. */
4800 if (invert)
4801 comp_code = invert_tree_comparison (comp_code, 0);
4803 /* VRP only handles integral and pointer types. */
4804 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
4805 && ! POINTER_TYPE_P (TREE_TYPE (val)))
4806 return false;
4808 /* Do not register always-false predicates.
4809 FIXME: this works around a limitation in fold() when dealing with
4810 enumerations. Given 'enum { N1, N2 } x;', fold will not
4811 fold 'if (x > N2)' to 'if (0)'. */
4812 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
4813 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
4815 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
4816 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
4818 if (comp_code == GT_EXPR
4819 && (!max
4820 || compare_values (val, max) == 0))
4821 return false;
4823 if (comp_code == LT_EXPR
4824 && (!min
4825 || compare_values (val, min) == 0))
4826 return false;
4828 *code_p = comp_code;
4829 *val_p = val;
4830 return true;
4833 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
4834 (otherwise return VAL). VAL and MASK must be zero-extended for
4835 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
4836 (to transform signed values into unsigned) and at the end xor
4837 SGNBIT back. */
4839 static wide_int
4840 masked_increment (const wide_int &val_in, const wide_int &mask,
4841 const wide_int &sgnbit, unsigned int prec)
4843 wide_int bit = wi::one (prec), res;
4844 unsigned int i;
4846 wide_int val = val_in ^ sgnbit;
4847 for (i = 0; i < prec; i++, bit += bit)
4849 res = mask;
4850 if ((res & bit) == 0)
4851 continue;
4852 res = bit - 1;
4853 res = wi::bit_and_not (val + bit, res);
4854 res &= mask;
4855 if (wi::gtu_p (res, val))
4856 return res ^ sgnbit;
4858 return val ^ sgnbit;
4861 /* Helper for overflow_comparison_p
4863 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
4864 OP1's defining statement to see if it ultimately has the form
4865 OP0 CODE (OP0 PLUS INTEGER_CST)
4867 If so, return TRUE indicating this is an overflow test and store into
4868 *NEW_CST an updated constant that can be used in a narrowed range test.
4870 REVERSED indicates if the comparison was originally:
4872 OP1 CODE' OP0.
4874 This affects how we build the updated constant. */
4876 static bool
4877 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
4878 bool follow_assert_exprs, bool reversed, tree *new_cst)
4880 /* See if this is a relational operation between two SSA_NAMES with
4881 unsigned, overflow wrapping values. If so, check it more deeply. */
4882 if ((code == LT_EXPR || code == LE_EXPR
4883 || code == GE_EXPR || code == GT_EXPR)
4884 && TREE_CODE (op0) == SSA_NAME
4885 && TREE_CODE (op1) == SSA_NAME
4886 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
4887 && TYPE_UNSIGNED (TREE_TYPE (op0))
4888 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
4890 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
4892 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
4893 if (follow_assert_exprs)
4895 while (gimple_assign_single_p (op1_def)
4896 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
4898 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
4899 if (TREE_CODE (op1) != SSA_NAME)
4900 break;
4901 op1_def = SSA_NAME_DEF_STMT (op1);
4905 /* Now look at the defining statement of OP1 to see if it adds
4906 or subtracts a nonzero constant from another operand. */
4907 if (op1_def
4908 && is_gimple_assign (op1_def)
4909 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
4910 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
4911 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
4913 tree target = gimple_assign_rhs1 (op1_def);
4915 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
4916 for one where TARGET appears on the RHS. */
4917 if (follow_assert_exprs)
4919 /* Now see if that "other operand" is op0, following the chain
4920 of ASSERT_EXPRs if necessary. */
4921 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
4922 while (op0 != target
4923 && gimple_assign_single_p (op0_def)
4924 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
4926 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
4927 if (TREE_CODE (op0) != SSA_NAME)
4928 break;
4929 op0_def = SSA_NAME_DEF_STMT (op0);
4933 /* If we did not find our target SSA_NAME, then this is not
4934 an overflow test. */
4935 if (op0 != target)
4936 return false;
4938 tree type = TREE_TYPE (op0);
4939 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
4940 tree inc = gimple_assign_rhs2 (op1_def);
4941 if (reversed)
4942 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
4943 else
4944 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
4945 return true;
4948 return false;
4951 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
4952 OP1's defining statement to see if it ultimately has the form
4953 OP0 CODE (OP0 PLUS INTEGER_CST)
4955 If so, return TRUE indicating this is an overflow test and store into
4956 *NEW_CST an updated constant that can be used in a narrowed range test.
4958 These statements are left as-is in the IL to facilitate discovery of
4959 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
4960 the alternate range representation is often useful within VRP. */
4962 static bool
4963 overflow_comparison_p (tree_code code, tree name, tree val,
4964 bool use_equiv_p, tree *new_cst)
4966 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
4967 return true;
4968 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
4969 use_equiv_p, true, new_cst);
4973 /* Try to register an edge assertion for SSA name NAME on edge E for
4974 the condition COND contributing to the conditional jump pointed to by BSI.
4975 Invert the condition COND if INVERT is true. */
4977 static void
4978 register_edge_assert_for_2 (tree name, edge e,
4979 enum tree_code cond_code,
4980 tree cond_op0, tree cond_op1, bool invert,
4981 vec<assert_info> &asserts)
4983 tree val;
4984 enum tree_code comp_code;
4986 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
4987 cond_op0,
4988 cond_op1,
4989 invert, &comp_code, &val))
4990 return;
4992 /* Queue the assert. */
4993 tree x;
4994 if (overflow_comparison_p (comp_code, name, val, false, &x))
4996 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
4997 ? GT_EXPR : LE_EXPR);
4998 add_assert_info (asserts, name, name, new_code, x);
5000 add_assert_info (asserts, name, name, comp_code, val);
5002 /* In the case of NAME <= CST and NAME being defined as
5003 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
5004 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
5005 This catches range and anti-range tests. */
5006 if ((comp_code == LE_EXPR
5007 || comp_code == GT_EXPR)
5008 && TREE_CODE (val) == INTEGER_CST
5009 && TYPE_UNSIGNED (TREE_TYPE (val)))
5011 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5012 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
5014 /* Extract CST2 from the (optional) addition. */
5015 if (is_gimple_assign (def_stmt)
5016 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
5018 name2 = gimple_assign_rhs1 (def_stmt);
5019 cst2 = gimple_assign_rhs2 (def_stmt);
5020 if (TREE_CODE (name2) == SSA_NAME
5021 && TREE_CODE (cst2) == INTEGER_CST)
5022 def_stmt = SSA_NAME_DEF_STMT (name2);
5025 /* Extract NAME2 from the (optional) sign-changing cast. */
5026 if (gimple_assign_cast_p (def_stmt))
5028 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
5029 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5030 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
5031 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
5032 name3 = gimple_assign_rhs1 (def_stmt);
5035 /* If name3 is used later, create an ASSERT_EXPR for it. */
5036 if (name3 != NULL_TREE
5037 && TREE_CODE (name3) == SSA_NAME
5038 && (cst2 == NULL_TREE
5039 || TREE_CODE (cst2) == INTEGER_CST)
5040 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
5042 tree tmp;
5044 /* Build an expression for the range test. */
5045 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
5046 if (cst2 != NULL_TREE)
5047 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5049 if (dump_file)
5051 fprintf (dump_file, "Adding assert for ");
5052 print_generic_expr (dump_file, name3);
5053 fprintf (dump_file, " from ");
5054 print_generic_expr (dump_file, tmp);
5055 fprintf (dump_file, "\n");
5058 add_assert_info (asserts, name3, tmp, comp_code, val);
5061 /* If name2 is used later, create an ASSERT_EXPR for it. */
5062 if (name2 != NULL_TREE
5063 && TREE_CODE (name2) == SSA_NAME
5064 && TREE_CODE (cst2) == INTEGER_CST
5065 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
5067 tree tmp;
5069 /* Build an expression for the range test. */
5070 tmp = name2;
5071 if (TREE_TYPE (name) != TREE_TYPE (name2))
5072 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
5073 if (cst2 != NULL_TREE)
5074 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5076 if (dump_file)
5078 fprintf (dump_file, "Adding assert for ");
5079 print_generic_expr (dump_file, name2);
5080 fprintf (dump_file, " from ");
5081 print_generic_expr (dump_file, tmp);
5082 fprintf (dump_file, "\n");
5085 add_assert_info (asserts, name2, tmp, comp_code, val);
5089 /* In the case of post-in/decrement tests like if (i++) ... and uses
5090 of the in/decremented value on the edge the extra name we want to
5091 assert for is not on the def chain of the name compared. Instead
5092 it is in the set of use stmts.
5093 Similar cases happen for conversions that were simplified through
5094 fold_{sign_changed,widened}_comparison. */
5095 if ((comp_code == NE_EXPR
5096 || comp_code == EQ_EXPR)
5097 && TREE_CODE (val) == INTEGER_CST)
5099 imm_use_iterator ui;
5100 gimple *use_stmt;
5101 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
5103 if (!is_gimple_assign (use_stmt))
5104 continue;
5106 /* Cut off to use-stmts that are dominating the predecessor. */
5107 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
5108 continue;
5110 tree name2 = gimple_assign_lhs (use_stmt);
5111 if (TREE_CODE (name2) != SSA_NAME)
5112 continue;
5114 enum tree_code code = gimple_assign_rhs_code (use_stmt);
5115 tree cst;
5116 if (code == PLUS_EXPR
5117 || code == MINUS_EXPR)
5119 cst = gimple_assign_rhs2 (use_stmt);
5120 if (TREE_CODE (cst) != INTEGER_CST)
5121 continue;
5122 cst = int_const_binop (code, val, cst);
5124 else if (CONVERT_EXPR_CODE_P (code))
5126 /* For truncating conversions we cannot record
5127 an inequality. */
5128 if (comp_code == NE_EXPR
5129 && (TYPE_PRECISION (TREE_TYPE (name2))
5130 < TYPE_PRECISION (TREE_TYPE (name))))
5131 continue;
5132 cst = fold_convert (TREE_TYPE (name2), val);
5134 else
5135 continue;
5137 if (TREE_OVERFLOW_P (cst))
5138 cst = drop_tree_overflow (cst);
5139 add_assert_info (asserts, name2, name2, comp_code, cst);
5143 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
5144 && TREE_CODE (val) == INTEGER_CST)
5146 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5147 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
5148 tree val2 = NULL_TREE;
5149 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
5150 wide_int mask = wi::zero (prec);
5151 unsigned int nprec = prec;
5152 enum tree_code rhs_code = ERROR_MARK;
5154 if (is_gimple_assign (def_stmt))
5155 rhs_code = gimple_assign_rhs_code (def_stmt);
5157 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
5158 assert that A != CST1 -+ CST2. */
5159 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5160 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
5162 tree op0 = gimple_assign_rhs1 (def_stmt);
5163 tree op1 = gimple_assign_rhs2 (def_stmt);
5164 if (TREE_CODE (op0) == SSA_NAME
5165 && TREE_CODE (op1) == INTEGER_CST)
5167 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
5168 ? MINUS_EXPR : PLUS_EXPR);
5169 op1 = int_const_binop (reverse_op, val, op1);
5170 if (TREE_OVERFLOW (op1))
5171 op1 = drop_tree_overflow (op1);
5172 add_assert_info (asserts, op0, op0, comp_code, op1);
5176 /* Add asserts for NAME cmp CST and NAME being defined
5177 as NAME = (int) NAME2. */
5178 if (!TYPE_UNSIGNED (TREE_TYPE (val))
5179 && (comp_code == LE_EXPR || comp_code == LT_EXPR
5180 || comp_code == GT_EXPR || comp_code == GE_EXPR)
5181 && gimple_assign_cast_p (def_stmt))
5183 name2 = gimple_assign_rhs1 (def_stmt);
5184 if (CONVERT_EXPR_CODE_P (rhs_code)
5185 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5186 && TYPE_UNSIGNED (TREE_TYPE (name2))
5187 && prec == TYPE_PRECISION (TREE_TYPE (name2))
5188 && (comp_code == LE_EXPR || comp_code == GT_EXPR
5189 || !tree_int_cst_equal (val,
5190 TYPE_MIN_VALUE (TREE_TYPE (val)))))
5192 tree tmp, cst;
5193 enum tree_code new_comp_code = comp_code;
5195 cst = fold_convert (TREE_TYPE (name2),
5196 TYPE_MIN_VALUE (TREE_TYPE (val)));
5197 /* Build an expression for the range test. */
5198 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
5199 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
5200 fold_convert (TREE_TYPE (name2), val));
5201 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5203 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
5204 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
5205 build_int_cst (TREE_TYPE (name2), 1));
5208 if (dump_file)
5210 fprintf (dump_file, "Adding assert for ");
5211 print_generic_expr (dump_file, name2);
5212 fprintf (dump_file, " from ");
5213 print_generic_expr (dump_file, tmp);
5214 fprintf (dump_file, "\n");
5217 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
5221 /* Add asserts for NAME cmp CST and NAME being defined as
5222 NAME = NAME2 >> CST2.
5224 Extract CST2 from the right shift. */
5225 if (rhs_code == RSHIFT_EXPR)
5227 name2 = gimple_assign_rhs1 (def_stmt);
5228 cst2 = gimple_assign_rhs2 (def_stmt);
5229 if (TREE_CODE (name2) == SSA_NAME
5230 && tree_fits_uhwi_p (cst2)
5231 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5232 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
5233 && type_has_mode_precision_p (TREE_TYPE (val)))
5235 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
5236 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
5239 if (val2 != NULL_TREE
5240 && TREE_CODE (val2) == INTEGER_CST
5241 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
5242 TREE_TYPE (val),
5243 val2, cst2), val))
5245 enum tree_code new_comp_code = comp_code;
5246 tree tmp, new_val;
5248 tmp = name2;
5249 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
5251 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
5253 tree type = build_nonstandard_integer_type (prec, 1);
5254 tmp = build1 (NOP_EXPR, type, name2);
5255 val2 = fold_convert (type, val2);
5257 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
5258 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
5259 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
5261 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5263 wide_int minval
5264 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5265 new_val = val2;
5266 if (minval == wi::to_wide (new_val))
5267 new_val = NULL_TREE;
5269 else
5271 wide_int maxval
5272 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5273 mask |= wi::to_wide (val2);
5274 if (wi::eq_p (mask, maxval))
5275 new_val = NULL_TREE;
5276 else
5277 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
5280 if (new_val)
5282 if (dump_file)
5284 fprintf (dump_file, "Adding assert for ");
5285 print_generic_expr (dump_file, name2);
5286 fprintf (dump_file, " from ");
5287 print_generic_expr (dump_file, tmp);
5288 fprintf (dump_file, "\n");
5291 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
5295 /* Add asserts for NAME cmp CST and NAME being defined as
5296 NAME = NAME2 & CST2.
5298 Extract CST2 from the and.
5300 Also handle
5301 NAME = (unsigned) NAME2;
5302 casts where NAME's type is unsigned and has smaller precision
5303 than NAME2's type as if it was NAME = NAME2 & MASK. */
5304 names[0] = NULL_TREE;
5305 names[1] = NULL_TREE;
5306 cst2 = NULL_TREE;
5307 if (rhs_code == BIT_AND_EXPR
5308 || (CONVERT_EXPR_CODE_P (rhs_code)
5309 && INTEGRAL_TYPE_P (TREE_TYPE (val))
5310 && TYPE_UNSIGNED (TREE_TYPE (val))
5311 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5312 > prec))
5314 name2 = gimple_assign_rhs1 (def_stmt);
5315 if (rhs_code == BIT_AND_EXPR)
5316 cst2 = gimple_assign_rhs2 (def_stmt);
5317 else
5319 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
5320 nprec = TYPE_PRECISION (TREE_TYPE (name2));
5322 if (TREE_CODE (name2) == SSA_NAME
5323 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5324 && TREE_CODE (cst2) == INTEGER_CST
5325 && !integer_zerop (cst2)
5326 && (nprec > 1
5327 || TYPE_UNSIGNED (TREE_TYPE (val))))
5329 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
5330 if (gimple_assign_cast_p (def_stmt2))
5332 names[1] = gimple_assign_rhs1 (def_stmt2);
5333 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
5334 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
5335 || (TYPE_PRECISION (TREE_TYPE (name2))
5336 != TYPE_PRECISION (TREE_TYPE (names[1]))))
5337 names[1] = NULL_TREE;
5339 names[0] = name2;
5342 if (names[0] || names[1])
5344 wide_int minv, maxv, valv, cst2v;
5345 wide_int tem, sgnbit;
5346 bool valid_p = false, valn, cst2n;
5347 enum tree_code ccode = comp_code;
5349 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
5350 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
5351 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
5352 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
5353 /* If CST2 doesn't have most significant bit set,
5354 but VAL is negative, we have comparison like
5355 if ((x & 0x123) > -4) (always true). Just give up. */
5356 if (!cst2n && valn)
5357 ccode = ERROR_MARK;
5358 if (cst2n)
5359 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5360 else
5361 sgnbit = wi::zero (nprec);
5362 minv = valv & cst2v;
5363 switch (ccode)
5365 case EQ_EXPR:
5366 /* Minimum unsigned value for equality is VAL & CST2
5367 (should be equal to VAL, otherwise we probably should
5368 have folded the comparison into false) and
5369 maximum unsigned value is VAL | ~CST2. */
5370 maxv = valv | ~cst2v;
5371 valid_p = true;
5372 break;
5374 case NE_EXPR:
5375 tem = valv | ~cst2v;
5376 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
5377 if (valv == 0)
5379 cst2n = false;
5380 sgnbit = wi::zero (nprec);
5381 goto gt_expr;
5383 /* If (VAL | ~CST2) is all ones, handle it as
5384 (X & CST2) < VAL. */
5385 if (tem == -1)
5387 cst2n = false;
5388 valn = false;
5389 sgnbit = wi::zero (nprec);
5390 goto lt_expr;
5392 if (!cst2n && wi::neg_p (cst2v))
5393 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5394 if (sgnbit != 0)
5396 if (valv == sgnbit)
5398 cst2n = true;
5399 valn = true;
5400 goto gt_expr;
5402 if (tem == wi::mask (nprec - 1, false, nprec))
5404 cst2n = true;
5405 goto lt_expr;
5407 if (!cst2n)
5408 sgnbit = wi::zero (nprec);
5410 break;
5412 case GE_EXPR:
5413 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
5414 is VAL and maximum unsigned value is ~0. For signed
5415 comparison, if CST2 doesn't have most significant bit
5416 set, handle it similarly. If CST2 has MSB set,
5417 the minimum is the same, and maximum is ~0U/2. */
5418 if (minv != valv)
5420 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
5421 VAL. */
5422 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5423 if (minv == valv)
5424 break;
5426 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5427 valid_p = true;
5428 break;
5430 case GT_EXPR:
5431 gt_expr:
5432 /* Find out smallest MINV where MINV > VAL
5433 && (MINV & CST2) == MINV, if any. If VAL is signed and
5434 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
5435 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5436 if (minv == valv)
5437 break;
5438 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5439 valid_p = true;
5440 break;
5442 case LE_EXPR:
5443 /* Minimum unsigned value for <= is 0 and maximum
5444 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
5445 Otherwise, find smallest VAL2 where VAL2 > VAL
5446 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5447 as maximum.
5448 For signed comparison, if CST2 doesn't have most
5449 significant bit set, handle it similarly. If CST2 has
5450 MSB set, the maximum is the same and minimum is INT_MIN. */
5451 if (minv == valv)
5452 maxv = valv;
5453 else
5455 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5456 if (maxv == valv)
5457 break;
5458 maxv -= 1;
5460 maxv |= ~cst2v;
5461 minv = sgnbit;
5462 valid_p = true;
5463 break;
5465 case LT_EXPR:
5466 lt_expr:
5467 /* Minimum unsigned value for < is 0 and maximum
5468 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
5469 Otherwise, find smallest VAL2 where VAL2 > VAL
5470 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5471 as maximum.
5472 For signed comparison, if CST2 doesn't have most
5473 significant bit set, handle it similarly. If CST2 has
5474 MSB set, the maximum is the same and minimum is INT_MIN. */
5475 if (minv == valv)
5477 if (valv == sgnbit)
5478 break;
5479 maxv = valv;
5481 else
5483 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5484 if (maxv == valv)
5485 break;
5487 maxv -= 1;
5488 maxv |= ~cst2v;
5489 minv = sgnbit;
5490 valid_p = true;
5491 break;
5493 default:
5494 break;
5496 if (valid_p
5497 && (maxv - minv) != -1)
5499 tree tmp, new_val, type;
5500 int i;
5502 for (i = 0; i < 2; i++)
5503 if (names[i])
5505 wide_int maxv2 = maxv;
5506 tmp = names[i];
5507 type = TREE_TYPE (names[i]);
5508 if (!TYPE_UNSIGNED (type))
5510 type = build_nonstandard_integer_type (nprec, 1);
5511 tmp = build1 (NOP_EXPR, type, names[i]);
5513 if (minv != 0)
5515 tmp = build2 (PLUS_EXPR, type, tmp,
5516 wide_int_to_tree (type, -minv));
5517 maxv2 = maxv - minv;
5519 new_val = wide_int_to_tree (type, maxv2);
5521 if (dump_file)
5523 fprintf (dump_file, "Adding assert for ");
5524 print_generic_expr (dump_file, names[i]);
5525 fprintf (dump_file, " from ");
5526 print_generic_expr (dump_file, tmp);
5527 fprintf (dump_file, "\n");
5530 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
5537 /* OP is an operand of a truth value expression which is known to have
5538 a particular value. Register any asserts for OP and for any
5539 operands in OP's defining statement.
5541 If CODE is EQ_EXPR, then we want to register OP is zero (false),
5542 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
5544 static void
5545 register_edge_assert_for_1 (tree op, enum tree_code code,
5546 edge e, vec<assert_info> &asserts)
5548 gimple *op_def;
5549 tree val;
5550 enum tree_code rhs_code;
5552 /* We only care about SSA_NAMEs. */
5553 if (TREE_CODE (op) != SSA_NAME)
5554 return;
5556 /* We know that OP will have a zero or nonzero value. */
5557 val = build_int_cst (TREE_TYPE (op), 0);
5558 add_assert_info (asserts, op, op, code, val);
5560 /* Now look at how OP is set. If it's set from a comparison,
5561 a truth operation or some bit operations, then we may be able
5562 to register information about the operands of that assignment. */
5563 op_def = SSA_NAME_DEF_STMT (op);
5564 if (gimple_code (op_def) != GIMPLE_ASSIGN)
5565 return;
5567 rhs_code = gimple_assign_rhs_code (op_def);
5569 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
5571 bool invert = (code == EQ_EXPR ? true : false);
5572 tree op0 = gimple_assign_rhs1 (op_def);
5573 tree op1 = gimple_assign_rhs2 (op_def);
5575 if (TREE_CODE (op0) == SSA_NAME)
5576 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
5577 if (TREE_CODE (op1) == SSA_NAME)
5578 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
5580 else if ((code == NE_EXPR
5581 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
5582 || (code == EQ_EXPR
5583 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
5585 /* Recurse on each operand. */
5586 tree op0 = gimple_assign_rhs1 (op_def);
5587 tree op1 = gimple_assign_rhs2 (op_def);
5588 if (TREE_CODE (op0) == SSA_NAME
5589 && has_single_use (op0))
5590 register_edge_assert_for_1 (op0, code, e, asserts);
5591 if (TREE_CODE (op1) == SSA_NAME
5592 && has_single_use (op1))
5593 register_edge_assert_for_1 (op1, code, e, asserts);
5595 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
5596 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
5598 /* Recurse, flipping CODE. */
5599 code = invert_tree_comparison (code, false);
5600 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
5602 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
5604 /* Recurse through the copy. */
5605 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
5607 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
5609 /* Recurse through the type conversion, unless it is a narrowing
5610 conversion or conversion from non-integral type. */
5611 tree rhs = gimple_assign_rhs1 (op_def);
5612 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
5613 && (TYPE_PRECISION (TREE_TYPE (rhs))
5614 <= TYPE_PRECISION (TREE_TYPE (op))))
5615 register_edge_assert_for_1 (rhs, code, e, asserts);
5619 /* Check if comparison
5620 NAME COND_OP INTEGER_CST
5621 has a form of
5622 (X & 11...100..0) COND_OP XX...X00...0
5623 Such comparison can yield assertions like
5624 X >= XX...X00...0
5625 X <= XX...X11...1
5626 in case of COND_OP being NE_EXPR or
5627 X < XX...X00...0
5628 X > XX...X11...1
5629 in case of EQ_EXPR. */
5631 static bool
5632 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
5633 tree *new_name, tree *low, enum tree_code *low_code,
5634 tree *high, enum tree_code *high_code)
5636 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5638 if (!is_gimple_assign (def_stmt)
5639 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
5640 return false;
5642 tree t = gimple_assign_rhs1 (def_stmt);
5643 tree maskt = gimple_assign_rhs2 (def_stmt);
5644 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
5645 return false;
5647 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
5648 wide_int inv_mask = ~mask;
5649 /* Assume VALT is INTEGER_CST. */
5650 wi::tree_to_wide_ref val = wi::to_wide (valt);
5652 if ((inv_mask & (inv_mask + 1)) != 0
5653 || (val & mask) != val)
5654 return false;
5656 bool is_range = cond_code == EQ_EXPR;
5658 tree type = TREE_TYPE (t);
5659 wide_int min = wi::min_value (type),
5660 max = wi::max_value (type);
5662 if (is_range)
5664 *low_code = val == min ? ERROR_MARK : GE_EXPR;
5665 *high_code = val == max ? ERROR_MARK : LE_EXPR;
5667 else
5669 /* We can still generate assertion if one of alternatives
5670 is known to always be false. */
5671 if (val == min)
5673 *low_code = (enum tree_code) 0;
5674 *high_code = GT_EXPR;
5676 else if ((val | inv_mask) == max)
5678 *low_code = LT_EXPR;
5679 *high_code = (enum tree_code) 0;
5681 else
5682 return false;
5685 *new_name = t;
5686 *low = wide_int_to_tree (type, val);
5687 *high = wide_int_to_tree (type, val | inv_mask);
5689 if (wi::neg_p (val, TYPE_SIGN (type)))
5690 std::swap (*low, *high);
5692 return true;
5695 /* Try to register an edge assertion for SSA name NAME on edge E for
5696 the condition COND contributing to the conditional jump pointed to by
5697 SI. */
5699 static void
5700 register_edge_assert_for (tree name, edge e,
5701 enum tree_code cond_code, tree cond_op0,
5702 tree cond_op1, vec<assert_info> &asserts)
5704 tree val;
5705 enum tree_code comp_code;
5706 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
5708 /* Do not attempt to infer anything in names that flow through
5709 abnormal edges. */
5710 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
5711 return;
5713 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5714 cond_op0, cond_op1,
5715 is_else_edge,
5716 &comp_code, &val))
5717 return;
5719 /* Register ASSERT_EXPRs for name. */
5720 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
5721 cond_op1, is_else_edge, asserts);
5724 /* If COND is effectively an equality test of an SSA_NAME against
5725 the value zero or one, then we may be able to assert values
5726 for SSA_NAMEs which flow into COND. */
5728 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
5729 statement of NAME we can assert both operands of the BIT_AND_EXPR
5730 have nonzero value. */
5731 if (((comp_code == EQ_EXPR && integer_onep (val))
5732 || (comp_code == NE_EXPR && integer_zerop (val))))
5734 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5736 if (is_gimple_assign (def_stmt)
5737 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
5739 tree op0 = gimple_assign_rhs1 (def_stmt);
5740 tree op1 = gimple_assign_rhs2 (def_stmt);
5741 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
5742 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
5746 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
5747 statement of NAME we can assert both operands of the BIT_IOR_EXPR
5748 have zero value. */
5749 if (((comp_code == EQ_EXPR && integer_zerop (val))
5750 || (comp_code == NE_EXPR && integer_onep (val))))
5752 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5754 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
5755 necessarily zero value, or if type-precision is one. */
5756 if (is_gimple_assign (def_stmt)
5757 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
5758 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
5759 || comp_code == EQ_EXPR)))
5761 tree op0 = gimple_assign_rhs1 (def_stmt);
5762 tree op1 = gimple_assign_rhs2 (def_stmt);
5763 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
5764 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
5768 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
5769 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5770 && TREE_CODE (val) == INTEGER_CST)
5772 enum tree_code low_code, high_code;
5773 tree low, high;
5774 if (is_masked_range_test (name, val, comp_code, &name, &low,
5775 &low_code, &high, &high_code))
5777 if (low_code != ERROR_MARK)
5778 register_edge_assert_for_2 (name, e, low_code, name,
5779 low, /*invert*/false, asserts);
5780 if (high_code != ERROR_MARK)
5781 register_edge_assert_for_2 (name, e, high_code, name,
5782 high, /*invert*/false, asserts);
5787 /* Finish found ASSERTS for E and register them at GSI. */
5789 static void
5790 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
5791 vec<assert_info> &asserts)
5793 for (unsigned i = 0; i < asserts.length (); ++i)
5794 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
5795 reachable from E. */
5796 if (live_on_edge (e, asserts[i].name))
5797 register_new_assert_for (asserts[i].name, asserts[i].expr,
5798 asserts[i].comp_code, asserts[i].val,
5799 NULL, e, gsi);
5804 /* Determine whether the outgoing edges of BB should receive an
5805 ASSERT_EXPR for each of the operands of BB's LAST statement.
5806 The last statement of BB must be a COND_EXPR.
5808 If any of the sub-graphs rooted at BB have an interesting use of
5809 the predicate operands, an assert location node is added to the
5810 list of assertions for the corresponding operands. */
5812 static void
5813 find_conditional_asserts (basic_block bb, gcond *last)
5815 gimple_stmt_iterator bsi;
5816 tree op;
5817 edge_iterator ei;
5818 edge e;
5819 ssa_op_iter iter;
5821 bsi = gsi_for_stmt (last);
5823 /* Look for uses of the operands in each of the sub-graphs
5824 rooted at BB. We need to check each of the outgoing edges
5825 separately, so that we know what kind of ASSERT_EXPR to
5826 insert. */
5827 FOR_EACH_EDGE (e, ei, bb->succs)
5829 if (e->dest == bb)
5830 continue;
5832 /* Register the necessary assertions for each operand in the
5833 conditional predicate. */
5834 auto_vec<assert_info, 8> asserts;
5835 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
5836 register_edge_assert_for (op, e,
5837 gimple_cond_code (last),
5838 gimple_cond_lhs (last),
5839 gimple_cond_rhs (last), asserts);
5840 finish_register_edge_assert_for (e, bsi, asserts);
5844 struct case_info
5846 tree expr;
5847 basic_block bb;
5850 /* Compare two case labels sorting first by the destination bb index
5851 and then by the case value. */
5853 static int
5854 compare_case_labels (const void *p1, const void *p2)
5856 const struct case_info *ci1 = (const struct case_info *) p1;
5857 const struct case_info *ci2 = (const struct case_info *) p2;
5858 int idx1 = ci1->bb->index;
5859 int idx2 = ci2->bb->index;
5861 if (idx1 < idx2)
5862 return -1;
5863 else if (idx1 == idx2)
5865 /* Make sure the default label is first in a group. */
5866 if (!CASE_LOW (ci1->expr))
5867 return -1;
5868 else if (!CASE_LOW (ci2->expr))
5869 return 1;
5870 else
5871 return tree_int_cst_compare (CASE_LOW (ci1->expr),
5872 CASE_LOW (ci2->expr));
5874 else
5875 return 1;
5878 /* Determine whether the outgoing edges of BB should receive an
5879 ASSERT_EXPR for each of the operands of BB's LAST statement.
5880 The last statement of BB must be a SWITCH_EXPR.
5882 If any of the sub-graphs rooted at BB have an interesting use of
5883 the predicate operands, an assert location node is added to the
5884 list of assertions for the corresponding operands. */
5886 static void
5887 find_switch_asserts (basic_block bb, gswitch *last)
5889 gimple_stmt_iterator bsi;
5890 tree op;
5891 edge e;
5892 struct case_info *ci;
5893 size_t n = gimple_switch_num_labels (last);
5894 #if GCC_VERSION >= 4000
5895 unsigned int idx;
5896 #else
5897 /* Work around GCC 3.4 bug (PR 37086). */
5898 volatile unsigned int idx;
5899 #endif
5901 bsi = gsi_for_stmt (last);
5902 op = gimple_switch_index (last);
5903 if (TREE_CODE (op) != SSA_NAME)
5904 return;
5906 /* Build a vector of case labels sorted by destination label. */
5907 ci = XNEWVEC (struct case_info, n);
5908 for (idx = 0; idx < n; ++idx)
5910 ci[idx].expr = gimple_switch_label (last, idx);
5911 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
5913 edge default_edge = find_edge (bb, ci[0].bb);
5914 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
5916 for (idx = 0; idx < n; ++idx)
5918 tree min, max;
5919 tree cl = ci[idx].expr;
5920 basic_block cbb = ci[idx].bb;
5922 min = CASE_LOW (cl);
5923 max = CASE_HIGH (cl);
5925 /* If there are multiple case labels with the same destination
5926 we need to combine them to a single value range for the edge. */
5927 if (idx + 1 < n && cbb == ci[idx + 1].bb)
5929 /* Skip labels until the last of the group. */
5930 do {
5931 ++idx;
5932 } while (idx < n && cbb == ci[idx].bb);
5933 --idx;
5935 /* Pick up the maximum of the case label range. */
5936 if (CASE_HIGH (ci[idx].expr))
5937 max = CASE_HIGH (ci[idx].expr);
5938 else
5939 max = CASE_LOW (ci[idx].expr);
5942 /* Can't extract a useful assertion out of a range that includes the
5943 default label. */
5944 if (min == NULL_TREE)
5945 continue;
5947 /* Find the edge to register the assert expr on. */
5948 e = find_edge (bb, cbb);
5950 /* Register the necessary assertions for the operand in the
5951 SWITCH_EXPR. */
5952 auto_vec<assert_info, 8> asserts;
5953 register_edge_assert_for (op, e,
5954 max ? GE_EXPR : EQ_EXPR,
5955 op, fold_convert (TREE_TYPE (op), min),
5956 asserts);
5957 if (max)
5958 register_edge_assert_for (op, e, LE_EXPR, op,
5959 fold_convert (TREE_TYPE (op), max),
5960 asserts);
5961 finish_register_edge_assert_for (e, bsi, asserts);
5964 XDELETEVEC (ci);
5966 if (!live_on_edge (default_edge, op))
5967 return;
5969 /* Now register along the default label assertions that correspond to the
5970 anti-range of each label. */
5971 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
5972 if (insertion_limit == 0)
5973 return;
5975 /* We can't do this if the default case shares a label with another case. */
5976 tree default_cl = gimple_switch_default_label (last);
5977 for (idx = 1; idx < n; idx++)
5979 tree min, max;
5980 tree cl = gimple_switch_label (last, idx);
5981 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
5982 continue;
5984 min = CASE_LOW (cl);
5985 max = CASE_HIGH (cl);
5987 /* Combine contiguous case ranges to reduce the number of assertions
5988 to insert. */
5989 for (idx = idx + 1; idx < n; idx++)
5991 tree next_min, next_max;
5992 tree next_cl = gimple_switch_label (last, idx);
5993 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
5994 break;
5996 next_min = CASE_LOW (next_cl);
5997 next_max = CASE_HIGH (next_cl);
5999 wide_int difference = (wi::to_wide (next_min)
6000 - wi::to_wide (max ? max : min));
6001 if (wi::eq_p (difference, 1))
6002 max = next_max ? next_max : next_min;
6003 else
6004 break;
6006 idx--;
6008 if (max == NULL_TREE)
6010 /* Register the assertion OP != MIN. */
6011 auto_vec<assert_info, 8> asserts;
6012 min = fold_convert (TREE_TYPE (op), min);
6013 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
6014 asserts);
6015 finish_register_edge_assert_for (default_edge, bsi, asserts);
6017 else
6019 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
6020 which will give OP the anti-range ~[MIN,MAX]. */
6021 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
6022 min = fold_convert (TREE_TYPE (uop), min);
6023 max = fold_convert (TREE_TYPE (uop), max);
6025 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
6026 tree rhs = int_const_binop (MINUS_EXPR, max, min);
6027 register_new_assert_for (op, lhs, GT_EXPR, rhs,
6028 NULL, default_edge, bsi);
6031 if (--insertion_limit == 0)
6032 break;
6037 /* Traverse all the statements in block BB looking for statements that
6038 may generate useful assertions for the SSA names in their operand.
6039 If a statement produces a useful assertion A for name N_i, then the
6040 list of assertions already generated for N_i is scanned to
6041 determine if A is actually needed.
6043 If N_i already had the assertion A at a location dominating the
6044 current location, then nothing needs to be done. Otherwise, the
6045 new location for A is recorded instead.
6047 1- For every statement S in BB, all the variables used by S are
6048 added to bitmap FOUND_IN_SUBGRAPH.
6050 2- If statement S uses an operand N in a way that exposes a known
6051 value range for N, then if N was not already generated by an
6052 ASSERT_EXPR, create a new assert location for N. For instance,
6053 if N is a pointer and the statement dereferences it, we can
6054 assume that N is not NULL.
6056 3- COND_EXPRs are a special case of #2. We can derive range
6057 information from the predicate but need to insert different
6058 ASSERT_EXPRs for each of the sub-graphs rooted at the
6059 conditional block. If the last statement of BB is a conditional
6060 expression of the form 'X op Y', then
6062 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
6064 b) If the conditional is the only entry point to the sub-graph
6065 corresponding to the THEN_CLAUSE, recurse into it. On
6066 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
6067 an ASSERT_EXPR is added for the corresponding variable.
6069 c) Repeat step (b) on the ELSE_CLAUSE.
6071 d) Mark X and Y in FOUND_IN_SUBGRAPH.
6073 For instance,
6075 if (a == 9)
6076 b = a;
6077 else
6078 b = c + 1;
6080 In this case, an assertion on the THEN clause is useful to
6081 determine that 'a' is always 9 on that edge. However, an assertion
6082 on the ELSE clause would be unnecessary.
6084 4- If BB does not end in a conditional expression, then we recurse
6085 into BB's dominator children.
6087 At the end of the recursive traversal, every SSA name will have a
6088 list of locations where ASSERT_EXPRs should be added. When a new
6089 location for name N is found, it is registered by calling
6090 register_new_assert_for. That function keeps track of all the
6091 registered assertions to prevent adding unnecessary assertions.
6092 For instance, if a pointer P_4 is dereferenced more than once in a
6093 dominator tree, only the location dominating all the dereference of
6094 P_4 will receive an ASSERT_EXPR. */
6096 static void
6097 find_assert_locations_1 (basic_block bb, sbitmap live)
6099 gimple *last;
6101 last = last_stmt (bb);
6103 /* If BB's last statement is a conditional statement involving integer
6104 operands, determine if we need to add ASSERT_EXPRs. */
6105 if (last
6106 && gimple_code (last) == GIMPLE_COND
6107 && !fp_predicate (last)
6108 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6109 find_conditional_asserts (bb, as_a <gcond *> (last));
6111 /* If BB's last statement is a switch statement involving integer
6112 operands, determine if we need to add ASSERT_EXPRs. */
6113 if (last
6114 && gimple_code (last) == GIMPLE_SWITCH
6115 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6116 find_switch_asserts (bb, as_a <gswitch *> (last));
6118 /* Traverse all the statements in BB marking used names and looking
6119 for statements that may infer assertions for their used operands. */
6120 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
6121 gsi_prev (&si))
6123 gimple *stmt;
6124 tree op;
6125 ssa_op_iter i;
6127 stmt = gsi_stmt (si);
6129 if (is_gimple_debug (stmt))
6130 continue;
6132 /* See if we can derive an assertion for any of STMT's operands. */
6133 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6135 tree value;
6136 enum tree_code comp_code;
6138 /* If op is not live beyond this stmt, do not bother to insert
6139 asserts for it. */
6140 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
6141 continue;
6143 /* If OP is used in such a way that we can infer a value
6144 range for it, and we don't find a previous assertion for
6145 it, create a new assertion location node for OP. */
6146 if (infer_value_range (stmt, op, &comp_code, &value))
6148 /* If we are able to infer a nonzero value range for OP,
6149 then walk backwards through the use-def chain to see if OP
6150 was set via a typecast.
6152 If so, then we can also infer a nonzero value range
6153 for the operand of the NOP_EXPR. */
6154 if (comp_code == NE_EXPR && integer_zerop (value))
6156 tree t = op;
6157 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
6159 while (is_gimple_assign (def_stmt)
6160 && CONVERT_EXPR_CODE_P
6161 (gimple_assign_rhs_code (def_stmt))
6162 && TREE_CODE
6163 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
6164 && POINTER_TYPE_P
6165 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
6167 t = gimple_assign_rhs1 (def_stmt);
6168 def_stmt = SSA_NAME_DEF_STMT (t);
6170 /* Note we want to register the assert for the
6171 operand of the NOP_EXPR after SI, not after the
6172 conversion. */
6173 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
6174 register_new_assert_for (t, t, comp_code, value,
6175 bb, NULL, si);
6179 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
6183 /* Update live. */
6184 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6185 bitmap_set_bit (live, SSA_NAME_VERSION (op));
6186 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
6187 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
6190 /* Traverse all PHI nodes in BB, updating live. */
6191 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6192 gsi_next (&si))
6194 use_operand_p arg_p;
6195 ssa_op_iter i;
6196 gphi *phi = si.phi ();
6197 tree res = gimple_phi_result (phi);
6199 if (virtual_operand_p (res))
6200 continue;
6202 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
6204 tree arg = USE_FROM_PTR (arg_p);
6205 if (TREE_CODE (arg) == SSA_NAME)
6206 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
6209 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
6213 /* Do an RPO walk over the function computing SSA name liveness
6214 on-the-fly and deciding on assert expressions to insert. */
6216 static void
6217 find_assert_locations (void)
6219 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6220 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6221 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
6222 int rpo_cnt, i;
6224 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
6225 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
6226 for (i = 0; i < rpo_cnt; ++i)
6227 bb_rpo[rpo[i]] = i;
6229 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
6230 the order we compute liveness and insert asserts we otherwise
6231 fail to insert asserts into the loop latch. */
6232 loop_p loop;
6233 FOR_EACH_LOOP (loop, 0)
6235 i = loop->latch->index;
6236 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
6237 for (gphi_iterator gsi = gsi_start_phis (loop->header);
6238 !gsi_end_p (gsi); gsi_next (&gsi))
6240 gphi *phi = gsi.phi ();
6241 if (virtual_operand_p (gimple_phi_result (phi)))
6242 continue;
6243 tree arg = gimple_phi_arg_def (phi, j);
6244 if (TREE_CODE (arg) == SSA_NAME)
6246 if (live[i] == NULL)
6248 live[i] = sbitmap_alloc (num_ssa_names);
6249 bitmap_clear (live[i]);
6251 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
6256 for (i = rpo_cnt - 1; i >= 0; --i)
6258 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
6259 edge e;
6260 edge_iterator ei;
6262 if (!live[rpo[i]])
6264 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
6265 bitmap_clear (live[rpo[i]]);
6268 /* Process BB and update the live information with uses in
6269 this block. */
6270 find_assert_locations_1 (bb, live[rpo[i]]);
6272 /* Merge liveness into the predecessor blocks and free it. */
6273 if (!bitmap_empty_p (live[rpo[i]]))
6275 int pred_rpo = i;
6276 FOR_EACH_EDGE (e, ei, bb->preds)
6278 int pred = e->src->index;
6279 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
6280 continue;
6282 if (!live[pred])
6284 live[pred] = sbitmap_alloc (num_ssa_names);
6285 bitmap_clear (live[pred]);
6287 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
6289 if (bb_rpo[pred] < pred_rpo)
6290 pred_rpo = bb_rpo[pred];
6293 /* Record the RPO number of the last visited block that needs
6294 live information from this block. */
6295 last_rpo[rpo[i]] = pred_rpo;
6297 else
6299 sbitmap_free (live[rpo[i]]);
6300 live[rpo[i]] = NULL;
6303 /* We can free all successors live bitmaps if all their
6304 predecessors have been visited already. */
6305 FOR_EACH_EDGE (e, ei, bb->succs)
6306 if (last_rpo[e->dest->index] == i
6307 && live[e->dest->index])
6309 sbitmap_free (live[e->dest->index]);
6310 live[e->dest->index] = NULL;
6314 XDELETEVEC (rpo);
6315 XDELETEVEC (bb_rpo);
6316 XDELETEVEC (last_rpo);
6317 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
6318 if (live[i])
6319 sbitmap_free (live[i]);
6320 XDELETEVEC (live);
6323 /* Create an ASSERT_EXPR for NAME and insert it in the location
6324 indicated by LOC. Return true if we made any edge insertions. */
6326 static bool
6327 process_assert_insertions_for (tree name, assert_locus *loc)
6329 /* Build the comparison expression NAME_i COMP_CODE VAL. */
6330 gimple *stmt;
6331 tree cond;
6332 gimple *assert_stmt;
6333 edge_iterator ei;
6334 edge e;
6336 /* If we have X <=> X do not insert an assert expr for that. */
6337 if (loc->expr == loc->val)
6338 return false;
6340 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
6341 assert_stmt = build_assert_expr_for (cond, name);
6342 if (loc->e)
6344 /* We have been asked to insert the assertion on an edge. This
6345 is used only by COND_EXPR and SWITCH_EXPR assertions. */
6346 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
6347 || (gimple_code (gsi_stmt (loc->si))
6348 == GIMPLE_SWITCH));
6350 gsi_insert_on_edge (loc->e, assert_stmt);
6351 return true;
6354 /* If the stmt iterator points at the end then this is an insertion
6355 at the beginning of a block. */
6356 if (gsi_end_p (loc->si))
6358 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
6359 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
6360 return false;
6363 /* Otherwise, we can insert right after LOC->SI iff the
6364 statement must not be the last statement in the block. */
6365 stmt = gsi_stmt (loc->si);
6366 if (!stmt_ends_bb_p (stmt))
6368 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
6369 return false;
6372 /* If STMT must be the last statement in BB, we can only insert new
6373 assertions on the non-abnormal edge out of BB. Note that since
6374 STMT is not control flow, there may only be one non-abnormal/eh edge
6375 out of BB. */
6376 FOR_EACH_EDGE (e, ei, loc->bb->succs)
6377 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
6379 gsi_insert_on_edge (e, assert_stmt);
6380 return true;
6383 gcc_unreachable ();
6386 /* Qsort helper for sorting assert locations. If stable is true, don't
6387 use iterative_hash_expr because it can be unstable for -fcompare-debug,
6388 on the other side some pointers might be NULL. */
6390 template <bool stable>
6391 static int
6392 compare_assert_loc (const void *pa, const void *pb)
6394 assert_locus * const a = *(assert_locus * const *)pa;
6395 assert_locus * const b = *(assert_locus * const *)pb;
6397 /* If stable, some asserts might be optimized away already, sort
6398 them last. */
6399 if (stable)
6401 if (a == NULL)
6402 return b != NULL;
6403 else if (b == NULL)
6404 return -1;
6407 if (a->e == NULL && b->e != NULL)
6408 return 1;
6409 else if (a->e != NULL && b->e == NULL)
6410 return -1;
6412 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
6413 no need to test both a->e and b->e. */
6415 /* Sort after destination index. */
6416 if (a->e == NULL)
6418 else if (a->e->dest->index > b->e->dest->index)
6419 return 1;
6420 else if (a->e->dest->index < b->e->dest->index)
6421 return -1;
6423 /* Sort after comp_code. */
6424 if (a->comp_code > b->comp_code)
6425 return 1;
6426 else if (a->comp_code < b->comp_code)
6427 return -1;
6429 hashval_t ha, hb;
6431 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
6432 uses DECL_UID of the VAR_DECL, so sorting might differ between
6433 -g and -g0. When doing the removal of redundant assert exprs
6434 and commonization to successors, this does not matter, but for
6435 the final sort needs to be stable. */
6436 if (stable)
6438 ha = 0;
6439 hb = 0;
6441 else
6443 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
6444 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
6447 /* Break the tie using hashing and source/bb index. */
6448 if (ha == hb)
6449 return (a->e != NULL
6450 ? a->e->src->index - b->e->src->index
6451 : a->bb->index - b->bb->index);
6452 return ha > hb ? 1 : -1;
6455 /* Process all the insertions registered for every name N_i registered
6456 in NEED_ASSERT_FOR. The list of assertions to be inserted are
6457 found in ASSERTS_FOR[i]. */
6459 static void
6460 process_assert_insertions (void)
6462 unsigned i;
6463 bitmap_iterator bi;
6464 bool update_edges_p = false;
6465 int num_asserts = 0;
6467 if (dump_file && (dump_flags & TDF_DETAILS))
6468 dump_all_asserts (dump_file);
6470 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
6472 assert_locus *loc = asserts_for[i];
6473 gcc_assert (loc);
6475 auto_vec<assert_locus *, 16> asserts;
6476 for (; loc; loc = loc->next)
6477 asserts.safe_push (loc);
6478 asserts.qsort (compare_assert_loc<false>);
6480 /* Push down common asserts to successors and remove redundant ones. */
6481 unsigned ecnt = 0;
6482 assert_locus *common = NULL;
6483 unsigned commonj = 0;
6484 for (unsigned j = 0; j < asserts.length (); ++j)
6486 loc = asserts[j];
6487 if (! loc->e)
6488 common = NULL;
6489 else if (! common
6490 || loc->e->dest != common->e->dest
6491 || loc->comp_code != common->comp_code
6492 || ! operand_equal_p (loc->val, common->val, 0)
6493 || ! operand_equal_p (loc->expr, common->expr, 0))
6495 commonj = j;
6496 common = loc;
6497 ecnt = 1;
6499 else if (loc->e == asserts[j-1]->e)
6501 /* Remove duplicate asserts. */
6502 if (commonj == j - 1)
6504 commonj = j;
6505 common = loc;
6507 free (asserts[j-1]);
6508 asserts[j-1] = NULL;
6510 else
6512 ecnt++;
6513 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
6515 /* We have the same assertion on all incoming edges of a BB.
6516 Insert it at the beginning of that block. */
6517 loc->bb = loc->e->dest;
6518 loc->e = NULL;
6519 loc->si = gsi_none ();
6520 common = NULL;
6521 /* Clear asserts commoned. */
6522 for (; commonj != j; ++commonj)
6523 if (asserts[commonj])
6525 free (asserts[commonj]);
6526 asserts[commonj] = NULL;
6532 /* The asserts vector sorting above might be unstable for
6533 -fcompare-debug, sort again to ensure a stable sort. */
6534 asserts.qsort (compare_assert_loc<true>);
6535 for (unsigned j = 0; j < asserts.length (); ++j)
6537 loc = asserts[j];
6538 if (! loc)
6539 break;
6540 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
6541 num_asserts++;
6542 free (loc);
6546 if (update_edges_p)
6547 gsi_commit_edge_inserts ();
6549 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
6550 num_asserts);
6554 /* Traverse the flowgraph looking for conditional jumps to insert range
6555 expressions. These range expressions are meant to provide information
6556 to optimizations that need to reason in terms of value ranges. They
6557 will not be expanded into RTL. For instance, given:
6559 x = ...
6560 y = ...
6561 if (x < y)
6562 y = x - 2;
6563 else
6564 x = y + 3;
6566 this pass will transform the code into:
6568 x = ...
6569 y = ...
6570 if (x < y)
6572 x = ASSERT_EXPR <x, x < y>
6573 y = x - 2
6575 else
6577 y = ASSERT_EXPR <y, x >= y>
6578 x = y + 3
6581 The idea is that once copy and constant propagation have run, other
6582 optimizations will be able to determine what ranges of values can 'x'
6583 take in different paths of the code, simply by checking the reaching
6584 definition of 'x'. */
6586 static void
6587 insert_range_assertions (void)
6589 need_assert_for = BITMAP_ALLOC (NULL);
6590 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
6592 calculate_dominance_info (CDI_DOMINATORS);
6594 find_assert_locations ();
6595 if (!bitmap_empty_p (need_assert_for))
6597 process_assert_insertions ();
6598 update_ssa (TODO_update_ssa_no_phi);
6601 if (dump_file && (dump_flags & TDF_DETAILS))
6603 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
6604 dump_function_to_file (current_function_decl, dump_file, dump_flags);
6607 free (asserts_for);
6608 BITMAP_FREE (need_assert_for);
6611 class vrp_prop : public ssa_propagation_engine
6613 public:
6614 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
6615 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
6617 void vrp_initialize (void);
6618 void vrp_finalize (bool);
6619 void check_all_array_refs (void);
6620 void check_array_ref (location_t, tree, bool);
6621 void search_for_addr_array (tree, location_t);
6623 class vr_values vr_values;
6624 /* Temporary delegator to minimize code churn. */
6625 value_range *get_value_range (const_tree op)
6626 { return vr_values.get_value_range (op); }
6627 void set_defs_to_varying (gimple *stmt)
6628 { return vr_values.set_defs_to_varying (stmt); }
6629 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
6630 tree *output_p, value_range *vr)
6631 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
6632 bool update_value_range (const_tree op, value_range *vr)
6633 { return vr_values.update_value_range (op, vr); }
6634 void extract_range_basic (value_range *vr, gimple *stmt)
6635 { vr_values.extract_range_basic (vr, stmt); }
6636 void extract_range_from_phi_node (gphi *phi, value_range *vr)
6637 { vr_values.extract_range_from_phi_node (phi, vr); }
6640 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
6641 and "struct" hacks. If VRP can determine that the
6642 array subscript is a constant, check if it is outside valid
6643 range. If the array subscript is a RANGE, warn if it is
6644 non-overlapping with valid range.
6645 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
6647 void
6648 vrp_prop::check_array_ref (location_t location, tree ref,
6649 bool ignore_off_by_one)
6651 value_range *vr = NULL;
6652 tree low_sub, up_sub;
6653 tree low_bound, up_bound, up_bound_p1;
6655 if (TREE_NO_WARNING (ref))
6656 return;
6658 low_sub = up_sub = TREE_OPERAND (ref, 1);
6659 up_bound = array_ref_up_bound (ref);
6661 /* Can not check flexible arrays. */
6662 if (!up_bound
6663 || TREE_CODE (up_bound) != INTEGER_CST)
6664 return;
6666 /* Accesses to trailing arrays via pointers may access storage
6667 beyond the types array bounds. */
6668 if (warn_array_bounds < 2
6669 && array_at_struct_end_p (ref))
6670 return;
6672 low_bound = array_ref_low_bound (ref);
6673 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
6674 build_int_cst (TREE_TYPE (up_bound), 1));
6676 /* Empty array. */
6677 if (tree_int_cst_equal (low_bound, up_bound_p1))
6679 warning_at (location, OPT_Warray_bounds,
6680 "array subscript is above array bounds");
6681 TREE_NO_WARNING (ref) = 1;
6684 if (TREE_CODE (low_sub) == SSA_NAME)
6686 vr = get_value_range (low_sub);
6687 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
6689 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
6690 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
6694 if (vr && vr->type == VR_ANTI_RANGE)
6696 if (TREE_CODE (up_sub) == INTEGER_CST
6697 && (ignore_off_by_one
6698 ? tree_int_cst_lt (up_bound, up_sub)
6699 : tree_int_cst_le (up_bound, up_sub))
6700 && TREE_CODE (low_sub) == INTEGER_CST
6701 && tree_int_cst_le (low_sub, low_bound))
6703 warning_at (location, OPT_Warray_bounds,
6704 "array subscript is outside array bounds");
6705 TREE_NO_WARNING (ref) = 1;
6708 else if (TREE_CODE (up_sub) == INTEGER_CST
6709 && (ignore_off_by_one
6710 ? !tree_int_cst_le (up_sub, up_bound_p1)
6711 : !tree_int_cst_le (up_sub, up_bound)))
6713 if (dump_file && (dump_flags & TDF_DETAILS))
6715 fprintf (dump_file, "Array bound warning for ");
6716 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6717 fprintf (dump_file, "\n");
6719 warning_at (location, OPT_Warray_bounds,
6720 "array subscript is above array bounds");
6721 TREE_NO_WARNING (ref) = 1;
6723 else if (TREE_CODE (low_sub) == INTEGER_CST
6724 && tree_int_cst_lt (low_sub, low_bound))
6726 if (dump_file && (dump_flags & TDF_DETAILS))
6728 fprintf (dump_file, "Array bound warning for ");
6729 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6730 fprintf (dump_file, "\n");
6732 warning_at (location, OPT_Warray_bounds,
6733 "array subscript is below array bounds");
6734 TREE_NO_WARNING (ref) = 1;
6738 /* Searches if the expr T, located at LOCATION computes
6739 address of an ARRAY_REF, and call check_array_ref on it. */
6741 void
6742 vrp_prop::search_for_addr_array (tree t, location_t location)
6744 /* Check each ARRAY_REFs in the reference chain. */
6747 if (TREE_CODE (t) == ARRAY_REF)
6748 check_array_ref (location, t, true /*ignore_off_by_one*/);
6750 t = TREE_OPERAND (t, 0);
6752 while (handled_component_p (t));
6754 if (TREE_CODE (t) == MEM_REF
6755 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
6756 && !TREE_NO_WARNING (t))
6758 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
6759 tree low_bound, up_bound, el_sz;
6760 offset_int idx;
6761 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
6762 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
6763 || !TYPE_DOMAIN (TREE_TYPE (tem)))
6764 return;
6766 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6767 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6768 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
6769 if (!low_bound
6770 || TREE_CODE (low_bound) != INTEGER_CST
6771 || !up_bound
6772 || TREE_CODE (up_bound) != INTEGER_CST
6773 || !el_sz
6774 || TREE_CODE (el_sz) != INTEGER_CST)
6775 return;
6777 idx = mem_ref_offset (t);
6778 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
6779 if (idx < 0)
6781 if (dump_file && (dump_flags & TDF_DETAILS))
6783 fprintf (dump_file, "Array bound warning for ");
6784 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6785 fprintf (dump_file, "\n");
6787 warning_at (location, OPT_Warray_bounds,
6788 "array subscript is below array bounds");
6789 TREE_NO_WARNING (t) = 1;
6791 else if (idx > (wi::to_offset (up_bound)
6792 - wi::to_offset (low_bound) + 1))
6794 if (dump_file && (dump_flags & TDF_DETAILS))
6796 fprintf (dump_file, "Array bound warning for ");
6797 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6798 fprintf (dump_file, "\n");
6800 warning_at (location, OPT_Warray_bounds,
6801 "array subscript is above array bounds");
6802 TREE_NO_WARNING (t) = 1;
6807 /* walk_tree() callback that checks if *TP is
6808 an ARRAY_REF inside an ADDR_EXPR (in which an array
6809 subscript one outside the valid range is allowed). Call
6810 check_array_ref for each ARRAY_REF found. The location is
6811 passed in DATA. */
6813 static tree
6814 check_array_bounds (tree *tp, int *walk_subtree, void *data)
6816 tree t = *tp;
6817 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
6818 location_t location;
6820 if (EXPR_HAS_LOCATION (t))
6821 location = EXPR_LOCATION (t);
6822 else
6823 location = gimple_location (wi->stmt);
6825 *walk_subtree = TRUE;
6827 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
6828 if (TREE_CODE (t) == ARRAY_REF)
6829 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
6831 else if (TREE_CODE (t) == ADDR_EXPR)
6833 vrp_prop->search_for_addr_array (t, location);
6834 *walk_subtree = FALSE;
6837 return NULL_TREE;
6840 /* Walk over all statements of all reachable BBs and call check_array_bounds
6841 on them. */
6843 void
6844 vrp_prop::check_all_array_refs ()
6846 basic_block bb;
6847 gimple_stmt_iterator si;
6849 FOR_EACH_BB_FN (bb, cfun)
6851 edge_iterator ei;
6852 edge e;
6853 bool executable = false;
6855 /* Skip blocks that were found to be unreachable. */
6856 FOR_EACH_EDGE (e, ei, bb->preds)
6857 executable |= !!(e->flags & EDGE_EXECUTABLE);
6858 if (!executable)
6859 continue;
6861 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
6863 gimple *stmt = gsi_stmt (si);
6864 struct walk_stmt_info wi;
6865 if (!gimple_has_location (stmt)
6866 || is_gimple_debug (stmt))
6867 continue;
6869 memset (&wi, 0, sizeof (wi));
6871 wi.info = this;
6873 walk_gimple_op (gsi_stmt (si),
6874 check_array_bounds,
6875 &wi);
6880 /* Return true if all imm uses of VAR are either in STMT, or
6881 feed (optionally through a chain of single imm uses) GIMPLE_COND
6882 in basic block COND_BB. */
6884 static bool
6885 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
6887 use_operand_p use_p, use2_p;
6888 imm_use_iterator iter;
6890 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
6891 if (USE_STMT (use_p) != stmt)
6893 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
6894 if (is_gimple_debug (use_stmt))
6895 continue;
6896 while (is_gimple_assign (use_stmt)
6897 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
6898 && single_imm_use (gimple_assign_lhs (use_stmt),
6899 &use2_p, &use_stmt2))
6900 use_stmt = use_stmt2;
6901 if (gimple_code (use_stmt) != GIMPLE_COND
6902 || gimple_bb (use_stmt) != cond_bb)
6903 return false;
6905 return true;
6908 /* Handle
6909 _4 = x_3 & 31;
6910 if (_4 != 0)
6911 goto <bb 6>;
6912 else
6913 goto <bb 7>;
6914 <bb 6>:
6915 __builtin_unreachable ();
6916 <bb 7>:
6917 x_5 = ASSERT_EXPR <x_3, ...>;
6918 If x_3 has no other immediate uses (checked by caller),
6919 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
6920 from the non-zero bitmask. */
6922 static void
6923 maybe_set_nonzero_bits (basic_block bb, tree var)
6925 edge e = single_pred_edge (bb);
6926 basic_block cond_bb = e->src;
6927 gimple *stmt = last_stmt (cond_bb);
6928 tree cst;
6930 if (stmt == NULL
6931 || gimple_code (stmt) != GIMPLE_COND
6932 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
6933 ? EQ_EXPR : NE_EXPR)
6934 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
6935 || !integer_zerop (gimple_cond_rhs (stmt)))
6936 return;
6938 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
6939 if (!is_gimple_assign (stmt)
6940 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
6941 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
6942 return;
6943 if (gimple_assign_rhs1 (stmt) != var)
6945 gimple *stmt2;
6947 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
6948 return;
6949 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
6950 if (!gimple_assign_cast_p (stmt2)
6951 || gimple_assign_rhs1 (stmt2) != var
6952 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
6953 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
6954 != TYPE_PRECISION (TREE_TYPE (var))))
6955 return;
6957 cst = gimple_assign_rhs2 (stmt);
6958 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
6959 wi::to_wide (cst)));
6962 /* Convert range assertion expressions into the implied copies and
6963 copy propagate away the copies. Doing the trivial copy propagation
6964 here avoids the need to run the full copy propagation pass after
6965 VRP.
6967 FIXME, this will eventually lead to copy propagation removing the
6968 names that had useful range information attached to them. For
6969 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
6970 then N_i will have the range [3, +INF].
6972 However, by converting the assertion into the implied copy
6973 operation N_i = N_j, we will then copy-propagate N_j into the uses
6974 of N_i and lose the range information. We may want to hold on to
6975 ASSERT_EXPRs a little while longer as the ranges could be used in
6976 things like jump threading.
6978 The problem with keeping ASSERT_EXPRs around is that passes after
6979 VRP need to handle them appropriately.
6981 Another approach would be to make the range information a first
6982 class property of the SSA_NAME so that it can be queried from
6983 any pass. This is made somewhat more complex by the need for
6984 multiple ranges to be associated with one SSA_NAME. */
6986 static void
6987 remove_range_assertions (void)
6989 basic_block bb;
6990 gimple_stmt_iterator si;
6991 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
6992 a basic block preceeded by GIMPLE_COND branching to it and
6993 __builtin_trap, -1 if not yet checked, 0 otherwise. */
6994 int is_unreachable;
6996 /* Note that the BSI iterator bump happens at the bottom of the
6997 loop and no bump is necessary if we're removing the statement
6998 referenced by the current BSI. */
6999 FOR_EACH_BB_FN (bb, cfun)
7000 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
7002 gimple *stmt = gsi_stmt (si);
7004 if (is_gimple_assign (stmt)
7005 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
7007 tree lhs = gimple_assign_lhs (stmt);
7008 tree rhs = gimple_assign_rhs1 (stmt);
7009 tree var;
7011 var = ASSERT_EXPR_VAR (rhs);
7013 if (TREE_CODE (var) == SSA_NAME
7014 && !POINTER_TYPE_P (TREE_TYPE (lhs))
7015 && SSA_NAME_RANGE_INFO (lhs))
7017 if (is_unreachable == -1)
7019 is_unreachable = 0;
7020 if (single_pred_p (bb)
7021 && assert_unreachable_fallthru_edge_p
7022 (single_pred_edge (bb)))
7023 is_unreachable = 1;
7025 /* Handle
7026 if (x_7 >= 10 && x_7 < 20)
7027 __builtin_unreachable ();
7028 x_8 = ASSERT_EXPR <x_7, ...>;
7029 if the only uses of x_7 are in the ASSERT_EXPR and
7030 in the condition. In that case, we can copy the
7031 range info from x_8 computed in this pass also
7032 for x_7. */
7033 if (is_unreachable
7034 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
7035 single_pred (bb)))
7037 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
7038 SSA_NAME_RANGE_INFO (lhs)->get_min (),
7039 SSA_NAME_RANGE_INFO (lhs)->get_max ());
7040 maybe_set_nonzero_bits (bb, var);
7044 /* Propagate the RHS into every use of the LHS. For SSA names
7045 also propagate abnormals as it merely restores the original
7046 IL in this case (an replace_uses_by would assert). */
7047 if (TREE_CODE (var) == SSA_NAME)
7049 imm_use_iterator iter;
7050 use_operand_p use_p;
7051 gimple *use_stmt;
7052 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
7053 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
7054 SET_USE (use_p, var);
7056 else
7057 replace_uses_by (lhs, var);
7059 /* And finally, remove the copy, it is not needed. */
7060 gsi_remove (&si, true);
7061 release_defs (stmt);
7063 else
7065 if (!is_gimple_debug (gsi_stmt (si)))
7066 is_unreachable = 0;
7067 gsi_next (&si);
7073 /* Return true if STMT is interesting for VRP. */
7075 static bool
7076 stmt_interesting_for_vrp (gimple *stmt)
7078 if (gimple_code (stmt) == GIMPLE_PHI)
7080 tree res = gimple_phi_result (stmt);
7081 return (!virtual_operand_p (res)
7082 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
7083 || POINTER_TYPE_P (TREE_TYPE (res))));
7085 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
7087 tree lhs = gimple_get_lhs (stmt);
7089 /* In general, assignments with virtual operands are not useful
7090 for deriving ranges, with the obvious exception of calls to
7091 builtin functions. */
7092 if (lhs && TREE_CODE (lhs) == SSA_NAME
7093 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7094 || POINTER_TYPE_P (TREE_TYPE (lhs)))
7095 && (is_gimple_call (stmt)
7096 || !gimple_vuse (stmt)))
7097 return true;
7098 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
7099 switch (gimple_call_internal_fn (stmt))
7101 case IFN_ADD_OVERFLOW:
7102 case IFN_SUB_OVERFLOW:
7103 case IFN_MUL_OVERFLOW:
7104 case IFN_ATOMIC_COMPARE_EXCHANGE:
7105 /* These internal calls return _Complex integer type,
7106 but are interesting to VRP nevertheless. */
7107 if (lhs && TREE_CODE (lhs) == SSA_NAME)
7108 return true;
7109 break;
7110 default:
7111 break;
7114 else if (gimple_code (stmt) == GIMPLE_COND
7115 || gimple_code (stmt) == GIMPLE_SWITCH)
7116 return true;
7118 return false;
7121 /* Initialize VRP lattice. */
7123 vr_values::vr_values () : vrp_value_range_pool ("Tree VRP value ranges")
7125 values_propagated = false;
7126 num_vr_values = num_ssa_names;
7127 vr_value = XCNEWVEC (value_range *, num_vr_values);
7128 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
7129 bitmap_obstack_initialize (&vrp_equiv_obstack);
7132 /* Initialization required by ssa_propagate engine. */
7134 void
7135 vrp_prop::vrp_initialize ()
7137 basic_block bb;
7139 FOR_EACH_BB_FN (bb, cfun)
7141 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
7142 gsi_next (&si))
7144 gphi *phi = si.phi ();
7145 if (!stmt_interesting_for_vrp (phi))
7147 tree lhs = PHI_RESULT (phi);
7148 set_value_range_to_varying (get_value_range (lhs));
7149 prop_set_simulate_again (phi, false);
7151 else
7152 prop_set_simulate_again (phi, true);
7155 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
7156 gsi_next (&si))
7158 gimple *stmt = gsi_stmt (si);
7160 /* If the statement is a control insn, then we do not
7161 want to avoid simulating the statement once. Failure
7162 to do so means that those edges will never get added. */
7163 if (stmt_ends_bb_p (stmt))
7164 prop_set_simulate_again (stmt, true);
7165 else if (!stmt_interesting_for_vrp (stmt))
7167 set_defs_to_varying (stmt);
7168 prop_set_simulate_again (stmt, false);
7170 else
7171 prop_set_simulate_again (stmt, true);
7176 /* A hack. */
7177 static class vr_values *x_vr_values;
7179 /* Return the singleton value-range for NAME or NAME. */
7181 static inline tree
7182 vrp_valueize (tree name)
7184 if (TREE_CODE (name) == SSA_NAME)
7186 value_range *vr = x_vr_values->get_value_range (name);
7187 if (vr->type == VR_RANGE
7188 && (TREE_CODE (vr->min) == SSA_NAME
7189 || is_gimple_min_invariant (vr->min))
7190 && vrp_operand_equal_p (vr->min, vr->max))
7191 return vr->min;
7193 return name;
7196 /* Return the singleton value-range for NAME if that is a constant
7197 but signal to not follow SSA edges. */
7199 static inline tree
7200 vrp_valueize_1 (tree name)
7202 if (TREE_CODE (name) == SSA_NAME)
7204 /* If the definition may be simulated again we cannot follow
7205 this SSA edge as the SSA propagator does not necessarily
7206 re-visit the use. */
7207 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
7208 if (!gimple_nop_p (def_stmt)
7209 && prop_simulate_again_p (def_stmt))
7210 return NULL_TREE;
7211 value_range *vr = x_vr_values->get_value_range (name);
7212 if (range_int_cst_singleton_p (vr))
7213 return vr->min;
7215 return name;
7218 /* Visit assignment STMT. If it produces an interesting range, record
7219 the range in VR and set LHS to OUTPUT_P. */
7221 void
7222 vr_values::vrp_visit_assignment_or_call (gimple *stmt, tree *output_p,
7223 value_range *vr)
7225 tree lhs;
7226 enum gimple_code code = gimple_code (stmt);
7227 lhs = gimple_get_lhs (stmt);
7228 *output_p = NULL_TREE;
7230 /* We only keep track of ranges in integral and pointer types. */
7231 if (TREE_CODE (lhs) == SSA_NAME
7232 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7233 /* It is valid to have NULL MIN/MAX values on a type. See
7234 build_range_type. */
7235 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
7236 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
7237 || POINTER_TYPE_P (TREE_TYPE (lhs))))
7239 *output_p = lhs;
7241 /* Try folding the statement to a constant first. */
7242 x_vr_values = this;
7243 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
7244 vrp_valueize_1);
7245 x_vr_values = NULL;
7246 if (tem)
7248 if (TREE_CODE (tem) == SSA_NAME
7249 && (SSA_NAME_IS_DEFAULT_DEF (tem)
7250 || ! prop_simulate_again_p (SSA_NAME_DEF_STMT (tem))))
7252 extract_range_from_ssa_name (vr, tem);
7253 return;
7255 else if (is_gimple_min_invariant (tem))
7257 set_value_range_to_value (vr, tem, NULL);
7258 return;
7261 /* Then dispatch to value-range extracting functions. */
7262 if (code == GIMPLE_CALL)
7263 extract_range_basic (vr, stmt);
7264 else
7265 extract_range_from_assignment (vr, as_a <gassign *> (stmt));
7269 /* Helper that gets the value range of the SSA_NAME with version I
7270 or a symbolic range containing the SSA_NAME only if the value range
7271 is varying or undefined. */
7273 value_range
7274 vr_values::get_vr_for_comparison (int i)
7276 value_range vr = *get_value_range (ssa_name (i));
7278 /* If name N_i does not have a valid range, use N_i as its own
7279 range. This allows us to compare against names that may
7280 have N_i in their ranges. */
7281 if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
7283 vr.type = VR_RANGE;
7284 vr.min = ssa_name (i);
7285 vr.max = ssa_name (i);
7288 return vr;
7291 /* Compare all the value ranges for names equivalent to VAR with VAL
7292 using comparison code COMP. Return the same value returned by
7293 compare_range_with_value, including the setting of
7294 *STRICT_OVERFLOW_P. */
7296 tree
7297 vr_values::compare_name_with_value (enum tree_code comp, tree var, tree val,
7298 bool *strict_overflow_p, bool use_equiv_p)
7300 bitmap_iterator bi;
7301 unsigned i;
7302 bitmap e;
7303 tree retval, t;
7304 int used_strict_overflow;
7305 bool sop;
7306 value_range equiv_vr;
7308 /* Get the set of equivalences for VAR. */
7309 e = get_value_range (var)->equiv;
7311 /* Start at -1. Set it to 0 if we do a comparison without relying
7312 on overflow, or 1 if all comparisons rely on overflow. */
7313 used_strict_overflow = -1;
7315 /* Compare vars' value range with val. */
7316 equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
7317 sop = false;
7318 retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
7319 if (retval)
7320 used_strict_overflow = sop ? 1 : 0;
7322 /* If the equiv set is empty we have done all work we need to do. */
7323 if (e == NULL)
7325 if (retval
7326 && used_strict_overflow > 0)
7327 *strict_overflow_p = true;
7328 return retval;
7331 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
7333 tree name = ssa_name (i);
7334 if (! name)
7335 continue;
7337 if (! use_equiv_p
7338 && ! SSA_NAME_IS_DEFAULT_DEF (name)
7339 && prop_simulate_again_p (SSA_NAME_DEF_STMT (name)))
7340 continue;
7342 equiv_vr = get_vr_for_comparison (i);
7343 sop = false;
7344 t = compare_range_with_value (comp, &equiv_vr, val, &sop);
7345 if (t)
7347 /* If we get different answers from different members
7348 of the equivalence set this check must be in a dead
7349 code region. Folding it to a trap representation
7350 would be correct here. For now just return don't-know. */
7351 if (retval != NULL
7352 && t != retval)
7354 retval = NULL_TREE;
7355 break;
7357 retval = t;
7359 if (!sop)
7360 used_strict_overflow = 0;
7361 else if (used_strict_overflow < 0)
7362 used_strict_overflow = 1;
7366 if (retval
7367 && used_strict_overflow > 0)
7368 *strict_overflow_p = true;
7370 return retval;
7374 /* Given a comparison code COMP and names N1 and N2, compare all the
7375 ranges equivalent to N1 against all the ranges equivalent to N2
7376 to determine the value of N1 COMP N2. Return the same value
7377 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
7378 whether we relied on undefined signed overflow in the comparison. */
7381 tree
7382 vr_values::compare_names (enum tree_code comp, tree n1, tree n2,
7383 bool *strict_overflow_p)
7385 tree t, retval;
7386 bitmap e1, e2;
7387 bitmap_iterator bi1, bi2;
7388 unsigned i1, i2;
7389 int used_strict_overflow;
7390 static bitmap_obstack *s_obstack = NULL;
7391 static bitmap s_e1 = NULL, s_e2 = NULL;
7393 /* Compare the ranges of every name equivalent to N1 against the
7394 ranges of every name equivalent to N2. */
7395 e1 = get_value_range (n1)->equiv;
7396 e2 = get_value_range (n2)->equiv;
7398 /* Use the fake bitmaps if e1 or e2 are not available. */
7399 if (s_obstack == NULL)
7401 s_obstack = XNEW (bitmap_obstack);
7402 bitmap_obstack_initialize (s_obstack);
7403 s_e1 = BITMAP_ALLOC (s_obstack);
7404 s_e2 = BITMAP_ALLOC (s_obstack);
7406 if (e1 == NULL)
7407 e1 = s_e1;
7408 if (e2 == NULL)
7409 e2 = s_e2;
7411 /* Add N1 and N2 to their own set of equivalences to avoid
7412 duplicating the body of the loop just to check N1 and N2
7413 ranges. */
7414 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
7415 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
7417 /* If the equivalence sets have a common intersection, then the two
7418 names can be compared without checking their ranges. */
7419 if (bitmap_intersect_p (e1, e2))
7421 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7422 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7424 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
7425 ? boolean_true_node
7426 : boolean_false_node;
7429 /* Start at -1. Set it to 0 if we do a comparison without relying
7430 on overflow, or 1 if all comparisons rely on overflow. */
7431 used_strict_overflow = -1;
7433 /* Otherwise, compare all the equivalent ranges. First, add N1 and
7434 N2 to their own set of equivalences to avoid duplicating the body
7435 of the loop just to check N1 and N2 ranges. */
7436 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
7438 if (! ssa_name (i1))
7439 continue;
7441 value_range vr1 = get_vr_for_comparison (i1);
7443 t = retval = NULL_TREE;
7444 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
7446 if (! ssa_name (i2))
7447 continue;
7449 bool sop = false;
7451 value_range vr2 = get_vr_for_comparison (i2);
7453 t = compare_ranges (comp, &vr1, &vr2, &sop);
7454 if (t)
7456 /* If we get different answers from different members
7457 of the equivalence set this check must be in a dead
7458 code region. Folding it to a trap representation
7459 would be correct here. For now just return don't-know. */
7460 if (retval != NULL
7461 && t != retval)
7463 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7464 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7465 return NULL_TREE;
7467 retval = t;
7469 if (!sop)
7470 used_strict_overflow = 0;
7471 else if (used_strict_overflow < 0)
7472 used_strict_overflow = 1;
7476 if (retval)
7478 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7479 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7480 if (used_strict_overflow > 0)
7481 *strict_overflow_p = true;
7482 return retval;
7486 /* None of the equivalent ranges are useful in computing this
7487 comparison. */
7488 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7489 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7490 return NULL_TREE;
7493 /* Helper function for vrp_evaluate_conditional_warnv & other
7494 optimizers. */
7496 tree
7497 vr_values::vrp_evaluate_conditional_warnv_with_ops_using_ranges
7498 (enum tree_code code, tree op0, tree op1, bool * strict_overflow_p)
7500 value_range *vr0, *vr1;
7502 vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
7503 vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
7505 tree res = NULL_TREE;
7506 if (vr0 && vr1)
7507 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
7508 if (!res && vr0)
7509 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
7510 if (!res && vr1)
7511 res = (compare_range_with_value
7512 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
7513 return res;
7516 /* Helper function for vrp_evaluate_conditional_warnv. */
7518 tree
7519 vr_values::vrp_evaluate_conditional_warnv_with_ops (enum tree_code code,
7520 tree op0, tree op1,
7521 bool use_equiv_p,
7522 bool *strict_overflow_p,
7523 bool *only_ranges)
7525 tree ret;
7526 if (only_ranges)
7527 *only_ranges = true;
7529 /* We only deal with integral and pointer types. */
7530 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
7531 && !POINTER_TYPE_P (TREE_TYPE (op0)))
7532 return NULL_TREE;
7534 /* If OP0 CODE OP1 is an overflow comparison, if it can be expressed
7535 as a simple equality test, then prefer that over its current form
7536 for evaluation.
7538 An overflow test which collapses to an equality test can always be
7539 expressed as a comparison of one argument against zero. Overflow
7540 occurs when the chosen argument is zero and does not occur if the
7541 chosen argument is not zero. */
7542 tree x;
7543 if (overflow_comparison_p (code, op0, op1, use_equiv_p, &x))
7545 wide_int max = wi::max_value (TYPE_PRECISION (TREE_TYPE (op0)), UNSIGNED);
7546 /* B = A - 1; if (A < B) -> B = A - 1; if (A == 0)
7547 B = A - 1; if (A > B) -> B = A - 1; if (A != 0)
7548 B = A + 1; if (B < A) -> B = A + 1; if (B == 0)
7549 B = A + 1; if (B > A) -> B = A + 1; if (B != 0) */
7550 if (integer_zerop (x))
7552 op1 = x;
7553 code = (code == LT_EXPR || code == LE_EXPR) ? EQ_EXPR : NE_EXPR;
7555 /* B = A + 1; if (A > B) -> B = A + 1; if (B == 0)
7556 B = A + 1; if (A < B) -> B = A + 1; if (B != 0)
7557 B = A - 1; if (B > A) -> B = A - 1; if (A == 0)
7558 B = A - 1; if (B < A) -> B = A - 1; if (A != 0) */
7559 else if (wi::to_wide (x) == max - 1)
7561 op0 = op1;
7562 op1 = wide_int_to_tree (TREE_TYPE (op0), 0);
7563 code = (code == GT_EXPR || code == GE_EXPR) ? EQ_EXPR : NE_EXPR;
7567 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
7568 (code, op0, op1, strict_overflow_p)))
7569 return ret;
7570 if (only_ranges)
7571 *only_ranges = false;
7572 /* Do not use compare_names during propagation, it's quadratic. */
7573 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
7574 && use_equiv_p)
7575 return compare_names (code, op0, op1, strict_overflow_p);
7576 else if (TREE_CODE (op0) == SSA_NAME)
7577 return compare_name_with_value (code, op0, op1,
7578 strict_overflow_p, use_equiv_p);
7579 else if (TREE_CODE (op1) == SSA_NAME)
7580 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
7581 strict_overflow_p, use_equiv_p);
7582 return NULL_TREE;
7585 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
7586 information. Return NULL if the conditional can not be evaluated.
7587 The ranges of all the names equivalent with the operands in COND
7588 will be used when trying to compute the value. If the result is
7589 based on undefined signed overflow, issue a warning if
7590 appropriate. */
7592 tree
7593 vr_values::vrp_evaluate_conditional (tree_code code, tree op0,
7594 tree op1, gimple *stmt)
7596 bool sop;
7597 tree ret;
7598 bool only_ranges;
7600 /* Some passes and foldings leak constants with overflow flag set
7601 into the IL. Avoid doing wrong things with these and bail out. */
7602 if ((TREE_CODE (op0) == INTEGER_CST
7603 && TREE_OVERFLOW (op0))
7604 || (TREE_CODE (op1) == INTEGER_CST
7605 && TREE_OVERFLOW (op1)))
7606 return NULL_TREE;
7608 sop = false;
7609 ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
7610 &only_ranges);
7612 if (ret && sop)
7614 enum warn_strict_overflow_code wc;
7615 const char* warnmsg;
7617 if (is_gimple_min_invariant (ret))
7619 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
7620 warnmsg = G_("assuming signed overflow does not occur when "
7621 "simplifying conditional to constant");
7623 else
7625 wc = WARN_STRICT_OVERFLOW_COMPARISON;
7626 warnmsg = G_("assuming signed overflow does not occur when "
7627 "simplifying conditional");
7630 if (issue_strict_overflow_warning (wc))
7632 location_t location;
7634 if (!gimple_has_location (stmt))
7635 location = input_location;
7636 else
7637 location = gimple_location (stmt);
7638 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
7642 if (warn_type_limits
7643 && ret && only_ranges
7644 && TREE_CODE_CLASS (code) == tcc_comparison
7645 && TREE_CODE (op0) == SSA_NAME)
7647 /* If the comparison is being folded and the operand on the LHS
7648 is being compared against a constant value that is outside of
7649 the natural range of OP0's type, then the predicate will
7650 always fold regardless of the value of OP0. If -Wtype-limits
7651 was specified, emit a warning. */
7652 tree type = TREE_TYPE (op0);
7653 value_range *vr0 = get_value_range (op0);
7655 if (vr0->type == VR_RANGE
7656 && INTEGRAL_TYPE_P (type)
7657 && vrp_val_is_min (vr0->min)
7658 && vrp_val_is_max (vr0->max)
7659 && is_gimple_min_invariant (op1))
7661 location_t location;
7663 if (!gimple_has_location (stmt))
7664 location = input_location;
7665 else
7666 location = gimple_location (stmt);
7668 warning_at (location, OPT_Wtype_limits,
7669 integer_zerop (ret)
7670 ? G_("comparison always false "
7671 "due to limited range of data type")
7672 : G_("comparison always true "
7673 "due to limited range of data type"));
7677 return ret;
7681 /* Visit conditional statement STMT. If we can determine which edge
7682 will be taken out of STMT's basic block, record it in
7683 *TAKEN_EDGE_P. Otherwise, set *TAKEN_EDGE_P to NULL. */
7685 void
7686 vr_values::vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
7688 tree val;
7690 *taken_edge_p = NULL;
7692 if (dump_file && (dump_flags & TDF_DETAILS))
7694 tree use;
7695 ssa_op_iter i;
7697 fprintf (dump_file, "\nVisiting conditional with predicate: ");
7698 print_gimple_stmt (dump_file, stmt, 0);
7699 fprintf (dump_file, "\nWith known ranges\n");
7701 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
7703 fprintf (dump_file, "\t");
7704 print_generic_expr (dump_file, use);
7705 fprintf (dump_file, ": ");
7706 dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
7709 fprintf (dump_file, "\n");
7712 /* Compute the value of the predicate COND by checking the known
7713 ranges of each of its operands.
7715 Note that we cannot evaluate all the equivalent ranges here
7716 because those ranges may not yet be final and with the current
7717 propagation strategy, we cannot determine when the value ranges
7718 of the names in the equivalence set have changed.
7720 For instance, given the following code fragment
7722 i_5 = PHI <8, i_13>
7724 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
7725 if (i_14 == 1)
7728 Assume that on the first visit to i_14, i_5 has the temporary
7729 range [8, 8] because the second argument to the PHI function is
7730 not yet executable. We derive the range ~[0, 0] for i_14 and the
7731 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
7732 the first time, since i_14 is equivalent to the range [8, 8], we
7733 determine that the predicate is always false.
7735 On the next round of propagation, i_13 is determined to be
7736 VARYING, which causes i_5 to drop down to VARYING. So, another
7737 visit to i_14 is scheduled. In this second visit, we compute the
7738 exact same range and equivalence set for i_14, namely ~[0, 0] and
7739 { i_5 }. But we did not have the previous range for i_5
7740 registered, so vrp_visit_assignment thinks that the range for
7741 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
7742 is not visited again, which stops propagation from visiting
7743 statements in the THEN clause of that if().
7745 To properly fix this we would need to keep the previous range
7746 value for the names in the equivalence set. This way we would've
7747 discovered that from one visit to the other i_5 changed from
7748 range [8, 8] to VR_VARYING.
7750 However, fixing this apparent limitation may not be worth the
7751 additional checking. Testing on several code bases (GCC, DLV,
7752 MICO, TRAMP3D and SPEC2000) showed that doing this results in
7753 4 more predicates folded in SPEC. */
7755 bool sop;
7756 val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
7757 gimple_cond_lhs (stmt),
7758 gimple_cond_rhs (stmt),
7759 false, &sop, NULL);
7760 if (val)
7761 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
7763 if (dump_file && (dump_flags & TDF_DETAILS))
7765 fprintf (dump_file, "\nPredicate evaluates to: ");
7766 if (val == NULL_TREE)
7767 fprintf (dump_file, "DON'T KNOW\n");
7768 else
7769 print_generic_stmt (dump_file, val);
7773 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
7774 that includes the value VAL. The search is restricted to the range
7775 [START_IDX, n - 1] where n is the size of VEC.
7777 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
7778 returned.
7780 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
7781 it is placed in IDX and false is returned.
7783 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
7784 returned. */
7786 static bool
7787 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
7789 size_t n = gimple_switch_num_labels (stmt);
7790 size_t low, high;
7792 /* Find case label for minimum of the value range or the next one.
7793 At each iteration we are searching in [low, high - 1]. */
7795 for (low = start_idx, high = n; high != low; )
7797 tree t;
7798 int cmp;
7799 /* Note that i != high, so we never ask for n. */
7800 size_t i = (high + low) / 2;
7801 t = gimple_switch_label (stmt, i);
7803 /* Cache the result of comparing CASE_LOW and val. */
7804 cmp = tree_int_cst_compare (CASE_LOW (t), val);
7806 if (cmp == 0)
7808 /* Ranges cannot be empty. */
7809 *idx = i;
7810 return true;
7812 else if (cmp > 0)
7813 high = i;
7814 else
7816 low = i + 1;
7817 if (CASE_HIGH (t) != NULL
7818 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
7820 *idx = i;
7821 return true;
7826 *idx = high;
7827 return false;
7830 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
7831 for values between MIN and MAX. The first index is placed in MIN_IDX. The
7832 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
7833 then MAX_IDX < MIN_IDX.
7834 Returns true if the default label is not needed. */
7836 static bool
7837 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
7838 size_t *max_idx)
7840 size_t i, j;
7841 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
7842 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
7844 if (i == j
7845 && min_take_default
7846 && max_take_default)
7848 /* Only the default case label reached.
7849 Return an empty range. */
7850 *min_idx = 1;
7851 *max_idx = 0;
7852 return false;
7854 else
7856 bool take_default = min_take_default || max_take_default;
7857 tree low, high;
7858 size_t k;
7860 if (max_take_default)
7861 j--;
7863 /* If the case label range is continuous, we do not need
7864 the default case label. Verify that. */
7865 high = CASE_LOW (gimple_switch_label (stmt, i));
7866 if (CASE_HIGH (gimple_switch_label (stmt, i)))
7867 high = CASE_HIGH (gimple_switch_label (stmt, i));
7868 for (k = i + 1; k <= j; ++k)
7870 low = CASE_LOW (gimple_switch_label (stmt, k));
7871 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
7873 take_default = true;
7874 break;
7876 high = low;
7877 if (CASE_HIGH (gimple_switch_label (stmt, k)))
7878 high = CASE_HIGH (gimple_switch_label (stmt, k));
7881 *min_idx = i;
7882 *max_idx = j;
7883 return !take_default;
7887 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
7888 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
7889 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
7890 Returns true if the default label is not needed. */
7892 static bool
7893 find_case_label_ranges (gswitch *stmt, value_range *vr, size_t *min_idx1,
7894 size_t *max_idx1, size_t *min_idx2,
7895 size_t *max_idx2)
7897 size_t i, j, k, l;
7898 unsigned int n = gimple_switch_num_labels (stmt);
7899 bool take_default;
7900 tree case_low, case_high;
7901 tree min = vr->min, max = vr->max;
7903 gcc_checking_assert (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE);
7905 take_default = !find_case_label_range (stmt, min, max, &i, &j);
7907 /* Set second range to emtpy. */
7908 *min_idx2 = 1;
7909 *max_idx2 = 0;
7911 if (vr->type == VR_RANGE)
7913 *min_idx1 = i;
7914 *max_idx1 = j;
7915 return !take_default;
7918 /* Set first range to all case labels. */
7919 *min_idx1 = 1;
7920 *max_idx1 = n - 1;
7922 if (i > j)
7923 return false;
7925 /* Make sure all the values of case labels [i , j] are contained in
7926 range [MIN, MAX]. */
7927 case_low = CASE_LOW (gimple_switch_label (stmt, i));
7928 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
7929 if (tree_int_cst_compare (case_low, min) < 0)
7930 i += 1;
7931 if (case_high != NULL_TREE
7932 && tree_int_cst_compare (max, case_high) < 0)
7933 j -= 1;
7935 if (i > j)
7936 return false;
7938 /* If the range spans case labels [i, j], the corresponding anti-range spans
7939 the labels [1, i - 1] and [j + 1, n - 1]. */
7940 k = j + 1;
7941 l = n - 1;
7942 if (k > l)
7944 k = 1;
7945 l = 0;
7948 j = i - 1;
7949 i = 1;
7950 if (i > j)
7952 i = k;
7953 j = l;
7954 k = 1;
7955 l = 0;
7958 *min_idx1 = i;
7959 *max_idx1 = j;
7960 *min_idx2 = k;
7961 *max_idx2 = l;
7962 return false;
7965 /* Visit switch statement STMT. If we can determine which edge
7966 will be taken out of STMT's basic block, record it in
7967 *TAKEN_EDGE_P. Otherwise, *TAKEN_EDGE_P set to NULL. */
7969 void
7970 vr_values::vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
7972 tree op, val;
7973 value_range *vr;
7974 size_t i = 0, j = 0, k, l;
7975 bool take_default;
7977 *taken_edge_p = NULL;
7978 op = gimple_switch_index (stmt);
7979 if (TREE_CODE (op) != SSA_NAME)
7980 return;
7982 vr = get_value_range (op);
7983 if (dump_file && (dump_flags & TDF_DETAILS))
7985 fprintf (dump_file, "\nVisiting switch expression with operand ");
7986 print_generic_expr (dump_file, op);
7987 fprintf (dump_file, " with known range ");
7988 dump_value_range (dump_file, vr);
7989 fprintf (dump_file, "\n");
7992 if ((vr->type != VR_RANGE
7993 && vr->type != VR_ANTI_RANGE)
7994 || symbolic_range_p (vr))
7995 return;
7997 /* Find the single edge that is taken from the switch expression. */
7998 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
8000 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
8001 label */
8002 if (j < i)
8004 gcc_assert (take_default);
8005 val = gimple_switch_default_label (stmt);
8007 else
8009 /* Check if labels with index i to j and maybe the default label
8010 are all reaching the same label. */
8012 val = gimple_switch_label (stmt, i);
8013 if (take_default
8014 && CASE_LABEL (gimple_switch_default_label (stmt))
8015 != 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;
8022 for (++i; i <= j; ++i)
8024 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
8026 if (dump_file && (dump_flags & TDF_DETAILS))
8027 fprintf (dump_file, " not a single destination for this "
8028 "range\n");
8029 return;
8032 for (; k <= l; ++k)
8034 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
8036 if (dump_file && (dump_flags & TDF_DETAILS))
8037 fprintf (dump_file, " not a single destination for this "
8038 "range\n");
8039 return;
8044 *taken_edge_p = find_edge (gimple_bb (stmt),
8045 label_to_block (CASE_LABEL (val)));
8047 if (dump_file && (dump_flags & TDF_DETAILS))
8049 fprintf (dump_file, " will take edge to ");
8050 print_generic_stmt (dump_file, CASE_LABEL (val));
8055 /* Evaluate statement STMT. If the statement produces a useful range,
8056 set VR and corepsponding OUTPUT_P.
8058 If STMT is a conditional branch and we can determine its truth
8059 value, the taken edge is recorded in *TAKEN_EDGE_P. */
8061 void
8062 vr_values::extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
8063 tree *output_p, value_range *vr)
8066 if (dump_file && (dump_flags & TDF_DETAILS))
8068 fprintf (dump_file, "\nVisiting statement:\n");
8069 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
8072 if (!stmt_interesting_for_vrp (stmt))
8073 gcc_assert (stmt_ends_bb_p (stmt));
8074 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
8075 vrp_visit_assignment_or_call (stmt, output_p, vr);
8076 else if (gimple_code (stmt) == GIMPLE_COND)
8077 vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
8078 else if (gimple_code (stmt) == GIMPLE_SWITCH)
8079 vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
8082 /* Evaluate statement STMT. If the statement produces a useful range,
8083 return SSA_PROP_INTERESTING and record the SSA name with the
8084 interesting range into *OUTPUT_P.
8086 If STMT is a conditional branch and we can determine its truth
8087 value, the taken edge is recorded in *TAKEN_EDGE_P.
8089 If STMT produces a varying value, return SSA_PROP_VARYING. */
8091 enum ssa_prop_result
8092 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
8094 value_range vr = VR_INITIALIZER;
8095 tree lhs = gimple_get_lhs (stmt);
8096 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
8098 if (*output_p)
8100 if (update_value_range (*output_p, &vr))
8102 if (dump_file && (dump_flags & TDF_DETAILS))
8104 fprintf (dump_file, "Found new range for ");
8105 print_generic_expr (dump_file, *output_p);
8106 fprintf (dump_file, ": ");
8107 dump_value_range (dump_file, &vr);
8108 fprintf (dump_file, "\n");
8111 if (vr.type == VR_VARYING)
8112 return SSA_PROP_VARYING;
8114 return SSA_PROP_INTERESTING;
8116 return SSA_PROP_NOT_INTERESTING;
8119 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
8120 switch (gimple_call_internal_fn (stmt))
8122 case IFN_ADD_OVERFLOW:
8123 case IFN_SUB_OVERFLOW:
8124 case IFN_MUL_OVERFLOW:
8125 case IFN_ATOMIC_COMPARE_EXCHANGE:
8126 /* These internal calls return _Complex integer type,
8127 which VRP does not track, but the immediate uses
8128 thereof might be interesting. */
8129 if (lhs && TREE_CODE (lhs) == SSA_NAME)
8131 imm_use_iterator iter;
8132 use_operand_p use_p;
8133 enum ssa_prop_result res = SSA_PROP_VARYING;
8135 set_value_range_to_varying (get_value_range (lhs));
8137 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
8139 gimple *use_stmt = USE_STMT (use_p);
8140 if (!is_gimple_assign (use_stmt))
8141 continue;
8142 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
8143 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
8144 continue;
8145 tree rhs1 = gimple_assign_rhs1 (use_stmt);
8146 tree use_lhs = gimple_assign_lhs (use_stmt);
8147 if (TREE_CODE (rhs1) != rhs_code
8148 || TREE_OPERAND (rhs1, 0) != lhs
8149 || TREE_CODE (use_lhs) != SSA_NAME
8150 || !stmt_interesting_for_vrp (use_stmt)
8151 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
8152 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
8153 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
8154 continue;
8156 /* If there is a change in the value range for any of the
8157 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
8158 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
8159 or IMAGPART_EXPR immediate uses, but none of them have
8160 a change in their value ranges, return
8161 SSA_PROP_NOT_INTERESTING. If there are no
8162 {REAL,IMAG}PART_EXPR uses at all,
8163 return SSA_PROP_VARYING. */
8164 value_range new_vr = VR_INITIALIZER;
8165 extract_range_basic (&new_vr, use_stmt);
8166 value_range *old_vr = get_value_range (use_lhs);
8167 if (old_vr->type != new_vr.type
8168 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
8169 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
8170 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
8171 res = SSA_PROP_INTERESTING;
8172 else
8173 res = SSA_PROP_NOT_INTERESTING;
8174 BITMAP_FREE (new_vr.equiv);
8175 if (res == SSA_PROP_INTERESTING)
8177 *output_p = lhs;
8178 return res;
8182 return res;
8184 break;
8185 default:
8186 break;
8189 /* All other statements produce nothing of interest for VRP, so mark
8190 their outputs varying and prevent further simulation. */
8191 set_defs_to_varying (stmt);
8193 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
8196 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8197 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8198 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8199 possible such range. The resulting range is not canonicalized. */
8201 static void
8202 union_ranges (enum value_range_type *vr0type,
8203 tree *vr0min, tree *vr0max,
8204 enum value_range_type vr1type,
8205 tree vr1min, tree vr1max)
8207 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8208 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8210 /* [] is vr0, () is vr1 in the following classification comments. */
8211 if (mineq && maxeq)
8213 /* [( )] */
8214 if (*vr0type == vr1type)
8215 /* Nothing to do for equal ranges. */
8217 else if ((*vr0type == VR_RANGE
8218 && vr1type == VR_ANTI_RANGE)
8219 || (*vr0type == VR_ANTI_RANGE
8220 && vr1type == VR_RANGE))
8222 /* For anti-range with range union the result is varying. */
8223 goto give_up;
8225 else
8226 gcc_unreachable ();
8228 else if (operand_less_p (*vr0max, vr1min) == 1
8229 || operand_less_p (vr1max, *vr0min) == 1)
8231 /* [ ] ( ) or ( ) [ ]
8232 If the ranges have an empty intersection, result of the union
8233 operation is the anti-range or if both are anti-ranges
8234 it covers all. */
8235 if (*vr0type == VR_ANTI_RANGE
8236 && vr1type == VR_ANTI_RANGE)
8237 goto give_up;
8238 else if (*vr0type == VR_ANTI_RANGE
8239 && vr1type == VR_RANGE)
8241 else if (*vr0type == VR_RANGE
8242 && vr1type == VR_ANTI_RANGE)
8244 *vr0type = vr1type;
8245 *vr0min = vr1min;
8246 *vr0max = vr1max;
8248 else if (*vr0type == VR_RANGE
8249 && vr1type == VR_RANGE)
8251 /* The result is the convex hull of both ranges. */
8252 if (operand_less_p (*vr0max, vr1min) == 1)
8254 /* If the result can be an anti-range, create one. */
8255 if (TREE_CODE (*vr0max) == INTEGER_CST
8256 && TREE_CODE (vr1min) == INTEGER_CST
8257 && vrp_val_is_min (*vr0min)
8258 && vrp_val_is_max (vr1max))
8260 tree min = int_const_binop (PLUS_EXPR,
8261 *vr0max,
8262 build_int_cst (TREE_TYPE (*vr0max), 1));
8263 tree max = int_const_binop (MINUS_EXPR,
8264 vr1min,
8265 build_int_cst (TREE_TYPE (vr1min), 1));
8266 if (!operand_less_p (max, min))
8268 *vr0type = VR_ANTI_RANGE;
8269 *vr0min = min;
8270 *vr0max = max;
8272 else
8273 *vr0max = vr1max;
8275 else
8276 *vr0max = vr1max;
8278 else
8280 /* If the result can be an anti-range, create one. */
8281 if (TREE_CODE (vr1max) == INTEGER_CST
8282 && TREE_CODE (*vr0min) == INTEGER_CST
8283 && vrp_val_is_min (vr1min)
8284 && vrp_val_is_max (*vr0max))
8286 tree min = int_const_binop (PLUS_EXPR,
8287 vr1max,
8288 build_int_cst (TREE_TYPE (vr1max), 1));
8289 tree max = int_const_binop (MINUS_EXPR,
8290 *vr0min,
8291 build_int_cst (TREE_TYPE (*vr0min), 1));
8292 if (!operand_less_p (max, min))
8294 *vr0type = VR_ANTI_RANGE;
8295 *vr0min = min;
8296 *vr0max = max;
8298 else
8299 *vr0min = vr1min;
8301 else
8302 *vr0min = vr1min;
8305 else
8306 gcc_unreachable ();
8308 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8309 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8311 /* [ ( ) ] or [( ) ] or [ ( )] */
8312 if (*vr0type == VR_RANGE
8313 && vr1type == VR_RANGE)
8315 else if (*vr0type == VR_ANTI_RANGE
8316 && vr1type == VR_ANTI_RANGE)
8318 *vr0type = vr1type;
8319 *vr0min = vr1min;
8320 *vr0max = vr1max;
8322 else if (*vr0type == VR_ANTI_RANGE
8323 && vr1type == VR_RANGE)
8325 /* Arbitrarily choose the right or left gap. */
8326 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
8327 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8328 build_int_cst (TREE_TYPE (vr1min), 1));
8329 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
8330 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8331 build_int_cst (TREE_TYPE (vr1max), 1));
8332 else
8333 goto give_up;
8335 else if (*vr0type == VR_RANGE
8336 && vr1type == VR_ANTI_RANGE)
8337 /* The result covers everything. */
8338 goto give_up;
8339 else
8340 gcc_unreachable ();
8342 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8343 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8345 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8346 if (*vr0type == VR_RANGE
8347 && vr1type == VR_RANGE)
8349 *vr0type = vr1type;
8350 *vr0min = vr1min;
8351 *vr0max = vr1max;
8353 else if (*vr0type == VR_ANTI_RANGE
8354 && vr1type == VR_ANTI_RANGE)
8356 else if (*vr0type == VR_RANGE
8357 && vr1type == VR_ANTI_RANGE)
8359 *vr0type = VR_ANTI_RANGE;
8360 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
8362 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8363 build_int_cst (TREE_TYPE (*vr0min), 1));
8364 *vr0min = vr1min;
8366 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
8368 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8369 build_int_cst (TREE_TYPE (*vr0max), 1));
8370 *vr0max = vr1max;
8372 else
8373 goto give_up;
8375 else if (*vr0type == VR_ANTI_RANGE
8376 && vr1type == VR_RANGE)
8377 /* The result covers everything. */
8378 goto give_up;
8379 else
8380 gcc_unreachable ();
8382 else if ((operand_less_p (vr1min, *vr0max) == 1
8383 || operand_equal_p (vr1min, *vr0max, 0))
8384 && operand_less_p (*vr0min, vr1min) == 1
8385 && operand_less_p (*vr0max, vr1max) == 1)
8387 /* [ ( ] ) or [ ]( ) */
8388 if (*vr0type == VR_RANGE
8389 && vr1type == VR_RANGE)
8390 *vr0max = vr1max;
8391 else if (*vr0type == VR_ANTI_RANGE
8392 && vr1type == VR_ANTI_RANGE)
8393 *vr0min = vr1min;
8394 else if (*vr0type == VR_ANTI_RANGE
8395 && vr1type == VR_RANGE)
8397 if (TREE_CODE (vr1min) == INTEGER_CST)
8398 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8399 build_int_cst (TREE_TYPE (vr1min), 1));
8400 else
8401 goto give_up;
8403 else if (*vr0type == VR_RANGE
8404 && vr1type == VR_ANTI_RANGE)
8406 if (TREE_CODE (*vr0max) == INTEGER_CST)
8408 *vr0type = vr1type;
8409 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8410 build_int_cst (TREE_TYPE (*vr0max), 1));
8411 *vr0max = vr1max;
8413 else
8414 goto give_up;
8416 else
8417 gcc_unreachable ();
8419 else if ((operand_less_p (*vr0min, vr1max) == 1
8420 || operand_equal_p (*vr0min, vr1max, 0))
8421 && operand_less_p (vr1min, *vr0min) == 1
8422 && operand_less_p (vr1max, *vr0max) == 1)
8424 /* ( [ ) ] or ( )[ ] */
8425 if (*vr0type == VR_RANGE
8426 && vr1type == VR_RANGE)
8427 *vr0min = vr1min;
8428 else if (*vr0type == VR_ANTI_RANGE
8429 && vr1type == VR_ANTI_RANGE)
8430 *vr0max = vr1max;
8431 else if (*vr0type == VR_ANTI_RANGE
8432 && vr1type == VR_RANGE)
8434 if (TREE_CODE (vr1max) == INTEGER_CST)
8435 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8436 build_int_cst (TREE_TYPE (vr1max), 1));
8437 else
8438 goto give_up;
8440 else if (*vr0type == VR_RANGE
8441 && vr1type == VR_ANTI_RANGE)
8443 if (TREE_CODE (*vr0min) == INTEGER_CST)
8445 *vr0type = vr1type;
8446 *vr0min = vr1min;
8447 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8448 build_int_cst (TREE_TYPE (*vr0min), 1));
8450 else
8451 goto give_up;
8453 else
8454 gcc_unreachable ();
8456 else
8457 goto give_up;
8459 return;
8461 give_up:
8462 *vr0type = VR_VARYING;
8463 *vr0min = NULL_TREE;
8464 *vr0max = NULL_TREE;
8467 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8468 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8469 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8470 possible such range. The resulting range is not canonicalized. */
8472 static void
8473 intersect_ranges (enum value_range_type *vr0type,
8474 tree *vr0min, tree *vr0max,
8475 enum value_range_type vr1type,
8476 tree vr1min, tree vr1max)
8478 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8479 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8481 /* [] is vr0, () is vr1 in the following classification comments. */
8482 if (mineq && maxeq)
8484 /* [( )] */
8485 if (*vr0type == vr1type)
8486 /* Nothing to do for equal ranges. */
8488 else if ((*vr0type == VR_RANGE
8489 && vr1type == VR_ANTI_RANGE)
8490 || (*vr0type == VR_ANTI_RANGE
8491 && vr1type == VR_RANGE))
8493 /* For anti-range with range intersection the result is empty. */
8494 *vr0type = VR_UNDEFINED;
8495 *vr0min = NULL_TREE;
8496 *vr0max = NULL_TREE;
8498 else
8499 gcc_unreachable ();
8501 else if (operand_less_p (*vr0max, vr1min) == 1
8502 || operand_less_p (vr1max, *vr0min) == 1)
8504 /* [ ] ( ) or ( ) [ ]
8505 If the ranges have an empty intersection, the result of the
8506 intersect operation is the range for intersecting an
8507 anti-range with a range or empty when intersecting two ranges. */
8508 if (*vr0type == VR_RANGE
8509 && vr1type == VR_ANTI_RANGE)
8511 else if (*vr0type == VR_ANTI_RANGE
8512 && vr1type == VR_RANGE)
8514 *vr0type = vr1type;
8515 *vr0min = vr1min;
8516 *vr0max = vr1max;
8518 else if (*vr0type == VR_RANGE
8519 && vr1type == VR_RANGE)
8521 *vr0type = VR_UNDEFINED;
8522 *vr0min = NULL_TREE;
8523 *vr0max = NULL_TREE;
8525 else if (*vr0type == VR_ANTI_RANGE
8526 && vr1type == VR_ANTI_RANGE)
8528 /* If the anti-ranges are adjacent to each other merge them. */
8529 if (TREE_CODE (*vr0max) == INTEGER_CST
8530 && TREE_CODE (vr1min) == INTEGER_CST
8531 && operand_less_p (*vr0max, vr1min) == 1
8532 && integer_onep (int_const_binop (MINUS_EXPR,
8533 vr1min, *vr0max)))
8534 *vr0max = vr1max;
8535 else if (TREE_CODE (vr1max) == INTEGER_CST
8536 && TREE_CODE (*vr0min) == INTEGER_CST
8537 && operand_less_p (vr1max, *vr0min) == 1
8538 && integer_onep (int_const_binop (MINUS_EXPR,
8539 *vr0min, vr1max)))
8540 *vr0min = vr1min;
8541 /* Else arbitrarily take VR0. */
8544 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8545 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8547 /* [ ( ) ] or [( ) ] or [ ( )] */
8548 if (*vr0type == VR_RANGE
8549 && vr1type == VR_RANGE)
8551 /* If both are ranges the result is the inner one. */
8552 *vr0type = vr1type;
8553 *vr0min = vr1min;
8554 *vr0max = vr1max;
8556 else if (*vr0type == VR_RANGE
8557 && vr1type == VR_ANTI_RANGE)
8559 /* Choose the right gap if the left one is empty. */
8560 if (mineq)
8562 if (TREE_CODE (vr1max) != INTEGER_CST)
8563 *vr0min = vr1max;
8564 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
8565 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
8566 *vr0min
8567 = int_const_binop (MINUS_EXPR, vr1max,
8568 build_int_cst (TREE_TYPE (vr1max), -1));
8569 else
8570 *vr0min
8571 = int_const_binop (PLUS_EXPR, vr1max,
8572 build_int_cst (TREE_TYPE (vr1max), 1));
8574 /* Choose the left gap if the right one is empty. */
8575 else if (maxeq)
8577 if (TREE_CODE (vr1min) != INTEGER_CST)
8578 *vr0max = vr1min;
8579 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
8580 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
8581 *vr0max
8582 = int_const_binop (PLUS_EXPR, vr1min,
8583 build_int_cst (TREE_TYPE (vr1min), -1));
8584 else
8585 *vr0max
8586 = int_const_binop (MINUS_EXPR, vr1min,
8587 build_int_cst (TREE_TYPE (vr1min), 1));
8589 /* Choose the anti-range if the range is effectively varying. */
8590 else if (vrp_val_is_min (*vr0min)
8591 && vrp_val_is_max (*vr0max))
8593 *vr0type = vr1type;
8594 *vr0min = vr1min;
8595 *vr0max = vr1max;
8597 /* Else choose the range. */
8599 else if (*vr0type == VR_ANTI_RANGE
8600 && vr1type == VR_ANTI_RANGE)
8601 /* If both are anti-ranges the result is the outer one. */
8603 else if (*vr0type == VR_ANTI_RANGE
8604 && vr1type == VR_RANGE)
8606 /* The intersection is empty. */
8607 *vr0type = VR_UNDEFINED;
8608 *vr0min = NULL_TREE;
8609 *vr0max = NULL_TREE;
8611 else
8612 gcc_unreachable ();
8614 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8615 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8617 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8618 if (*vr0type == VR_RANGE
8619 && vr1type == VR_RANGE)
8620 /* Choose the inner range. */
8622 else if (*vr0type == VR_ANTI_RANGE
8623 && vr1type == VR_RANGE)
8625 /* Choose the right gap if the left is empty. */
8626 if (mineq)
8628 *vr0type = VR_RANGE;
8629 if (TREE_CODE (*vr0max) != INTEGER_CST)
8630 *vr0min = *vr0max;
8631 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
8632 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
8633 *vr0min
8634 = int_const_binop (MINUS_EXPR, *vr0max,
8635 build_int_cst (TREE_TYPE (*vr0max), -1));
8636 else
8637 *vr0min
8638 = int_const_binop (PLUS_EXPR, *vr0max,
8639 build_int_cst (TREE_TYPE (*vr0max), 1));
8640 *vr0max = vr1max;
8642 /* Choose the left gap if the right is empty. */
8643 else if (maxeq)
8645 *vr0type = VR_RANGE;
8646 if (TREE_CODE (*vr0min) != INTEGER_CST)
8647 *vr0max = *vr0min;
8648 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
8649 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
8650 *vr0max
8651 = int_const_binop (PLUS_EXPR, *vr0min,
8652 build_int_cst (TREE_TYPE (*vr0min), -1));
8653 else
8654 *vr0max
8655 = int_const_binop (MINUS_EXPR, *vr0min,
8656 build_int_cst (TREE_TYPE (*vr0min), 1));
8657 *vr0min = vr1min;
8659 /* Choose the anti-range if the range is effectively varying. */
8660 else if (vrp_val_is_min (vr1min)
8661 && vrp_val_is_max (vr1max))
8663 /* Choose the anti-range if it is ~[0,0], that range is special
8664 enough to special case when vr1's range is relatively wide. */
8665 else if (*vr0min == *vr0max
8666 && integer_zerop (*vr0min)
8667 && (TYPE_PRECISION (TREE_TYPE (*vr0min))
8668 == TYPE_PRECISION (ptr_type_node))
8669 && TREE_CODE (vr1max) == INTEGER_CST
8670 && TREE_CODE (vr1min) == INTEGER_CST
8671 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
8672 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
8674 /* Else choose the range. */
8675 else
8677 *vr0type = vr1type;
8678 *vr0min = vr1min;
8679 *vr0max = vr1max;
8682 else if (*vr0type == VR_ANTI_RANGE
8683 && vr1type == VR_ANTI_RANGE)
8685 /* If both are anti-ranges the result is the outer one. */
8686 *vr0type = vr1type;
8687 *vr0min = vr1min;
8688 *vr0max = vr1max;
8690 else if (vr1type == VR_ANTI_RANGE
8691 && *vr0type == VR_RANGE)
8693 /* The intersection is empty. */
8694 *vr0type = VR_UNDEFINED;
8695 *vr0min = NULL_TREE;
8696 *vr0max = NULL_TREE;
8698 else
8699 gcc_unreachable ();
8701 else if ((operand_less_p (vr1min, *vr0max) == 1
8702 || operand_equal_p (vr1min, *vr0max, 0))
8703 && operand_less_p (*vr0min, vr1min) == 1)
8705 /* [ ( ] ) or [ ]( ) */
8706 if (*vr0type == VR_ANTI_RANGE
8707 && vr1type == VR_ANTI_RANGE)
8708 *vr0max = vr1max;
8709 else if (*vr0type == VR_RANGE
8710 && vr1type == VR_RANGE)
8711 *vr0min = vr1min;
8712 else if (*vr0type == VR_RANGE
8713 && vr1type == VR_ANTI_RANGE)
8715 if (TREE_CODE (vr1min) == INTEGER_CST)
8716 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8717 build_int_cst (TREE_TYPE (vr1min), 1));
8718 else
8719 *vr0max = vr1min;
8721 else if (*vr0type == VR_ANTI_RANGE
8722 && vr1type == VR_RANGE)
8724 *vr0type = VR_RANGE;
8725 if (TREE_CODE (*vr0max) == INTEGER_CST)
8726 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8727 build_int_cst (TREE_TYPE (*vr0max), 1));
8728 else
8729 *vr0min = *vr0max;
8730 *vr0max = vr1max;
8732 else
8733 gcc_unreachable ();
8735 else if ((operand_less_p (*vr0min, vr1max) == 1
8736 || operand_equal_p (*vr0min, vr1max, 0))
8737 && operand_less_p (vr1min, *vr0min) == 1)
8739 /* ( [ ) ] or ( )[ ] */
8740 if (*vr0type == VR_ANTI_RANGE
8741 && vr1type == VR_ANTI_RANGE)
8742 *vr0min = vr1min;
8743 else if (*vr0type == VR_RANGE
8744 && vr1type == VR_RANGE)
8745 *vr0max = vr1max;
8746 else if (*vr0type == VR_RANGE
8747 && vr1type == VR_ANTI_RANGE)
8749 if (TREE_CODE (vr1max) == INTEGER_CST)
8750 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8751 build_int_cst (TREE_TYPE (vr1max), 1));
8752 else
8753 *vr0min = vr1max;
8755 else if (*vr0type == VR_ANTI_RANGE
8756 && vr1type == VR_RANGE)
8758 *vr0type = VR_RANGE;
8759 if (TREE_CODE (*vr0min) == INTEGER_CST)
8760 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8761 build_int_cst (TREE_TYPE (*vr0min), 1));
8762 else
8763 *vr0max = *vr0min;
8764 *vr0min = vr1min;
8766 else
8767 gcc_unreachable ();
8770 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
8771 result for the intersection. That's always a conservative
8772 correct estimate unless VR1 is a constant singleton range
8773 in which case we choose that. */
8774 if (vr1type == VR_RANGE
8775 && is_gimple_min_invariant (vr1min)
8776 && vrp_operand_equal_p (vr1min, vr1max))
8778 *vr0type = vr1type;
8779 *vr0min = vr1min;
8780 *vr0max = vr1max;
8783 return;
8787 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
8788 in *VR0. This may not be the smallest possible such range. */
8790 static void
8791 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
8793 value_range saved;
8795 /* If either range is VR_VARYING the other one wins. */
8796 if (vr1->type == VR_VARYING)
8797 return;
8798 if (vr0->type == VR_VARYING)
8800 copy_value_range (vr0, vr1);
8801 return;
8804 /* When either range is VR_UNDEFINED the resulting range is
8805 VR_UNDEFINED, too. */
8806 if (vr0->type == VR_UNDEFINED)
8807 return;
8808 if (vr1->type == VR_UNDEFINED)
8810 set_value_range_to_undefined (vr0);
8811 return;
8814 /* Save the original vr0 so we can return it as conservative intersection
8815 result when our worker turns things to varying. */
8816 saved = *vr0;
8817 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
8818 vr1->type, vr1->min, vr1->max);
8819 /* Make sure to canonicalize the result though as the inversion of a
8820 VR_RANGE can still be a VR_RANGE. */
8821 set_and_canonicalize_value_range (vr0, vr0->type,
8822 vr0->min, vr0->max, vr0->equiv);
8823 /* If that failed, use the saved original VR0. */
8824 if (vr0->type == VR_VARYING)
8826 *vr0 = saved;
8827 return;
8829 /* If the result is VR_UNDEFINED there is no need to mess with
8830 the equivalencies. */
8831 if (vr0->type == VR_UNDEFINED)
8832 return;
8834 /* The resulting set of equivalences for range intersection is the union of
8835 the two sets. */
8836 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8837 bitmap_ior_into (vr0->equiv, vr1->equiv);
8838 else if (vr1->equiv && !vr0->equiv)
8840 /* All equivalence bitmaps are allocated from the same obstack. So
8841 we can use the obstack associated with VR to allocate vr0->equiv. */
8842 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
8843 bitmap_copy (vr0->equiv, vr1->equiv);
8847 void
8848 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
8850 if (dump_file && (dump_flags & TDF_DETAILS))
8852 fprintf (dump_file, "Intersecting\n ");
8853 dump_value_range (dump_file, vr0);
8854 fprintf (dump_file, "\nand\n ");
8855 dump_value_range (dump_file, vr1);
8856 fprintf (dump_file, "\n");
8858 vrp_intersect_ranges_1 (vr0, vr1);
8859 if (dump_file && (dump_flags & TDF_DETAILS))
8861 fprintf (dump_file, "to\n ");
8862 dump_value_range (dump_file, vr0);
8863 fprintf (dump_file, "\n");
8867 /* Meet operation for value ranges. Given two value ranges VR0 and
8868 VR1, store in VR0 a range that contains both VR0 and VR1. This
8869 may not be the smallest possible such range. */
8871 static void
8872 vrp_meet_1 (value_range *vr0, const value_range *vr1)
8874 value_range saved;
8876 if (vr0->type == VR_UNDEFINED)
8878 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
8879 return;
8882 if (vr1->type == VR_UNDEFINED)
8884 /* VR0 already has the resulting range. */
8885 return;
8888 if (vr0->type == VR_VARYING)
8890 /* Nothing to do. VR0 already has the resulting range. */
8891 return;
8894 if (vr1->type == VR_VARYING)
8896 set_value_range_to_varying (vr0);
8897 return;
8900 saved = *vr0;
8901 union_ranges (&vr0->type, &vr0->min, &vr0->max,
8902 vr1->type, vr1->min, vr1->max);
8903 if (vr0->type == VR_VARYING)
8905 /* Failed to find an efficient meet. Before giving up and setting
8906 the result to VARYING, see if we can at least derive a useful
8907 anti-range. FIXME, all this nonsense about distinguishing
8908 anti-ranges from ranges is necessary because of the odd
8909 semantics of range_includes_zero_p and friends. */
8910 if (((saved.type == VR_RANGE
8911 && range_includes_zero_p (saved.min, saved.max) == 0)
8912 || (saved.type == VR_ANTI_RANGE
8913 && range_includes_zero_p (saved.min, saved.max) == 1))
8914 && ((vr1->type == VR_RANGE
8915 && range_includes_zero_p (vr1->min, vr1->max) == 0)
8916 || (vr1->type == VR_ANTI_RANGE
8917 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
8919 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
8921 /* Since this meet operation did not result from the meeting of
8922 two equivalent names, VR0 cannot have any equivalences. */
8923 if (vr0->equiv)
8924 bitmap_clear (vr0->equiv);
8925 return;
8928 set_value_range_to_varying (vr0);
8929 return;
8931 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
8932 vr0->equiv);
8933 if (vr0->type == VR_VARYING)
8934 return;
8936 /* The resulting set of equivalences is always the intersection of
8937 the two sets. */
8938 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8939 bitmap_and_into (vr0->equiv, vr1->equiv);
8940 else if (vr0->equiv && !vr1->equiv)
8941 bitmap_clear (vr0->equiv);
8944 void
8945 vrp_meet (value_range *vr0, const value_range *vr1)
8947 if (dump_file && (dump_flags & TDF_DETAILS))
8949 fprintf (dump_file, "Meeting\n ");
8950 dump_value_range (dump_file, vr0);
8951 fprintf (dump_file, "\nand\n ");
8952 dump_value_range (dump_file, vr1);
8953 fprintf (dump_file, "\n");
8955 vrp_meet_1 (vr0, vr1);
8956 if (dump_file && (dump_flags & TDF_DETAILS))
8958 fprintf (dump_file, "to\n ");
8959 dump_value_range (dump_file, vr0);
8960 fprintf (dump_file, "\n");
8965 /* Visit all arguments for PHI node PHI that flow through executable
8966 edges. If a valid value range can be derived from all the incoming
8967 value ranges, set a new range in VR_RESULT. */
8969 void
8970 vr_values::extract_range_from_phi_node (gphi *phi, value_range *vr_result)
8972 size_t i;
8973 tree lhs = PHI_RESULT (phi);
8974 value_range *lhs_vr = get_value_range (lhs);
8975 bool first = true;
8976 int edges, old_edges;
8977 struct loop *l;
8979 if (dump_file && (dump_flags & TDF_DETAILS))
8981 fprintf (dump_file, "\nVisiting PHI node: ");
8982 print_gimple_stmt (dump_file, phi, 0, dump_flags);
8985 bool may_simulate_backedge_again = false;
8986 edges = 0;
8987 for (i = 0; i < gimple_phi_num_args (phi); i++)
8989 edge e = gimple_phi_arg_edge (phi, i);
8991 if (dump_file && (dump_flags & TDF_DETAILS))
8993 fprintf (dump_file,
8994 " Argument #%d (%d -> %d %sexecutable)\n",
8995 (int) i, e->src->index, e->dest->index,
8996 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
8999 if (e->flags & EDGE_EXECUTABLE)
9001 tree arg = PHI_ARG_DEF (phi, i);
9002 value_range vr_arg;
9004 ++edges;
9006 if (TREE_CODE (arg) == SSA_NAME)
9008 /* See if we are eventually going to change one of the args. */
9009 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
9010 if (! gimple_nop_p (def_stmt)
9011 && prop_simulate_again_p (def_stmt)
9012 && e->flags & EDGE_DFS_BACK)
9013 may_simulate_backedge_again = true;
9015 vr_arg = *(get_value_range (arg));
9016 /* Do not allow equivalences or symbolic ranges to leak in from
9017 backedges. That creates invalid equivalencies.
9018 See PR53465 and PR54767. */
9019 if (e->flags & EDGE_DFS_BACK)
9021 if (vr_arg.type == VR_RANGE
9022 || vr_arg.type == VR_ANTI_RANGE)
9024 vr_arg.equiv = NULL;
9025 if (symbolic_range_p (&vr_arg))
9027 vr_arg.type = VR_VARYING;
9028 vr_arg.min = NULL_TREE;
9029 vr_arg.max = NULL_TREE;
9033 else
9035 /* If the non-backedge arguments range is VR_VARYING then
9036 we can still try recording a simple equivalence. */
9037 if (vr_arg.type == VR_VARYING)
9039 vr_arg.type = VR_RANGE;
9040 vr_arg.min = arg;
9041 vr_arg.max = arg;
9042 vr_arg.equiv = NULL;
9046 else
9048 if (TREE_OVERFLOW_P (arg))
9049 arg = drop_tree_overflow (arg);
9051 vr_arg.type = VR_RANGE;
9052 vr_arg.min = arg;
9053 vr_arg.max = arg;
9054 vr_arg.equiv = NULL;
9057 if (dump_file && (dump_flags & TDF_DETAILS))
9059 fprintf (dump_file, "\t");
9060 print_generic_expr (dump_file, arg, dump_flags);
9061 fprintf (dump_file, ": ");
9062 dump_value_range (dump_file, &vr_arg);
9063 fprintf (dump_file, "\n");
9066 if (first)
9067 copy_value_range (vr_result, &vr_arg);
9068 else
9069 vrp_meet (vr_result, &vr_arg);
9070 first = false;
9072 if (vr_result->type == VR_VARYING)
9073 break;
9077 if (vr_result->type == VR_VARYING)
9078 goto varying;
9079 else if (vr_result->type == VR_UNDEFINED)
9080 goto update_range;
9082 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
9083 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
9085 /* To prevent infinite iterations in the algorithm, derive ranges
9086 when the new value is slightly bigger or smaller than the
9087 previous one. We don't do this if we have seen a new executable
9088 edge; this helps us avoid an infinity for conditionals
9089 which are not in a loop. If the old value-range was VR_UNDEFINED
9090 use the updated range and iterate one more time. If we will not
9091 simulate this PHI again via the backedge allow us to iterate. */
9092 if (edges > 0
9093 && gimple_phi_num_args (phi) > 1
9094 && edges == old_edges
9095 && lhs_vr->type != VR_UNDEFINED
9096 && may_simulate_backedge_again)
9098 /* Compare old and new ranges, fall back to varying if the
9099 values are not comparable. */
9100 int cmp_min = compare_values (lhs_vr->min, vr_result->min);
9101 if (cmp_min == -2)
9102 goto varying;
9103 int cmp_max = compare_values (lhs_vr->max, vr_result->max);
9104 if (cmp_max == -2)
9105 goto varying;
9107 /* For non VR_RANGE or for pointers fall back to varying if
9108 the range changed. */
9109 if ((lhs_vr->type != VR_RANGE || vr_result->type != VR_RANGE
9110 || POINTER_TYPE_P (TREE_TYPE (lhs)))
9111 && (cmp_min != 0 || cmp_max != 0))
9112 goto varying;
9114 /* If the new minimum is larger than the previous one
9115 retain the old value. If the new minimum value is smaller
9116 than the previous one and not -INF go all the way to -INF + 1.
9117 In the first case, to avoid infinite bouncing between different
9118 minimums, and in the other case to avoid iterating millions of
9119 times to reach -INF. Going to -INF + 1 also lets the following
9120 iteration compute whether there will be any overflow, at the
9121 expense of one additional iteration. */
9122 if (cmp_min < 0)
9123 vr_result->min = lhs_vr->min;
9124 else if (cmp_min > 0
9125 && !vrp_val_is_min (vr_result->min))
9126 vr_result->min
9127 = int_const_binop (PLUS_EXPR,
9128 vrp_val_min (TREE_TYPE (vr_result->min)),
9129 build_int_cst (TREE_TYPE (vr_result->min), 1));
9131 /* Similarly for the maximum value. */
9132 if (cmp_max > 0)
9133 vr_result->max = lhs_vr->max;
9134 else if (cmp_max < 0
9135 && !vrp_val_is_max (vr_result->max))
9136 vr_result->max
9137 = int_const_binop (MINUS_EXPR,
9138 vrp_val_max (TREE_TYPE (vr_result->min)),
9139 build_int_cst (TREE_TYPE (vr_result->min), 1));
9141 /* If we dropped either bound to +-INF then if this is a loop
9142 PHI node SCEV may known more about its value-range. */
9143 if (cmp_min > 0 || cmp_min < 0
9144 || cmp_max < 0 || cmp_max > 0)
9145 goto scev_check;
9147 goto infinite_check;
9150 goto update_range;
9152 varying:
9153 set_value_range_to_varying (vr_result);
9155 scev_check:
9156 /* If this is a loop PHI node SCEV may known more about its value-range.
9157 scev_check can be reached from two paths, one is a fall through from above
9158 "varying" label, the other is direct goto from code block which tries to
9159 avoid infinite simulation. */
9160 if ((l = loop_containing_stmt (phi))
9161 && l->header == gimple_bb (phi))
9162 adjust_range_with_scev (vr_result, l, phi, lhs);
9164 infinite_check:
9165 /* If we will end up with a (-INF, +INF) range, set it to
9166 VARYING. Same if the previous max value was invalid for
9167 the type and we end up with vr_result.min > vr_result.max. */
9168 if ((vr_result->type == VR_RANGE || vr_result->type == VR_ANTI_RANGE)
9169 && !((vrp_val_is_max (vr_result->max) && vrp_val_is_min (vr_result->min))
9170 || compare_values (vr_result->min, vr_result->max) > 0))
9172 else
9173 set_value_range_to_varying (vr_result);
9175 /* If the new range is different than the previous value, keep
9176 iterating. */
9177 update_range:
9178 return;
9181 /* Visit all arguments for PHI node PHI that flow through executable
9182 edges. If a valid value range can be derived from all the incoming
9183 value ranges, set a new range for the LHS of PHI. */
9185 enum ssa_prop_result
9186 vrp_prop::visit_phi (gphi *phi)
9188 tree lhs = PHI_RESULT (phi);
9189 value_range vr_result = VR_INITIALIZER;
9190 extract_range_from_phi_node (phi, &vr_result);
9191 if (update_value_range (lhs, &vr_result))
9193 if (dump_file && (dump_flags & TDF_DETAILS))
9195 fprintf (dump_file, "Found new range for ");
9196 print_generic_expr (dump_file, lhs);
9197 fprintf (dump_file, ": ");
9198 dump_value_range (dump_file, &vr_result);
9199 fprintf (dump_file, "\n");
9202 if (vr_result.type == VR_VARYING)
9203 return SSA_PROP_VARYING;
9205 return SSA_PROP_INTERESTING;
9208 /* Nothing changed, don't add outgoing edges. */
9209 return SSA_PROP_NOT_INTERESTING;
9212 /* Simplify boolean operations if the source is known
9213 to be already a boolean. */
9214 bool
9215 vr_values::simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi,
9216 gimple *stmt)
9218 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9219 tree lhs, op0, op1;
9220 bool need_conversion;
9222 /* We handle only !=/== case here. */
9223 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
9225 op0 = gimple_assign_rhs1 (stmt);
9226 if (!op_with_boolean_value_range_p (op0))
9227 return false;
9229 op1 = gimple_assign_rhs2 (stmt);
9230 if (!op_with_boolean_value_range_p (op1))
9231 return false;
9233 /* Reduce number of cases to handle to NE_EXPR. As there is no
9234 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
9235 if (rhs_code == EQ_EXPR)
9237 if (TREE_CODE (op1) == INTEGER_CST)
9238 op1 = int_const_binop (BIT_XOR_EXPR, op1,
9239 build_int_cst (TREE_TYPE (op1), 1));
9240 else
9241 return false;
9244 lhs = gimple_assign_lhs (stmt);
9245 need_conversion
9246 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
9248 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
9249 if (need_conversion
9250 && !TYPE_UNSIGNED (TREE_TYPE (op0))
9251 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
9252 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
9253 return false;
9255 /* For A != 0 we can substitute A itself. */
9256 if (integer_zerop (op1))
9257 gimple_assign_set_rhs_with_ops (gsi,
9258 need_conversion
9259 ? NOP_EXPR : TREE_CODE (op0), op0);
9260 /* For A != B we substitute A ^ B. Either with conversion. */
9261 else if (need_conversion)
9263 tree tem = make_ssa_name (TREE_TYPE (op0));
9264 gassign *newop
9265 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
9266 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
9267 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
9268 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
9269 set_range_info (tem, VR_RANGE,
9270 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
9271 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
9272 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
9274 /* Or without. */
9275 else
9276 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
9277 update_stmt (gsi_stmt (*gsi));
9278 fold_stmt (gsi, follow_single_use_edges);
9280 return true;
9283 /* Simplify a division or modulo operator to a right shift or bitwise and
9284 if the first operand is unsigned or is greater than zero and the second
9285 operand is an exact power of two. For TRUNC_MOD_EXPR op0 % op1 with
9286 constant op1 (op1min = op1) or with op1 in [op1min, op1max] range,
9287 optimize it into just op0 if op0's range is known to be a subset of
9288 [-op1min + 1, op1min - 1] for signed and [0, op1min - 1] for unsigned
9289 modulo. */
9291 bool
9292 vr_values::simplify_div_or_mod_using_ranges (gimple_stmt_iterator *gsi,
9293 gimple *stmt)
9295 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9296 tree val = NULL;
9297 tree op0 = gimple_assign_rhs1 (stmt);
9298 tree op1 = gimple_assign_rhs2 (stmt);
9299 tree op0min = NULL_TREE, op0max = NULL_TREE;
9300 tree op1min = op1;
9301 value_range *vr = NULL;
9303 if (TREE_CODE (op0) == INTEGER_CST)
9305 op0min = op0;
9306 op0max = op0;
9308 else
9310 vr = get_value_range (op0);
9311 if (range_int_cst_p (vr))
9313 op0min = vr->min;
9314 op0max = vr->max;
9318 if (rhs_code == TRUNC_MOD_EXPR
9319 && TREE_CODE (op1) == SSA_NAME)
9321 value_range *vr1 = get_value_range (op1);
9322 if (range_int_cst_p (vr1))
9323 op1min = vr1->min;
9325 if (rhs_code == TRUNC_MOD_EXPR
9326 && TREE_CODE (op1min) == INTEGER_CST
9327 && tree_int_cst_sgn (op1min) == 1
9328 && op0max
9329 && tree_int_cst_lt (op0max, op1min))
9331 if (TYPE_UNSIGNED (TREE_TYPE (op0))
9332 || tree_int_cst_sgn (op0min) >= 0
9333 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1min), op1min),
9334 op0min))
9336 /* If op0 already has the range op0 % op1 has,
9337 then TRUNC_MOD_EXPR won't change anything. */
9338 gimple_assign_set_rhs_from_tree (gsi, op0);
9339 return true;
9343 if (TREE_CODE (op0) != SSA_NAME)
9344 return false;
9346 if (!integer_pow2p (op1))
9348 /* X % -Y can be only optimized into X % Y either if
9349 X is not INT_MIN, or Y is not -1. Fold it now, as after
9350 remove_range_assertions the range info might be not available
9351 anymore. */
9352 if (rhs_code == TRUNC_MOD_EXPR
9353 && fold_stmt (gsi, follow_single_use_edges))
9354 return true;
9355 return false;
9358 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
9359 val = integer_one_node;
9360 else
9362 bool sop = false;
9364 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
9366 if (val
9367 && sop
9368 && integer_onep (val)
9369 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9371 location_t location;
9373 if (!gimple_has_location (stmt))
9374 location = input_location;
9375 else
9376 location = gimple_location (stmt);
9377 warning_at (location, OPT_Wstrict_overflow,
9378 "assuming signed overflow does not occur when "
9379 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
9383 if (val && integer_onep (val))
9385 tree t;
9387 if (rhs_code == TRUNC_DIV_EXPR)
9389 t = build_int_cst (integer_type_node, tree_log2 (op1));
9390 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
9391 gimple_assign_set_rhs1 (stmt, op0);
9392 gimple_assign_set_rhs2 (stmt, t);
9394 else
9396 t = build_int_cst (TREE_TYPE (op1), 1);
9397 t = int_const_binop (MINUS_EXPR, op1, t);
9398 t = fold_convert (TREE_TYPE (op0), t);
9400 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
9401 gimple_assign_set_rhs1 (stmt, op0);
9402 gimple_assign_set_rhs2 (stmt, t);
9405 update_stmt (stmt);
9406 fold_stmt (gsi, follow_single_use_edges);
9407 return true;
9410 return false;
9413 /* Simplify a min or max if the ranges of the two operands are
9414 disjoint. Return true if we do simplify. */
9416 bool
9417 vr_values::simplify_min_or_max_using_ranges (gimple_stmt_iterator *gsi,
9418 gimple *stmt)
9420 tree op0 = gimple_assign_rhs1 (stmt);
9421 tree op1 = gimple_assign_rhs2 (stmt);
9422 bool sop = false;
9423 tree val;
9425 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9426 (LE_EXPR, op0, op1, &sop));
9427 if (!val)
9429 sop = false;
9430 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9431 (LT_EXPR, op0, op1, &sop));
9434 if (val)
9436 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9438 location_t location;
9440 if (!gimple_has_location (stmt))
9441 location = input_location;
9442 else
9443 location = gimple_location (stmt);
9444 warning_at (location, OPT_Wstrict_overflow,
9445 "assuming signed overflow does not occur when "
9446 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
9449 /* VAL == TRUE -> OP0 < or <= op1
9450 VAL == FALSE -> OP0 > or >= op1. */
9451 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
9452 == integer_zerop (val)) ? op0 : op1;
9453 gimple_assign_set_rhs_from_tree (gsi, res);
9454 return true;
9457 return false;
9460 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
9461 ABS_EXPR. If the operand is <= 0, then simplify the
9462 ABS_EXPR into a NEGATE_EXPR. */
9464 bool
9465 vr_values::simplify_abs_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9467 tree op = gimple_assign_rhs1 (stmt);
9468 value_range *vr = get_value_range (op);
9470 if (vr)
9472 tree val = NULL;
9473 bool sop = false;
9475 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
9476 if (!val)
9478 /* The range is neither <= 0 nor > 0. Now see if it is
9479 either < 0 or >= 0. */
9480 sop = false;
9481 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
9482 &sop);
9485 if (val)
9487 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9489 location_t location;
9491 if (!gimple_has_location (stmt))
9492 location = input_location;
9493 else
9494 location = gimple_location (stmt);
9495 warning_at (location, OPT_Wstrict_overflow,
9496 "assuming signed overflow does not occur when "
9497 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
9500 gimple_assign_set_rhs1 (stmt, op);
9501 if (integer_zerop (val))
9502 gimple_assign_set_rhs_code (stmt, SSA_NAME);
9503 else
9504 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
9505 update_stmt (stmt);
9506 fold_stmt (gsi, follow_single_use_edges);
9507 return true;
9511 return false;
9514 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
9515 If all the bits that are being cleared by & are already
9516 known to be zero from VR, or all the bits that are being
9517 set by | are already known to be one from VR, the bit
9518 operation is redundant. */
9520 bool
9521 vr_values::simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi,
9522 gimple *stmt)
9524 tree op0 = gimple_assign_rhs1 (stmt);
9525 tree op1 = gimple_assign_rhs2 (stmt);
9526 tree op = NULL_TREE;
9527 value_range vr0 = VR_INITIALIZER;
9528 value_range vr1 = VR_INITIALIZER;
9529 wide_int may_be_nonzero0, may_be_nonzero1;
9530 wide_int must_be_nonzero0, must_be_nonzero1;
9531 wide_int mask;
9533 if (TREE_CODE (op0) == SSA_NAME)
9534 vr0 = *(get_value_range (op0));
9535 else if (is_gimple_min_invariant (op0))
9536 set_value_range_to_value (&vr0, op0, NULL);
9537 else
9538 return false;
9540 if (TREE_CODE (op1) == SSA_NAME)
9541 vr1 = *(get_value_range (op1));
9542 else if (is_gimple_min_invariant (op1))
9543 set_value_range_to_value (&vr1, op1, NULL);
9544 else
9545 return false;
9547 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
9548 &must_be_nonzero0))
9549 return false;
9550 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
9551 &must_be_nonzero1))
9552 return false;
9554 switch (gimple_assign_rhs_code (stmt))
9556 case BIT_AND_EXPR:
9557 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
9558 if (mask == 0)
9560 op = op0;
9561 break;
9563 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
9564 if (mask == 0)
9566 op = op1;
9567 break;
9569 break;
9570 case BIT_IOR_EXPR:
9571 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
9572 if (mask == 0)
9574 op = op1;
9575 break;
9577 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
9578 if (mask == 0)
9580 op = op0;
9581 break;
9583 break;
9584 default:
9585 gcc_unreachable ();
9588 if (op == NULL_TREE)
9589 return false;
9591 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
9592 update_stmt (gsi_stmt (*gsi));
9593 return true;
9596 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
9597 a known value range VR.
9599 If there is one and only one value which will satisfy the
9600 conditional, then return that value. Else return NULL.
9602 If signed overflow must be undefined for the value to satisfy
9603 the conditional, then set *STRICT_OVERFLOW_P to true. */
9605 static tree
9606 test_for_singularity (enum tree_code cond_code, tree op0,
9607 tree op1, value_range *vr)
9609 tree min = NULL;
9610 tree max = NULL;
9612 /* Extract minimum/maximum values which satisfy the conditional as it was
9613 written. */
9614 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
9616 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
9618 max = op1;
9619 if (cond_code == LT_EXPR)
9621 tree one = build_int_cst (TREE_TYPE (op0), 1);
9622 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
9623 /* Signal to compare_values_warnv this expr doesn't overflow. */
9624 if (EXPR_P (max))
9625 TREE_NO_WARNING (max) = 1;
9628 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
9630 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
9632 min = op1;
9633 if (cond_code == GT_EXPR)
9635 tree one = build_int_cst (TREE_TYPE (op0), 1);
9636 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
9637 /* Signal to compare_values_warnv this expr doesn't overflow. */
9638 if (EXPR_P (min))
9639 TREE_NO_WARNING (min) = 1;
9643 /* Now refine the minimum and maximum values using any
9644 value range information we have for op0. */
9645 if (min && max)
9647 if (compare_values (vr->min, min) == 1)
9648 min = vr->min;
9649 if (compare_values (vr->max, max) == -1)
9650 max = vr->max;
9652 /* If the new min/max values have converged to a single value,
9653 then there is only one value which can satisfy the condition,
9654 return that value. */
9655 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
9656 return min;
9658 return NULL;
9661 /* Return whether the value range *VR fits in an integer type specified
9662 by PRECISION and UNSIGNED_P. */
9664 static bool
9665 range_fits_type_p (value_range *vr, unsigned dest_precision, signop dest_sgn)
9667 tree src_type;
9668 unsigned src_precision;
9669 widest_int tem;
9670 signop src_sgn;
9672 /* We can only handle integral and pointer types. */
9673 src_type = TREE_TYPE (vr->min);
9674 if (!INTEGRAL_TYPE_P (src_type)
9675 && !POINTER_TYPE_P (src_type))
9676 return false;
9678 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
9679 and so is an identity transform. */
9680 src_precision = TYPE_PRECISION (TREE_TYPE (vr->min));
9681 src_sgn = TYPE_SIGN (src_type);
9682 if ((src_precision < dest_precision
9683 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
9684 || (src_precision == dest_precision && src_sgn == dest_sgn))
9685 return true;
9687 /* Now we can only handle ranges with constant bounds. */
9688 if (vr->type != VR_RANGE
9689 || TREE_CODE (vr->min) != INTEGER_CST
9690 || TREE_CODE (vr->max) != INTEGER_CST)
9691 return false;
9693 /* For sign changes, the MSB of the wide_int has to be clear.
9694 An unsigned value with its MSB set cannot be represented by
9695 a signed wide_int, while a negative value cannot be represented
9696 by an unsigned wide_int. */
9697 if (src_sgn != dest_sgn
9698 && (wi::lts_p (wi::to_wide (vr->min), 0)
9699 || wi::lts_p (wi::to_wide (vr->max), 0)))
9700 return false;
9702 /* Then we can perform the conversion on both ends and compare
9703 the result for equality. */
9704 tem = wi::ext (wi::to_widest (vr->min), dest_precision, dest_sgn);
9705 if (tem != wi::to_widest (vr->min))
9706 return false;
9707 tem = wi::ext (wi::to_widest (vr->max), dest_precision, dest_sgn);
9708 if (tem != wi::to_widest (vr->max))
9709 return false;
9711 return true;
9714 /* Simplify a conditional using a relational operator to an equality
9715 test if the range information indicates only one value can satisfy
9716 the original conditional. */
9718 bool
9719 vr_values::simplify_cond_using_ranges_1 (gcond *stmt)
9721 tree op0 = gimple_cond_lhs (stmt);
9722 tree op1 = gimple_cond_rhs (stmt);
9723 enum tree_code cond_code = gimple_cond_code (stmt);
9725 if (cond_code != NE_EXPR
9726 && cond_code != EQ_EXPR
9727 && TREE_CODE (op0) == SSA_NAME
9728 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9729 && is_gimple_min_invariant (op1))
9731 value_range *vr = get_value_range (op0);
9733 /* If we have range information for OP0, then we might be
9734 able to simplify this conditional. */
9735 if (vr->type == VR_RANGE)
9737 tree new_tree = test_for_singularity (cond_code, op0, op1, vr);
9738 if (new_tree)
9740 if (dump_file)
9742 fprintf (dump_file, "Simplified relational ");
9743 print_gimple_stmt (dump_file, stmt, 0);
9744 fprintf (dump_file, " into ");
9747 gimple_cond_set_code (stmt, EQ_EXPR);
9748 gimple_cond_set_lhs (stmt, op0);
9749 gimple_cond_set_rhs (stmt, new_tree);
9751 update_stmt (stmt);
9753 if (dump_file)
9755 print_gimple_stmt (dump_file, stmt, 0);
9756 fprintf (dump_file, "\n");
9759 return true;
9762 /* Try again after inverting the condition. We only deal
9763 with integral types here, so no need to worry about
9764 issues with inverting FP comparisons. */
9765 new_tree = test_for_singularity
9766 (invert_tree_comparison (cond_code, false),
9767 op0, op1, vr);
9768 if (new_tree)
9770 if (dump_file)
9772 fprintf (dump_file, "Simplified relational ");
9773 print_gimple_stmt (dump_file, stmt, 0);
9774 fprintf (dump_file, " into ");
9777 gimple_cond_set_code (stmt, NE_EXPR);
9778 gimple_cond_set_lhs (stmt, op0);
9779 gimple_cond_set_rhs (stmt, new_tree);
9781 update_stmt (stmt);
9783 if (dump_file)
9785 print_gimple_stmt (dump_file, stmt, 0);
9786 fprintf (dump_file, "\n");
9789 return true;
9793 return false;
9796 /* STMT is a conditional at the end of a basic block.
9798 If the conditional is of the form SSA_NAME op constant and the SSA_NAME
9799 was set via a type conversion, try to replace the SSA_NAME with the RHS
9800 of the type conversion. Doing so makes the conversion dead which helps
9801 subsequent passes. */
9803 void
9804 vr_values::simplify_cond_using_ranges_2 (gcond *stmt)
9806 tree op0 = gimple_cond_lhs (stmt);
9807 tree op1 = gimple_cond_rhs (stmt);
9809 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
9810 see if OP0 was set by a type conversion where the source of
9811 the conversion is another SSA_NAME with a range that fits
9812 into the range of OP0's type.
9814 If so, the conversion is redundant as the earlier SSA_NAME can be
9815 used for the comparison directly if we just massage the constant in the
9816 comparison. */
9817 if (TREE_CODE (op0) == SSA_NAME
9818 && TREE_CODE (op1) == INTEGER_CST)
9820 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
9821 tree innerop;
9823 if (!is_gimple_assign (def_stmt)
9824 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
9825 return;
9827 innerop = gimple_assign_rhs1 (def_stmt);
9829 if (TREE_CODE (innerop) == SSA_NAME
9830 && !POINTER_TYPE_P (TREE_TYPE (innerop))
9831 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
9832 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
9834 value_range *vr = get_value_range (innerop);
9836 if (range_int_cst_p (vr)
9837 && range_fits_type_p (vr,
9838 TYPE_PRECISION (TREE_TYPE (op0)),
9839 TYPE_SIGN (TREE_TYPE (op0)))
9840 && int_fits_type_p (op1, TREE_TYPE (innerop)))
9842 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
9843 gimple_cond_set_lhs (stmt, innerop);
9844 gimple_cond_set_rhs (stmt, newconst);
9845 update_stmt (stmt);
9846 if (dump_file && (dump_flags & TDF_DETAILS))
9848 fprintf (dump_file, "Folded into: ");
9849 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
9850 fprintf (dump_file, "\n");
9857 /* Simplify a switch statement using the value range of the switch
9858 argument. */
9860 bool
9861 vr_values::simplify_switch_using_ranges (gswitch *stmt)
9863 tree op = gimple_switch_index (stmt);
9864 value_range *vr = NULL;
9865 bool take_default;
9866 edge e;
9867 edge_iterator ei;
9868 size_t i = 0, j = 0, n, n2;
9869 tree vec2;
9870 switch_update su;
9871 size_t k = 1, l = 0;
9873 if (TREE_CODE (op) == SSA_NAME)
9875 vr = get_value_range (op);
9877 /* We can only handle integer ranges. */
9878 if ((vr->type != VR_RANGE
9879 && vr->type != VR_ANTI_RANGE)
9880 || symbolic_range_p (vr))
9881 return false;
9883 /* Find case label for min/max of the value range. */
9884 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
9886 else if (TREE_CODE (op) == INTEGER_CST)
9888 take_default = !find_case_label_index (stmt, 1, op, &i);
9889 if (take_default)
9891 i = 1;
9892 j = 0;
9894 else
9896 j = i;
9899 else
9900 return false;
9902 n = gimple_switch_num_labels (stmt);
9904 /* We can truncate the case label ranges that partially overlap with OP's
9905 value range. */
9906 size_t min_idx = 1, max_idx = 0;
9907 if (vr != NULL)
9908 find_case_label_range (stmt, vr->min, vr->max, &min_idx, &max_idx);
9909 if (min_idx <= max_idx)
9911 tree min_label = gimple_switch_label (stmt, min_idx);
9912 tree max_label = gimple_switch_label (stmt, max_idx);
9914 /* Avoid changing the type of the case labels when truncating. */
9915 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
9916 tree vr_min = fold_convert (case_label_type, vr->min);
9917 tree vr_max = fold_convert (case_label_type, vr->max);
9919 if (vr->type == VR_RANGE)
9921 /* If OP's value range is [2,8] and the low label range is
9922 0 ... 3, truncate the label's range to 2 .. 3. */
9923 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9924 && CASE_HIGH (min_label) != NULL_TREE
9925 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9926 CASE_LOW (min_label) = vr_min;
9928 /* If OP's value range is [2,8] and the high label range is
9929 7 ... 10, truncate the label's range to 7 .. 8. */
9930 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9931 && CASE_HIGH (max_label) != NULL_TREE
9932 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9933 CASE_HIGH (max_label) = vr_max;
9935 else if (vr->type == VR_ANTI_RANGE)
9937 tree one_cst = build_one_cst (case_label_type);
9939 if (min_label == max_label)
9941 /* If OP's value range is ~[7,8] and the label's range is
9942 7 ... 10, truncate the label's range to 9 ... 10. */
9943 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
9944 && CASE_HIGH (min_label) != NULL_TREE
9945 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
9946 CASE_LOW (min_label)
9947 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9949 /* If OP's value range is ~[7,8] and the label's range is
9950 5 ... 8, truncate the label's range to 5 ... 6. */
9951 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9952 && CASE_HIGH (min_label) != NULL_TREE
9953 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
9954 CASE_HIGH (min_label)
9955 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9957 else
9959 /* If OP's value range is ~[2,8] and the low label range is
9960 0 ... 3, truncate the label's range to 0 ... 1. */
9961 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9962 && CASE_HIGH (min_label) != NULL_TREE
9963 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9964 CASE_HIGH (min_label)
9965 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9967 /* If OP's value range is ~[2,8] and the high label range is
9968 7 ... 10, truncate the label's range to 9 ... 10. */
9969 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9970 && CASE_HIGH (max_label) != NULL_TREE
9971 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9972 CASE_LOW (max_label)
9973 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9977 /* Canonicalize singleton case ranges. */
9978 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
9979 CASE_HIGH (min_label) = NULL_TREE;
9980 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
9981 CASE_HIGH (max_label) = NULL_TREE;
9984 /* We can also eliminate case labels that lie completely outside OP's value
9985 range. */
9987 /* Bail out if this is just all edges taken. */
9988 if (i == 1
9989 && j == n - 1
9990 && take_default)
9991 return false;
9993 /* Build a new vector of taken case labels. */
9994 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
9995 n2 = 0;
9997 /* Add the default edge, if necessary. */
9998 if (take_default)
9999 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
10001 for (; i <= j; ++i, ++n2)
10002 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
10004 for (; k <= l; ++k, ++n2)
10005 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
10007 /* Mark needed edges. */
10008 for (i = 0; i < n2; ++i)
10010 e = find_edge (gimple_bb (stmt),
10011 label_to_block (CASE_LABEL (TREE_VEC_ELT (vec2, i))));
10012 e->aux = (void *)-1;
10015 /* Queue not needed edges for later removal. */
10016 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
10018 if (e->aux == (void *)-1)
10020 e->aux = NULL;
10021 continue;
10024 if (dump_file && (dump_flags & TDF_DETAILS))
10026 fprintf (dump_file, "removing unreachable case label\n");
10028 to_remove_edges.safe_push (e);
10029 e->flags &= ~EDGE_EXECUTABLE;
10032 /* And queue an update for the stmt. */
10033 su.stmt = stmt;
10034 su.vec = vec2;
10035 to_update_switch_stmts.safe_push (su);
10036 return false;
10039 /* Simplify an integral conversion from an SSA name in STMT. */
10041 static bool
10042 simplify_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10044 tree innerop, middleop, finaltype;
10045 gimple *def_stmt;
10046 signop inner_sgn, middle_sgn, final_sgn;
10047 unsigned inner_prec, middle_prec, final_prec;
10048 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
10050 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
10051 if (!INTEGRAL_TYPE_P (finaltype))
10052 return false;
10053 middleop = gimple_assign_rhs1 (stmt);
10054 def_stmt = SSA_NAME_DEF_STMT (middleop);
10055 if (!is_gimple_assign (def_stmt)
10056 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
10057 return false;
10058 innerop = gimple_assign_rhs1 (def_stmt);
10059 if (TREE_CODE (innerop) != SSA_NAME
10060 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
10061 return false;
10063 /* Get the value-range of the inner operand. Use get_range_info in
10064 case innerop was created during substitute-and-fold. */
10065 wide_int imin, imax;
10066 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop))
10067 || get_range_info (innerop, &imin, &imax) != VR_RANGE)
10068 return false;
10069 innermin = widest_int::from (imin, TYPE_SIGN (TREE_TYPE (innerop)));
10070 innermax = widest_int::from (imax, TYPE_SIGN (TREE_TYPE (innerop)));
10072 /* Simulate the conversion chain to check if the result is equal if
10073 the middle conversion is removed. */
10074 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
10075 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
10076 final_prec = TYPE_PRECISION (finaltype);
10078 /* If the first conversion is not injective, the second must not
10079 be widening. */
10080 if (wi::gtu_p (innermax - innermin,
10081 wi::mask <widest_int> (middle_prec, false))
10082 && middle_prec < final_prec)
10083 return false;
10084 /* We also want a medium value so that we can track the effect that
10085 narrowing conversions with sign change have. */
10086 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
10087 if (inner_sgn == UNSIGNED)
10088 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
10089 else
10090 innermed = 0;
10091 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
10092 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
10093 innermed = innermin;
10095 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
10096 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
10097 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
10098 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
10100 /* Require that the final conversion applied to both the original
10101 and the intermediate range produces the same result. */
10102 final_sgn = TYPE_SIGN (finaltype);
10103 if (wi::ext (middlemin, final_prec, final_sgn)
10104 != wi::ext (innermin, final_prec, final_sgn)
10105 || wi::ext (middlemed, final_prec, final_sgn)
10106 != wi::ext (innermed, final_prec, final_sgn)
10107 || wi::ext (middlemax, final_prec, final_sgn)
10108 != wi::ext (innermax, final_prec, final_sgn))
10109 return false;
10111 gimple_assign_set_rhs1 (stmt, innerop);
10112 fold_stmt (gsi, follow_single_use_edges);
10113 return true;
10116 /* Simplify a conversion from integral SSA name to float in STMT. */
10118 bool
10119 vr_values::simplify_float_conversion_using_ranges (gimple_stmt_iterator *gsi,
10120 gimple *stmt)
10122 tree rhs1 = gimple_assign_rhs1 (stmt);
10123 value_range *vr = get_value_range (rhs1);
10124 scalar_float_mode fltmode
10125 = SCALAR_FLOAT_TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
10126 scalar_int_mode mode;
10127 tree tem;
10128 gassign *conv;
10130 /* We can only handle constant ranges. */
10131 if (vr->type != VR_RANGE
10132 || TREE_CODE (vr->min) != INTEGER_CST
10133 || TREE_CODE (vr->max) != INTEGER_CST)
10134 return false;
10136 /* First check if we can use a signed type in place of an unsigned. */
10137 scalar_int_mode rhs_mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (rhs1));
10138 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
10139 && can_float_p (fltmode, rhs_mode, 0) != CODE_FOR_nothing
10140 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
10141 mode = rhs_mode;
10142 /* If we can do the conversion in the current input mode do nothing. */
10143 else if (can_float_p (fltmode, rhs_mode,
10144 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
10145 return false;
10146 /* Otherwise search for a mode we can use, starting from the narrowest
10147 integer mode available. */
10148 else
10150 mode = NARROWEST_INT_MODE;
10151 for (;;)
10153 /* If we cannot do a signed conversion to float from mode
10154 or if the value-range does not fit in the signed type
10155 try with a wider mode. */
10156 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
10157 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
10158 break;
10160 /* But do not widen the input. Instead leave that to the
10161 optabs expansion code. */
10162 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
10163 || GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
10164 return false;
10168 /* It works, insert a truncation or sign-change before the
10169 float conversion. */
10170 tem = make_ssa_name (build_nonstandard_integer_type
10171 (GET_MODE_PRECISION (mode), 0));
10172 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
10173 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
10174 gimple_assign_set_rhs1 (stmt, tem);
10175 fold_stmt (gsi, follow_single_use_edges);
10177 return true;
10180 /* Simplify an internal fn call using ranges if possible. */
10182 bool
10183 vr_values::simplify_internal_call_using_ranges (gimple_stmt_iterator *gsi,
10184 gimple *stmt)
10186 enum tree_code subcode;
10187 bool is_ubsan = false;
10188 bool ovf = false;
10189 switch (gimple_call_internal_fn (stmt))
10191 case IFN_UBSAN_CHECK_ADD:
10192 subcode = PLUS_EXPR;
10193 is_ubsan = true;
10194 break;
10195 case IFN_UBSAN_CHECK_SUB:
10196 subcode = MINUS_EXPR;
10197 is_ubsan = true;
10198 break;
10199 case IFN_UBSAN_CHECK_MUL:
10200 subcode = MULT_EXPR;
10201 is_ubsan = true;
10202 break;
10203 case IFN_ADD_OVERFLOW:
10204 subcode = PLUS_EXPR;
10205 break;
10206 case IFN_SUB_OVERFLOW:
10207 subcode = MINUS_EXPR;
10208 break;
10209 case IFN_MUL_OVERFLOW:
10210 subcode = MULT_EXPR;
10211 break;
10212 default:
10213 return false;
10216 tree op0 = gimple_call_arg (stmt, 0);
10217 tree op1 = gimple_call_arg (stmt, 1);
10218 tree type;
10219 if (is_ubsan)
10221 type = TREE_TYPE (op0);
10222 if (VECTOR_TYPE_P (type))
10223 return false;
10225 else if (gimple_call_lhs (stmt) == NULL_TREE)
10226 return false;
10227 else
10228 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
10229 if (!check_for_binary_op_overflow (subcode, type, op0, op1, &ovf)
10230 || (is_ubsan && ovf))
10231 return false;
10233 gimple *g;
10234 location_t loc = gimple_location (stmt);
10235 if (is_ubsan)
10236 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
10237 else
10239 int prec = TYPE_PRECISION (type);
10240 tree utype = type;
10241 if (ovf
10242 || !useless_type_conversion_p (type, TREE_TYPE (op0))
10243 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
10244 utype = build_nonstandard_integer_type (prec, 1);
10245 if (TREE_CODE (op0) == INTEGER_CST)
10246 op0 = fold_convert (utype, op0);
10247 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
10249 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
10250 gimple_set_location (g, loc);
10251 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10252 op0 = gimple_assign_lhs (g);
10254 if (TREE_CODE (op1) == INTEGER_CST)
10255 op1 = fold_convert (utype, op1);
10256 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
10258 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
10259 gimple_set_location (g, loc);
10260 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10261 op1 = gimple_assign_lhs (g);
10263 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
10264 gimple_set_location (g, loc);
10265 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10266 if (utype != type)
10268 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
10269 gimple_assign_lhs (g));
10270 gimple_set_location (g, loc);
10271 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10273 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
10274 gimple_assign_lhs (g),
10275 build_int_cst (type, ovf));
10277 gimple_set_location (g, loc);
10278 gsi_replace (gsi, g, false);
10279 return true;
10282 /* Return true if VAR is a two-valued variable. Set a and b with the
10283 two-values when it is true. Return false otherwise. */
10285 bool
10286 vr_values::two_valued_val_range_p (tree var, tree *a, tree *b)
10288 value_range *vr = get_value_range (var);
10289 if ((vr->type != VR_RANGE
10290 && vr->type != VR_ANTI_RANGE)
10291 || TREE_CODE (vr->min) != INTEGER_CST
10292 || TREE_CODE (vr->max) != INTEGER_CST)
10293 return false;
10295 if (vr->type == VR_RANGE
10296 && wi::to_wide (vr->max) - wi::to_wide (vr->min) == 1)
10298 *a = vr->min;
10299 *b = vr->max;
10300 return true;
10303 /* ~[TYPE_MIN + 1, TYPE_MAX - 1] */
10304 if (vr->type == VR_ANTI_RANGE
10305 && (wi::to_wide (vr->min)
10306 - wi::to_wide (vrp_val_min (TREE_TYPE (var)))) == 1
10307 && (wi::to_wide (vrp_val_max (TREE_TYPE (var)))
10308 - wi::to_wide (vr->max)) == 1)
10310 *a = vrp_val_min (TREE_TYPE (var));
10311 *b = vrp_val_max (TREE_TYPE (var));
10312 return true;
10315 return false;
10318 /* Simplify STMT using ranges if possible. */
10320 bool
10321 vr_values::simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
10323 gimple *stmt = gsi_stmt (*gsi);
10324 if (is_gimple_assign (stmt))
10326 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
10327 tree rhs1 = gimple_assign_rhs1 (stmt);
10328 tree rhs2 = gimple_assign_rhs2 (stmt);
10329 tree lhs = gimple_assign_lhs (stmt);
10330 tree val1 = NULL_TREE, val2 = NULL_TREE;
10331 use_operand_p use_p;
10332 gimple *use_stmt;
10334 /* Convert:
10335 LHS = CST BINOP VAR
10336 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10338 LHS = VAR == VAL1 ? (CST BINOP VAL1) : (CST BINOP VAL2)
10340 Also handles:
10341 LHS = VAR BINOP CST
10342 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10344 LHS = VAR == VAL1 ? (VAL1 BINOP CST) : (VAL2 BINOP CST) */
10346 if (TREE_CODE_CLASS (rhs_code) == tcc_binary
10347 && INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10348 && ((TREE_CODE (rhs1) == INTEGER_CST
10349 && TREE_CODE (rhs2) == SSA_NAME)
10350 || (TREE_CODE (rhs2) == INTEGER_CST
10351 && TREE_CODE (rhs1) == SSA_NAME))
10352 && single_imm_use (lhs, &use_p, &use_stmt)
10353 && gimple_code (use_stmt) == GIMPLE_COND)
10356 tree new_rhs1 = NULL_TREE;
10357 tree new_rhs2 = NULL_TREE;
10358 tree cmp_var = NULL_TREE;
10360 if (TREE_CODE (rhs2) == SSA_NAME
10361 && two_valued_val_range_p (rhs2, &val1, &val2))
10363 /* Optimize RHS1 OP [VAL1, VAL2]. */
10364 new_rhs1 = int_const_binop (rhs_code, rhs1, val1);
10365 new_rhs2 = int_const_binop (rhs_code, rhs1, val2);
10366 cmp_var = rhs2;
10368 else if (TREE_CODE (rhs1) == SSA_NAME
10369 && two_valued_val_range_p (rhs1, &val1, &val2))
10371 /* Optimize [VAL1, VAL2] OP RHS2. */
10372 new_rhs1 = int_const_binop (rhs_code, val1, rhs2);
10373 new_rhs2 = int_const_binop (rhs_code, val2, rhs2);
10374 cmp_var = rhs1;
10377 /* If we could not find two-vals or the optimzation is invalid as
10378 in divide by zero, new_rhs1 / new_rhs will be NULL_TREE. */
10379 if (new_rhs1 && new_rhs2)
10381 tree cond = build2 (EQ_EXPR, boolean_type_node, cmp_var, val1);
10382 gimple_assign_set_rhs_with_ops (gsi,
10383 COND_EXPR, cond,
10384 new_rhs1,
10385 new_rhs2);
10386 update_stmt (gsi_stmt (*gsi));
10387 fold_stmt (gsi, follow_single_use_edges);
10388 return true;
10392 switch (rhs_code)
10394 case EQ_EXPR:
10395 case NE_EXPR:
10396 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
10397 if the RHS is zero or one, and the LHS are known to be boolean
10398 values. */
10399 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10400 return simplify_truth_ops_using_ranges (gsi, stmt);
10401 break;
10403 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
10404 and BIT_AND_EXPR respectively if the first operand is greater
10405 than zero and the second operand is an exact power of two.
10406 Also optimize TRUNC_MOD_EXPR away if the second operand is
10407 constant and the first operand already has the right value
10408 range. */
10409 case TRUNC_DIV_EXPR:
10410 case TRUNC_MOD_EXPR:
10411 if ((TREE_CODE (rhs1) == SSA_NAME
10412 || TREE_CODE (rhs1) == INTEGER_CST)
10413 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10414 return simplify_div_or_mod_using_ranges (gsi, stmt);
10415 break;
10417 /* Transform ABS (X) into X or -X as appropriate. */
10418 case ABS_EXPR:
10419 if (TREE_CODE (rhs1) == SSA_NAME
10420 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10421 return simplify_abs_using_ranges (gsi, stmt);
10422 break;
10424 case BIT_AND_EXPR:
10425 case BIT_IOR_EXPR:
10426 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
10427 if all the bits being cleared are already cleared or
10428 all the bits being set are already set. */
10429 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10430 return simplify_bit_ops_using_ranges (gsi, stmt);
10431 break;
10433 CASE_CONVERT:
10434 if (TREE_CODE (rhs1) == SSA_NAME
10435 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10436 return simplify_conversion_using_ranges (gsi, stmt);
10437 break;
10439 case FLOAT_EXPR:
10440 if (TREE_CODE (rhs1) == SSA_NAME
10441 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10442 return simplify_float_conversion_using_ranges (gsi, stmt);
10443 break;
10445 case MIN_EXPR:
10446 case MAX_EXPR:
10447 return simplify_min_or_max_using_ranges (gsi, stmt);
10449 default:
10450 break;
10453 else if (gimple_code (stmt) == GIMPLE_COND)
10454 return simplify_cond_using_ranges_1 (as_a <gcond *> (stmt));
10455 else if (gimple_code (stmt) == GIMPLE_SWITCH)
10456 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
10457 else if (is_gimple_call (stmt)
10458 && gimple_call_internal_p (stmt))
10459 return simplify_internal_call_using_ranges (gsi, stmt);
10461 return false;
10464 class vrp_folder : public substitute_and_fold_engine
10466 public:
10467 tree get_value (tree) FINAL OVERRIDE;
10468 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
10469 bool fold_predicate_in (gimple_stmt_iterator *);
10471 class vr_values *vr_values;
10473 /* Delegators. */
10474 tree vrp_evaluate_conditional (tree_code code, tree op0,
10475 tree op1, gimple *stmt)
10476 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
10477 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
10478 { return vr_values->simplify_stmt_using_ranges (gsi); }
10479 tree op_with_constant_singleton_value_range (tree op)
10480 { return vr_values->op_with_constant_singleton_value_range (op); }
10483 /* If the statement pointed by SI has a predicate whose value can be
10484 computed using the value range information computed by VRP, compute
10485 its value and return true. Otherwise, return false. */
10487 bool
10488 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
10490 bool assignment_p = false;
10491 tree val;
10492 gimple *stmt = gsi_stmt (*si);
10494 if (is_gimple_assign (stmt)
10495 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
10497 assignment_p = true;
10498 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
10499 gimple_assign_rhs1 (stmt),
10500 gimple_assign_rhs2 (stmt),
10501 stmt);
10503 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10504 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10505 gimple_cond_lhs (cond_stmt),
10506 gimple_cond_rhs (cond_stmt),
10507 stmt);
10508 else
10509 return false;
10511 if (val)
10513 if (assignment_p)
10514 val = fold_convert (gimple_expr_type (stmt), val);
10516 if (dump_file)
10518 fprintf (dump_file, "Folding predicate ");
10519 print_gimple_expr (dump_file, stmt, 0);
10520 fprintf (dump_file, " to ");
10521 print_generic_expr (dump_file, val);
10522 fprintf (dump_file, "\n");
10525 if (is_gimple_assign (stmt))
10526 gimple_assign_set_rhs_from_tree (si, val);
10527 else
10529 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
10530 gcond *cond_stmt = as_a <gcond *> (stmt);
10531 if (integer_zerop (val))
10532 gimple_cond_make_false (cond_stmt);
10533 else if (integer_onep (val))
10534 gimple_cond_make_true (cond_stmt);
10535 else
10536 gcc_unreachable ();
10539 return true;
10542 return false;
10545 /* Callback for substitute_and_fold folding the stmt at *SI. */
10547 bool
10548 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
10550 if (fold_predicate_in (si))
10551 return true;
10553 return simplify_stmt_using_ranges (si);
10556 /* If OP has a value range with a single constant value return that,
10557 otherwise return NULL_TREE. This returns OP itself if OP is a
10558 constant.
10560 Implemented as a pure wrapper right now, but this will change. */
10562 tree
10563 vrp_folder::get_value (tree op)
10565 return op_with_constant_singleton_value_range (op);
10568 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
10569 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
10570 BB. If no such ASSERT_EXPR is found, return OP. */
10572 static tree
10573 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
10575 imm_use_iterator imm_iter;
10576 gimple *use_stmt;
10577 use_operand_p use_p;
10579 if (TREE_CODE (op) == SSA_NAME)
10581 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
10583 use_stmt = USE_STMT (use_p);
10584 if (use_stmt != stmt
10585 && gimple_assign_single_p (use_stmt)
10586 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
10587 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
10588 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
10589 return gimple_assign_lhs (use_stmt);
10592 return op;
10595 /* A trivial wrapper so that we can present the generic jump threading
10596 code with a simple API for simplifying statements. STMT is the
10597 statement we want to simplify, WITHIN_STMT provides the location
10598 for any overflow warnings. */
10600 static tree
10601 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
10602 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
10603 basic_block bb)
10605 /* First see if the conditional is in the hash table. */
10606 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
10607 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
10608 return cached_lhs;
10610 vr_values *vr_values = x_vr_values;
10611 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10613 tree op0 = gimple_cond_lhs (cond_stmt);
10614 op0 = lhs_of_dominating_assert (op0, bb, stmt);
10616 tree op1 = gimple_cond_rhs (cond_stmt);
10617 op1 = lhs_of_dominating_assert (op1, bb, stmt);
10619 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10620 op0, op1, within_stmt);
10623 /* We simplify a switch statement by trying to determine which case label
10624 will be taken. If we are successful then we return the corresponding
10625 CASE_LABEL_EXPR. */
10626 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
10628 tree op = gimple_switch_index (switch_stmt);
10629 if (TREE_CODE (op) != SSA_NAME)
10630 return NULL_TREE;
10632 op = lhs_of_dominating_assert (op, bb, stmt);
10634 value_range *vr = vr_values->get_value_range (op);
10635 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
10636 || symbolic_range_p (vr))
10637 return NULL_TREE;
10639 if (vr->type == VR_RANGE)
10641 size_t i, j;
10642 /* Get the range of labels that contain a part of the operand's
10643 value range. */
10644 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
10646 /* Is there only one such label? */
10647 if (i == j)
10649 tree label = gimple_switch_label (switch_stmt, i);
10651 /* The i'th label will be taken only if the value range of the
10652 operand is entirely within the bounds of this label. */
10653 if (CASE_HIGH (label) != NULL_TREE
10654 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
10655 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
10656 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
10657 && tree_int_cst_equal (vr->min, vr->max)))
10658 return label;
10661 /* If there are no such labels then the default label will be
10662 taken. */
10663 if (i > j)
10664 return gimple_switch_label (switch_stmt, 0);
10667 if (vr->type == VR_ANTI_RANGE)
10669 unsigned n = gimple_switch_num_labels (switch_stmt);
10670 tree min_label = gimple_switch_label (switch_stmt, 1);
10671 tree max_label = gimple_switch_label (switch_stmt, n - 1);
10673 /* The default label will be taken only if the anti-range of the
10674 operand is entirely outside the bounds of all the (non-default)
10675 case labels. */
10676 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
10677 && (CASE_HIGH (max_label) != NULL_TREE
10678 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
10679 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
10680 return gimple_switch_label (switch_stmt, 0);
10683 return NULL_TREE;
10686 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
10688 value_range new_vr = VR_INITIALIZER;
10689 tree lhs = gimple_assign_lhs (assign_stmt);
10691 if (TREE_CODE (lhs) == SSA_NAME
10692 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10693 || POINTER_TYPE_P (TREE_TYPE (lhs))))
10695 vr_values->extract_range_from_assignment (&new_vr, assign_stmt);
10696 if (range_int_cst_singleton_p (&new_vr))
10697 return new_vr.min;
10701 return NULL_TREE;
10704 class vrp_dom_walker : public dom_walker
10706 public:
10707 vrp_dom_walker (cdi_direction direction,
10708 class const_and_copies *const_and_copies,
10709 class avail_exprs_stack *avail_exprs_stack)
10710 : dom_walker (direction, true),
10711 m_const_and_copies (const_and_copies),
10712 m_avail_exprs_stack (avail_exprs_stack),
10713 m_dummy_cond (NULL) {}
10715 virtual edge before_dom_children (basic_block);
10716 virtual void after_dom_children (basic_block);
10718 class vr_values *vr_values;
10720 private:
10721 class const_and_copies *m_const_and_copies;
10722 class avail_exprs_stack *m_avail_exprs_stack;
10724 gcond *m_dummy_cond;
10728 /* Called before processing dominator children of BB. We want to look
10729 at ASSERT_EXPRs and record information from them in the appropriate
10730 tables.
10732 We could look at other statements here. It's not seen as likely
10733 to significantly increase the jump threads we discover. */
10735 edge
10736 vrp_dom_walker::before_dom_children (basic_block bb)
10738 gimple_stmt_iterator gsi;
10740 m_avail_exprs_stack->push_marker ();
10741 m_const_and_copies->push_marker ();
10742 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
10744 gimple *stmt = gsi_stmt (gsi);
10745 if (gimple_assign_single_p (stmt)
10746 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
10748 tree rhs1 = gimple_assign_rhs1 (stmt);
10749 tree cond = TREE_OPERAND (rhs1, 1);
10750 tree inverted = invert_truthvalue (cond);
10751 vec<cond_equivalence> p;
10752 p.create (3);
10753 record_conditions (&p, cond, inverted);
10754 for (unsigned int i = 0; i < p.length (); i++)
10755 m_avail_exprs_stack->record_cond (&p[i]);
10757 tree lhs = gimple_assign_lhs (stmt);
10758 m_const_and_copies->record_const_or_copy (lhs,
10759 TREE_OPERAND (rhs1, 0));
10760 p.release ();
10761 continue;
10763 break;
10765 return NULL;
10768 /* Called after processing dominator children of BB. This is where we
10769 actually call into the threader. */
10770 void
10771 vrp_dom_walker::after_dom_children (basic_block bb)
10773 if (!m_dummy_cond)
10774 m_dummy_cond = gimple_build_cond (NE_EXPR,
10775 integer_zero_node, integer_zero_node,
10776 NULL, NULL);
10778 x_vr_values = vr_values;
10779 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
10780 m_avail_exprs_stack,
10781 simplify_stmt_for_jump_threading);
10782 x_vr_values = NULL;
10784 m_avail_exprs_stack->pop_to_marker ();
10785 m_const_and_copies->pop_to_marker ();
10788 /* Blocks which have more than one predecessor and more than
10789 one successor present jump threading opportunities, i.e.,
10790 when the block is reached from a specific predecessor, we
10791 may be able to determine which of the outgoing edges will
10792 be traversed. When this optimization applies, we are able
10793 to avoid conditionals at runtime and we may expose secondary
10794 optimization opportunities.
10796 This routine is effectively a driver for the generic jump
10797 threading code. It basically just presents the generic code
10798 with edges that may be suitable for jump threading.
10800 Unlike DOM, we do not iterate VRP if jump threading was successful.
10801 While iterating may expose new opportunities for VRP, it is expected
10802 those opportunities would be very limited and the compile time cost
10803 to expose those opportunities would be significant.
10805 As jump threading opportunities are discovered, they are registered
10806 for later realization. */
10808 static void
10809 identify_jump_threads (class vr_values *vr_values)
10811 int i;
10812 edge e;
10814 /* Ugh. When substituting values earlier in this pass we can
10815 wipe the dominance information. So rebuild the dominator
10816 information as we need it within the jump threading code. */
10817 calculate_dominance_info (CDI_DOMINATORS);
10819 /* We do not allow VRP information to be used for jump threading
10820 across a back edge in the CFG. Otherwise it becomes too
10821 difficult to avoid eliminating loop exit tests. Of course
10822 EDGE_DFS_BACK is not accurate at this time so we have to
10823 recompute it. */
10824 mark_dfs_back_edges ();
10826 /* Do not thread across edges we are about to remove. Just marking
10827 them as EDGE_IGNORE will do. */
10828 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10829 e->flags |= EDGE_IGNORE;
10831 /* Allocate our unwinder stack to unwind any temporary equivalences
10832 that might be recorded. */
10833 const_and_copies *equiv_stack = new const_and_copies ();
10835 hash_table<expr_elt_hasher> *avail_exprs
10836 = new hash_table<expr_elt_hasher> (1024);
10837 avail_exprs_stack *avail_exprs_stack
10838 = new class avail_exprs_stack (avail_exprs);
10840 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
10841 walker.vr_values = vr_values;
10842 walker.walk (cfun->cfg->x_entry_block_ptr);
10844 /* Clear EDGE_IGNORE. */
10845 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10846 e->flags &= ~EDGE_IGNORE;
10848 /* We do not actually update the CFG or SSA graphs at this point as
10849 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
10850 handle ASSERT_EXPRs gracefully. */
10851 delete equiv_stack;
10852 delete avail_exprs;
10853 delete avail_exprs_stack;
10856 /* Free VRP lattice. */
10858 vr_values::~vr_values ()
10860 /* Free allocated memory. */
10861 free (vr_value);
10862 free (vr_phi_edge_counts);
10863 bitmap_obstack_release (&vrp_equiv_obstack);
10864 vrp_value_range_pool.release ();
10866 /* So that we can distinguish between VRP data being available
10867 and not available. */
10868 vr_value = NULL;
10869 vr_phi_edge_counts = NULL;
10872 /* Traverse all the blocks folding conditionals with known ranges. */
10874 void
10875 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
10877 size_t i;
10879 vr_values.values_propagated = true;
10881 if (dump_file)
10883 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
10884 vr_values.dump_all_value_ranges (dump_file);
10885 fprintf (dump_file, "\n");
10888 /* Set value range to non pointer SSA_NAMEs. */
10889 for (i = 0; i < num_ssa_names; i++)
10891 tree name = ssa_name (i);
10892 if (!name)
10893 continue;
10895 value_range *vr = get_value_range (name);
10896 if (!name
10897 || (vr->type == VR_VARYING)
10898 || (vr->type == VR_UNDEFINED)
10899 || (TREE_CODE (vr->min) != INTEGER_CST)
10900 || (TREE_CODE (vr->max) != INTEGER_CST))
10901 continue;
10903 if (POINTER_TYPE_P (TREE_TYPE (name))
10904 && ((vr->type == VR_RANGE
10905 && range_includes_zero_p (vr->min, vr->max) == 0)
10906 || (vr->type == VR_ANTI_RANGE
10907 && range_includes_zero_p (vr->min, vr->max) == 1)))
10908 set_ptr_nonnull (name);
10909 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
10910 set_range_info (name, vr->type,
10911 wi::to_wide (vr->min),
10912 wi::to_wide (vr->max));
10915 class vrp_folder vrp_folder;
10916 vrp_folder.vr_values = &vr_values;
10917 vrp_folder.substitute_and_fold ();
10919 if (warn_array_bounds && warn_array_bounds_p)
10920 check_all_array_refs ();
10923 /* evrp_dom_walker visits the basic blocks in the dominance order and set
10924 the Value Ranges (VR) for SSA_NAMEs in the scope. Use this VR to
10925 discover more VRs. */
10927 class evrp_dom_walker : public dom_walker
10929 public:
10930 evrp_dom_walker ()
10931 : dom_walker (CDI_DOMINATORS), stack (10)
10933 need_eh_cleanup = BITMAP_ALLOC (NULL);
10935 ~evrp_dom_walker ()
10937 BITMAP_FREE (need_eh_cleanup);
10939 virtual edge before_dom_children (basic_block);
10940 virtual void after_dom_children (basic_block);
10941 void push_value_range (tree var, value_range *vr);
10942 value_range *pop_value_range (tree var);
10943 value_range *try_find_new_range (tree, tree op, tree_code code, tree limit);
10945 /* Cond_stack holds the old VR. */
10946 auto_vec<std::pair <tree, value_range*> > stack;
10947 bitmap need_eh_cleanup;
10948 auto_vec<gimple *> stmts_to_fixup;
10949 auto_vec<gimple *> stmts_to_remove;
10951 class vr_values vr_values;
10953 /* Temporary delegators. */
10954 value_range *get_value_range (const_tree op)
10955 { return vr_values.get_value_range (op); }
10956 bool update_value_range (const_tree op, value_range *vr)
10957 { return vr_values.update_value_range (op, vr); }
10958 void extract_range_from_phi_node (gphi *phi, value_range *vr)
10959 { vr_values.extract_range_from_phi_node (phi, vr); }
10960 void extract_range_for_var_from_comparison_expr (tree var,
10961 enum tree_code cond_code,
10962 tree op, tree limit,
10963 value_range *vr_p)
10964 { vr_values.extract_range_for_var_from_comparison_expr (var, cond_code,
10965 op, limit, vr_p); }
10966 void adjust_range_with_scev (value_range *vr, struct loop *loop,
10967 gimple *stmt, tree var)
10968 { vr_values.adjust_range_with_scev (vr, loop, stmt, var); }
10969 tree op_with_constant_singleton_value_range (tree op)
10970 { return vr_values.op_with_constant_singleton_value_range (op); }
10971 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
10972 tree *output_p, value_range *vr)
10973 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
10974 void set_defs_to_varying (gimple *stmt)
10975 { return vr_values.set_defs_to_varying (stmt); }
10976 void set_vr_value (tree name, value_range *vr)
10977 { vr_values.set_vr_value (name, vr); }
10978 void simplify_cond_using_ranges_2 (gcond *stmt)
10979 { vr_values.simplify_cond_using_ranges_2 (stmt); }
10980 void vrp_visit_cond_stmt (gcond *cond, edge *e)
10981 { vr_values.vrp_visit_cond_stmt (cond, e); }
10984 /* Find new range for NAME such that (OP CODE LIMIT) is true. */
10986 value_range *
10987 evrp_dom_walker::try_find_new_range (tree name,
10988 tree op, tree_code code, tree limit)
10990 value_range vr = VR_INITIALIZER;
10991 value_range *old_vr = get_value_range (name);
10993 /* Discover VR when condition is true. */
10994 extract_range_for_var_from_comparison_expr (name, code, op,
10995 limit, &vr);
10996 /* If we found any usable VR, set the VR to ssa_name and create a
10997 PUSH old value in the stack with the old VR. */
10998 if (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE)
11000 if (old_vr->type == vr.type
11001 && vrp_operand_equal_p (old_vr->min, vr.min)
11002 && vrp_operand_equal_p (old_vr->max, vr.max))
11003 return NULL;
11004 value_range *new_vr = vr_values.vrp_value_range_pool.allocate ();
11005 *new_vr = vr;
11006 return new_vr;
11008 return NULL;
11011 /* See if there is any new scope is entered with new VR and set that VR to
11012 ssa_name before visiting the statements in the scope. */
11014 edge
11015 evrp_dom_walker::before_dom_children (basic_block bb)
11017 if (dump_file && (dump_flags & TDF_DETAILS))
11018 fprintf (dump_file, "Visiting BB%d\n", bb->index);
11020 stack.safe_push (std::make_pair (NULL_TREE, (value_range *)NULL));
11022 edge pred_e = single_pred_edge_ignoring_loop_edges (bb, false);
11023 if (pred_e)
11025 gimple *stmt = last_stmt (pred_e->src);
11026 tree op0 = NULL_TREE;
11028 if (stmt
11029 && gimple_code (stmt) == GIMPLE_COND
11030 && (op0 = gimple_cond_lhs (stmt))
11031 && TREE_CODE (op0) == SSA_NAME
11032 && (INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))
11033 || POINTER_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))))
11035 if (dump_file && (dump_flags & TDF_DETAILS))
11037 fprintf (dump_file, "Visiting controlling predicate ");
11038 print_gimple_stmt (dump_file, stmt, 0);
11040 /* Entering a new scope. Try to see if we can find a VR
11041 here. */
11042 tree op1 = gimple_cond_rhs (stmt);
11043 if (TREE_OVERFLOW_P (op1))
11044 op1 = drop_tree_overflow (op1);
11045 tree_code code = gimple_cond_code (stmt);
11047 auto_vec<assert_info, 8> asserts;
11048 register_edge_assert_for (op0, pred_e, code, op0, op1, asserts);
11049 if (TREE_CODE (op1) == SSA_NAME)
11050 register_edge_assert_for (op1, pred_e, code, op0, op1, asserts);
11052 auto_vec<std::pair<tree, value_range *>, 8> vrs;
11053 for (unsigned i = 0; i < asserts.length (); ++i)
11055 value_range *vr = try_find_new_range (asserts[i].name,
11056 asserts[i].expr,
11057 asserts[i].comp_code,
11058 asserts[i].val);
11059 if (vr)
11060 vrs.safe_push (std::make_pair (asserts[i].name, vr));
11062 /* Push updated ranges only after finding all of them to avoid
11063 ordering issues that can lead to worse ranges. */
11064 for (unsigned i = 0; i < vrs.length (); ++i)
11065 push_value_range (vrs[i].first, vrs[i].second);
11069 /* Visit PHI stmts and discover any new VRs possible. */
11070 bool has_unvisited_preds = false;
11071 edge_iterator ei;
11072 edge e;
11073 FOR_EACH_EDGE (e, ei, bb->preds)
11074 if (e->flags & EDGE_EXECUTABLE
11075 && !(e->src->flags & BB_VISITED))
11077 has_unvisited_preds = true;
11078 break;
11081 for (gphi_iterator gpi = gsi_start_phis (bb);
11082 !gsi_end_p (gpi); gsi_next (&gpi))
11084 gphi *phi = gpi.phi ();
11085 tree lhs = PHI_RESULT (phi);
11086 if (virtual_operand_p (lhs))
11087 continue;
11088 value_range vr_result = VR_INITIALIZER;
11089 bool interesting = stmt_interesting_for_vrp (phi);
11090 if (interesting && dump_file && (dump_flags & TDF_DETAILS))
11092 fprintf (dump_file, "Visiting PHI node ");
11093 print_gimple_stmt (dump_file, phi, 0);
11095 if (!has_unvisited_preds
11096 && interesting)
11097 extract_range_from_phi_node (phi, &vr_result);
11098 else
11100 set_value_range_to_varying (&vr_result);
11101 /* When we have an unvisited executable predecessor we can't
11102 use PHI arg ranges which may be still UNDEFINED but have
11103 to use VARYING for them. But we can still resort to
11104 SCEV for loop header PHIs. */
11105 struct loop *l;
11106 if (interesting
11107 && (l = loop_containing_stmt (phi))
11108 && l->header == gimple_bb (phi))
11109 adjust_range_with_scev (&vr_result, l, phi, lhs);
11111 update_value_range (lhs, &vr_result);
11113 /* Mark PHIs whose lhs we fully propagate for removal. */
11114 tree val = op_with_constant_singleton_value_range (lhs);
11115 if (val && may_propagate_copy (lhs, val))
11117 stmts_to_remove.safe_push (phi);
11118 continue;
11121 /* Set the SSA with the value range. */
11122 if (INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
11124 if ((vr_result.type == VR_RANGE
11125 || vr_result.type == VR_ANTI_RANGE)
11126 && (TREE_CODE (vr_result.min) == INTEGER_CST)
11127 && (TREE_CODE (vr_result.max) == INTEGER_CST))
11128 set_range_info (lhs, vr_result.type,
11129 wi::to_wide (vr_result.min),
11130 wi::to_wide (vr_result.max));
11132 else if (POINTER_TYPE_P (TREE_TYPE (lhs))
11133 && ((vr_result.type == VR_RANGE
11134 && range_includes_zero_p (vr_result.min,
11135 vr_result.max) == 0)
11136 || (vr_result.type == VR_ANTI_RANGE
11137 && range_includes_zero_p (vr_result.min,
11138 vr_result.max) == 1)))
11139 set_ptr_nonnull (lhs);
11142 edge taken_edge = NULL;
11144 /* Visit all other stmts and discover any new VRs possible. */
11145 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
11146 !gsi_end_p (gsi); gsi_next (&gsi))
11148 gimple *stmt = gsi_stmt (gsi);
11149 tree output = NULL_TREE;
11150 gimple *old_stmt = stmt;
11151 bool was_noreturn = (is_gimple_call (stmt)
11152 && gimple_call_noreturn_p (stmt));
11154 if (dump_file && (dump_flags & TDF_DETAILS))
11156 fprintf (dump_file, "Visiting stmt ");
11157 print_gimple_stmt (dump_file, stmt, 0);
11160 if (gcond *cond = dyn_cast <gcond *> (stmt))
11162 vrp_visit_cond_stmt (cond, &taken_edge);
11163 if (taken_edge)
11165 if (taken_edge->flags & EDGE_TRUE_VALUE)
11166 gimple_cond_make_true (cond);
11167 else if (taken_edge->flags & EDGE_FALSE_VALUE)
11168 gimple_cond_make_false (cond);
11169 else
11170 gcc_unreachable ();
11171 update_stmt (stmt);
11174 else if (stmt_interesting_for_vrp (stmt))
11176 edge taken_edge;
11177 value_range vr = VR_INITIALIZER;
11178 extract_range_from_stmt (stmt, &taken_edge, &output, &vr);
11179 if (output
11180 && (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE))
11182 update_value_range (output, &vr);
11183 vr = *get_value_range (output);
11185 /* Mark stmts whose output we fully propagate for removal. */
11186 tree val;
11187 if ((val = op_with_constant_singleton_value_range (output))
11188 && may_propagate_copy (output, val)
11189 && !stmt_could_throw_p (stmt)
11190 && !gimple_has_side_effects (stmt))
11192 stmts_to_remove.safe_push (stmt);
11193 continue;
11196 /* Set the SSA with the value range. */
11197 if (INTEGRAL_TYPE_P (TREE_TYPE (output)))
11199 if ((vr.type == VR_RANGE
11200 || vr.type == VR_ANTI_RANGE)
11201 && (TREE_CODE (vr.min) == INTEGER_CST)
11202 && (TREE_CODE (vr.max) == INTEGER_CST))
11203 set_range_info (output, vr.type,
11204 wi::to_wide (vr.min),
11205 wi::to_wide (vr.max));
11207 else if (POINTER_TYPE_P (TREE_TYPE (output))
11208 && ((vr.type == VR_RANGE
11209 && range_includes_zero_p (vr.min,
11210 vr.max) == 0)
11211 || (vr.type == VR_ANTI_RANGE
11212 && range_includes_zero_p (vr.min,
11213 vr.max) == 1)))
11214 set_ptr_nonnull (output);
11216 else
11217 set_defs_to_varying (stmt);
11219 else
11220 set_defs_to_varying (stmt);
11222 /* See if we can derive a range for any of STMT's operands. */
11223 tree op;
11224 ssa_op_iter i;
11225 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
11227 tree value;
11228 enum tree_code comp_code;
11230 /* If OP is used in such a way that we can infer a value
11231 range for it, and we don't find a previous assertion for
11232 it, create a new assertion location node for OP. */
11233 if (infer_value_range (stmt, op, &comp_code, &value))
11235 /* If we are able to infer a nonzero value range for OP,
11236 then walk backwards through the use-def chain to see if OP
11237 was set via a typecast.
11238 If so, then we can also infer a nonzero value range
11239 for the operand of the NOP_EXPR. */
11240 if (comp_code == NE_EXPR && integer_zerop (value))
11242 tree t = op;
11243 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
11244 while (is_gimple_assign (def_stmt)
11245 && CONVERT_EXPR_CODE_P
11246 (gimple_assign_rhs_code (def_stmt))
11247 && TREE_CODE
11248 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
11249 && POINTER_TYPE_P
11250 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
11252 t = gimple_assign_rhs1 (def_stmt);
11253 def_stmt = SSA_NAME_DEF_STMT (t);
11255 /* Add VR when (T COMP_CODE value) condition is
11256 true. */
11257 value_range *op_range
11258 = try_find_new_range (t, t, comp_code, value);
11259 if (op_range)
11260 push_value_range (t, op_range);
11263 /* Add VR when (OP COMP_CODE value) condition is true. */
11264 value_range *op_range = try_find_new_range (op, op,
11265 comp_code, value);
11266 if (op_range)
11267 push_value_range (op, op_range);
11271 /* Try folding stmts with the VR discovered. */
11272 class vrp_folder vrp_folder;
11273 vrp_folder.vr_values = &vr_values;
11274 bool did_replace = vrp_folder.replace_uses_in (stmt);
11275 if (fold_stmt (&gsi, follow_single_use_edges)
11276 || did_replace)
11278 stmt = gsi_stmt (gsi);
11279 update_stmt (stmt);
11280 did_replace = true;
11283 if (did_replace)
11285 /* If we cleaned up EH information from the statement,
11286 remove EH edges. */
11287 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
11288 bitmap_set_bit (need_eh_cleanup, bb->index);
11290 /* If we turned a not noreturn call into a noreturn one
11291 schedule it for fixup. */
11292 if (!was_noreturn
11293 && is_gimple_call (stmt)
11294 && gimple_call_noreturn_p (stmt))
11295 stmts_to_fixup.safe_push (stmt);
11297 if (gimple_assign_single_p (stmt))
11299 tree rhs = gimple_assign_rhs1 (stmt);
11300 if (TREE_CODE (rhs) == ADDR_EXPR)
11301 recompute_tree_invariant_for_addr_expr (rhs);
11306 /* Visit BB successor PHI nodes and replace PHI args. */
11307 FOR_EACH_EDGE (e, ei, bb->succs)
11309 for (gphi_iterator gpi = gsi_start_phis (e->dest);
11310 !gsi_end_p (gpi); gsi_next (&gpi))
11312 gphi *phi = gpi.phi ();
11313 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
11314 tree arg = USE_FROM_PTR (use_p);
11315 if (TREE_CODE (arg) != SSA_NAME
11316 || virtual_operand_p (arg))
11317 continue;
11318 tree val = op_with_constant_singleton_value_range (arg);
11319 if (val && may_propagate_copy (arg, val))
11320 propagate_value (use_p, val);
11324 bb->flags |= BB_VISITED;
11326 return taken_edge;
11329 /* Restore/pop VRs valid only for BB when we leave BB. */
11331 void
11332 evrp_dom_walker::after_dom_children (basic_block bb ATTRIBUTE_UNUSED)
11334 gcc_checking_assert (!stack.is_empty ());
11335 while (stack.last ().first != NULL_TREE)
11336 pop_value_range (stack.last ().first);
11337 stack.pop ();
11340 void
11341 vr_values::set_vr_value (tree var, value_range *vr)
11343 if (SSA_NAME_VERSION (var) >= num_vr_values)
11344 return;
11345 vr_value[SSA_NAME_VERSION (var)] = vr;
11348 /* Push the Value Range of VAR to the stack and update it with new VR. */
11350 void
11351 evrp_dom_walker::push_value_range (tree var, value_range *vr)
11353 if (dump_file && (dump_flags & TDF_DETAILS))
11355 fprintf (dump_file, "pushing new range for ");
11356 print_generic_expr (dump_file, var);
11357 fprintf (dump_file, ": ");
11358 dump_value_range (dump_file, vr);
11359 fprintf (dump_file, "\n");
11361 stack.safe_push (std::make_pair (var, get_value_range (var)));
11362 set_vr_value (var, vr);
11365 /* Pop the Value Range from the vrp_stack and update VAR with it. */
11367 value_range *
11368 evrp_dom_walker::pop_value_range (tree var)
11370 value_range *vr = stack.last ().second;
11371 gcc_checking_assert (var == stack.last ().first);
11372 if (dump_file && (dump_flags & TDF_DETAILS))
11374 fprintf (dump_file, "popping range for ");
11375 print_generic_expr (dump_file, var);
11376 fprintf (dump_file, ", restoring ");
11377 dump_value_range (dump_file, vr);
11378 fprintf (dump_file, "\n");
11380 set_vr_value (var, vr);
11381 stack.pop ();
11382 return vr;
11386 /* Main entry point for the early vrp pass which is a simplified non-iterative
11387 version of vrp where basic blocks are visited in dominance order. Value
11388 ranges discovered in early vrp will also be used by ipa-vrp. */
11390 static unsigned int
11391 execute_early_vrp ()
11393 edge e;
11394 edge_iterator ei;
11395 basic_block bb;
11397 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11398 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11399 scev_initialize ();
11400 calculate_dominance_info (CDI_DOMINATORS);
11401 FOR_EACH_BB_FN (bb, cfun)
11403 bb->flags &= ~BB_VISITED;
11404 FOR_EACH_EDGE (e, ei, bb->preds)
11405 e->flags |= EDGE_EXECUTABLE;
11408 /* Walk stmts in dominance order and propagate VRP. */
11409 evrp_dom_walker walker;
11410 walker.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
11412 if (dump_file)
11414 fprintf (dump_file, "\nValue ranges after Early VRP:\n\n");
11415 walker.vr_values.dump_all_value_ranges (dump_file);
11416 fprintf (dump_file, "\n");
11419 /* Remove stmts in reverse order to make debug stmt creation possible. */
11420 while (! walker.stmts_to_remove.is_empty ())
11422 gimple *stmt = walker.stmts_to_remove.pop ();
11423 if (dump_file && dump_flags & TDF_DETAILS)
11425 fprintf (dump_file, "Removing dead stmt ");
11426 print_gimple_stmt (dump_file, stmt, 0);
11427 fprintf (dump_file, "\n");
11429 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
11430 if (gimple_code (stmt) == GIMPLE_PHI)
11431 remove_phi_node (&gsi, true);
11432 else
11434 unlink_stmt_vdef (stmt);
11435 gsi_remove (&gsi, true);
11436 release_defs (stmt);
11440 if (!bitmap_empty_p (walker.need_eh_cleanup))
11441 gimple_purge_all_dead_eh_edges (walker.need_eh_cleanup);
11443 /* Fixup stmts that became noreturn calls. This may require splitting
11444 blocks and thus isn't possible during the dominator walk. Do this
11445 in reverse order so we don't inadvertedly remove a stmt we want to
11446 fixup by visiting a dominating now noreturn call first. */
11447 while (!walker.stmts_to_fixup.is_empty ())
11449 gimple *stmt = walker.stmts_to_fixup.pop ();
11450 fixup_noreturn_call (stmt);
11453 scev_finalize ();
11454 loop_optimizer_finalize ();
11455 return 0;
11459 /* Main entry point to VRP (Value Range Propagation). This pass is
11460 loosely based on J. R. C. Patterson, ``Accurate Static Branch
11461 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
11462 Programming Language Design and Implementation, pp. 67-78, 1995.
11463 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
11465 This is essentially an SSA-CCP pass modified to deal with ranges
11466 instead of constants.
11468 While propagating ranges, we may find that two or more SSA name
11469 have equivalent, though distinct ranges. For instance,
11471 1 x_9 = p_3->a;
11472 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
11473 3 if (p_4 == q_2)
11474 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
11475 5 endif
11476 6 if (q_2)
11478 In the code above, pointer p_5 has range [q_2, q_2], but from the
11479 code we can also determine that p_5 cannot be NULL and, if q_2 had
11480 a non-varying range, p_5's range should also be compatible with it.
11482 These equivalences are created by two expressions: ASSERT_EXPR and
11483 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
11484 result of another assertion, then we can use the fact that p_5 and
11485 p_4 are equivalent when evaluating p_5's range.
11487 Together with value ranges, we also propagate these equivalences
11488 between names so that we can take advantage of information from
11489 multiple ranges when doing final replacement. Note that this
11490 equivalency relation is transitive but not symmetric.
11492 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
11493 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
11494 in contexts where that assertion does not hold (e.g., in line 6).
11496 TODO, the main difference between this pass and Patterson's is that
11497 we do not propagate edge probabilities. We only compute whether
11498 edges can be taken or not. That is, instead of having a spectrum
11499 of jump probabilities between 0 and 1, we only deal with 0, 1 and
11500 DON'T KNOW. In the future, it may be worthwhile to propagate
11501 probabilities to aid branch prediction. */
11503 static unsigned int
11504 execute_vrp (bool warn_array_bounds_p)
11506 int i;
11507 edge e;
11508 switch_update *su;
11510 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11511 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11512 scev_initialize ();
11514 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
11515 Inserting assertions may split edges which will invalidate
11516 EDGE_DFS_BACK. */
11517 insert_range_assertions ();
11519 to_remove_edges.create (10);
11520 to_update_switch_stmts.create (5);
11521 threadedge_initialize_values ();
11523 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
11524 mark_dfs_back_edges ();
11526 class vrp_prop vrp_prop;
11527 vrp_prop.vrp_initialize ();
11528 vrp_prop.ssa_propagate ();
11529 vrp_prop.vrp_finalize (warn_array_bounds_p);
11531 /* We must identify jump threading opportunities before we release
11532 the datastructures built by VRP. */
11533 identify_jump_threads (&vrp_prop.vr_values);
11535 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
11536 was set by a type conversion can often be rewritten to use the
11537 RHS of the type conversion.
11539 However, doing so inhibits jump threading through the comparison.
11540 So that transformation is not performed until after jump threading
11541 is complete. */
11542 basic_block bb;
11543 FOR_EACH_BB_FN (bb, cfun)
11545 gimple *last = last_stmt (bb);
11546 if (last && gimple_code (last) == GIMPLE_COND)
11547 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
11550 free_numbers_of_iterations_estimates (cfun);
11552 /* ASSERT_EXPRs must be removed before finalizing jump threads
11553 as finalizing jump threads calls the CFG cleanup code which
11554 does not properly handle ASSERT_EXPRs. */
11555 remove_range_assertions ();
11557 /* If we exposed any new variables, go ahead and put them into
11558 SSA form now, before we handle jump threading. This simplifies
11559 interactions between rewriting of _DECL nodes into SSA form
11560 and rewriting SSA_NAME nodes into SSA form after block
11561 duplication and CFG manipulation. */
11562 update_ssa (TODO_update_ssa);
11564 /* We identified all the jump threading opportunities earlier, but could
11565 not transform the CFG at that time. This routine transforms the
11566 CFG and arranges for the dominator tree to be rebuilt if necessary.
11568 Note the SSA graph update will occur during the normal TODO
11569 processing by the pass manager. */
11570 thread_through_all_blocks (false);
11572 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
11573 CFG in a broken state and requires a cfg_cleanup run. */
11574 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
11575 remove_edge (e);
11576 /* Update SWITCH_EXPR case label vector. */
11577 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
11579 size_t j;
11580 size_t n = TREE_VEC_LENGTH (su->vec);
11581 tree label;
11582 gimple_switch_set_num_labels (su->stmt, n);
11583 for (j = 0; j < n; j++)
11584 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
11585 /* As we may have replaced the default label with a regular one
11586 make sure to make it a real default label again. This ensures
11587 optimal expansion. */
11588 label = gimple_switch_label (su->stmt, 0);
11589 CASE_LOW (label) = NULL_TREE;
11590 CASE_HIGH (label) = NULL_TREE;
11593 if (to_remove_edges.length () > 0)
11595 free_dominance_info (CDI_DOMINATORS);
11596 loops_state_set (LOOPS_NEED_FIXUP);
11599 to_remove_edges.release ();
11600 to_update_switch_stmts.release ();
11601 threadedge_finalize_values ();
11603 scev_finalize ();
11604 loop_optimizer_finalize ();
11605 return 0;
11608 namespace {
11610 const pass_data pass_data_vrp =
11612 GIMPLE_PASS, /* type */
11613 "vrp", /* name */
11614 OPTGROUP_NONE, /* optinfo_flags */
11615 TV_TREE_VRP, /* tv_id */
11616 PROP_ssa, /* properties_required */
11617 0, /* properties_provided */
11618 0, /* properties_destroyed */
11619 0, /* todo_flags_start */
11620 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
11623 class pass_vrp : public gimple_opt_pass
11625 public:
11626 pass_vrp (gcc::context *ctxt)
11627 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
11630 /* opt_pass methods: */
11631 opt_pass * clone () { return new pass_vrp (m_ctxt); }
11632 void set_pass_param (unsigned int n, bool param)
11634 gcc_assert (n == 0);
11635 warn_array_bounds_p = param;
11637 virtual bool gate (function *) { return flag_tree_vrp != 0; }
11638 virtual unsigned int execute (function *)
11639 { return execute_vrp (warn_array_bounds_p); }
11641 private:
11642 bool warn_array_bounds_p;
11643 }; // class pass_vrp
11645 } // anon namespace
11647 gimple_opt_pass *
11648 make_pass_vrp (gcc::context *ctxt)
11650 return new pass_vrp (ctxt);
11653 namespace {
11655 const pass_data pass_data_early_vrp =
11657 GIMPLE_PASS, /* type */
11658 "evrp", /* name */
11659 OPTGROUP_NONE, /* optinfo_flags */
11660 TV_TREE_EARLY_VRP, /* tv_id */
11661 PROP_ssa, /* properties_required */
11662 0, /* properties_provided */
11663 0, /* properties_destroyed */
11664 0, /* todo_flags_start */
11665 ( TODO_cleanup_cfg | TODO_update_ssa | TODO_verify_all ),
11668 class pass_early_vrp : public gimple_opt_pass
11670 public:
11671 pass_early_vrp (gcc::context *ctxt)
11672 : gimple_opt_pass (pass_data_early_vrp, ctxt)
11675 /* opt_pass methods: */
11676 opt_pass * clone () { return new pass_early_vrp (m_ctxt); }
11677 virtual bool gate (function *)
11679 return flag_tree_vrp != 0;
11681 virtual unsigned int execute (function *)
11682 { return execute_early_vrp (); }
11684 }; // class pass_vrp
11685 } // anon namespace
11687 gimple_opt_pass *
11688 make_pass_early_vrp (gcc::context *ctxt)
11690 return new pass_early_vrp (ctxt);