c++: catch parm initialization tweak
[official-gcc.git] / gcc / vr-values.cc
blob71fed1e6a7e5c63abfd7497a8b7f631e554217a6
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2022 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "backend.h"
24 #include "insn-codes.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "ssa.h"
28 #include "optabs-tree.h"
29 #include "gimple-pretty-print.h"
30 #include "diagnostic-core.h"
31 #include "flags.h"
32 #include "fold-const.h"
33 #include "calls.h"
34 #include "cfganal.h"
35 #include "gimple-iterator.h"
36 #include "gimple-fold.h"
37 #include "tree-cfg.h"
38 #include "tree-ssa-loop-niter.h"
39 #include "tree-ssa-loop.h"
40 #include "intl.h"
41 #include "cfgloop.h"
42 #include "tree-scalar-evolution.h"
43 #include "tree-ssa-propagate.h"
44 #include "tree-chrec.h"
45 #include "omp-general.h"
46 #include "case-cfn-macros.h"
47 #include "alloc-pool.h"
48 #include "attribs.h"
49 #include "range.h"
50 #include "vr-values.h"
51 #include "cfghooks.h"
52 #include "range-op.h"
53 #include "gimple-range.h"
55 /* Set value range VR to a non-negative range of type TYPE. */
57 static inline void
58 set_value_range_to_nonnegative (value_range_equiv *vr, tree type)
60 tree zero = build_int_cst (type, 0);
61 vr->update (zero, vrp_val_max (type));
64 /* Set value range VR to a range of a truthvalue of type TYPE. */
66 static inline void
67 set_value_range_to_truthvalue (value_range_equiv *vr, tree type)
69 if (TYPE_PRECISION (type) == 1)
70 vr->set_varying (type);
71 else
72 vr->update (build_int_cst (type, 0), build_int_cst (type, 1));
75 /* Return the lattice entry for VAR or NULL if it doesn't exist or cannot
76 be initialized. */
78 value_range_equiv *
79 vr_values::get_lattice_entry (const_tree var)
81 value_range_equiv *vr;
82 tree sym;
83 unsigned ver = SSA_NAME_VERSION (var);
85 /* If we query the entry for a new SSA name avoid reallocating the lattice
86 since we should get here at most from the substitute-and-fold stage which
87 will never try to change values. */
88 if (ver >= num_vr_values)
89 return NULL;
91 vr = vr_value[ver];
92 if (vr)
93 return vr;
95 /* Create a default value range. */
96 vr = allocate_value_range_equiv ();
97 vr_value[ver] = vr;
99 /* After propagation finished return varying. */
100 if (values_propagated)
102 vr->set_varying (TREE_TYPE (var));
103 return vr;
106 vr->set_undefined ();
108 /* If VAR is a default definition of a parameter, the variable can
109 take any value in VAR's type. */
110 if (SSA_NAME_IS_DEFAULT_DEF (var))
112 sym = SSA_NAME_VAR (var);
113 if (TREE_CODE (sym) == PARM_DECL)
115 /* Try to use the "nonnull" attribute to create ~[0, 0]
116 anti-ranges for pointers. Note that this is only valid with
117 default definitions of PARM_DECLs. */
118 if (POINTER_TYPE_P (TREE_TYPE (sym))
119 && (nonnull_arg_p (sym)
120 || (get_global_range_query ()->range_of_expr (*vr,
121 const_cast <tree> (var))
122 && vr->nonzero_p ())))
124 vr->set_nonzero (TREE_TYPE (sym));
125 vr->equiv_clear ();
127 else if (INTEGRAL_TYPE_P (TREE_TYPE (sym)))
129 get_global_range_query ()->range_of_expr (*vr, const_cast <tree> (var));
130 if (vr->undefined_p ())
131 vr->set_varying (TREE_TYPE (sym));
133 else
134 vr->set_varying (TREE_TYPE (sym));
136 else if (TREE_CODE (sym) == RESULT_DECL
137 && DECL_BY_REFERENCE (sym))
139 vr->set_nonzero (TREE_TYPE (sym));
140 vr->equiv_clear ();
144 return vr;
147 /* Return value range information for VAR.
149 If we have no values ranges recorded (ie, VRP is not running), then
150 return NULL. Otherwise create an empty range if none existed for VAR. */
152 const value_range_equiv *
153 vr_values::get_value_range (const_tree var,
154 gimple *stmt ATTRIBUTE_UNUSED)
156 /* If we have no recorded ranges, then return NULL. */
157 if (!vr_value)
158 return NULL;
160 value_range_equiv *vr = get_lattice_entry (var);
162 /* Reallocate the lattice if needed. */
163 if (!vr)
165 unsigned int old_sz = num_vr_values;
166 num_vr_values = num_ssa_names + num_ssa_names / 10;
167 vr_value = XRESIZEVEC (value_range_equiv *, vr_value, num_vr_values);
168 for ( ; old_sz < num_vr_values; old_sz++)
169 vr_value [old_sz] = NULL;
171 /* Now that the lattice has been resized, we should never fail. */
172 vr = get_lattice_entry (var);
173 gcc_assert (vr);
176 return vr;
179 bool
180 vr_values::range_of_expr (vrange &r, tree expr, gimple *stmt)
182 if (!gimple_range_ssa_p (expr))
183 return get_tree_range (r, expr, stmt);
185 if (const value_range *vr = get_value_range (expr, stmt))
187 if (!vr->supports_type_p (TREE_TYPE (expr)))
189 // vr_values::extract_range_basic() use of ranger's
190 // fold_range() can create a situation where we are asked
191 // for the range of an unsupported legacy type. Since
192 // get_value_range() above will return varying or undefined
193 // for such types, avoid copying incompatible range types.
194 if (vr->undefined_p ())
195 r.set_undefined ();
196 else
197 r.set_varying (TREE_TYPE (expr));
198 return true;
200 if (vr->undefined_p () || vr->constant_p ())
201 r = *vr;
202 else
204 value_range tmp = *vr;
205 tmp.normalize_symbolics ();
206 r = tmp;
208 return true;
210 return false;
213 tree
214 vr_values::value_of_expr (tree op, gimple *)
216 return op_with_constant_singleton_value_range (op);
219 tree
220 vr_values::value_on_edge (edge, tree op)
222 return op_with_constant_singleton_value_range (op);
225 tree
226 vr_values::value_of_stmt (gimple *stmt, tree op)
228 if (!op)
229 op = gimple_get_lhs (stmt);
231 gcc_checking_assert (!op|| op == gimple_get_lhs (stmt));
233 if (op)
234 return op_with_constant_singleton_value_range (op);
235 return NULL_TREE;
238 /* Set the lattice entry for DEF to VARYING. */
240 void
241 vr_values::set_def_to_varying (const_tree def)
243 value_range_equiv *vr = get_lattice_entry (def);
244 if (vr)
245 vr->set_varying (TREE_TYPE (def));
248 /* Set value-ranges of all SSA names defined by STMT to varying. */
250 void
251 vr_values::set_defs_to_varying (gimple *stmt)
253 ssa_op_iter i;
254 tree def;
255 FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
256 set_def_to_varying (def);
259 /* Update the value range and equivalence set for variable VAR to
260 NEW_VR. Return true if NEW_VR is different from VAR's previous
261 value.
263 NOTE: This function assumes that NEW_VR is a temporary value range
264 object created for the sole purpose of updating VAR's range. The
265 storage used by the equivalence set from NEW_VR will be freed by
266 this function. Do not call update_value_range when NEW_VR
267 is the range object associated with another SSA name. */
269 bool
270 vr_values::update_value_range (const_tree var, value_range_equiv *new_vr)
272 value_range_equiv *old_vr;
273 bool is_new;
275 /* If there is a value-range on the SSA name from earlier analysis
276 factor that in. */
277 if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
279 value_range_equiv nr;
280 get_global_range_query ()->range_of_expr (nr, const_cast <tree> (var));
281 if (!nr.undefined_p ())
282 new_vr->legacy_verbose_intersect (&nr);
285 /* Update the value range, if necessary. If we cannot allocate a lattice
286 entry for VAR keep it at VARYING. This happens when DOM feeds us stmts
287 with SSA names allocated after setting up the lattice. */
288 old_vr = get_lattice_entry (var);
289 if (!old_vr)
290 return false;
291 is_new = !old_vr->equal_p (*new_vr, /*ignore_equivs=*/false);
293 if (is_new)
295 /* Do not allow transitions up the lattice. The following
296 is slightly more awkward than just new_vr->type < old_vr->type
297 because VR_RANGE and VR_ANTI_RANGE need to be considered
298 the same. We may not have is_new when transitioning to
299 UNDEFINED. If old_vr->type is VARYING, we shouldn't be
300 called, if we are anyway, keep it VARYING. */
301 if (old_vr->varying_p ())
303 new_vr->set_varying (TREE_TYPE (var));
304 is_new = false;
306 else if (new_vr->undefined_p ())
308 old_vr->set_varying (TREE_TYPE (var));
309 new_vr->set_varying (TREE_TYPE (var));
310 return true;
312 else
313 old_vr->set (new_vr->min (), new_vr->max (), new_vr->equiv (),
314 new_vr->kind ());
317 new_vr->equiv_clear ();
319 return is_new;
322 /* Return true if value range VR involves exactly one symbol SYM. */
324 static bool
325 symbolic_range_based_on_p (value_range *vr, const_tree sym)
327 bool neg, min_has_symbol, max_has_symbol;
328 tree inv;
330 if (is_gimple_min_invariant (vr->min ()))
331 min_has_symbol = false;
332 else if (get_single_symbol (vr->min (), &neg, &inv) == sym)
333 min_has_symbol = true;
334 else
335 return false;
337 if (is_gimple_min_invariant (vr->max ()))
338 max_has_symbol = false;
339 else if (get_single_symbol (vr->max (), &neg, &inv) == sym)
340 max_has_symbol = true;
341 else
342 return false;
344 return (min_has_symbol || max_has_symbol);
347 /* Return true if the result of assignment STMT is know to be non-zero. */
349 static bool
350 gimple_assign_nonzero_p (gimple *stmt)
352 enum tree_code code = gimple_assign_rhs_code (stmt);
353 bool strict_overflow_p;
354 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
355 switch (get_gimple_rhs_class (code))
357 case GIMPLE_UNARY_RHS:
358 return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
359 type,
360 gimple_assign_rhs1 (stmt),
361 &strict_overflow_p);
362 case GIMPLE_BINARY_RHS:
363 return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
364 type,
365 gimple_assign_rhs1 (stmt),
366 gimple_assign_rhs2 (stmt),
367 &strict_overflow_p);
368 case GIMPLE_TERNARY_RHS:
369 return false;
370 case GIMPLE_SINGLE_RHS:
371 return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
372 &strict_overflow_p);
373 case GIMPLE_INVALID_RHS:
374 gcc_unreachable ();
375 default:
376 gcc_unreachable ();
380 /* Return true if STMT is known to compute a non-zero value. */
382 static bool
383 gimple_stmt_nonzero_p (gimple *stmt)
385 switch (gimple_code (stmt))
387 case GIMPLE_ASSIGN:
388 return gimple_assign_nonzero_p (stmt);
389 case GIMPLE_CALL:
391 gcall *call_stmt = as_a<gcall *> (stmt);
392 return (gimple_call_nonnull_result_p (call_stmt)
393 || gimple_call_nonnull_arg (call_stmt));
395 default:
396 gcc_unreachable ();
399 /* Like tree_expr_nonzero_p, but this function uses value ranges
400 obtained so far. */
402 bool
403 vr_values::vrp_stmt_computes_nonzero (gimple *stmt)
405 if (gimple_stmt_nonzero_p (stmt))
406 return true;
408 /* If we have an expression of the form &X->a, then the expression
409 is nonnull if X is nonnull. */
410 if (is_gimple_assign (stmt)
411 && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
413 tree expr = gimple_assign_rhs1 (stmt);
414 poly_int64 bitsize, bitpos;
415 tree offset;
416 machine_mode mode;
417 int unsignedp, reversep, volatilep;
418 tree base = get_inner_reference (TREE_OPERAND (expr, 0), &bitsize,
419 &bitpos, &offset, &mode, &unsignedp,
420 &reversep, &volatilep);
422 if (base != NULL_TREE
423 && TREE_CODE (base) == MEM_REF
424 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
426 poly_offset_int off = 0;
427 bool off_cst = false;
428 if (offset == NULL_TREE || TREE_CODE (offset) == INTEGER_CST)
430 off = mem_ref_offset (base);
431 if (offset)
432 off += poly_offset_int::from (wi::to_poly_wide (offset),
433 SIGNED);
434 off <<= LOG2_BITS_PER_UNIT;
435 off += bitpos;
436 off_cst = true;
438 /* If &X->a is equal to X and X is ~[0, 0], the result is too.
439 For -fdelete-null-pointer-checks -fno-wrapv-pointer we don't
440 allow going from non-NULL pointer to NULL. */
441 if ((off_cst && known_eq (off, 0))
442 || (flag_delete_null_pointer_checks
443 && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (expr))))
445 const value_range_equiv *vr
446 = get_value_range (TREE_OPERAND (base, 0), stmt);
447 if (!range_includes_zero_p (vr))
448 return true;
450 /* If MEM_REF has a "positive" offset, consider it non-NULL
451 always, for -fdelete-null-pointer-checks also "negative"
452 ones. Punt for unknown offsets (e.g. variable ones). */
453 if (!TYPE_OVERFLOW_WRAPS (TREE_TYPE (expr))
454 && off_cst
455 && known_ne (off, 0)
456 && (flag_delete_null_pointer_checks || known_gt (off, 0)))
457 return true;
461 return false;
464 /* Returns true if EXPR is a valid value (as expected by compare_values) --
465 a gimple invariant, or SSA_NAME +- CST. */
467 static bool
468 valid_value_p (tree expr)
470 if (TREE_CODE (expr) == SSA_NAME)
471 return true;
473 if (TREE_CODE (expr) == PLUS_EXPR
474 || TREE_CODE (expr) == MINUS_EXPR)
475 return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
476 && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
478 return is_gimple_min_invariant (expr);
481 /* If OP has a value range with a single constant value return that,
482 otherwise return NULL_TREE. This returns OP itself if OP is a
483 constant. */
485 tree
486 vr_values::op_with_constant_singleton_value_range (tree op)
488 if (is_gimple_min_invariant (op))
489 return op;
491 if (TREE_CODE (op) != SSA_NAME)
492 return NULL_TREE;
494 tree t;
495 if (get_value_range (op)->singleton_p (&t))
496 return t;
497 return NULL;
500 /* Return true if op is in a boolean [0, 1] value-range. */
502 bool
503 simplify_using_ranges::op_with_boolean_value_range_p (tree op, gimple *s)
505 if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
506 return true;
508 if (integer_zerop (op)
509 || integer_onep (op))
510 return true;
512 if (TREE_CODE (op) != SSA_NAME)
513 return false;
515 /* ?? Errr, this should probably check for [0,0] and [1,1] as well
516 as [0,1]. */
517 const value_range *vr = query->get_value_range (op, s);
518 return *vr == value_range (build_zero_cst (TREE_TYPE (op)),
519 build_one_cst (TREE_TYPE (op)));
522 /* Extract value range information for VAR when (OP COND_CODE LIMIT) is
523 true and store it in *VR_P. */
525 void
526 vr_values::extract_range_for_var_from_comparison_expr (tree var,
527 enum tree_code cond_code,
528 tree op, tree limit,
529 value_range_equiv *vr_p)
531 tree min, max, type;
532 const value_range_equiv *limit_vr;
533 type = TREE_TYPE (var);
535 /* For pointer arithmetic, we only keep track of pointer equality
536 and inequality. If we arrive here with unfolded conditions like
537 _1 > _1 do not derive anything. */
538 if ((POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
539 || limit == var)
541 vr_p->set_varying (type);
542 return;
545 /* If LIMIT is another SSA name and LIMIT has a range of its own,
546 try to use LIMIT's range to avoid creating symbolic ranges
547 unnecessarily. */
548 limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
550 /* LIMIT's range is only interesting if it has any useful information. */
551 if (! limit_vr
552 || limit_vr->undefined_p ()
553 || limit_vr->varying_p ()
554 || (limit_vr->symbolic_p ()
555 && ! (limit_vr->kind () == VR_RANGE
556 && (limit_vr->min () == limit_vr->max ()
557 || operand_equal_p (limit_vr->min (),
558 limit_vr->max (), 0)))))
559 limit_vr = NULL;
561 /* Initially, the new range has the same set of equivalences of
562 VAR's range. This will be revised before returning the final
563 value. Since assertions may be chained via mutually exclusive
564 predicates, we will need to trim the set of equivalences before
565 we are done. */
566 gcc_assert (vr_p->equiv () == NULL);
567 vr_p->equiv_add (var, get_value_range (var), &vrp_equiv_obstack);
569 /* Extract a new range based on the asserted comparison for VAR and
570 LIMIT's value range. Notice that if LIMIT has an anti-range, we
571 will only use it for equality comparisons (EQ_EXPR). For any
572 other kind of assertion, we cannot derive a range from LIMIT's
573 anti-range that can be used to describe the new range. For
574 instance, ASSERT_EXPR <x_2, x_2 <= b_4>. If b_4 is ~[2, 10],
575 then b_4 takes on the ranges [-INF, 1] and [11, +INF]. There is
576 no single range for x_2 that could describe LE_EXPR, so we might
577 as well build the range [b_4, +INF] for it.
578 One special case we handle is extracting a range from a
579 range test encoded as (unsigned)var + CST <= limit. */
580 if (TREE_CODE (op) == NOP_EXPR
581 || TREE_CODE (op) == PLUS_EXPR)
583 if (TREE_CODE (op) == PLUS_EXPR)
585 min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (op, 1)),
586 TREE_OPERAND (op, 1));
587 max = int_const_binop (PLUS_EXPR, limit, min);
588 op = TREE_OPERAND (op, 0);
590 else
592 min = build_int_cst (TREE_TYPE (var), 0);
593 max = limit;
596 /* Make sure to not set TREE_OVERFLOW on the final type
597 conversion. We are willingly interpreting large positive
598 unsigned values as negative signed values here. */
599 min = force_fit_type (TREE_TYPE (var), wi::to_widest (min), 0, false);
600 max = force_fit_type (TREE_TYPE (var), wi::to_widest (max), 0, false);
602 /* We can transform a max, min range to an anti-range or
603 vice-versa. Use set_and_canonicalize which does this for
604 us. */
605 if (cond_code == LE_EXPR)
606 vr_p->set (min, max, vr_p->equiv ());
607 else if (cond_code == GT_EXPR)
608 vr_p->set (min, max, vr_p->equiv (), VR_ANTI_RANGE);
609 else
610 gcc_unreachable ();
612 else if (cond_code == EQ_EXPR)
614 enum value_range_kind range_kind;
616 if (limit_vr)
618 range_kind = limit_vr->kind ();
619 min = limit_vr->min ();
620 max = limit_vr->max ();
622 else
624 range_kind = VR_RANGE;
625 min = limit;
626 max = limit;
629 vr_p->update (min, max, range_kind);
631 /* When asserting the equality VAR == LIMIT and LIMIT is another
632 SSA name, the new range will also inherit the equivalence set
633 from LIMIT. */
634 if (TREE_CODE (limit) == SSA_NAME)
635 vr_p->equiv_add (limit, get_value_range (limit), &vrp_equiv_obstack);
637 else if (cond_code == NE_EXPR)
639 /* As described above, when LIMIT's range is an anti-range and
640 this assertion is an inequality (NE_EXPR), then we cannot
641 derive anything from the anti-range. For instance, if
642 LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
643 not imply that VAR's range is [0, 0]. So, in the case of
644 anti-ranges, we just assert the inequality using LIMIT and
645 not its anti-range.
647 If LIMIT_VR is a range, we can only use it to build a new
648 anti-range if LIMIT_VR is a single-valued range. For
649 instance, if LIMIT_VR is [0, 1], the predicate
650 VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
651 Rather, it means that for value 0 VAR should be ~[0, 0]
652 and for value 1, VAR should be ~[1, 1]. We cannot
653 represent these ranges.
655 The only situation in which we can build a valid
656 anti-range is when LIMIT_VR is a single-valued range
657 (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX). In that case,
658 build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX]. */
659 if (limit_vr
660 && limit_vr->kind () == VR_RANGE
661 && compare_values (limit_vr->min (), limit_vr->max ()) == 0)
663 min = limit_vr->min ();
664 max = limit_vr->max ();
666 else
668 /* In any other case, we cannot use LIMIT's range to build a
669 valid anti-range. */
670 min = max = limit;
673 /* If MIN and MAX cover the whole range for their type, then
674 just use the original LIMIT. */
675 if (INTEGRAL_TYPE_P (type)
676 && vrp_val_is_min (min)
677 && vrp_val_is_max (max))
678 min = max = limit;
680 vr_p->set (min, max, vr_p->equiv (), VR_ANTI_RANGE);
682 else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
684 min = TYPE_MIN_VALUE (type);
686 if (limit_vr == NULL || limit_vr->kind () == VR_ANTI_RANGE)
687 max = limit;
688 else
690 /* If LIMIT_VR is of the form [N1, N2], we need to build the
691 range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
692 LT_EXPR. */
693 max = limit_vr->max ();
696 /* If the maximum value forces us to be out of bounds, simply punt.
697 It would be pointless to try and do anything more since this
698 all should be optimized away above us. */
699 if (cond_code == LT_EXPR
700 && compare_values (max, min) == 0)
701 vr_p->set_varying (TREE_TYPE (min));
702 else
704 /* For LT_EXPR, we create the range [MIN, MAX - 1]. */
705 if (cond_code == LT_EXPR)
707 if (TYPE_PRECISION (TREE_TYPE (max)) == 1
708 && !TYPE_UNSIGNED (TREE_TYPE (max)))
709 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
710 build_int_cst (TREE_TYPE (max), -1));
711 else
712 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
713 build_int_cst (TREE_TYPE (max), 1));
714 /* Signal to compare_values_warnv this expr doesn't overflow. */
715 if (EXPR_P (max))
716 suppress_warning (max, OPT_Woverflow);
719 vr_p->update (min, max);
722 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
724 max = TYPE_MAX_VALUE (type);
726 if (limit_vr == NULL || limit_vr->kind () == VR_ANTI_RANGE)
727 min = limit;
728 else
730 /* If LIMIT_VR is of the form [N1, N2], we need to build the
731 range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
732 GT_EXPR. */
733 min = limit_vr->min ();
736 /* If the minimum value forces us to be out of bounds, simply punt.
737 It would be pointless to try and do anything more since this
738 all should be optimized away above us. */
739 if (cond_code == GT_EXPR
740 && compare_values (min, max) == 0)
741 vr_p->set_varying (TREE_TYPE (min));
742 else
744 /* For GT_EXPR, we create the range [MIN + 1, MAX]. */
745 if (cond_code == GT_EXPR)
747 if (TYPE_PRECISION (TREE_TYPE (min)) == 1
748 && !TYPE_UNSIGNED (TREE_TYPE (min)))
749 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
750 build_int_cst (TREE_TYPE (min), -1));
751 else
752 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
753 build_int_cst (TREE_TYPE (min), 1));
754 /* Signal to compare_values_warnv this expr doesn't overflow. */
755 if (EXPR_P (min))
756 suppress_warning (min, OPT_Woverflow);
759 vr_p->update (min, max);
762 else
763 gcc_unreachable ();
765 /* Finally intersect the new range with what we already know about var. */
766 vr_p->legacy_verbose_intersect (get_value_range (var));
769 /* Extract value range information from an ASSERT_EXPR EXPR and store
770 it in *VR_P. */
772 void
773 vr_values::extract_range_from_assert (value_range_equiv *vr_p, tree expr)
775 tree var = ASSERT_EXPR_VAR (expr);
776 tree cond = ASSERT_EXPR_COND (expr);
777 tree limit, op;
778 enum tree_code cond_code;
779 gcc_assert (COMPARISON_CLASS_P (cond));
781 /* Find VAR in the ASSERT_EXPR conditional. */
782 if (var == TREE_OPERAND (cond, 0)
783 || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
784 || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
786 /* If the predicate is of the form VAR COMP LIMIT, then we just
787 take LIMIT from the RHS and use the same comparison code. */
788 cond_code = TREE_CODE (cond);
789 limit = TREE_OPERAND (cond, 1);
790 op = TREE_OPERAND (cond, 0);
792 else
794 /* If the predicate is of the form LIMIT COMP VAR, then we need
795 to flip around the comparison code to create the proper range
796 for VAR. */
797 cond_code = swap_tree_comparison (TREE_CODE (cond));
798 limit = TREE_OPERAND (cond, 0);
799 op = TREE_OPERAND (cond, 1);
801 extract_range_for_var_from_comparison_expr (var, cond_code, op,
802 limit, vr_p);
805 /* Extract range information from SSA name VAR and store it in VR. If
806 VAR has an interesting range, use it. Otherwise, create the
807 range [VAR, VAR] and return it. This is useful in situations where
808 we may have conditionals testing values of VARYING names. For
809 instance,
811 x_3 = y_5;
812 if (x_3 > y_5)
815 Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
816 always false. */
818 void
819 vr_values::extract_range_from_ssa_name (value_range_equiv *vr, tree var)
821 const value_range_equiv *var_vr = get_value_range (var);
823 if (!var_vr->varying_p ())
824 vr->deep_copy (var_vr);
825 else
826 vr->set (var);
828 if (!vr->undefined_p ())
829 vr->equiv_add (var, get_value_range (var), &vrp_equiv_obstack);
832 /* Extract range information from a binary expression OP0 CODE OP1 based on
833 the ranges of each of its operands with resulting type EXPR_TYPE.
834 The resulting range is stored in *VR. */
836 void
837 vr_values::extract_range_from_binary_expr (value_range_equiv *vr,
838 enum tree_code code,
839 tree expr_type, tree op0, tree op1)
841 /* Get value ranges for each operand. For constant operands, create
842 a new value range with the operand to simplify processing. */
843 value_range vr0, vr1;
844 if (TREE_CODE (op0) == SSA_NAME)
845 vr0 = *(get_value_range (op0));
846 else if (is_gimple_min_invariant (op0))
847 vr0.set (op0, op0);
848 else
849 vr0.set_varying (TREE_TYPE (op0));
851 if (TREE_CODE (op1) == SSA_NAME)
852 vr1 = *(get_value_range (op1));
853 else if (is_gimple_min_invariant (op1))
854 vr1.set (op1, op1);
855 else
856 vr1.set_varying (TREE_TYPE (op1));
858 /* If one argument is varying, we can sometimes still deduce a
859 range for the output: any + [3, +INF] is in [MIN+3, +INF]. */
860 if (INTEGRAL_TYPE_P (TREE_TYPE (op0))
861 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0)))
863 if (vr0.varying_p () && !vr1.varying_p ())
864 vr0 = value_range (vrp_val_min (expr_type), vrp_val_max (expr_type));
865 else if (vr1.varying_p () && !vr0.varying_p ())
866 vr1 = value_range (vrp_val_min (expr_type), vrp_val_max (expr_type));
869 range_fold_binary_expr (vr, code, expr_type, &vr0, &vr1);
871 /* Set value_range for n in following sequence:
872 def = __builtin_memchr (arg, 0, sz)
873 n = def - arg
874 Here the range for n can be set to [0, PTRDIFF_MAX - 1]. */
876 if (vr->varying_p ()
877 && code == POINTER_DIFF_EXPR
878 && TREE_CODE (op0) == SSA_NAME
879 && TREE_CODE (op1) == SSA_NAME)
881 tree op0_ptype = TREE_TYPE (TREE_TYPE (op0));
882 tree op1_ptype = TREE_TYPE (TREE_TYPE (op1));
883 gcall *call_stmt = NULL;
885 if (TYPE_MODE (op0_ptype) == TYPE_MODE (char_type_node)
886 && TYPE_PRECISION (op0_ptype) == TYPE_PRECISION (char_type_node)
887 && TYPE_MODE (op1_ptype) == TYPE_MODE (char_type_node)
888 && TYPE_PRECISION (op1_ptype) == TYPE_PRECISION (char_type_node)
889 && (call_stmt = dyn_cast<gcall *>(SSA_NAME_DEF_STMT (op0)))
890 && gimple_call_builtin_p (call_stmt, BUILT_IN_MEMCHR)
891 && operand_equal_p (op0, gimple_call_lhs (call_stmt), 0)
892 && operand_equal_p (op1, gimple_call_arg (call_stmt, 0), 0)
893 && integer_zerop (gimple_call_arg (call_stmt, 1)))
895 tree max = vrp_val_max (ptrdiff_type_node);
896 wide_int wmax = wi::to_wide (max, TYPE_PRECISION (TREE_TYPE (max)));
897 tree range_min = build_zero_cst (expr_type);
898 tree range_max = wide_int_to_tree (expr_type, wmax - 1);
899 vr->set (range_min, range_max, NULL);
900 return;
904 /* Try harder for PLUS and MINUS if the range of one operand is symbolic
905 and based on the other operand, for example if it was deduced from a
906 symbolic comparison. When a bound of the range of the first operand
907 is invariant, we set the corresponding bound of the new range to INF
908 in order to avoid recursing on the range of the second operand. */
909 if (vr->varying_p ()
910 && (code == PLUS_EXPR || code == MINUS_EXPR)
911 && TREE_CODE (op1) == SSA_NAME
912 && vr0.kind () == VR_RANGE
913 && symbolic_range_based_on_p (&vr0, op1))
915 const bool minus_p = (code == MINUS_EXPR);
916 value_range n_vr1;
918 /* Try with VR0 and [-INF, OP1]. */
919 if (is_gimple_min_invariant (minus_p ? vr0.max () : vr0.min ()))
920 n_vr1.set (vrp_val_min (expr_type), op1);
922 /* Try with VR0 and [OP1, +INF]. */
923 else if (is_gimple_min_invariant (minus_p ? vr0.min () : vr0.max ()))
924 n_vr1.set (op1, vrp_val_max (expr_type));
926 /* Try with VR0 and [OP1, OP1]. */
927 else
928 n_vr1.set (op1, op1);
930 range_fold_binary_expr (vr, code, expr_type, &vr0, &n_vr1);
933 if (vr->varying_p ()
934 && (code == PLUS_EXPR || code == MINUS_EXPR)
935 && TREE_CODE (op0) == SSA_NAME
936 && vr1.kind () == VR_RANGE
937 && symbolic_range_based_on_p (&vr1, op0))
939 const bool minus_p = (code == MINUS_EXPR);
940 value_range n_vr0;
942 /* Try with [-INF, OP0] and VR1. */
943 if (is_gimple_min_invariant (minus_p ? vr1.max () : vr1.min ()))
944 n_vr0.set (vrp_val_min (expr_type), op0);
946 /* Try with [OP0, +INF] and VR1. */
947 else if (is_gimple_min_invariant (minus_p ? vr1.min (): vr1.max ()))
948 n_vr0.set (op0, vrp_val_max (expr_type));
950 /* Try with [OP0, OP0] and VR1. */
951 else
952 n_vr0.set (op0, op0);
954 range_fold_binary_expr (vr, code, expr_type, &n_vr0, &vr1);
957 /* If we didn't derive a range for MINUS_EXPR, and
958 op1's range is ~[op0,op0] or vice-versa, then we
959 can derive a non-null range. This happens often for
960 pointer subtraction. */
961 if (vr->varying_p ()
962 && (code == MINUS_EXPR || code == POINTER_DIFF_EXPR)
963 && TREE_CODE (op0) == SSA_NAME
964 && ((vr0.kind () == VR_ANTI_RANGE
965 && vr0.min () == op1
966 && vr0.min () == vr0.max ())
967 || (vr1.kind () == VR_ANTI_RANGE
968 && vr1.min () == op0
969 && vr1.min () == vr1.max ())))
971 vr->set_nonzero (expr_type);
972 vr->equiv_clear ();
976 /* Extract range information from a unary expression CODE OP0 based on
977 the range of its operand with resulting type TYPE.
978 The resulting range is stored in *VR. */
980 void
981 vr_values::extract_range_from_unary_expr (value_range_equiv *vr,
982 enum tree_code code,
983 tree type, tree op0)
985 value_range vr0;
987 /* Get value ranges for the operand. For constant operands, create
988 a new value range with the operand to simplify processing. */
989 if (TREE_CODE (op0) == SSA_NAME)
990 vr0 = *(get_value_range (op0));
991 else if (is_gimple_min_invariant (op0))
992 vr0.set (op0, op0);
993 else
994 vr0.set_varying (type);
996 range_fold_unary_expr (vr, code, type, &vr0, TREE_TYPE (op0));
1000 /* Extract range information from a conditional expression STMT based on
1001 the ranges of each of its operands and the expression code. */
1003 void
1004 vr_values::extract_range_from_cond_expr (value_range_equiv *vr, gassign *stmt)
1006 /* Get value ranges for each operand. For constant operands, create
1007 a new value range with the operand to simplify processing. */
1008 tree op0 = gimple_assign_rhs2 (stmt);
1009 value_range_equiv tem0;
1010 const value_range_equiv *vr0 = &tem0;
1011 if (TREE_CODE (op0) == SSA_NAME)
1012 vr0 = get_value_range (op0);
1013 else if (is_gimple_min_invariant (op0))
1014 tem0.set (op0);
1015 else
1016 tem0.set_varying (TREE_TYPE (op0));
1018 tree op1 = gimple_assign_rhs3 (stmt);
1019 value_range_equiv tem1;
1020 const value_range_equiv *vr1 = &tem1;
1021 if (TREE_CODE (op1) == SSA_NAME)
1022 vr1 = get_value_range (op1);
1023 else if (is_gimple_min_invariant (op1))
1024 tem1.set (op1);
1025 else
1026 tem1.set_varying (TREE_TYPE (op1));
1028 /* The resulting value range is the union of the operand ranges */
1029 vr->deep_copy (vr0);
1030 vr->legacy_verbose_union_ (vr1);
1034 /* Extract range information from a comparison expression EXPR based
1035 on the range of its operand and the expression code. */
1037 void
1038 vr_values::extract_range_from_comparison (value_range_equiv *vr,
1039 gimple *stmt)
1041 enum tree_code code = gimple_assign_rhs_code (stmt);
1042 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1043 tree op0 = gimple_assign_rhs1 (stmt);
1044 tree op1 = gimple_assign_rhs2 (stmt);
1045 bool sop;
1046 tree val
1047 = simplifier.vrp_evaluate_conditional_warnv_with_ops (stmt, code, op0, op1,
1048 false, &sop, NULL);
1049 if (val)
1051 /* Since this expression was found on the RHS of an assignment,
1052 its type may be different from _Bool. Convert VAL to EXPR's
1053 type. */
1054 val = fold_convert (type, val);
1055 if (is_gimple_min_invariant (val))
1056 vr->set (val);
1057 else
1058 vr->update (val, val);
1060 else
1061 /* The result of a comparison is always true or false. */
1062 set_value_range_to_truthvalue (vr, type);
1065 /* Helper function for simplify_internal_call_using_ranges and
1066 extract_range_basic. Return true if OP0 SUBCODE OP1 for
1067 SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
1068 always overflow. Set *OVF to true if it is known to always
1069 overflow. */
1071 static bool
1072 check_for_binary_op_overflow (range_query *query,
1073 enum tree_code subcode, tree type,
1074 tree op0, tree op1, bool *ovf, gimple *s = NULL)
1076 value_range vr0, vr1;
1077 if (TREE_CODE (op0) == SSA_NAME)
1078 vr0 = *query->get_value_range (op0, s);
1079 else if (TREE_CODE (op0) == INTEGER_CST)
1080 vr0.set (op0, op0);
1081 else
1082 vr0.set_varying (TREE_TYPE (op0));
1084 if (TREE_CODE (op1) == SSA_NAME)
1085 vr1 = *query->get_value_range (op1, s);
1086 else if (TREE_CODE (op1) == INTEGER_CST)
1087 vr1.set (op1, op1);
1088 else
1089 vr1.set_varying (TREE_TYPE (op1));
1091 tree vr0min = vr0.min (), vr0max = vr0.max ();
1092 tree vr1min = vr1.min (), vr1max = vr1.max ();
1093 if (!range_int_cst_p (&vr0)
1094 || TREE_OVERFLOW (vr0min)
1095 || TREE_OVERFLOW (vr0max))
1097 vr0min = vrp_val_min (TREE_TYPE (op0));
1098 vr0max = vrp_val_max (TREE_TYPE (op0));
1100 if (!range_int_cst_p (&vr1)
1101 || TREE_OVERFLOW (vr1min)
1102 || TREE_OVERFLOW (vr1max))
1104 vr1min = vrp_val_min (TREE_TYPE (op1));
1105 vr1max = vrp_val_max (TREE_TYPE (op1));
1107 *ovf = arith_overflowed_p (subcode, type, vr0min,
1108 subcode == MINUS_EXPR ? vr1max : vr1min);
1109 if (arith_overflowed_p (subcode, type, vr0max,
1110 subcode == MINUS_EXPR ? vr1min : vr1max) != *ovf)
1111 return false;
1112 if (subcode == MULT_EXPR)
1114 if (arith_overflowed_p (subcode, type, vr0min, vr1max) != *ovf
1115 || arith_overflowed_p (subcode, type, vr0max, vr1min) != *ovf)
1116 return false;
1118 if (*ovf)
1120 /* So far we found that there is an overflow on the boundaries.
1121 That doesn't prove that there is an overflow even for all values
1122 in between the boundaries. For that compute widest_int range
1123 of the result and see if it doesn't overlap the range of
1124 type. */
1125 widest_int wmin, wmax;
1126 widest_int w[4];
1127 int i;
1128 w[0] = wi::to_widest (vr0min);
1129 w[1] = wi::to_widest (vr0max);
1130 w[2] = wi::to_widest (vr1min);
1131 w[3] = wi::to_widest (vr1max);
1132 for (i = 0; i < 4; i++)
1134 widest_int wt;
1135 switch (subcode)
1137 case PLUS_EXPR:
1138 wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
1139 break;
1140 case MINUS_EXPR:
1141 wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
1142 break;
1143 case MULT_EXPR:
1144 wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
1145 break;
1146 default:
1147 gcc_unreachable ();
1149 if (i == 0)
1151 wmin = wt;
1152 wmax = wt;
1154 else
1156 wmin = wi::smin (wmin, wt);
1157 wmax = wi::smax (wmax, wt);
1160 /* The result of op0 CODE op1 is known to be in range
1161 [wmin, wmax]. */
1162 widest_int wtmin = wi::to_widest (vrp_val_min (type));
1163 widest_int wtmax = wi::to_widest (vrp_val_max (type));
1164 /* If all values in [wmin, wmax] are smaller than
1165 [wtmin, wtmax] or all are larger than [wtmin, wtmax],
1166 the arithmetic operation will always overflow. */
1167 if (wmax < wtmin || wmin > wtmax)
1168 return true;
1169 return false;
1171 return true;
1174 /* Derive a range from a builtin. Set range in VR and return TRUE if
1175 successful. */
1177 bool
1178 vr_values::extract_range_from_ubsan_builtin (value_range_equiv *vr, gimple *stmt)
1180 gcc_assert (is_gimple_call (stmt));
1181 enum tree_code subcode = ERROR_MARK;
1182 combined_fn cfn = gimple_call_combined_fn (stmt);
1183 scalar_int_mode mode;
1185 switch (cfn)
1187 case CFN_UBSAN_CHECK_ADD:
1188 subcode = PLUS_EXPR;
1189 break;
1190 case CFN_UBSAN_CHECK_SUB:
1191 subcode = MINUS_EXPR;
1192 break;
1193 case CFN_UBSAN_CHECK_MUL:
1194 subcode = MULT_EXPR;
1195 break;
1196 default:
1197 break;
1199 if (subcode != ERROR_MARK)
1201 bool saved_flag_wrapv = flag_wrapv;
1202 /* Pretend the arithmetics is wrapping. If there is
1203 any overflow, we'll complain, but will actually do
1204 wrapping operation. */
1205 flag_wrapv = 1;
1206 extract_range_from_binary_expr (vr, subcode,
1207 TREE_TYPE (gimple_call_arg (stmt, 0)),
1208 gimple_call_arg (stmt, 0),
1209 gimple_call_arg (stmt, 1));
1210 flag_wrapv = saved_flag_wrapv;
1212 /* If for both arguments vrp_valueize returned non-NULL,
1213 this should have been already folded and if not, it
1214 wasn't folded because of overflow. Avoid removing the
1215 UBSAN_CHECK_* calls in that case. */
1216 if (vr->kind () == VR_RANGE
1217 && (vr->min () == vr->max ()
1218 || operand_equal_p (vr->min (), vr->max (), 0)))
1219 vr->set_varying (vr->type ());
1221 return !vr->varying_p ();
1223 return false;
1226 /* Try to derive a nonnegative or nonzero range out of STMT relying
1227 primarily on generic routines in fold in conjunction with range data.
1228 Store the result in *VR */
1230 void
1231 vr_values::extract_range_basic (value_range_equiv *vr, gimple *stmt)
1233 bool sop;
1235 if (is_gimple_call (stmt))
1237 combined_fn cfn = gimple_call_combined_fn (stmt);
1238 switch (cfn)
1240 case CFN_UBSAN_CHECK_ADD:
1241 case CFN_UBSAN_CHECK_SUB:
1242 case CFN_UBSAN_CHECK_MUL:
1243 if (extract_range_from_ubsan_builtin (vr, stmt))
1244 return;
1245 break;
1246 default:
1247 if (fold_range (*vr, stmt, this))
1249 /* The original code nuked equivalences every time a
1250 range was found, so do the same here. */
1251 vr->equiv_clear ();
1252 return;
1254 break;
1257 /* Handle extraction of the two results (result of arithmetics and
1258 a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
1259 internal function. Similarly from ATOMIC_COMPARE_EXCHANGE. */
1260 if (is_gimple_assign (stmt)
1261 && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
1262 || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
1263 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt))))
1265 enum tree_code code = gimple_assign_rhs_code (stmt);
1266 tree op = gimple_assign_rhs1 (stmt);
1267 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1268 if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
1270 gimple *g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
1271 if (is_gimple_call (g) && gimple_call_internal_p (g))
1273 enum tree_code subcode = ERROR_MARK;
1274 switch (gimple_call_internal_fn (g))
1276 case IFN_ADD_OVERFLOW:
1277 subcode = PLUS_EXPR;
1278 break;
1279 case IFN_SUB_OVERFLOW:
1280 subcode = MINUS_EXPR;
1281 break;
1282 case IFN_MUL_OVERFLOW:
1283 subcode = MULT_EXPR;
1284 break;
1285 case IFN_ATOMIC_COMPARE_EXCHANGE:
1286 if (code == IMAGPART_EXPR)
1288 /* This is the boolean return value whether compare and
1289 exchange changed anything or not. */
1290 vr->set (build_int_cst (type, 0),
1291 build_int_cst (type, 1), NULL);
1292 return;
1294 break;
1295 default:
1296 break;
1298 if (subcode != ERROR_MARK)
1300 tree op0 = gimple_call_arg (g, 0);
1301 tree op1 = gimple_call_arg (g, 1);
1302 if (code == IMAGPART_EXPR)
1304 bool ovf = false;
1305 if (check_for_binary_op_overflow (this, subcode, type,
1306 op0, op1, &ovf))
1307 vr->set (build_int_cst (type, ovf));
1308 else if (TYPE_PRECISION (type) == 1
1309 && !TYPE_UNSIGNED (type))
1310 vr->set_varying (type);
1311 else
1312 vr->set (build_int_cst (type, 0),
1313 build_int_cst (type, 1), NULL);
1315 else if (types_compatible_p (type, TREE_TYPE (op0))
1316 && types_compatible_p (type, TREE_TYPE (op1)))
1318 bool saved_flag_wrapv = flag_wrapv;
1319 /* Pretend the arithmetics is wrapping. If there is
1320 any overflow, IMAGPART_EXPR will be set. */
1321 flag_wrapv = 1;
1322 extract_range_from_binary_expr (vr, subcode, type,
1323 op0, op1);
1324 flag_wrapv = saved_flag_wrapv;
1326 else
1328 value_range_equiv vr0, vr1;
1329 bool saved_flag_wrapv = flag_wrapv;
1330 /* Pretend the arithmetics is wrapping. If there is
1331 any overflow, IMAGPART_EXPR will be set. */
1332 flag_wrapv = 1;
1333 extract_range_from_unary_expr (&vr0, NOP_EXPR,
1334 type, op0);
1335 extract_range_from_unary_expr (&vr1, NOP_EXPR,
1336 type, op1);
1337 range_fold_binary_expr (vr, subcode, type, &vr0, &vr1);
1338 flag_wrapv = saved_flag_wrapv;
1340 return;
1345 /* None of the below should need a 'type', but we are only called
1346 for assignments and calls with a LHS. */
1347 tree type = TREE_TYPE (gimple_get_lhs (stmt));
1348 if (INTEGRAL_TYPE_P (type)
1349 && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
1350 set_value_range_to_nonnegative (vr, type);
1351 else if (vrp_stmt_computes_nonzero (stmt))
1353 vr->set_nonzero (type);
1354 vr->equiv_clear ();
1356 else
1357 vr->set_varying (type);
1361 /* Try to compute a useful range out of assignment STMT and store it
1362 in *VR. */
1364 void
1365 vr_values::extract_range_from_assignment (value_range_equiv *vr, gassign *stmt)
1367 enum tree_code code = gimple_assign_rhs_code (stmt);
1369 if (code == ASSERT_EXPR)
1370 extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
1371 else if (code == SSA_NAME)
1372 extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
1373 else if (TREE_CODE_CLASS (code) == tcc_binary)
1374 extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
1375 TREE_TYPE (gimple_assign_lhs (stmt)),
1376 gimple_assign_rhs1 (stmt),
1377 gimple_assign_rhs2 (stmt));
1378 else if (TREE_CODE_CLASS (code) == tcc_unary)
1379 extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
1380 TREE_TYPE (gimple_assign_lhs (stmt)),
1381 gimple_assign_rhs1 (stmt));
1382 else if (code == COND_EXPR)
1383 extract_range_from_cond_expr (vr, stmt);
1384 else if (TREE_CODE_CLASS (code) == tcc_comparison)
1385 extract_range_from_comparison (vr, stmt);
1386 else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
1387 && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
1388 vr->set (gimple_assign_rhs1 (stmt));
1389 else
1390 vr->set_varying (TREE_TYPE (gimple_assign_lhs (stmt)));
1392 if (vr->varying_p ())
1393 extract_range_basic (vr, stmt);
1396 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
1398 - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
1399 all the values in the ranges.
1401 - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
1403 - Return NULL_TREE if it is not always possible to determine the
1404 value of the comparison.
1406 Also set *STRICT_OVERFLOW_P to indicate whether comparision evaluation
1407 assumed signed overflow is undefined. */
1410 static tree
1411 compare_ranges (enum tree_code comp, const value_range_equiv *vr0,
1412 const value_range_equiv *vr1, bool *strict_overflow_p)
1414 /* VARYING or UNDEFINED ranges cannot be compared. */
1415 if (vr0->varying_p ()
1416 || vr0->undefined_p ()
1417 || vr1->varying_p ()
1418 || vr1->undefined_p ())
1419 return NULL_TREE;
1421 /* Anti-ranges need to be handled separately. */
1422 if (vr0->kind () == VR_ANTI_RANGE || vr1->kind () == VR_ANTI_RANGE)
1424 /* If both are anti-ranges, then we cannot compute any
1425 comparison. */
1426 if (vr0->kind () == VR_ANTI_RANGE && vr1->kind () == VR_ANTI_RANGE)
1427 return NULL_TREE;
1429 /* These comparisons are never statically computable. */
1430 if (comp == GT_EXPR
1431 || comp == GE_EXPR
1432 || comp == LT_EXPR
1433 || comp == LE_EXPR)
1434 return NULL_TREE;
1436 /* Equality can be computed only between a range and an
1437 anti-range. ~[VAL1, VAL2] == [VAL1, VAL2] is always false. */
1438 if (vr0->kind () == VR_RANGE)
1439 /* To simplify processing, make VR0 the anti-range. */
1440 std::swap (vr0, vr1);
1442 gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
1444 if (compare_values_warnv (vr0->min (), vr1->min (), strict_overflow_p) == 0
1445 && compare_values_warnv (vr0->max (), vr1->max (), strict_overflow_p) == 0)
1446 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1448 return NULL_TREE;
1451 /* Simplify processing. If COMP is GT_EXPR or GE_EXPR, switch the
1452 operands around and change the comparison code. */
1453 if (comp == GT_EXPR || comp == GE_EXPR)
1455 comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
1456 std::swap (vr0, vr1);
1459 if (comp == EQ_EXPR)
1461 /* Equality may only be computed if both ranges represent
1462 exactly one value. */
1463 if (compare_values_warnv (vr0->min (), vr0->max (), strict_overflow_p) == 0
1464 && compare_values_warnv (vr1->min (), vr1->max (), strict_overflow_p) == 0)
1466 int cmp_min = compare_values_warnv (vr0->min (), vr1->min (),
1467 strict_overflow_p);
1468 int cmp_max = compare_values_warnv (vr0->max (), vr1->max (),
1469 strict_overflow_p);
1470 if (cmp_min == 0 && cmp_max == 0)
1471 return boolean_true_node;
1472 else if (cmp_min != -2 && cmp_max != -2)
1473 return boolean_false_node;
1475 /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1. */
1476 else if (compare_values_warnv (vr0->min (), vr1->max (),
1477 strict_overflow_p) == 1
1478 || compare_values_warnv (vr1->min (), vr0->max (),
1479 strict_overflow_p) == 1)
1480 return boolean_false_node;
1482 return NULL_TREE;
1484 else if (comp == NE_EXPR)
1486 int cmp1, cmp2;
1488 /* If VR0 is completely to the left or completely to the right
1489 of VR1, they are always different. Notice that we need to
1490 make sure that both comparisons yield similar results to
1491 avoid comparing values that cannot be compared at
1492 compile-time. */
1493 cmp1 = compare_values_warnv (vr0->max (), vr1->min (), strict_overflow_p);
1494 cmp2 = compare_values_warnv (vr0->min (), vr1->max (), strict_overflow_p);
1495 if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
1496 return boolean_true_node;
1498 /* If VR0 and VR1 represent a single value and are identical,
1499 return false. */
1500 else if (compare_values_warnv (vr0->min (), vr0->max (),
1501 strict_overflow_p) == 0
1502 && compare_values_warnv (vr1->min (), vr1->max (),
1503 strict_overflow_p) == 0
1504 && compare_values_warnv (vr0->min (), vr1->min (),
1505 strict_overflow_p) == 0
1506 && compare_values_warnv (vr0->max (), vr1->max (),
1507 strict_overflow_p) == 0)
1508 return boolean_false_node;
1510 /* Otherwise, they may or may not be different. */
1511 else
1512 return NULL_TREE;
1514 else if (comp == LT_EXPR || comp == LE_EXPR)
1516 int tst;
1518 /* If VR0 is to the left of VR1, return true. */
1519 tst = compare_values_warnv (vr0->max (), vr1->min (), strict_overflow_p);
1520 if ((comp == LT_EXPR && tst == -1)
1521 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1522 return boolean_true_node;
1524 /* If VR0 is to the right of VR1, return false. */
1525 tst = compare_values_warnv (vr0->min (), vr1->max (), strict_overflow_p);
1526 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1527 || (comp == LE_EXPR && tst == 1))
1528 return boolean_false_node;
1530 /* Otherwise, we don't know. */
1531 return NULL_TREE;
1534 gcc_unreachable ();
1537 /* Given a value range VR, a value VAL and a comparison code COMP, return
1538 BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
1539 values in VR. Return BOOLEAN_FALSE_NODE if the comparison
1540 always returns false. Return NULL_TREE if it is not always
1541 possible to determine the value of the comparison. Also set
1542 *STRICT_OVERFLOW_P to indicate whether comparision evaluation
1543 assumed signed overflow is undefined. */
1545 static tree
1546 compare_range_with_value (enum tree_code comp, const value_range *vr,
1547 tree val, bool *strict_overflow_p)
1549 if (vr->varying_p () || vr->undefined_p ())
1550 return NULL_TREE;
1552 /* Anti-ranges need to be handled separately. */
1553 if (vr->kind () == VR_ANTI_RANGE)
1555 /* For anti-ranges, the only predicates that we can compute at
1556 compile time are equality and inequality. */
1557 if (comp == GT_EXPR
1558 || comp == GE_EXPR
1559 || comp == LT_EXPR
1560 || comp == LE_EXPR)
1561 return NULL_TREE;
1563 /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2. */
1564 if (!vr->may_contain_p (val))
1565 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1567 return NULL_TREE;
1570 if (comp == EQ_EXPR)
1572 /* EQ_EXPR may only be computed if VR represents exactly
1573 one value. */
1574 if (compare_values_warnv (vr->min (), vr->max (), strict_overflow_p) == 0)
1576 int cmp = compare_values_warnv (vr->min (), val, strict_overflow_p);
1577 if (cmp == 0)
1578 return boolean_true_node;
1579 else if (cmp == -1 || cmp == 1 || cmp == 2)
1580 return boolean_false_node;
1582 else if (compare_values_warnv (val, vr->min (), strict_overflow_p) == -1
1583 || compare_values_warnv (vr->max (), val, strict_overflow_p) == -1)
1584 return boolean_false_node;
1586 return NULL_TREE;
1588 else if (comp == NE_EXPR)
1590 /* If VAL is not inside VR, then they are always different. */
1591 if (compare_values_warnv (vr->max (), val, strict_overflow_p) == -1
1592 || compare_values_warnv (vr->min (), val, strict_overflow_p) == 1)
1593 return boolean_true_node;
1595 /* If VR represents exactly one value equal to VAL, then return
1596 false. */
1597 if (compare_values_warnv (vr->min (), vr->max (), strict_overflow_p) == 0
1598 && compare_values_warnv (vr->min (), val, strict_overflow_p) == 0)
1599 return boolean_false_node;
1601 /* Otherwise, they may or may not be different. */
1602 return NULL_TREE;
1604 else if (comp == LT_EXPR || comp == LE_EXPR)
1606 int tst;
1608 /* If VR is to the left of VAL, return true. */
1609 tst = compare_values_warnv (vr->max (), val, strict_overflow_p);
1610 if ((comp == LT_EXPR && tst == -1)
1611 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1612 return boolean_true_node;
1614 /* If VR is to the right of VAL, return false. */
1615 tst = compare_values_warnv (vr->min (), val, strict_overflow_p);
1616 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1617 || (comp == LE_EXPR && tst == 1))
1618 return boolean_false_node;
1620 /* Otherwise, we don't know. */
1621 return NULL_TREE;
1623 else if (comp == GT_EXPR || comp == GE_EXPR)
1625 int tst;
1627 /* If VR is to the right of VAL, return true. */
1628 tst = compare_values_warnv (vr->min (), val, strict_overflow_p);
1629 if ((comp == GT_EXPR && tst == 1)
1630 || (comp == GE_EXPR && (tst == 0 || tst == 1)))
1631 return boolean_true_node;
1633 /* If VR is to the left of VAL, return false. */
1634 tst = compare_values_warnv (vr->max (), val, strict_overflow_p);
1635 if ((comp == GT_EXPR && (tst == -1 || tst == 0))
1636 || (comp == GE_EXPR && tst == -1))
1637 return boolean_false_node;
1639 /* Otherwise, we don't know. */
1640 return NULL_TREE;
1643 gcc_unreachable ();
1646 static inline void
1647 fix_overflow (tree *min, tree *max)
1649 /* Even for valid range info, sometimes overflow flag will leak in.
1650 As GIMPLE IL should have no constants with TREE_OVERFLOW set, we
1651 drop them. */
1652 if (TREE_OVERFLOW_P (*min))
1653 *min = drop_tree_overflow (*min);
1654 if (TREE_OVERFLOW_P (*max))
1655 *max = drop_tree_overflow (*max);
1657 gcc_checking_assert (compare_values (*min, *max) != 1);
1660 /* Given a VAR in STMT within LOOP, determine the bounds of the
1661 variable and store it in MIN/MAX and return TRUE. If no bounds
1662 could be determined, return FALSE. */
1664 bool
1665 bounds_of_var_in_loop (tree *min, tree *max, range_query *query,
1666 class loop *loop, gimple *stmt, tree var)
1668 tree init, step, chrec, tmin, tmax, type = TREE_TYPE (var);
1669 enum ev_direction dir;
1670 int_range<2> r;
1672 chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
1674 /* Like in PR19590, scev can return a constant function. */
1675 if (is_gimple_min_invariant (chrec))
1677 *min = *max = chrec;
1678 fix_overflow (min, max);
1679 return true;
1682 if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
1683 return false;
1685 init = initial_condition_in_loop_num (chrec, loop->num);
1686 step = evolution_part_in_loop_num (chrec, loop->num);
1688 if (!init || !step)
1689 return false;
1691 Value_Range rinit (TREE_TYPE (init));
1692 Value_Range rstep (TREE_TYPE (step));
1693 /* If INIT is an SSA with a singleton range, set INIT to said
1694 singleton, otherwise leave INIT alone. */
1695 if (TREE_CODE (init) == SSA_NAME
1696 && query->range_of_expr (rinit, init, stmt))
1697 rinit.singleton_p (&init);
1698 /* Likewise for step. */
1699 if (TREE_CODE (step) == SSA_NAME
1700 && query->range_of_expr (rstep, step, stmt))
1701 rstep.singleton_p (&step);
1703 /* If STEP is symbolic, we can't know whether INIT will be the
1704 minimum or maximum value in the range. Also, unless INIT is
1705 a simple expression, compare_values and possibly other functions
1706 in tree-vrp won't be able to handle it. */
1707 if (step == NULL_TREE
1708 || !is_gimple_min_invariant (step)
1709 || !valid_value_p (init))
1710 return false;
1712 dir = scev_direction (chrec);
1713 if (/* Do not adjust ranges if we do not know whether the iv increases
1714 or decreases, ... */
1715 dir == EV_DIR_UNKNOWN
1716 /* ... or if it may wrap. */
1717 || scev_probably_wraps_p (NULL_TREE, init, step, stmt,
1718 get_chrec_loop (chrec), true))
1719 return false;
1721 if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
1722 tmin = lower_bound_in_type (type, type);
1723 else
1724 tmin = TYPE_MIN_VALUE (type);
1725 if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
1726 tmax = upper_bound_in_type (type, type);
1727 else
1728 tmax = TYPE_MAX_VALUE (type);
1730 /* Try to use estimated number of iterations for the loop to constrain the
1731 final value in the evolution. */
1732 if (TREE_CODE (step) == INTEGER_CST
1733 && is_gimple_val (init)
1734 && (TREE_CODE (init) != SSA_NAME
1735 || (query->range_of_expr (r, init, stmt)
1736 && r.kind () == VR_RANGE)))
1738 widest_int nit;
1740 /* We are only entering here for loop header PHI nodes, so using
1741 the number of latch executions is the correct thing to use. */
1742 if (max_loop_iterations (loop, &nit))
1744 signop sgn = TYPE_SIGN (TREE_TYPE (step));
1745 wi::overflow_type overflow;
1747 widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
1748 &overflow);
1749 /* If the multiplication overflowed we can't do a meaningful
1750 adjustment. Likewise if the result doesn't fit in the type
1751 of the induction variable. For a signed type we have to
1752 check whether the result has the expected signedness which
1753 is that of the step as number of iterations is unsigned. */
1754 if (!overflow
1755 && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
1756 && (sgn == UNSIGNED
1757 || wi::gts_p (wtmp, 0) == wi::gts_p (wi::to_wide (step), 0)))
1759 value_range maxvr, vr0, vr1;
1760 if (TREE_CODE (init) == SSA_NAME)
1761 query->range_of_expr (vr0, init, stmt);
1762 else if (is_gimple_min_invariant (init))
1763 vr0.set (init, init);
1764 else
1765 vr0.set_varying (TREE_TYPE (init));
1766 tree tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
1767 vr1.set (tem, tem);
1768 range_fold_binary_expr (&maxvr, PLUS_EXPR,
1769 TREE_TYPE (init), &vr0, &vr1);
1771 /* Likewise if the addition did. */
1772 if (maxvr.kind () == VR_RANGE)
1774 int_range<2> initvr;
1776 if (TREE_CODE (init) == SSA_NAME)
1777 query->range_of_expr (initvr, init, stmt);
1778 else if (is_gimple_min_invariant (init))
1779 initvr.set (init, init);
1780 else
1781 return false;
1783 /* Check if init + nit * step overflows. Though we checked
1784 scev {init, step}_loop doesn't wrap, it is not enough
1785 because the loop may exit immediately. Overflow could
1786 happen in the plus expression in this case. */
1787 if ((dir == EV_DIR_DECREASES
1788 && compare_values (maxvr.min (), initvr.min ()) != -1)
1789 || (dir == EV_DIR_GROWS
1790 && compare_values (maxvr.max (), initvr.max ()) != 1))
1791 return false;
1793 tmin = maxvr.min ();
1794 tmax = maxvr.max ();
1800 *min = tmin;
1801 *max = tmax;
1802 if (dir == EV_DIR_DECREASES)
1803 *max = init;
1804 else
1805 *min = init;
1807 fix_overflow (min, max);
1808 return true;
1811 /* Given a range VR, a LOOP and a variable VAR, determine whether it
1812 would be profitable to adjust VR using scalar evolution information
1813 for VAR. If so, update VR with the new limits. */
1815 void
1816 vr_values::adjust_range_with_scev (value_range_equiv *vr, class loop *loop,
1817 gimple *stmt, tree var)
1819 tree min, max;
1820 if (bounds_of_var_in_loop (&min, &max, this, loop, stmt, var))
1822 if (vr->undefined_p () || vr->varying_p ())
1824 /* For VARYING or UNDEFINED ranges, just about anything we get
1825 from scalar evolutions should be better. */
1826 vr->update (min, max);
1828 else if (vr->kind () == VR_RANGE)
1830 /* Start with the input range... */
1831 tree vrmin = vr->min ();
1832 tree vrmax = vr->max ();
1834 /* ...and narrow it down with what we got from SCEV. */
1835 if (compare_values (min, vrmin) == 1)
1836 vrmin = min;
1837 if (compare_values (max, vrmax) == -1)
1838 vrmax = max;
1840 vr->update (vrmin, vrmax);
1842 else if (vr->kind () == VR_ANTI_RANGE)
1844 /* ?? As an enhancement, if VR, MIN, and MAX are constants, one
1845 could just intersect VR with a range of [MIN,MAX]. */
1850 /* Dump value ranges of all SSA_NAMEs to FILE. */
1852 void
1853 vr_values::dump (FILE *file)
1855 size_t i;
1857 for (i = 0; i < num_vr_values; i++)
1859 if (vr_value[i] && ssa_name (i))
1861 print_generic_expr (file, ssa_name (i));
1862 fprintf (file, ": ");
1863 dump_value_range (file, vr_value[i]);
1864 fprintf (file, "\n");
1868 fprintf (file, "\n");
1871 /* Initialize VRP lattice. */
1873 vr_values::vr_values () : simplifier (this)
1875 values_propagated = false;
1876 num_vr_values = num_ssa_names * 2;
1877 vr_value = XCNEWVEC (value_range_equiv *, num_vr_values);
1878 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
1879 bitmap_obstack_initialize (&vrp_equiv_obstack);
1882 /* Free VRP lattice. */
1884 vr_values::~vr_values ()
1886 /* Free allocated memory. */
1887 free (vr_value);
1888 free (vr_phi_edge_counts);
1889 bitmap_obstack_release (&vrp_equiv_obstack);
1891 /* So that we can distinguish between VRP data being available
1892 and not available. */
1893 vr_value = NULL;
1894 vr_phi_edge_counts = NULL;
1898 /* A hack. */
1899 static class vr_values *x_vr_values;
1901 /* Return the singleton value-range for NAME or NAME. */
1903 static inline tree
1904 vrp_valueize (tree name)
1906 if (TREE_CODE (name) == SSA_NAME)
1908 const value_range_equiv *vr = x_vr_values->get_value_range (name);
1909 if (vr->kind () == VR_RANGE
1910 && (TREE_CODE (vr->min ()) == SSA_NAME
1911 || is_gimple_min_invariant (vr->min ()))
1912 && vrp_operand_equal_p (vr->min (), vr->max ()))
1913 return vr->min ();
1915 return name;
1918 /* Return the singleton value-range for NAME if that is a constant
1919 but signal to not follow SSA edges. */
1921 static inline tree
1922 vrp_valueize_1 (tree name)
1924 if (TREE_CODE (name) == SSA_NAME)
1926 /* If the definition may be simulated again we cannot follow
1927 this SSA edge as the SSA propagator does not necessarily
1928 re-visit the use. */
1929 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1930 if (!gimple_nop_p (def_stmt)
1931 && prop_simulate_again_p (def_stmt))
1932 return NULL_TREE;
1933 const value_range_equiv *vr = x_vr_values->get_value_range (name);
1934 tree singleton;
1935 if (vr->singleton_p (&singleton))
1936 return singleton;
1938 return name;
1941 /* Given STMT, an assignment or call, return its LHS if the type
1942 of the LHS is suitable for VRP analysis, else return NULL_TREE. */
1944 tree
1945 get_output_for_vrp (gimple *stmt)
1947 if (!is_gimple_assign (stmt) && !is_gimple_call (stmt))
1948 return NULL_TREE;
1950 /* We only keep track of ranges in integral and pointer types. */
1951 tree lhs = gimple_get_lhs (stmt);
1952 if (TREE_CODE (lhs) == SSA_NAME
1953 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
1954 /* It is valid to have NULL MIN/MAX values on a type. See
1955 build_range_type. */
1956 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
1957 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
1958 || POINTER_TYPE_P (TREE_TYPE (lhs))))
1959 return lhs;
1961 return NULL_TREE;
1964 /* Visit assignment STMT. If it produces an interesting range, record
1965 the range in VR and set LHS to OUTPUT_P. */
1967 void
1968 vr_values::vrp_visit_assignment_or_call (gimple *stmt, tree *output_p,
1969 value_range_equiv *vr)
1971 tree lhs = get_output_for_vrp (stmt);
1972 *output_p = lhs;
1974 /* We only keep track of ranges in integral and pointer types. */
1975 if (lhs)
1977 enum gimple_code code = gimple_code (stmt);
1979 /* Try folding the statement to a constant first. */
1980 x_vr_values = this;
1981 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
1982 vrp_valueize_1);
1983 x_vr_values = NULL;
1984 if (tem)
1986 if (TREE_CODE (tem) == SSA_NAME
1987 && (SSA_NAME_IS_DEFAULT_DEF (tem)
1988 || ! prop_simulate_again_p (SSA_NAME_DEF_STMT (tem))))
1990 extract_range_from_ssa_name (vr, tem);
1991 return;
1993 else if (is_gimple_min_invariant (tem))
1995 vr->set (tem);
1996 return;
1999 /* Then dispatch to value-range extracting functions. */
2000 if (code == GIMPLE_CALL)
2001 extract_range_basic (vr, stmt);
2002 else
2003 extract_range_from_assignment (vr, as_a <gassign *> (stmt));
2007 /* Helper that gets the value range of the SSA_NAME with version I
2008 or a symbolic range containing the SSA_NAME only if the value range
2009 is varying or undefined. Uses TEM as storage for the alternate range. */
2011 const value_range_equiv *
2012 simplify_using_ranges::get_vr_for_comparison (int i, value_range_equiv *tem,
2013 gimple *s)
2015 /* Shallow-copy equiv bitmap. */
2016 const value_range_equiv *vr = query->get_value_range (ssa_name (i), s);
2018 /* If name N_i does not have a valid range, use N_i as its own
2019 range. This allows us to compare against names that may
2020 have N_i in their ranges. */
2021 if (vr->varying_p () || vr->undefined_p ())
2023 tem->set (ssa_name (i));
2024 return tem;
2027 return vr;
2030 /* Compare all the value ranges for names equivalent to VAR with VAL
2031 using comparison code COMP. Return the same value returned by
2032 compare_range_with_value, including the setting of
2033 *STRICT_OVERFLOW_P. */
2035 tree
2036 simplify_using_ranges::compare_name_with_value
2037 (enum tree_code comp, tree var, tree val,
2038 bool *strict_overflow_p, bool use_equiv_p,
2039 gimple *s)
2041 /* Get the set of equivalences for VAR. */
2042 bitmap e = query->get_value_range (var, s)->equiv ();
2044 /* Start at -1. Set it to 0 if we do a comparison without relying
2045 on overflow, or 1 if all comparisons rely on overflow. */
2046 int used_strict_overflow = -1;
2048 /* Compare vars' value range with val. */
2049 value_range_equiv tem_vr;
2050 const value_range_equiv *equiv_vr
2051 = get_vr_for_comparison (SSA_NAME_VERSION (var), &tem_vr, s);
2052 bool sop = false;
2053 tree retval = compare_range_with_value (comp, equiv_vr, val, &sop);
2054 if (retval)
2055 used_strict_overflow = sop ? 1 : 0;
2057 /* If the equiv set is empty we have done all work we need to do. */
2058 if (e == NULL)
2060 if (retval && used_strict_overflow > 0)
2061 *strict_overflow_p = true;
2062 return retval;
2065 unsigned i;
2066 bitmap_iterator bi;
2067 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
2069 tree name = ssa_name (i);
2070 if (!name)
2071 continue;
2073 if (!use_equiv_p
2074 && !SSA_NAME_IS_DEFAULT_DEF (name)
2075 && prop_simulate_again_p (SSA_NAME_DEF_STMT (name)))
2076 continue;
2078 equiv_vr = get_vr_for_comparison (i, &tem_vr, s);
2079 sop = false;
2080 tree t = compare_range_with_value (comp, equiv_vr, val, &sop);
2081 if (t)
2083 /* If we get different answers from different members
2084 of the equivalence set this check must be in a dead
2085 code region. Folding it to a trap representation
2086 would be correct here. For now just return don't-know. */
2087 if (retval != NULL
2088 && t != retval)
2090 retval = NULL_TREE;
2091 break;
2093 retval = t;
2095 if (!sop)
2096 used_strict_overflow = 0;
2097 else if (used_strict_overflow < 0)
2098 used_strict_overflow = 1;
2102 if (retval && used_strict_overflow > 0)
2103 *strict_overflow_p = true;
2105 return retval;
2109 /* Given a comparison code COMP and names N1 and N2, compare all the
2110 ranges equivalent to N1 against all the ranges equivalent to N2
2111 to determine the value of N1 COMP N2. Return the same value
2112 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
2113 whether we relied on undefined signed overflow in the comparison. */
2116 tree
2117 simplify_using_ranges::compare_names (enum tree_code comp, tree n1, tree n2,
2118 bool *strict_overflow_p, gimple *s)
2120 /* Compare the ranges of every name equivalent to N1 against the
2121 ranges of every name equivalent to N2. */
2122 bitmap e1 = query->get_value_range (n1, s)->equiv ();
2123 bitmap e2 = query->get_value_range (n2, s)->equiv ();
2125 /* Use the fake bitmaps if e1 or e2 are not available. */
2126 static bitmap s_e1 = NULL, s_e2 = NULL;
2127 static bitmap_obstack *s_obstack = NULL;
2128 if (s_obstack == NULL)
2130 s_obstack = XNEW (bitmap_obstack);
2131 bitmap_obstack_initialize (s_obstack);
2132 s_e1 = BITMAP_ALLOC (s_obstack);
2133 s_e2 = BITMAP_ALLOC (s_obstack);
2135 if (e1 == NULL)
2136 e1 = s_e1;
2137 if (e2 == NULL)
2138 e2 = s_e2;
2140 /* Add N1 and N2 to their own set of equivalences to avoid
2141 duplicating the body of the loop just to check N1 and N2
2142 ranges. */
2143 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
2144 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
2146 /* If the equivalence sets have a common intersection, then the two
2147 names can be compared without checking their ranges. */
2148 if (bitmap_intersect_p (e1, e2))
2150 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2151 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2153 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
2154 ? boolean_true_node
2155 : boolean_false_node;
2158 /* Start at -1. Set it to 0 if we do a comparison without relying
2159 on overflow, or 1 if all comparisons rely on overflow. */
2160 int used_strict_overflow = -1;
2162 /* Otherwise, compare all the equivalent ranges. First, add N1 and
2163 N2 to their own set of equivalences to avoid duplicating the body
2164 of the loop just to check N1 and N2 ranges. */
2165 bitmap_iterator bi1;
2166 unsigned i1;
2167 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
2169 if (!ssa_name (i1))
2170 continue;
2172 value_range_equiv tem_vr1;
2173 const value_range_equiv *vr1 = get_vr_for_comparison (i1, &tem_vr1, s);
2175 tree t = NULL_TREE, retval = NULL_TREE;
2176 bitmap_iterator bi2;
2177 unsigned i2;
2178 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
2180 if (!ssa_name (i2))
2181 continue;
2183 bool sop = false;
2185 value_range_equiv tem_vr2;
2186 const value_range_equiv *vr2 = get_vr_for_comparison (i2, &tem_vr2,
2189 t = compare_ranges (comp, vr1, vr2, &sop);
2190 if (t)
2192 /* If we get different answers from different members
2193 of the equivalence set this check must be in a dead
2194 code region. Folding it to a trap representation
2195 would be correct here. For now just return don't-know. */
2196 if (retval != NULL && t != retval)
2198 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2199 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2200 return NULL_TREE;
2202 retval = t;
2204 if (!sop)
2205 used_strict_overflow = 0;
2206 else if (used_strict_overflow < 0)
2207 used_strict_overflow = 1;
2211 if (retval)
2213 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2214 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2215 if (used_strict_overflow > 0)
2216 *strict_overflow_p = true;
2217 return retval;
2221 /* None of the equivalent ranges are useful in computing this
2222 comparison. */
2223 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2224 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2225 return NULL_TREE;
2228 /* Helper function for vrp_evaluate_conditional_warnv & other
2229 optimizers. */
2231 tree
2232 simplify_using_ranges::vrp_evaluate_conditional_warnv_with_ops_using_ranges
2233 (enum tree_code code, tree op0, tree op1, bool * strict_overflow_p,
2234 gimple *s)
2236 const value_range_equiv *vr0, *vr1;
2237 vr0 = (TREE_CODE (op0) == SSA_NAME) ? query->get_value_range (op0, s) : NULL;
2238 vr1 = (TREE_CODE (op1) == SSA_NAME) ? query->get_value_range (op1, s) : NULL;
2240 tree res = NULL_TREE;
2241 if (vr0 && vr1)
2242 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
2243 if (!res && vr0)
2244 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
2245 if (!res && vr1)
2246 res = (compare_range_with_value
2247 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
2248 return res;
2251 /* Helper function for vrp_evaluate_conditional_warnv. */
2253 tree
2254 simplify_using_ranges::vrp_evaluate_conditional_warnv_with_ops
2255 (gimple *stmt,
2256 enum tree_code code,
2257 tree op0, tree op1,
2258 bool use_equiv_p,
2259 bool *strict_overflow_p,
2260 bool *only_ranges)
2262 tree ret;
2263 if (only_ranges)
2264 *only_ranges = true;
2266 /* We only deal with integral and pointer types. */
2267 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
2268 && !POINTER_TYPE_P (TREE_TYPE (op0)))
2269 return NULL_TREE;
2271 /* If OP0 CODE OP1 is an overflow comparison, if it can be expressed
2272 as a simple equality test, then prefer that over its current form
2273 for evaluation.
2275 An overflow test which collapses to an equality test can always be
2276 expressed as a comparison of one argument against zero. Overflow
2277 occurs when the chosen argument is zero and does not occur if the
2278 chosen argument is not zero. */
2279 tree x;
2280 if (overflow_comparison_p (code, op0, op1, use_equiv_p, &x))
2282 wide_int max = wi::max_value (TYPE_PRECISION (TREE_TYPE (op0)), UNSIGNED);
2283 /* B = A - 1; if (A < B) -> B = A - 1; if (A == 0)
2284 B = A - 1; if (A > B) -> B = A - 1; if (A != 0)
2285 B = A + 1; if (B < A) -> B = A + 1; if (B == 0)
2286 B = A + 1; if (B > A) -> B = A + 1; if (B != 0) */
2287 if (integer_zerop (x))
2289 op1 = x;
2290 code = (code == LT_EXPR || code == LE_EXPR) ? EQ_EXPR : NE_EXPR;
2292 /* B = A + 1; if (A > B) -> B = A + 1; if (B == 0)
2293 B = A + 1; if (A < B) -> B = A + 1; if (B != 0)
2294 B = A - 1; if (B > A) -> B = A - 1; if (A == 0)
2295 B = A - 1; if (B < A) -> B = A - 1; if (A != 0) */
2296 else if (wi::to_wide (x) == max - 1)
2298 op0 = op1;
2299 op1 = wide_int_to_tree (TREE_TYPE (op0), 0);
2300 code = (code == GT_EXPR || code == GE_EXPR) ? EQ_EXPR : NE_EXPR;
2302 else
2304 value_range vro, vri;
2305 if (code == GT_EXPR || code == GE_EXPR)
2307 vro.set (TYPE_MIN_VALUE (TREE_TYPE (op0)), x, VR_ANTI_RANGE);
2308 vri.set (TYPE_MIN_VALUE (TREE_TYPE (op0)), x);
2310 else if (code == LT_EXPR || code == LE_EXPR)
2312 vro.set (TYPE_MIN_VALUE (TREE_TYPE (op0)), x);
2313 vri.set (TYPE_MIN_VALUE (TREE_TYPE (op0)), x, VR_ANTI_RANGE);
2315 else
2316 gcc_unreachable ();
2317 const value_range_equiv *vr0 = query->get_value_range (op0, stmt);
2318 /* If vro, the range for OP0 to pass the overflow test, has
2319 no intersection with *vr0, OP0's known range, then the
2320 overflow test can't pass, so return the node for false.
2321 If it is the inverted range, vri, that has no
2322 intersection, then the overflow test must pass, so return
2323 the node for true. In other cases, we could proceed with
2324 a simplified condition comparing OP0 and X, with LE_EXPR
2325 for previously LE_ or LT_EXPR and GT_EXPR otherwise, but
2326 the comments next to the enclosing if suggest it's not
2327 generally profitable to do so. */
2328 vro.legacy_verbose_intersect (vr0);
2329 if (vro.undefined_p ())
2330 return boolean_false_node;
2331 vri.legacy_verbose_intersect (vr0);
2332 if (vri.undefined_p ())
2333 return boolean_true_node;
2337 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
2338 (code, op0, op1, strict_overflow_p, stmt)))
2339 return ret;
2340 if (only_ranges)
2341 *only_ranges = false;
2342 /* Do not use compare_names during propagation, it's quadratic. */
2343 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
2344 && use_equiv_p)
2345 return compare_names (code, op0, op1, strict_overflow_p, stmt);
2346 else if (TREE_CODE (op0) == SSA_NAME)
2347 return compare_name_with_value (code, op0, op1,
2348 strict_overflow_p, use_equiv_p, stmt);
2349 else if (TREE_CODE (op1) == SSA_NAME)
2350 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
2351 strict_overflow_p, use_equiv_p, stmt);
2352 return NULL_TREE;
2355 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
2356 information. Return NULL if the conditional cannot be evaluated.
2357 The ranges of all the names equivalent with the operands in COND
2358 will be used when trying to compute the value. If the result is
2359 based on undefined signed overflow, issue a warning if
2360 appropriate. */
2362 tree
2363 simplify_using_ranges::vrp_evaluate_conditional (tree_code code, tree op0,
2364 tree op1, gimple *stmt)
2366 bool sop;
2367 tree ret;
2368 bool only_ranges;
2370 /* Some passes and foldings leak constants with overflow flag set
2371 into the IL. Avoid doing wrong things with these and bail out. */
2372 if ((TREE_CODE (op0) == INTEGER_CST
2373 && TREE_OVERFLOW (op0))
2374 || (TREE_CODE (op1) == INTEGER_CST
2375 && TREE_OVERFLOW (op1)))
2376 return NULL_TREE;
2378 sop = false;
2379 ret = vrp_evaluate_conditional_warnv_with_ops (stmt, code, op0, op1, true,
2380 &sop, &only_ranges);
2382 if (ret && sop)
2384 enum warn_strict_overflow_code wc;
2385 const char* warnmsg;
2387 if (is_gimple_min_invariant (ret))
2389 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
2390 warnmsg = G_("assuming signed overflow does not occur when "
2391 "simplifying conditional to constant");
2393 else
2395 wc = WARN_STRICT_OVERFLOW_COMPARISON;
2396 warnmsg = G_("assuming signed overflow does not occur when "
2397 "simplifying conditional");
2400 if (issue_strict_overflow_warning (wc))
2402 location_t location;
2404 if (!gimple_has_location (stmt))
2405 location = input_location;
2406 else
2407 location = gimple_location (stmt);
2408 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
2412 if (warn_type_limits
2413 && ret && only_ranges
2414 && TREE_CODE_CLASS (code) == tcc_comparison
2415 && TREE_CODE (op0) == SSA_NAME)
2417 /* If the comparison is being folded and the operand on the LHS
2418 is being compared against a constant value that is outside of
2419 the natural range of OP0's type, then the predicate will
2420 always fold regardless of the value of OP0. If -Wtype-limits
2421 was specified, emit a warning. */
2422 tree type = TREE_TYPE (op0);
2423 const value_range_equiv *vr0 = query->get_value_range (op0, stmt);
2425 if (vr0->varying_p ()
2426 && INTEGRAL_TYPE_P (type)
2427 && is_gimple_min_invariant (op1))
2429 location_t location;
2431 if (!gimple_has_location (stmt))
2432 location = input_location;
2433 else
2434 location = gimple_location (stmt);
2436 warning_at (location, OPT_Wtype_limits,
2437 integer_zerop (ret)
2438 ? G_("comparison always false "
2439 "due to limited range of data type")
2440 : G_("comparison always true "
2441 "due to limited range of data type"));
2445 return ret;
2449 /* Visit conditional statement STMT. If we can determine which edge
2450 will be taken out of STMT's basic block, record it in
2451 *TAKEN_EDGE_P. Otherwise, set *TAKEN_EDGE_P to NULL. */
2453 void
2454 simplify_using_ranges::vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
2456 tree val;
2458 *taken_edge_p = NULL;
2460 if (dump_file && (dump_flags & TDF_DETAILS))
2462 tree use;
2463 ssa_op_iter i;
2465 fprintf (dump_file, "\nVisiting conditional with predicate: ");
2466 print_gimple_stmt (dump_file, stmt, 0);
2467 fprintf (dump_file, "\nWith known ranges\n");
2469 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
2471 fprintf (dump_file, "\t");
2472 print_generic_expr (dump_file, use);
2473 fprintf (dump_file, ": ");
2474 Value_Range r (TREE_TYPE (use));
2475 query->range_of_expr (r, use, stmt);
2476 r.dump (dump_file);
2479 fprintf (dump_file, "\n");
2482 /* Compute the value of the predicate COND by checking the known
2483 ranges of each of its operands.
2485 Note that we cannot evaluate all the equivalent ranges here
2486 because those ranges may not yet be final and with the current
2487 propagation strategy, we cannot determine when the value ranges
2488 of the names in the equivalence set have changed.
2490 For instance, given the following code fragment
2492 i_5 = PHI <8, i_13>
2494 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
2495 if (i_14 == 1)
2498 Assume that on the first visit to i_14, i_5 has the temporary
2499 range [8, 8] because the second argument to the PHI function is
2500 not yet executable. We derive the range ~[0, 0] for i_14 and the
2501 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
2502 the first time, since i_14 is equivalent to the range [8, 8], we
2503 determine that the predicate is always false.
2505 On the next round of propagation, i_13 is determined to be
2506 VARYING, which causes i_5 to drop down to VARYING. So, another
2507 visit to i_14 is scheduled. In this second visit, we compute the
2508 exact same range and equivalence set for i_14, namely ~[0, 0] and
2509 { i_5 }. But we did not have the previous range for i_5
2510 registered, so vrp_visit_assignment thinks that the range for
2511 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
2512 is not visited again, which stops propagation from visiting
2513 statements in the THEN clause of that if().
2515 To properly fix this we would need to keep the previous range
2516 value for the names in the equivalence set. This way we would've
2517 discovered that from one visit to the other i_5 changed from
2518 range [8, 8] to VR_VARYING.
2520 However, fixing this apparent limitation may not be worth the
2521 additional checking. Testing on several code bases (GCC, DLV,
2522 MICO, TRAMP3D and SPEC2000) showed that doing this results in
2523 4 more predicates folded in SPEC. */
2525 bool sop;
2526 val = vrp_evaluate_conditional_warnv_with_ops (stmt,
2527 gimple_cond_code (stmt),
2528 gimple_cond_lhs (stmt),
2529 gimple_cond_rhs (stmt),
2530 false, &sop, NULL);
2531 if (val)
2532 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
2534 if (dump_file && (dump_flags & TDF_DETAILS))
2536 fprintf (dump_file, "\nPredicate evaluates to: ");
2537 if (val == NULL_TREE)
2538 fprintf (dump_file, "DON'T KNOW\n");
2539 else
2540 print_generic_stmt (dump_file, val);
2544 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
2545 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
2546 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
2547 Returns true if the default label is not needed. */
2549 static bool
2550 find_case_label_ranges (gswitch *stmt, const value_range *vr,
2551 size_t *min_idx1, size_t *max_idx1,
2552 size_t *min_idx2, size_t *max_idx2)
2554 size_t i, j, k, l;
2555 unsigned int n = gimple_switch_num_labels (stmt);
2556 bool take_default;
2557 tree case_low, case_high;
2558 tree min = vr->min (), max = vr->max ();
2560 gcc_checking_assert (!vr->varying_p () && !vr->undefined_p ());
2562 take_default = !find_case_label_range (stmt, min, max, &i, &j);
2564 /* Set second range to empty. */
2565 *min_idx2 = 1;
2566 *max_idx2 = 0;
2568 if (vr->kind () == VR_RANGE)
2570 *min_idx1 = i;
2571 *max_idx1 = j;
2572 return !take_default;
2575 /* Set first range to all case labels. */
2576 *min_idx1 = 1;
2577 *max_idx1 = n - 1;
2579 if (i > j)
2580 return false;
2582 /* Make sure all the values of case labels [i , j] are contained in
2583 range [MIN, MAX]. */
2584 case_low = CASE_LOW (gimple_switch_label (stmt, i));
2585 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
2586 if (tree_int_cst_compare (case_low, min) < 0)
2587 i += 1;
2588 if (case_high != NULL_TREE
2589 && tree_int_cst_compare (max, case_high) < 0)
2590 j -= 1;
2592 if (i > j)
2593 return false;
2595 /* If the range spans case labels [i, j], the corresponding anti-range spans
2596 the labels [1, i - 1] and [j + 1, n - 1]. */
2597 k = j + 1;
2598 l = n - 1;
2599 if (k > l)
2601 k = 1;
2602 l = 0;
2605 j = i - 1;
2606 i = 1;
2607 if (i > j)
2609 i = k;
2610 j = l;
2611 k = 1;
2612 l = 0;
2615 *min_idx1 = i;
2616 *max_idx1 = j;
2617 *min_idx2 = k;
2618 *max_idx2 = l;
2619 return false;
2622 /* Visit switch statement STMT. If we can determine which edge
2623 will be taken out of STMT's basic block, record it in
2624 *TAKEN_EDGE_P. Otherwise, *TAKEN_EDGE_P set to NULL. */
2626 void
2627 vr_values::vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
2629 tree op, val;
2630 const value_range_equiv *vr;
2631 size_t i = 0, j = 0, k, l;
2632 bool take_default;
2634 *taken_edge_p = NULL;
2635 op = gimple_switch_index (stmt);
2636 if (TREE_CODE (op) != SSA_NAME)
2637 return;
2639 vr = get_value_range (op);
2640 if (dump_file && (dump_flags & TDF_DETAILS))
2642 fprintf (dump_file, "\nVisiting switch expression with operand ");
2643 print_generic_expr (dump_file, op);
2644 fprintf (dump_file, " with known range ");
2645 dump_value_range (dump_file, vr);
2646 fprintf (dump_file, "\n");
2649 if (vr->undefined_p ()
2650 || vr->varying_p ()
2651 || vr->symbolic_p ())
2652 return;
2654 /* Find the single edge that is taken from the switch expression. */
2655 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
2657 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
2658 label */
2659 if (j < i)
2661 gcc_assert (take_default);
2662 val = gimple_switch_default_label (stmt);
2664 else
2666 /* Check if labels with index i to j and maybe the default label
2667 are all reaching the same label. */
2669 val = gimple_switch_label (stmt, i);
2670 if (take_default
2671 && CASE_LABEL (gimple_switch_default_label (stmt))
2672 != CASE_LABEL (val))
2674 if (dump_file && (dump_flags & TDF_DETAILS))
2675 fprintf (dump_file, " not a single destination for this "
2676 "range\n");
2677 return;
2679 for (++i; i <= j; ++i)
2681 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
2683 if (dump_file && (dump_flags & TDF_DETAILS))
2684 fprintf (dump_file, " not a single destination for this "
2685 "range\n");
2686 return;
2689 for (; k <= l; ++k)
2691 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
2693 if (dump_file && (dump_flags & TDF_DETAILS))
2694 fprintf (dump_file, " not a single destination for this "
2695 "range\n");
2696 return;
2701 *taken_edge_p = find_edge (gimple_bb (stmt),
2702 label_to_block (cfun, CASE_LABEL (val)));
2704 if (dump_file && (dump_flags & TDF_DETAILS))
2706 fprintf (dump_file, " will take edge to ");
2707 print_generic_stmt (dump_file, CASE_LABEL (val));
2712 /* Evaluate statement STMT. If the statement produces a useful range,
2713 set VR and corepsponding OUTPUT_P.
2715 If STMT is a conditional branch and we can determine its truth
2716 value, the taken edge is recorded in *TAKEN_EDGE_P. */
2718 void
2719 vr_values::extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
2720 tree *output_p, value_range_equiv *vr)
2723 if (dump_file && (dump_flags & TDF_DETAILS))
2725 fprintf (dump_file, "\nextract_range_from_stmt visiting:\n");
2726 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
2729 if (!stmt_interesting_for_vrp (stmt))
2730 gcc_assert (stmt_ends_bb_p (stmt));
2731 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
2732 vrp_visit_assignment_or_call (stmt, output_p, vr);
2733 else if (gimple_code (stmt) == GIMPLE_COND)
2734 simplifier.vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
2735 else if (gimple_code (stmt) == GIMPLE_SWITCH)
2736 vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
2739 /* Visit all arguments for PHI node PHI that flow through executable
2740 edges. If a valid value range can be derived from all the incoming
2741 value ranges, set a new range in VR_RESULT. */
2743 void
2744 vr_values::extract_range_from_phi_node (gphi *phi,
2745 value_range_equiv *vr_result)
2747 tree lhs = PHI_RESULT (phi);
2748 const value_range_equiv *lhs_vr = get_value_range (lhs);
2749 bool first = true;
2750 int old_edges;
2751 class loop *l;
2753 if (dump_file && (dump_flags & TDF_DETAILS))
2755 fprintf (dump_file, "\nVisiting PHI node: ");
2756 print_gimple_stmt (dump_file, phi, 0, dump_flags);
2759 bool may_simulate_backedge_again = false;
2760 int edges = 0;
2761 for (size_t i = 0; i < gimple_phi_num_args (phi); i++)
2763 edge e = gimple_phi_arg_edge (phi, i);
2765 if (dump_file && (dump_flags & TDF_DETAILS))
2767 fprintf (dump_file,
2768 " Argument #%d (%d -> %d %sexecutable)\n",
2769 (int) i, e->src->index, e->dest->index,
2770 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
2773 if (e->flags & EDGE_EXECUTABLE)
2775 value_range_equiv vr_arg_tem;
2776 const value_range_equiv *vr_arg = &vr_arg_tem;
2778 ++edges;
2780 tree arg = PHI_ARG_DEF (phi, i);
2781 if (TREE_CODE (arg) == SSA_NAME)
2783 /* See if we are eventually going to change one of the args. */
2784 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
2785 if (! gimple_nop_p (def_stmt)
2786 && prop_simulate_again_p (def_stmt)
2787 && e->flags & EDGE_DFS_BACK)
2788 may_simulate_backedge_again = true;
2790 const value_range_equiv *vr_arg_ = get_value_range (arg);
2791 /* Do not allow equivalences or symbolic ranges to leak in from
2792 backedges. That creates invalid equivalencies.
2793 See PR53465 and PR54767. */
2794 if (e->flags & EDGE_DFS_BACK)
2796 if (!vr_arg_->varying_p () && !vr_arg_->undefined_p ())
2798 vr_arg_tem.set (vr_arg_->min (), vr_arg_->max (), NULL,
2799 vr_arg_->kind ());
2800 if (vr_arg_tem.symbolic_p ())
2801 vr_arg_tem.set_varying (TREE_TYPE (arg));
2803 else
2804 vr_arg = vr_arg_;
2806 /* If the non-backedge arguments range is VR_VARYING then
2807 we can still try recording a simple equivalence. */
2808 else if (vr_arg_->varying_p ())
2809 vr_arg_tem.set (arg);
2810 else
2811 vr_arg = vr_arg_;
2813 else
2815 if (TREE_OVERFLOW_P (arg))
2816 arg = drop_tree_overflow (arg);
2818 vr_arg_tem.set (arg);
2821 if (dump_file && (dump_flags & TDF_DETAILS))
2823 fprintf (dump_file, "\t");
2824 print_generic_expr (dump_file, arg, dump_flags);
2825 fprintf (dump_file, ": ");
2826 dump_value_range (dump_file, vr_arg);
2827 fprintf (dump_file, "\n");
2830 if (first)
2831 vr_result->deep_copy (vr_arg);
2832 else
2833 vr_result->legacy_verbose_union_ (vr_arg);
2834 first = false;
2836 if (vr_result->varying_p ())
2837 break;
2841 if (vr_result->varying_p ())
2842 goto varying;
2843 else if (vr_result->undefined_p ())
2844 goto update_range;
2846 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
2847 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
2849 /* To prevent infinite iterations in the algorithm, derive ranges
2850 when the new value is slightly bigger or smaller than the
2851 previous one. We don't do this if we have seen a new executable
2852 edge; this helps us avoid an infinity for conditionals
2853 which are not in a loop. If the old value-range was VR_UNDEFINED
2854 use the updated range and iterate one more time. If we will not
2855 simulate this PHI again via the backedge allow us to iterate. */
2856 if (edges > 0
2857 && gimple_phi_num_args (phi) > 1
2858 && edges == old_edges
2859 && !lhs_vr->undefined_p ()
2860 && may_simulate_backedge_again)
2862 /* Compare old and new ranges, fall back to varying if the
2863 values are not comparable. */
2864 int cmp_min = compare_values (lhs_vr->min (), vr_result->min ());
2865 if (cmp_min == -2)
2866 goto varying;
2867 int cmp_max = compare_values (lhs_vr->max (), vr_result->max ());
2868 if (cmp_max == -2)
2869 goto varying;
2871 /* For non VR_RANGE or for pointers fall back to varying if
2872 the range changed. */
2873 if ((lhs_vr->kind () != VR_RANGE || vr_result->kind () != VR_RANGE
2874 || POINTER_TYPE_P (TREE_TYPE (lhs)))
2875 && (cmp_min != 0 || cmp_max != 0))
2876 goto varying;
2878 /* If the new minimum is larger than the previous one
2879 retain the old value. If the new minimum value is smaller
2880 than the previous one and not -INF go all the way to -INF + 1.
2881 In the first case, to avoid infinite bouncing between different
2882 minimums, and in the other case to avoid iterating millions of
2883 times to reach -INF. Going to -INF + 1 also lets the following
2884 iteration compute whether there will be any overflow, at the
2885 expense of one additional iteration. */
2886 tree new_min = vr_result->min ();
2887 tree new_max = vr_result->max ();
2888 if (cmp_min < 0)
2889 new_min = lhs_vr->min ();
2890 else if (cmp_min > 0
2891 && (TREE_CODE (vr_result->min ()) != INTEGER_CST
2892 || tree_int_cst_lt (vrp_val_min (vr_result->type ()),
2893 vr_result->min ())))
2894 new_min = int_const_binop (PLUS_EXPR,
2895 vrp_val_min (vr_result->type ()),
2896 build_int_cst (vr_result->type (), 1));
2898 /* Similarly for the maximum value. */
2899 if (cmp_max > 0)
2900 new_max = lhs_vr->max ();
2901 else if (cmp_max < 0
2902 && (TREE_CODE (vr_result->max ()) != INTEGER_CST
2903 || tree_int_cst_lt (vr_result->max (),
2904 vrp_val_max (vr_result->type ()))))
2905 new_max = int_const_binop (MINUS_EXPR,
2906 vrp_val_max (vr_result->type ()),
2907 build_int_cst (vr_result->type (), 1));
2909 vr_result->update (new_min, new_max, vr_result->kind ());
2911 /* If we dropped either bound to +-INF then if this is a loop
2912 PHI node SCEV may known more about its value-range. */
2913 if (cmp_min > 0 || cmp_min < 0
2914 || cmp_max < 0 || cmp_max > 0)
2915 goto scev_check;
2917 goto infinite_check;
2920 goto update_range;
2922 varying:
2923 vr_result->set_varying (TREE_TYPE (lhs));
2925 scev_check:
2926 /* If this is a loop PHI node SCEV may known more about its value-range.
2927 scev_check can be reached from two paths, one is a fall through from above
2928 "varying" label, the other is direct goto from code block which tries to
2929 avoid infinite simulation. */
2930 if (scev_initialized_p ()
2931 && (l = loop_containing_stmt (phi))
2932 && l->header == gimple_bb (phi))
2933 adjust_range_with_scev (vr_result, l, phi, lhs);
2935 infinite_check:
2936 /* If we will end up with a (-INF, +INF) range, set it to
2937 VARYING. Same if the previous max value was invalid for
2938 the type and we end up with vr_result.min > vr_result.max. */
2939 if ((!vr_result->varying_p () && !vr_result->undefined_p ())
2940 && !((vrp_val_is_max (vr_result->max ()) && vrp_val_is_min (vr_result->min ()))
2941 || compare_values (vr_result->min (), vr_result->max ()) > 0))
2943 else
2944 vr_result->set_varying (TREE_TYPE (lhs));
2946 /* If the new range is different than the previous value, keep
2947 iterating. */
2948 update_range:
2949 return;
2952 /* Simplify boolean operations if the source is known
2953 to be already a boolean. */
2954 bool
2955 simplify_using_ranges::simplify_truth_ops_using_ranges
2956 (gimple_stmt_iterator *gsi,
2957 gimple *stmt)
2959 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
2960 tree lhs, op0, op1;
2961 bool need_conversion;
2963 /* We handle only !=/== case here. */
2964 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
2966 op0 = gimple_assign_rhs1 (stmt);
2967 if (!op_with_boolean_value_range_p (op0, stmt))
2968 return false;
2970 op1 = gimple_assign_rhs2 (stmt);
2971 if (!op_with_boolean_value_range_p (op1, stmt))
2972 return false;
2974 /* Reduce number of cases to handle to NE_EXPR. As there is no
2975 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
2976 if (rhs_code == EQ_EXPR)
2978 if (TREE_CODE (op1) == INTEGER_CST)
2979 op1 = int_const_binop (BIT_XOR_EXPR, op1,
2980 build_int_cst (TREE_TYPE (op1), 1));
2981 else
2982 return false;
2985 lhs = gimple_assign_lhs (stmt);
2986 need_conversion
2987 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
2989 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
2990 if (need_conversion
2991 && !TYPE_UNSIGNED (TREE_TYPE (op0))
2992 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
2993 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
2994 return false;
2996 /* For A != 0 we can substitute A itself. */
2997 if (integer_zerop (op1))
2998 gimple_assign_set_rhs_with_ops (gsi,
2999 need_conversion
3000 ? NOP_EXPR : TREE_CODE (op0), op0);
3001 /* For A != B we substitute A ^ B. Either with conversion. */
3002 else if (need_conversion)
3004 tree tem = make_ssa_name (TREE_TYPE (op0));
3005 gassign *newop
3006 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
3007 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
3008 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
3009 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
3011 value_range vr (TREE_TYPE (tem),
3012 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
3013 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
3014 set_range_info (tem, vr);
3016 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
3018 /* Or without. */
3019 else
3020 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
3021 update_stmt (gsi_stmt (*gsi));
3022 fold_stmt (gsi, follow_single_use_edges);
3024 return true;
3027 /* Simplify a division or modulo operator to a right shift or bitwise and
3028 if the first operand is unsigned or is greater than zero and the second
3029 operand is an exact power of two. For TRUNC_MOD_EXPR op0 % op1 with
3030 constant op1 (op1min = op1) or with op1 in [op1min, op1max] range,
3031 optimize it into just op0 if op0's range is known to be a subset of
3032 [-op1min + 1, op1min - 1] for signed and [0, op1min - 1] for unsigned
3033 modulo. */
3035 bool
3036 simplify_using_ranges::simplify_div_or_mod_using_ranges
3037 (gimple_stmt_iterator *gsi,
3038 gimple *stmt)
3040 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
3041 tree val = NULL;
3042 tree op0 = gimple_assign_rhs1 (stmt);
3043 tree op1 = gimple_assign_rhs2 (stmt);
3044 tree op0min = NULL_TREE, op0max = NULL_TREE;
3045 tree op1min = op1;
3046 const value_range *vr = NULL;
3048 if (TREE_CODE (op0) == INTEGER_CST)
3050 op0min = op0;
3051 op0max = op0;
3053 else
3055 vr = query->get_value_range (op0, stmt);
3056 if (range_int_cst_p (vr))
3058 op0min = vr->min ();
3059 op0max = vr->max ();
3063 if (rhs_code == TRUNC_MOD_EXPR
3064 && TREE_CODE (op1) == SSA_NAME)
3066 const value_range_equiv *vr1 = query->get_value_range (op1, stmt);
3067 if (range_int_cst_p (vr1))
3068 op1min = vr1->min ();
3070 if (rhs_code == TRUNC_MOD_EXPR
3071 && TREE_CODE (op1min) == INTEGER_CST
3072 && tree_int_cst_sgn (op1min) == 1
3073 && op0max
3074 && tree_int_cst_lt (op0max, op1min))
3076 if (TYPE_UNSIGNED (TREE_TYPE (op0))
3077 || tree_int_cst_sgn (op0min) >= 0
3078 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1min), op1min),
3079 op0min))
3081 /* If op0 already has the range op0 % op1 has,
3082 then TRUNC_MOD_EXPR won't change anything. */
3083 gimple_assign_set_rhs_from_tree (gsi, op0);
3084 return true;
3088 if (TREE_CODE (op0) != SSA_NAME)
3089 return false;
3091 if (!integer_pow2p (op1))
3093 /* X % -Y can be only optimized into X % Y either if
3094 X is not INT_MIN, or Y is not -1. Fold it now, as after
3095 remove_range_assertions the range info might be not available
3096 anymore. */
3097 if (rhs_code == TRUNC_MOD_EXPR
3098 && fold_stmt (gsi, follow_single_use_edges))
3099 return true;
3100 return false;
3103 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
3104 val = integer_one_node;
3105 else
3107 bool sop = false;
3109 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
3111 if (val
3112 && sop
3113 && integer_onep (val)
3114 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
3116 location_t location;
3118 if (!gimple_has_location (stmt))
3119 location = input_location;
3120 else
3121 location = gimple_location (stmt);
3122 warning_at (location, OPT_Wstrict_overflow,
3123 "assuming signed overflow does not occur when "
3124 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
3128 if (val && integer_onep (val))
3130 tree t;
3132 if (rhs_code == TRUNC_DIV_EXPR)
3134 t = build_int_cst (integer_type_node, tree_log2 (op1));
3135 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
3136 gimple_assign_set_rhs1 (stmt, op0);
3137 gimple_assign_set_rhs2 (stmt, t);
3139 else
3141 t = build_int_cst (TREE_TYPE (op1), 1);
3142 t = int_const_binop (MINUS_EXPR, op1, t);
3143 t = fold_convert (TREE_TYPE (op0), t);
3145 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
3146 gimple_assign_set_rhs1 (stmt, op0);
3147 gimple_assign_set_rhs2 (stmt, t);
3150 update_stmt (stmt);
3151 fold_stmt (gsi, follow_single_use_edges);
3152 return true;
3155 return false;
3158 /* Simplify a min or max if the ranges of the two operands are
3159 disjoint. Return true if we do simplify. */
3161 bool
3162 simplify_using_ranges::simplify_min_or_max_using_ranges
3163 (gimple_stmt_iterator *gsi,
3164 gimple *stmt)
3166 tree op0 = gimple_assign_rhs1 (stmt);
3167 tree op1 = gimple_assign_rhs2 (stmt);
3168 bool sop = false;
3169 tree val;
3171 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
3172 (LE_EXPR, op0, op1, &sop, stmt));
3173 if (!val)
3175 sop = false;
3176 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
3177 (LT_EXPR, op0, op1, &sop, stmt));
3180 if (val)
3182 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
3184 location_t location;
3186 if (!gimple_has_location (stmt))
3187 location = input_location;
3188 else
3189 location = gimple_location (stmt);
3190 warning_at (location, OPT_Wstrict_overflow,
3191 "assuming signed overflow does not occur when "
3192 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
3195 /* VAL == TRUE -> OP0 < or <= op1
3196 VAL == FALSE -> OP0 > or >= op1. */
3197 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
3198 == integer_zerop (val)) ? op0 : op1;
3199 gimple_assign_set_rhs_from_tree (gsi, res);
3200 return true;
3203 return false;
3206 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
3207 ABS_EXPR. If the operand is <= 0, then simplify the
3208 ABS_EXPR into a NEGATE_EXPR. */
3210 bool
3211 simplify_using_ranges::simplify_abs_using_ranges (gimple_stmt_iterator *gsi,
3212 gimple *stmt)
3214 tree op = gimple_assign_rhs1 (stmt);
3215 const value_range *vr = query->get_value_range (op, stmt);
3217 if (vr)
3219 tree val = NULL;
3220 bool sop = false;
3222 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
3223 if (!val)
3225 /* The range is neither <= 0 nor > 0. Now see if it is
3226 either < 0 or >= 0. */
3227 sop = false;
3228 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
3229 &sop);
3232 if (val)
3234 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
3236 location_t location;
3238 if (!gimple_has_location (stmt))
3239 location = input_location;
3240 else
3241 location = gimple_location (stmt);
3242 warning_at (location, OPT_Wstrict_overflow,
3243 "assuming signed overflow does not occur when "
3244 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
3247 gimple_assign_set_rhs1 (stmt, op);
3248 if (integer_zerop (val))
3249 gimple_assign_set_rhs_code (stmt, SSA_NAME);
3250 else
3251 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
3252 update_stmt (stmt);
3253 fold_stmt (gsi, follow_single_use_edges);
3254 return true;
3258 return false;
3261 /* value_range wrapper for wi_set_zero_nonzero_bits.
3263 Return TRUE if VR was a constant range and we were able to compute
3264 the bit masks. */
3266 static bool
3267 vr_set_zero_nonzero_bits (const tree expr_type,
3268 const value_range *vr,
3269 wide_int *may_be_nonzero,
3270 wide_int *must_be_nonzero)
3272 if (range_int_cst_p (vr))
3274 wi_set_zero_nonzero_bits (expr_type,
3275 wi::to_wide (vr->min ()),
3276 wi::to_wide (vr->max ()),
3277 *may_be_nonzero, *must_be_nonzero);
3278 return true;
3280 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
3281 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
3282 return false;
3285 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
3286 If all the bits that are being cleared by & are already
3287 known to be zero from VR, or all the bits that are being
3288 set by | are already known to be one from VR, the bit
3289 operation is redundant. */
3291 bool
3292 simplify_using_ranges::simplify_bit_ops_using_ranges
3293 (gimple_stmt_iterator *gsi,
3294 gimple *stmt)
3296 tree op0 = gimple_assign_rhs1 (stmt);
3297 tree op1 = gimple_assign_rhs2 (stmt);
3298 tree op = NULL_TREE;
3299 value_range vr0, vr1;
3300 wide_int may_be_nonzero0, may_be_nonzero1;
3301 wide_int must_be_nonzero0, must_be_nonzero1;
3302 wide_int mask;
3304 if (TREE_CODE (op0) == SSA_NAME)
3305 vr0 = *(query->get_value_range (op0, stmt));
3306 else if (is_gimple_min_invariant (op0))
3307 vr0.set (op0, op0);
3308 else
3309 return false;
3311 if (TREE_CODE (op1) == SSA_NAME)
3312 vr1 = *(query->get_value_range (op1, stmt));
3313 else if (is_gimple_min_invariant (op1))
3314 vr1.set (op1, op1);
3315 else
3316 return false;
3318 if (!vr_set_zero_nonzero_bits (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
3319 &must_be_nonzero0))
3320 return false;
3321 if (!vr_set_zero_nonzero_bits (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
3322 &must_be_nonzero1))
3323 return false;
3325 switch (gimple_assign_rhs_code (stmt))
3327 case BIT_AND_EXPR:
3328 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
3329 if (mask == 0)
3331 op = op0;
3332 break;
3334 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
3335 if (mask == 0)
3337 op = op1;
3338 break;
3340 break;
3341 case BIT_IOR_EXPR:
3342 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
3343 if (mask == 0)
3345 op = op1;
3346 break;
3348 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
3349 if (mask == 0)
3351 op = op0;
3352 break;
3354 break;
3355 default:
3356 gcc_unreachable ();
3359 if (op == NULL_TREE)
3360 return false;
3362 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
3363 update_stmt (gsi_stmt (*gsi));
3364 return true;
3367 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
3368 a known value range VR.
3370 If there is one and only one value which will satisfy the
3371 conditional, then return that value. Else return NULL.
3373 If signed overflow must be undefined for the value to satisfy
3374 the conditional, then set *STRICT_OVERFLOW_P to true. */
3376 static tree
3377 test_for_singularity (enum tree_code cond_code, tree op0,
3378 tree op1, const value_range *vr)
3380 tree min = NULL;
3381 tree max = NULL;
3383 /* Extract minimum/maximum values which satisfy the conditional as it was
3384 written. */
3385 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
3387 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
3389 max = op1;
3390 if (cond_code == LT_EXPR)
3392 tree one = build_int_cst (TREE_TYPE (op0), 1);
3393 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
3394 /* Signal to compare_values_warnv this expr doesn't overflow. */
3395 if (EXPR_P (max))
3396 suppress_warning (max, OPT_Woverflow);
3399 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
3401 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
3403 min = op1;
3404 if (cond_code == GT_EXPR)
3406 tree one = build_int_cst (TREE_TYPE (op0), 1);
3407 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
3408 /* Signal to compare_values_warnv this expr doesn't overflow. */
3409 if (EXPR_P (min))
3410 suppress_warning (min, OPT_Woverflow);
3414 /* Now refine the minimum and maximum values using any
3415 value range information we have for op0. */
3416 if (min && max)
3418 tree type = TREE_TYPE (op0);
3419 tree tmin = wide_int_to_tree (type, vr->lower_bound ());
3420 tree tmax = wide_int_to_tree (type, vr->upper_bound ());
3421 if (compare_values (tmin, min) == 1)
3422 min = tmin;
3423 if (compare_values (tmax, max) == -1)
3424 max = tmax;
3426 /* If the new min/max values have converged to a single value,
3427 then there is only one value which can satisfy the condition,
3428 return that value. */
3429 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
3430 return min;
3432 return NULL;
3435 /* Return whether the value range *VR fits in an integer type specified
3436 by PRECISION and UNSIGNED_P. */
3438 bool
3439 range_fits_type_p (const value_range *vr,
3440 unsigned dest_precision, signop dest_sgn)
3442 tree src_type;
3443 unsigned src_precision;
3444 widest_int tem;
3445 signop src_sgn;
3447 /* We can only handle integral and pointer types. */
3448 src_type = vr->type ();
3449 if (!INTEGRAL_TYPE_P (src_type)
3450 && !POINTER_TYPE_P (src_type))
3451 return false;
3453 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
3454 and so is an identity transform. */
3455 src_precision = TYPE_PRECISION (vr->type ());
3456 src_sgn = TYPE_SIGN (src_type);
3457 if ((src_precision < dest_precision
3458 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
3459 || (src_precision == dest_precision && src_sgn == dest_sgn))
3460 return true;
3462 /* Now we can only handle ranges with constant bounds. */
3463 if (!range_int_cst_p (vr))
3464 return false;
3466 /* For sign changes, the MSB of the wide_int has to be clear.
3467 An unsigned value with its MSB set cannot be represented by
3468 a signed wide_int, while a negative value cannot be represented
3469 by an unsigned wide_int. */
3470 if (src_sgn != dest_sgn
3471 && (wi::lts_p (wi::to_wide (vr->min ()), 0)
3472 || wi::lts_p (wi::to_wide (vr->max ()), 0)))
3473 return false;
3475 /* Then we can perform the conversion on both ends and compare
3476 the result for equality. */
3477 tem = wi::ext (wi::to_widest (vr->min ()), dest_precision, dest_sgn);
3478 if (tem != wi::to_widest (vr->min ()))
3479 return false;
3480 tem = wi::ext (wi::to_widest (vr->max ()), dest_precision, dest_sgn);
3481 if (tem != wi::to_widest (vr->max ()))
3482 return false;
3484 return true;
3487 // Clear edge E of EDGE_EXECUTABLE (it is unexecutable). If it wasn't
3488 // previously clear, propagate to successor blocks if appropriate.
3490 void
3491 simplify_using_ranges::set_and_propagate_unexecutable (edge e)
3493 // If not_executable is already set, we're done.
3494 // This works in the absence of a flag as well.
3495 if ((e->flags & m_not_executable_flag) == m_not_executable_flag)
3496 return;
3498 e->flags |= m_not_executable_flag;
3499 m_flag_set_edges.safe_push (e);
3501 // Check if the destination block needs to propagate the property.
3502 basic_block bb = e->dest;
3504 // If any incoming edge is executable, we are done.
3505 edge_iterator ei;
3506 FOR_EACH_EDGE (e, ei, bb->preds)
3507 if ((e->flags & m_not_executable_flag) == 0)
3508 return;
3510 // This block is also unexecutable, propagate to all exit edges as well.
3511 FOR_EACH_EDGE (e, ei, bb->succs)
3512 set_and_propagate_unexecutable (e);
3515 /* If COND can be folded entirely as TRUE or FALSE, rewrite the
3516 conditional as such, and return TRUE. */
3518 bool
3519 simplify_using_ranges::fold_cond (gcond *cond)
3521 int_range_max r;
3522 if (query->range_of_stmt (r, cond) && r.singleton_p ())
3524 // COND has already been folded if arguments are constant.
3525 if (TREE_CODE (gimple_cond_lhs (cond)) != SSA_NAME
3526 && TREE_CODE (gimple_cond_rhs (cond)) != SSA_NAME)
3527 return false;
3528 if (dump_file)
3530 fprintf (dump_file, "Folding predicate ");
3531 print_gimple_expr (dump_file, cond, 0);
3532 fprintf (dump_file, " to ");
3534 edge e0 = EDGE_SUCC (gimple_bb (cond), 0);
3535 edge e1 = EDGE_SUCC (gimple_bb (cond), 1);
3536 if (r.zero_p ())
3538 if (dump_file)
3539 fprintf (dump_file, "0\n");
3540 gimple_cond_make_false (cond);
3541 if (e0->flags & EDGE_TRUE_VALUE)
3542 set_and_propagate_unexecutable (e0);
3543 else
3544 set_and_propagate_unexecutable (e1);
3546 else
3548 if (dump_file)
3549 fprintf (dump_file, "1\n");
3550 gimple_cond_make_true (cond);
3551 if (e0->flags & EDGE_FALSE_VALUE)
3552 set_and_propagate_unexecutable (e0);
3553 else
3554 set_and_propagate_unexecutable (e1);
3556 update_stmt (cond);
3557 return true;
3560 /* ?? vrp_folder::fold_predicate_in() is a superset of this. At
3561 some point we should merge all variants of this code. */
3562 edge taken_edge;
3563 vrp_visit_cond_stmt (cond, &taken_edge);
3565 if (taken_edge)
3567 if (taken_edge->flags & EDGE_TRUE_VALUE)
3569 if (dump_file && (dump_flags & TDF_DETAILS))
3570 fprintf (dump_file, "\nVRP Predicate evaluates to: 1\n");
3571 gimple_cond_make_true (cond);
3573 else if (taken_edge->flags & EDGE_FALSE_VALUE)
3575 if (dump_file && (dump_flags & TDF_DETAILS))
3576 fprintf (dump_file, "\nVRP Predicate evaluates to: 0\n");
3577 gimple_cond_make_false (cond);
3579 else
3580 gcc_unreachable ();
3581 update_stmt (cond);
3582 return true;
3584 return false;
3587 /* Simplify a conditional using a relational operator to an equality
3588 test if the range information indicates only one value can satisfy
3589 the original conditional. */
3591 bool
3592 simplify_using_ranges::simplify_cond_using_ranges_1 (gcond *stmt)
3594 tree op0 = gimple_cond_lhs (stmt);
3595 tree op1 = gimple_cond_rhs (stmt);
3596 enum tree_code cond_code = gimple_cond_code (stmt);
3598 if (fold_cond (stmt))
3599 return true;
3601 if (cond_code != NE_EXPR
3602 && cond_code != EQ_EXPR
3603 && TREE_CODE (op0) == SSA_NAME
3604 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
3605 && is_gimple_min_invariant (op1))
3607 const value_range *vr = query->get_value_range (op0, stmt);
3609 /* If we have range information for OP0, then we might be
3610 able to simplify this conditional. */
3611 if (!vr->undefined_p () && !vr->varying_p ())
3613 tree new_tree = test_for_singularity (cond_code, op0, op1, vr);
3614 if (new_tree)
3616 if (dump_file)
3618 fprintf (dump_file, "Simplified relational ");
3619 print_gimple_stmt (dump_file, stmt, 0);
3620 fprintf (dump_file, " into ");
3623 gimple_cond_set_code (stmt, EQ_EXPR);
3624 gimple_cond_set_lhs (stmt, op0);
3625 gimple_cond_set_rhs (stmt, new_tree);
3627 update_stmt (stmt);
3629 if (dump_file)
3631 print_gimple_stmt (dump_file, stmt, 0);
3632 fprintf (dump_file, "\n");
3635 return true;
3638 /* Try again after inverting the condition. We only deal
3639 with integral types here, so no need to worry about
3640 issues with inverting FP comparisons. */
3641 new_tree = test_for_singularity
3642 (invert_tree_comparison (cond_code, false),
3643 op0, op1, vr);
3644 if (new_tree)
3646 if (dump_file)
3648 fprintf (dump_file, "Simplified relational ");
3649 print_gimple_stmt (dump_file, stmt, 0);
3650 fprintf (dump_file, " into ");
3653 gimple_cond_set_code (stmt, NE_EXPR);
3654 gimple_cond_set_lhs (stmt, op0);
3655 gimple_cond_set_rhs (stmt, new_tree);
3657 update_stmt (stmt);
3659 if (dump_file)
3661 print_gimple_stmt (dump_file, stmt, 0);
3662 fprintf (dump_file, "\n");
3665 return true;
3669 // Try to simplify casted conditions.
3670 return simplify_casted_cond (stmt);
3673 /* STMT is a conditional at the end of a basic block.
3675 If the conditional is of the form SSA_NAME op constant and the SSA_NAME
3676 was set via a type conversion, try to replace the SSA_NAME with the RHS
3677 of the type conversion. Doing so makes the conversion dead which helps
3678 subsequent passes. */
3680 bool
3681 simplify_using_ranges::simplify_casted_cond (gcond *stmt)
3683 tree op0 = gimple_cond_lhs (stmt);
3684 tree op1 = gimple_cond_rhs (stmt);
3686 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
3687 see if OP0 was set by a type conversion where the source of
3688 the conversion is another SSA_NAME with a range that fits
3689 into the range of OP0's type.
3691 If so, the conversion is redundant as the earlier SSA_NAME can be
3692 used for the comparison directly if we just massage the constant in the
3693 comparison. */
3694 if (TREE_CODE (op0) == SSA_NAME
3695 && TREE_CODE (op1) == INTEGER_CST)
3697 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
3698 tree innerop;
3700 if (!is_gimple_assign (def_stmt))
3701 return false;
3703 switch (gimple_assign_rhs_code (def_stmt))
3705 CASE_CONVERT:
3706 innerop = gimple_assign_rhs1 (def_stmt);
3707 break;
3708 case VIEW_CONVERT_EXPR:
3709 innerop = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), 0);
3710 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop)))
3711 return false;
3712 break;
3713 default:
3714 return false;
3717 if (TREE_CODE (innerop) == SSA_NAME
3718 && !POINTER_TYPE_P (TREE_TYPE (innerop))
3719 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
3720 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
3722 const value_range *vr = query->get_value_range (innerop);
3724 if (range_int_cst_p (vr)
3725 && range_fits_type_p (vr,
3726 TYPE_PRECISION (TREE_TYPE (op0)),
3727 TYPE_SIGN (TREE_TYPE (op0)))
3728 && int_fits_type_p (op1, TREE_TYPE (innerop)))
3730 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
3731 gimple_cond_set_lhs (stmt, innerop);
3732 gimple_cond_set_rhs (stmt, newconst);
3733 update_stmt (stmt);
3734 return true;
3738 return false;
3741 /* Simplify a switch statement using the value range of the switch
3742 argument. */
3744 bool
3745 simplify_using_ranges::simplify_switch_using_ranges (gswitch *stmt)
3747 tree op = gimple_switch_index (stmt);
3748 const value_range *vr = NULL;
3749 bool take_default;
3750 edge e;
3751 edge_iterator ei;
3752 size_t i = 0, j = 0, n, n2;
3753 tree vec2;
3754 switch_update su;
3755 size_t k = 1, l = 0;
3757 if (TREE_CODE (op) == SSA_NAME)
3759 vr = query->get_value_range (op, stmt);
3761 /* We can only handle integer ranges. */
3762 if (vr->varying_p ()
3763 || vr->undefined_p ()
3764 || vr->symbolic_p ())
3765 return false;
3767 /* Find case label for min/max of the value range. */
3768 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
3770 else if (TREE_CODE (op) == INTEGER_CST)
3772 take_default = !find_case_label_index (stmt, 1, op, &i);
3773 if (take_default)
3775 i = 1;
3776 j = 0;
3778 else
3780 j = i;
3783 else
3784 return false;
3786 n = gimple_switch_num_labels (stmt);
3788 /* We can truncate the case label ranges that partially overlap with OP's
3789 value range. */
3790 size_t min_idx = 1, max_idx = 0;
3791 if (vr != NULL)
3792 find_case_label_range (stmt, vr->min (), vr->max (), &min_idx, &max_idx);
3793 if (min_idx <= max_idx)
3795 tree min_label = gimple_switch_label (stmt, min_idx);
3796 tree max_label = gimple_switch_label (stmt, max_idx);
3798 /* Avoid changing the type of the case labels when truncating. */
3799 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
3800 tree vr_min = fold_convert (case_label_type, vr->min ());
3801 tree vr_max = fold_convert (case_label_type, vr->max ());
3803 if (vr->kind () == VR_RANGE)
3805 /* If OP's value range is [2,8] and the low label range is
3806 0 ... 3, truncate the label's range to 2 .. 3. */
3807 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
3808 && CASE_HIGH (min_label) != NULL_TREE
3809 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
3810 CASE_LOW (min_label) = vr_min;
3812 /* If OP's value range is [2,8] and the high label range is
3813 7 ... 10, truncate the label's range to 7 .. 8. */
3814 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
3815 && CASE_HIGH (max_label) != NULL_TREE
3816 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
3817 CASE_HIGH (max_label) = vr_max;
3819 else if (vr->kind () == VR_ANTI_RANGE)
3821 tree one_cst = build_one_cst (case_label_type);
3823 if (min_label == max_label)
3825 /* If OP's value range is ~[7,8] and the label's range is
3826 7 ... 10, truncate the label's range to 9 ... 10. */
3827 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
3828 && CASE_HIGH (min_label) != NULL_TREE
3829 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
3830 CASE_LOW (min_label)
3831 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
3833 /* If OP's value range is ~[7,8] and the label's range is
3834 5 ... 8, truncate the label's range to 5 ... 6. */
3835 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
3836 && CASE_HIGH (min_label) != NULL_TREE
3837 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
3838 CASE_HIGH (min_label)
3839 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
3841 else
3843 /* If OP's value range is ~[2,8] and the low label range is
3844 0 ... 3, truncate the label's range to 0 ... 1. */
3845 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
3846 && CASE_HIGH (min_label) != NULL_TREE
3847 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
3848 CASE_HIGH (min_label)
3849 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
3851 /* If OP's value range is ~[2,8] and the high label range is
3852 7 ... 10, truncate the label's range to 9 ... 10. */
3853 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
3854 && CASE_HIGH (max_label) != NULL_TREE
3855 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
3856 CASE_LOW (max_label)
3857 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
3861 /* Canonicalize singleton case ranges. */
3862 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
3863 CASE_HIGH (min_label) = NULL_TREE;
3864 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
3865 CASE_HIGH (max_label) = NULL_TREE;
3868 /* We can also eliminate case labels that lie completely outside OP's value
3869 range. */
3871 /* Bail out if this is just all edges taken. */
3872 if (i == 1
3873 && j == n - 1
3874 && take_default)
3875 return false;
3877 /* Build a new vector of taken case labels. */
3878 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
3879 n2 = 0;
3881 /* Add the default edge, if necessary. */
3882 if (take_default)
3883 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
3885 for (; i <= j; ++i, ++n2)
3886 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
3888 for (; k <= l; ++k, ++n2)
3889 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
3891 /* Mark needed edges. */
3892 for (i = 0; i < n2; ++i)
3894 e = find_edge (gimple_bb (stmt),
3895 label_to_block (cfun,
3896 CASE_LABEL (TREE_VEC_ELT (vec2, i))));
3897 e->aux = (void *)-1;
3900 /* Queue not needed edges for later removal. */
3901 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
3903 if (e->aux == (void *)-1)
3905 e->aux = NULL;
3906 continue;
3909 if (dump_file && (dump_flags & TDF_DETAILS))
3911 fprintf (dump_file, "removing unreachable case label\n");
3913 to_remove_edges.safe_push (e);
3914 set_and_propagate_unexecutable (e);
3915 e->flags &= ~EDGE_EXECUTABLE;
3916 e->flags |= EDGE_IGNORE;
3919 /* And queue an update for the stmt. */
3920 su.stmt = stmt;
3921 su.vec = vec2;
3922 to_update_switch_stmts.safe_push (su);
3923 return true;
3926 void
3927 simplify_using_ranges::cleanup_edges_and_switches (void)
3929 int i;
3930 edge e;
3931 switch_update *su;
3933 /* Clear any edges marked as not executable. */
3934 if (m_not_executable_flag)
3936 FOR_EACH_VEC_ELT (m_flag_set_edges, i, e)
3937 e->flags &= ~m_not_executable_flag;
3939 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
3940 CFG in a broken state and requires a cfg_cleanup run. */
3941 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
3942 remove_edge (e);
3944 /* Update SWITCH_EXPR case label vector. */
3945 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
3947 size_t j;
3948 size_t n = TREE_VEC_LENGTH (su->vec);
3949 tree label;
3950 gimple_switch_set_num_labels (su->stmt, n);
3951 for (j = 0; j < n; j++)
3952 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
3953 /* As we may have replaced the default label with a regular one
3954 make sure to make it a real default label again. This ensures
3955 optimal expansion. */
3956 label = gimple_switch_label (su->stmt, 0);
3957 CASE_LOW (label) = NULL_TREE;
3958 CASE_HIGH (label) = NULL_TREE;
3961 if (!to_remove_edges.is_empty ())
3963 free_dominance_info (CDI_DOMINATORS);
3964 loops_state_set (LOOPS_NEED_FIXUP);
3967 to_remove_edges.release ();
3968 to_update_switch_stmts.release ();
3971 /* Simplify an integral conversion from an SSA name in STMT. */
3973 static bool
3974 simplify_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
3976 tree innerop, middleop, finaltype;
3977 gimple *def_stmt;
3978 signop inner_sgn, middle_sgn, final_sgn;
3979 unsigned inner_prec, middle_prec, final_prec;
3980 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
3982 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
3983 if (!INTEGRAL_TYPE_P (finaltype))
3984 return false;
3985 middleop = gimple_assign_rhs1 (stmt);
3986 def_stmt = SSA_NAME_DEF_STMT (middleop);
3987 if (!is_gimple_assign (def_stmt)
3988 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
3989 return false;
3990 innerop = gimple_assign_rhs1 (def_stmt);
3991 if (TREE_CODE (innerop) != SSA_NAME
3992 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
3993 return false;
3995 /* Get the value-range of the inner operand. Use global ranges in
3996 case innerop was created during substitute-and-fold. */
3997 wide_int imin, imax;
3998 value_range vr;
3999 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop)))
4000 return false;
4001 get_range_query (cfun)->range_of_expr (vr, innerop, stmt);
4002 if (vr.undefined_p () || vr.varying_p ())
4003 return false;
4004 innermin = widest_int::from (vr.lower_bound (), TYPE_SIGN (TREE_TYPE (innerop)));
4005 innermax = widest_int::from (vr.upper_bound (), TYPE_SIGN (TREE_TYPE (innerop)));
4007 /* Simulate the conversion chain to check if the result is equal if
4008 the middle conversion is removed. */
4009 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
4010 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
4011 final_prec = TYPE_PRECISION (finaltype);
4013 /* If the first conversion is not injective, the second must not
4014 be widening. */
4015 if (wi::gtu_p (innermax - innermin,
4016 wi::mask <widest_int> (middle_prec, false))
4017 && middle_prec < final_prec)
4018 return false;
4019 /* We also want a medium value so that we can track the effect that
4020 narrowing conversions with sign change have. */
4021 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
4022 if (inner_sgn == UNSIGNED)
4023 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
4024 else
4025 innermed = 0;
4026 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
4027 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
4028 innermed = innermin;
4030 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
4031 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
4032 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
4033 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
4035 /* Require that the final conversion applied to both the original
4036 and the intermediate range produces the same result. */
4037 final_sgn = TYPE_SIGN (finaltype);
4038 if (wi::ext (middlemin, final_prec, final_sgn)
4039 != wi::ext (innermin, final_prec, final_sgn)
4040 || wi::ext (middlemed, final_prec, final_sgn)
4041 != wi::ext (innermed, final_prec, final_sgn)
4042 || wi::ext (middlemax, final_prec, final_sgn)
4043 != wi::ext (innermax, final_prec, final_sgn))
4044 return false;
4046 gimple_assign_set_rhs1 (stmt, innerop);
4047 fold_stmt (gsi, follow_single_use_edges);
4048 return true;
4051 /* Simplify a conversion from integral SSA name to float in STMT. */
4053 bool
4054 simplify_using_ranges::simplify_float_conversion_using_ranges
4055 (gimple_stmt_iterator *gsi,
4056 gimple *stmt)
4058 tree rhs1 = gimple_assign_rhs1 (stmt);
4059 const value_range *vr = query->get_value_range (rhs1, stmt);
4060 scalar_float_mode fltmode
4061 = SCALAR_FLOAT_TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
4062 scalar_int_mode mode;
4063 tree tem;
4064 gassign *conv;
4066 /* We can only handle constant ranges. */
4067 if (!range_int_cst_p (vr))
4068 return false;
4070 /* First check if we can use a signed type in place of an unsigned. */
4071 scalar_int_mode rhs_mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (rhs1));
4072 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
4073 && can_float_p (fltmode, rhs_mode, 0) != CODE_FOR_nothing
4074 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
4075 mode = rhs_mode;
4076 /* If we can do the conversion in the current input mode do nothing. */
4077 else if (can_float_p (fltmode, rhs_mode,
4078 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
4079 return false;
4080 /* Otherwise search for a mode we can use, starting from the narrowest
4081 integer mode available. */
4082 else
4084 mode = NARROWEST_INT_MODE;
4085 for (;;)
4087 /* If we cannot do a signed conversion to float from mode
4088 or if the value-range does not fit in the signed type
4089 try with a wider mode. */
4090 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
4091 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
4092 break;
4094 /* But do not widen the input. Instead leave that to the
4095 optabs expansion code. */
4096 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
4097 || GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
4098 return false;
4102 /* It works, insert a truncation or sign-change before the
4103 float conversion. */
4104 tem = make_ssa_name (build_nonstandard_integer_type
4105 (GET_MODE_PRECISION (mode), 0));
4106 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
4107 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
4108 gimple_assign_set_rhs1 (stmt, tem);
4109 fold_stmt (gsi, follow_single_use_edges);
4111 return true;
4114 /* Simplify an internal fn call using ranges if possible. */
4116 bool
4117 simplify_using_ranges::simplify_internal_call_using_ranges
4118 (gimple_stmt_iterator *gsi,
4119 gimple *stmt)
4121 enum tree_code subcode;
4122 bool is_ubsan = false;
4123 bool ovf = false;
4124 switch (gimple_call_internal_fn (stmt))
4126 case IFN_UBSAN_CHECK_ADD:
4127 subcode = PLUS_EXPR;
4128 is_ubsan = true;
4129 break;
4130 case IFN_UBSAN_CHECK_SUB:
4131 subcode = MINUS_EXPR;
4132 is_ubsan = true;
4133 break;
4134 case IFN_UBSAN_CHECK_MUL:
4135 subcode = MULT_EXPR;
4136 is_ubsan = true;
4137 break;
4138 case IFN_ADD_OVERFLOW:
4139 subcode = PLUS_EXPR;
4140 break;
4141 case IFN_SUB_OVERFLOW:
4142 subcode = MINUS_EXPR;
4143 break;
4144 case IFN_MUL_OVERFLOW:
4145 subcode = MULT_EXPR;
4146 break;
4147 default:
4148 return false;
4151 tree op0 = gimple_call_arg (stmt, 0);
4152 tree op1 = gimple_call_arg (stmt, 1);
4153 tree type;
4154 if (is_ubsan)
4156 type = TREE_TYPE (op0);
4157 if (VECTOR_TYPE_P (type))
4158 return false;
4160 else if (gimple_call_lhs (stmt) == NULL_TREE)
4161 return false;
4162 else
4163 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
4164 if (!check_for_binary_op_overflow (query, subcode, type, op0, op1, &ovf, stmt)
4165 || (is_ubsan && ovf))
4166 return false;
4168 gimple *g;
4169 location_t loc = gimple_location (stmt);
4170 if (is_ubsan)
4171 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
4172 else
4174 int prec = TYPE_PRECISION (type);
4175 tree utype = type;
4176 if (ovf
4177 || !useless_type_conversion_p (type, TREE_TYPE (op0))
4178 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
4179 utype = build_nonstandard_integer_type (prec, 1);
4180 if (TREE_CODE (op0) == INTEGER_CST)
4181 op0 = fold_convert (utype, op0);
4182 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
4184 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
4185 gimple_set_location (g, loc);
4186 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4187 op0 = gimple_assign_lhs (g);
4189 if (TREE_CODE (op1) == INTEGER_CST)
4190 op1 = fold_convert (utype, op1);
4191 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
4193 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
4194 gimple_set_location (g, loc);
4195 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4196 op1 = gimple_assign_lhs (g);
4198 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
4199 gimple_set_location (g, loc);
4200 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4201 if (utype != type)
4203 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
4204 gimple_assign_lhs (g));
4205 gimple_set_location (g, loc);
4206 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4208 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
4209 gimple_assign_lhs (g),
4210 build_int_cst (type, ovf));
4212 gimple_set_location (g, loc);
4213 gsi_replace (gsi, g, false);
4214 return true;
4217 /* Return true if VAR is a two-valued variable. Set a and b with the
4218 two-values when it is true. Return false otherwise. */
4220 bool
4221 simplify_using_ranges::two_valued_val_range_p (tree var, tree *a, tree *b,
4222 gimple *s)
4224 value_range vr = *query->get_value_range (var, s);
4225 vr.normalize_symbolics ();
4226 if (vr.varying_p () || vr.undefined_p ())
4227 return false;
4229 if ((vr.num_pairs () == 1 && vr.upper_bound () - vr.lower_bound () == 1)
4230 || (vr.num_pairs () == 2
4231 && vr.lower_bound (0) == vr.upper_bound (0)
4232 && vr.lower_bound (1) == vr.upper_bound (1)))
4234 *a = wide_int_to_tree (TREE_TYPE (var), vr.lower_bound ());
4235 *b = wide_int_to_tree (TREE_TYPE (var), vr.upper_bound ());
4236 return true;
4238 return false;
4241 simplify_using_ranges::simplify_using_ranges (range_query *query,
4242 int not_executable_flag)
4243 : query (query)
4245 to_remove_edges = vNULL;
4246 to_update_switch_stmts = vNULL;
4247 m_not_executable_flag = not_executable_flag;
4248 m_flag_set_edges = vNULL;
4251 simplify_using_ranges::~simplify_using_ranges ()
4253 cleanup_edges_and_switches ();
4254 m_flag_set_edges.release ();
4257 /* Simplify STMT using ranges if possible. */
4259 bool
4260 simplify_using_ranges::simplify (gimple_stmt_iterator *gsi)
4262 gcc_checking_assert (query);
4264 gimple *stmt = gsi_stmt (*gsi);
4265 if (is_gimple_assign (stmt))
4267 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
4268 tree rhs1 = gimple_assign_rhs1 (stmt);
4269 tree rhs2 = gimple_assign_rhs2 (stmt);
4270 tree lhs = gimple_assign_lhs (stmt);
4271 tree val1 = NULL_TREE, val2 = NULL_TREE;
4272 use_operand_p use_p;
4273 gimple *use_stmt;
4275 /* Convert:
4276 LHS = CST BINOP VAR
4277 Where VAR is two-valued and LHS is used in GIMPLE_COND only
4279 LHS = VAR == VAL1 ? (CST BINOP VAL1) : (CST BINOP VAL2)
4281 Also handles:
4282 LHS = VAR BINOP CST
4283 Where VAR is two-valued and LHS is used in GIMPLE_COND only
4285 LHS = VAR == VAL1 ? (VAL1 BINOP CST) : (VAL2 BINOP CST) */
4287 if (TREE_CODE_CLASS (rhs_code) == tcc_binary
4288 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
4289 && ((TREE_CODE (rhs1) == INTEGER_CST
4290 && TREE_CODE (rhs2) == SSA_NAME)
4291 || (TREE_CODE (rhs2) == INTEGER_CST
4292 && TREE_CODE (rhs1) == SSA_NAME))
4293 && single_imm_use (lhs, &use_p, &use_stmt)
4294 && gimple_code (use_stmt) == GIMPLE_COND)
4297 tree new_rhs1 = NULL_TREE;
4298 tree new_rhs2 = NULL_TREE;
4299 tree cmp_var = NULL_TREE;
4301 if (TREE_CODE (rhs2) == SSA_NAME
4302 && two_valued_val_range_p (rhs2, &val1, &val2, stmt))
4304 /* Optimize RHS1 OP [VAL1, VAL2]. */
4305 new_rhs1 = int_const_binop (rhs_code, rhs1, val1);
4306 new_rhs2 = int_const_binop (rhs_code, rhs1, val2);
4307 cmp_var = rhs2;
4309 else if (TREE_CODE (rhs1) == SSA_NAME
4310 && two_valued_val_range_p (rhs1, &val1, &val2, stmt))
4312 /* Optimize [VAL1, VAL2] OP RHS2. */
4313 new_rhs1 = int_const_binop (rhs_code, val1, rhs2);
4314 new_rhs2 = int_const_binop (rhs_code, val2, rhs2);
4315 cmp_var = rhs1;
4318 /* If we could not find two-vals or the optimzation is invalid as
4319 in divide by zero, new_rhs1 / new_rhs will be NULL_TREE. */
4320 if (new_rhs1 && new_rhs2)
4322 tree cond = gimple_build (gsi, true, GSI_SAME_STMT,
4323 UNKNOWN_LOCATION,
4324 EQ_EXPR, boolean_type_node,
4325 cmp_var, val1);
4326 gimple_assign_set_rhs_with_ops (gsi,
4327 COND_EXPR, cond,
4328 new_rhs1,
4329 new_rhs2);
4330 update_stmt (gsi_stmt (*gsi));
4331 fold_stmt (gsi, follow_single_use_edges);
4332 return true;
4336 switch (rhs_code)
4338 case EQ_EXPR:
4339 case NE_EXPR:
4340 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
4341 if the RHS is zero or one, and the LHS are known to be boolean
4342 values. */
4343 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4344 return simplify_truth_ops_using_ranges (gsi, stmt);
4345 break;
4347 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
4348 and BIT_AND_EXPR respectively if the first operand is greater
4349 than zero and the second operand is an exact power of two.
4350 Also optimize TRUNC_MOD_EXPR away if the second operand is
4351 constant and the first operand already has the right value
4352 range. */
4353 case TRUNC_DIV_EXPR:
4354 case TRUNC_MOD_EXPR:
4355 if ((TREE_CODE (rhs1) == SSA_NAME
4356 || TREE_CODE (rhs1) == INTEGER_CST)
4357 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4358 return simplify_div_or_mod_using_ranges (gsi, stmt);
4359 break;
4361 /* Transform ABS (X) into X or -X as appropriate. */
4362 case ABS_EXPR:
4363 if (TREE_CODE (rhs1) == SSA_NAME
4364 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4365 return simplify_abs_using_ranges (gsi, stmt);
4366 break;
4368 case BIT_AND_EXPR:
4369 case BIT_IOR_EXPR:
4370 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
4371 if all the bits being cleared are already cleared or
4372 all the bits being set are already set. */
4373 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4374 return simplify_bit_ops_using_ranges (gsi, stmt);
4375 break;
4377 CASE_CONVERT:
4378 if (TREE_CODE (rhs1) == SSA_NAME
4379 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4380 return simplify_conversion_using_ranges (gsi, stmt);
4381 break;
4383 case FLOAT_EXPR:
4384 if (TREE_CODE (rhs1) == SSA_NAME
4385 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4386 return simplify_float_conversion_using_ranges (gsi, stmt);
4387 break;
4389 case MIN_EXPR:
4390 case MAX_EXPR:
4391 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4392 return simplify_min_or_max_using_ranges (gsi, stmt);
4393 break;
4395 case RSHIFT_EXPR:
4397 tree op0 = gimple_assign_rhs1 (stmt);
4398 tree type = TREE_TYPE (op0);
4399 int_range_max range;
4400 if (TYPE_SIGN (type) == SIGNED
4401 && query->range_of_expr (range, op0, stmt))
4403 unsigned prec = TYPE_PRECISION (TREE_TYPE (op0));
4404 int_range<2> nzm1 (type, wi::minus_one (prec), wi::zero (prec),
4405 VR_ANTI_RANGE);
4406 range.intersect (nzm1);
4407 // If there are no ranges other than [-1, 0] remove the shift.
4408 if (range.undefined_p ())
4410 gimple_assign_set_rhs_from_tree (gsi, op0);
4411 return true;
4413 return false;
4415 break;
4417 default:
4418 break;
4421 else if (gimple_code (stmt) == GIMPLE_COND)
4422 return simplify_cond_using_ranges_1 (as_a <gcond *> (stmt));
4423 else if (gimple_code (stmt) == GIMPLE_SWITCH)
4424 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
4425 else if (is_gimple_call (stmt)
4426 && gimple_call_internal_p (stmt))
4427 return simplify_internal_call_using_ranges (gsi, stmt);
4429 return false;
4432 /* Set the lattice entry for VAR to VR. */
4434 void
4435 vr_values::set_vr_value (tree var, value_range_equiv *vr)
4437 if (SSA_NAME_VERSION (var) >= num_vr_values)
4438 return;
4439 vr_value[SSA_NAME_VERSION (var)] = vr;
4442 /* Swap the lattice entry for VAR with VR and return the old entry. */
4444 value_range_equiv *
4445 vr_values::swap_vr_value (tree var, value_range_equiv *vr)
4447 if (SSA_NAME_VERSION (var) >= num_vr_values)
4448 return NULL;
4449 std::swap (vr_value[SSA_NAME_VERSION (var)], vr);
4450 return vr;