[aarch64] Use op_mode instead of vmode in aarch64_vectorize_vec_perm_const.
[official-gcc.git] / gcc / vr-values.cc
blob6b9c630fed34ee1d87a5dd8b3839aaaaa61abc2c
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->undefined_p () || vr->constant_p ())
188 r = *vr;
189 else
191 value_range tmp = *vr;
192 tmp.normalize_symbolics ();
193 r = tmp;
195 return true;
197 return false;
200 tree
201 vr_values::value_of_expr (tree op, gimple *)
203 return op_with_constant_singleton_value_range (op);
206 tree
207 vr_values::value_on_edge (edge, tree op)
209 return op_with_constant_singleton_value_range (op);
212 tree
213 vr_values::value_of_stmt (gimple *stmt, tree op)
215 if (!op)
216 op = gimple_get_lhs (stmt);
218 gcc_checking_assert (!op|| op == gimple_get_lhs (stmt));
220 if (op)
221 return op_with_constant_singleton_value_range (op);
222 return NULL_TREE;
225 /* Set the lattice entry for DEF to VARYING. */
227 void
228 vr_values::set_def_to_varying (const_tree def)
230 value_range_equiv *vr = get_lattice_entry (def);
231 if (vr)
232 vr->set_varying (TREE_TYPE (def));
235 /* Set value-ranges of all SSA names defined by STMT to varying. */
237 void
238 vr_values::set_defs_to_varying (gimple *stmt)
240 ssa_op_iter i;
241 tree def;
242 FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
243 set_def_to_varying (def);
246 /* Update the value range and equivalence set for variable VAR to
247 NEW_VR. Return true if NEW_VR is different from VAR's previous
248 value.
250 NOTE: This function assumes that NEW_VR is a temporary value range
251 object created for the sole purpose of updating VAR's range. The
252 storage used by the equivalence set from NEW_VR will be freed by
253 this function. Do not call update_value_range when NEW_VR
254 is the range object associated with another SSA name. */
256 bool
257 vr_values::update_value_range (const_tree var, value_range_equiv *new_vr)
259 value_range_equiv *old_vr;
260 bool is_new;
262 /* If there is a value-range on the SSA name from earlier analysis
263 factor that in. */
264 if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
266 value_range_equiv nr;
267 get_global_range_query ()->range_of_expr (nr, const_cast <tree> (var));
268 if (!nr.undefined_p ())
269 new_vr->legacy_verbose_intersect (&nr);
272 /* Update the value range, if necessary. If we cannot allocate a lattice
273 entry for VAR keep it at VARYING. This happens when DOM feeds us stmts
274 with SSA names allocated after setting up the lattice. */
275 old_vr = get_lattice_entry (var);
276 if (!old_vr)
277 return false;
278 is_new = !old_vr->equal_p (*new_vr, /*ignore_equivs=*/false);
280 if (is_new)
282 /* Do not allow transitions up the lattice. The following
283 is slightly more awkward than just new_vr->type < old_vr->type
284 because VR_RANGE and VR_ANTI_RANGE need to be considered
285 the same. We may not have is_new when transitioning to
286 UNDEFINED. If old_vr->type is VARYING, we shouldn't be
287 called, if we are anyway, keep it VARYING. */
288 if (old_vr->varying_p ())
290 new_vr->set_varying (TREE_TYPE (var));
291 is_new = false;
293 else if (new_vr->undefined_p ())
295 old_vr->set_varying (TREE_TYPE (var));
296 new_vr->set_varying (TREE_TYPE (var));
297 return true;
299 else
300 old_vr->set (new_vr->min (), new_vr->max (), new_vr->equiv (),
301 new_vr->kind ());
304 new_vr->equiv_clear ();
306 return is_new;
309 /* Return true if value range VR involves exactly one symbol SYM. */
311 static bool
312 symbolic_range_based_on_p (value_range *vr, const_tree sym)
314 bool neg, min_has_symbol, max_has_symbol;
315 tree inv;
317 if (is_gimple_min_invariant (vr->min ()))
318 min_has_symbol = false;
319 else if (get_single_symbol (vr->min (), &neg, &inv) == sym)
320 min_has_symbol = true;
321 else
322 return false;
324 if (is_gimple_min_invariant (vr->max ()))
325 max_has_symbol = false;
326 else if (get_single_symbol (vr->max (), &neg, &inv) == sym)
327 max_has_symbol = true;
328 else
329 return false;
331 return (min_has_symbol || max_has_symbol);
334 /* Return true if the result of assignment STMT is know to be non-zero. */
336 static bool
337 gimple_assign_nonzero_p (gimple *stmt)
339 enum tree_code code = gimple_assign_rhs_code (stmt);
340 bool strict_overflow_p;
341 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
342 switch (get_gimple_rhs_class (code))
344 case GIMPLE_UNARY_RHS:
345 return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
346 type,
347 gimple_assign_rhs1 (stmt),
348 &strict_overflow_p);
349 case GIMPLE_BINARY_RHS:
350 return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
351 type,
352 gimple_assign_rhs1 (stmt),
353 gimple_assign_rhs2 (stmt),
354 &strict_overflow_p);
355 case GIMPLE_TERNARY_RHS:
356 return false;
357 case GIMPLE_SINGLE_RHS:
358 return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
359 &strict_overflow_p);
360 case GIMPLE_INVALID_RHS:
361 gcc_unreachable ();
362 default:
363 gcc_unreachable ();
367 /* Return true if STMT is known to compute a non-zero value. */
369 static bool
370 gimple_stmt_nonzero_p (gimple *stmt)
372 switch (gimple_code (stmt))
374 case GIMPLE_ASSIGN:
375 return gimple_assign_nonzero_p (stmt);
376 case GIMPLE_CALL:
378 gcall *call_stmt = as_a<gcall *> (stmt);
379 return (gimple_call_nonnull_result_p (call_stmt)
380 || gimple_call_nonnull_arg (call_stmt));
382 default:
383 gcc_unreachable ();
386 /* Like tree_expr_nonzero_p, but this function uses value ranges
387 obtained so far. */
389 bool
390 vr_values::vrp_stmt_computes_nonzero (gimple *stmt)
392 if (gimple_stmt_nonzero_p (stmt))
393 return true;
395 /* If we have an expression of the form &X->a, then the expression
396 is nonnull if X is nonnull. */
397 if (is_gimple_assign (stmt)
398 && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
400 tree expr = gimple_assign_rhs1 (stmt);
401 poly_int64 bitsize, bitpos;
402 tree offset;
403 machine_mode mode;
404 int unsignedp, reversep, volatilep;
405 tree base = get_inner_reference (TREE_OPERAND (expr, 0), &bitsize,
406 &bitpos, &offset, &mode, &unsignedp,
407 &reversep, &volatilep);
409 if (base != NULL_TREE
410 && TREE_CODE (base) == MEM_REF
411 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
413 poly_offset_int off = 0;
414 bool off_cst = false;
415 if (offset == NULL_TREE || TREE_CODE (offset) == INTEGER_CST)
417 off = mem_ref_offset (base);
418 if (offset)
419 off += poly_offset_int::from (wi::to_poly_wide (offset),
420 SIGNED);
421 off <<= LOG2_BITS_PER_UNIT;
422 off += bitpos;
423 off_cst = true;
425 /* If &X->a is equal to X and X is ~[0, 0], the result is too.
426 For -fdelete-null-pointer-checks -fno-wrapv-pointer we don't
427 allow going from non-NULL pointer to NULL. */
428 if ((off_cst && known_eq (off, 0))
429 || (flag_delete_null_pointer_checks
430 && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (expr))))
432 const value_range_equiv *vr
433 = get_value_range (TREE_OPERAND (base, 0), stmt);
434 if (!range_includes_zero_p (vr))
435 return true;
437 /* If MEM_REF has a "positive" offset, consider it non-NULL
438 always, for -fdelete-null-pointer-checks also "negative"
439 ones. Punt for unknown offsets (e.g. variable ones). */
440 if (!TYPE_OVERFLOW_WRAPS (TREE_TYPE (expr))
441 && off_cst
442 && known_ne (off, 0)
443 && (flag_delete_null_pointer_checks || known_gt (off, 0)))
444 return true;
448 return false;
451 /* Returns true if EXPR is a valid value (as expected by compare_values) --
452 a gimple invariant, or SSA_NAME +- CST. */
454 static bool
455 valid_value_p (tree expr)
457 if (TREE_CODE (expr) == SSA_NAME)
458 return true;
460 if (TREE_CODE (expr) == PLUS_EXPR
461 || TREE_CODE (expr) == MINUS_EXPR)
462 return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
463 && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
465 return is_gimple_min_invariant (expr);
468 /* If OP has a value range with a single constant value return that,
469 otherwise return NULL_TREE. This returns OP itself if OP is a
470 constant. */
472 tree
473 vr_values::op_with_constant_singleton_value_range (tree op)
475 if (is_gimple_min_invariant (op))
476 return op;
478 if (TREE_CODE (op) != SSA_NAME)
479 return NULL_TREE;
481 tree t;
482 if (get_value_range (op)->singleton_p (&t))
483 return t;
484 return NULL;
487 /* Return true if op is in a boolean [0, 1] value-range. */
489 bool
490 simplify_using_ranges::op_with_boolean_value_range_p (tree op, gimple *s)
492 if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
493 return true;
495 if (integer_zerop (op)
496 || integer_onep (op))
497 return true;
499 if (TREE_CODE (op) != SSA_NAME)
500 return false;
502 /* ?? Errr, this should probably check for [0,0] and [1,1] as well
503 as [0,1]. */
504 const value_range *vr = query->get_value_range (op, s);
505 return *vr == value_range (build_zero_cst (TREE_TYPE (op)),
506 build_one_cst (TREE_TYPE (op)));
509 /* Extract value range information for VAR when (OP COND_CODE LIMIT) is
510 true and store it in *VR_P. */
512 void
513 vr_values::extract_range_for_var_from_comparison_expr (tree var,
514 enum tree_code cond_code,
515 tree op, tree limit,
516 value_range_equiv *vr_p)
518 tree min, max, type;
519 const value_range_equiv *limit_vr;
520 type = TREE_TYPE (var);
522 /* For pointer arithmetic, we only keep track of pointer equality
523 and inequality. If we arrive here with unfolded conditions like
524 _1 > _1 do not derive anything. */
525 if ((POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
526 || limit == var)
528 vr_p->set_varying (type);
529 return;
532 /* If LIMIT is another SSA name and LIMIT has a range of its own,
533 try to use LIMIT's range to avoid creating symbolic ranges
534 unnecessarily. */
535 limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
537 /* LIMIT's range is only interesting if it has any useful information. */
538 if (! limit_vr
539 || limit_vr->undefined_p ()
540 || limit_vr->varying_p ()
541 || (limit_vr->symbolic_p ()
542 && ! (limit_vr->kind () == VR_RANGE
543 && (limit_vr->min () == limit_vr->max ()
544 || operand_equal_p (limit_vr->min (),
545 limit_vr->max (), 0)))))
546 limit_vr = NULL;
548 /* Initially, the new range has the same set of equivalences of
549 VAR's range. This will be revised before returning the final
550 value. Since assertions may be chained via mutually exclusive
551 predicates, we will need to trim the set of equivalences before
552 we are done. */
553 gcc_assert (vr_p->equiv () == NULL);
554 vr_p->equiv_add (var, get_value_range (var), &vrp_equiv_obstack);
556 /* Extract a new range based on the asserted comparison for VAR and
557 LIMIT's value range. Notice that if LIMIT has an anti-range, we
558 will only use it for equality comparisons (EQ_EXPR). For any
559 other kind of assertion, we cannot derive a range from LIMIT's
560 anti-range that can be used to describe the new range. For
561 instance, ASSERT_EXPR <x_2, x_2 <= b_4>. If b_4 is ~[2, 10],
562 then b_4 takes on the ranges [-INF, 1] and [11, +INF]. There is
563 no single range for x_2 that could describe LE_EXPR, so we might
564 as well build the range [b_4, +INF] for it.
565 One special case we handle is extracting a range from a
566 range test encoded as (unsigned)var + CST <= limit. */
567 if (TREE_CODE (op) == NOP_EXPR
568 || TREE_CODE (op) == PLUS_EXPR)
570 if (TREE_CODE (op) == PLUS_EXPR)
572 min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (op, 1)),
573 TREE_OPERAND (op, 1));
574 max = int_const_binop (PLUS_EXPR, limit, min);
575 op = TREE_OPERAND (op, 0);
577 else
579 min = build_int_cst (TREE_TYPE (var), 0);
580 max = limit;
583 /* Make sure to not set TREE_OVERFLOW on the final type
584 conversion. We are willingly interpreting large positive
585 unsigned values as negative signed values here. */
586 min = force_fit_type (TREE_TYPE (var), wi::to_widest (min), 0, false);
587 max = force_fit_type (TREE_TYPE (var), wi::to_widest (max), 0, false);
589 /* We can transform a max, min range to an anti-range or
590 vice-versa. Use set_and_canonicalize which does this for
591 us. */
592 if (cond_code == LE_EXPR)
593 vr_p->set (min, max, vr_p->equiv ());
594 else if (cond_code == GT_EXPR)
595 vr_p->set (min, max, vr_p->equiv (), VR_ANTI_RANGE);
596 else
597 gcc_unreachable ();
599 else if (cond_code == EQ_EXPR)
601 enum value_range_kind range_kind;
603 if (limit_vr)
605 range_kind = limit_vr->kind ();
606 min = limit_vr->min ();
607 max = limit_vr->max ();
609 else
611 range_kind = VR_RANGE;
612 min = limit;
613 max = limit;
616 vr_p->update (min, max, range_kind);
618 /* When asserting the equality VAR == LIMIT and LIMIT is another
619 SSA name, the new range will also inherit the equivalence set
620 from LIMIT. */
621 if (TREE_CODE (limit) == SSA_NAME)
622 vr_p->equiv_add (limit, get_value_range (limit), &vrp_equiv_obstack);
624 else if (cond_code == NE_EXPR)
626 /* As described above, when LIMIT's range is an anti-range and
627 this assertion is an inequality (NE_EXPR), then we cannot
628 derive anything from the anti-range. For instance, if
629 LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
630 not imply that VAR's range is [0, 0]. So, in the case of
631 anti-ranges, we just assert the inequality using LIMIT and
632 not its anti-range.
634 If LIMIT_VR is a range, we can only use it to build a new
635 anti-range if LIMIT_VR is a single-valued range. For
636 instance, if LIMIT_VR is [0, 1], the predicate
637 VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
638 Rather, it means that for value 0 VAR should be ~[0, 0]
639 and for value 1, VAR should be ~[1, 1]. We cannot
640 represent these ranges.
642 The only situation in which we can build a valid
643 anti-range is when LIMIT_VR is a single-valued range
644 (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX). In that case,
645 build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX]. */
646 if (limit_vr
647 && limit_vr->kind () == VR_RANGE
648 && compare_values (limit_vr->min (), limit_vr->max ()) == 0)
650 min = limit_vr->min ();
651 max = limit_vr->max ();
653 else
655 /* In any other case, we cannot use LIMIT's range to build a
656 valid anti-range. */
657 min = max = limit;
660 /* If MIN and MAX cover the whole range for their type, then
661 just use the original LIMIT. */
662 if (INTEGRAL_TYPE_P (type)
663 && vrp_val_is_min (min)
664 && vrp_val_is_max (max))
665 min = max = limit;
667 vr_p->set (min, max, vr_p->equiv (), VR_ANTI_RANGE);
669 else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
671 min = TYPE_MIN_VALUE (type);
673 if (limit_vr == NULL || limit_vr->kind () == VR_ANTI_RANGE)
674 max = limit;
675 else
677 /* If LIMIT_VR is of the form [N1, N2], we need to build the
678 range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
679 LT_EXPR. */
680 max = limit_vr->max ();
683 /* If the maximum value forces us to be out of bounds, simply punt.
684 It would be pointless to try and do anything more since this
685 all should be optimized away above us. */
686 if (cond_code == LT_EXPR
687 && compare_values (max, min) == 0)
688 vr_p->set_varying (TREE_TYPE (min));
689 else
691 /* For LT_EXPR, we create the range [MIN, MAX - 1]. */
692 if (cond_code == LT_EXPR)
694 if (TYPE_PRECISION (TREE_TYPE (max)) == 1
695 && !TYPE_UNSIGNED (TREE_TYPE (max)))
696 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
697 build_int_cst (TREE_TYPE (max), -1));
698 else
699 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
700 build_int_cst (TREE_TYPE (max), 1));
701 /* Signal to compare_values_warnv this expr doesn't overflow. */
702 if (EXPR_P (max))
703 suppress_warning (max, OPT_Woverflow);
706 vr_p->update (min, max);
709 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
711 max = TYPE_MAX_VALUE (type);
713 if (limit_vr == NULL || limit_vr->kind () == VR_ANTI_RANGE)
714 min = limit;
715 else
717 /* If LIMIT_VR is of the form [N1, N2], we need to build the
718 range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
719 GT_EXPR. */
720 min = limit_vr->min ();
723 /* If the minimum value forces us to be out of bounds, simply punt.
724 It would be pointless to try and do anything more since this
725 all should be optimized away above us. */
726 if (cond_code == GT_EXPR
727 && compare_values (min, max) == 0)
728 vr_p->set_varying (TREE_TYPE (min));
729 else
731 /* For GT_EXPR, we create the range [MIN + 1, MAX]. */
732 if (cond_code == GT_EXPR)
734 if (TYPE_PRECISION (TREE_TYPE (min)) == 1
735 && !TYPE_UNSIGNED (TREE_TYPE (min)))
736 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
737 build_int_cst (TREE_TYPE (min), -1));
738 else
739 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
740 build_int_cst (TREE_TYPE (min), 1));
741 /* Signal to compare_values_warnv this expr doesn't overflow. */
742 if (EXPR_P (min))
743 suppress_warning (min, OPT_Woverflow);
746 vr_p->update (min, max);
749 else
750 gcc_unreachable ();
752 /* Finally intersect the new range with what we already know about var. */
753 vr_p->legacy_verbose_intersect (get_value_range (var));
756 /* Extract value range information from an ASSERT_EXPR EXPR and store
757 it in *VR_P. */
759 void
760 vr_values::extract_range_from_assert (value_range_equiv *vr_p, tree expr)
762 tree var = ASSERT_EXPR_VAR (expr);
763 tree cond = ASSERT_EXPR_COND (expr);
764 tree limit, op;
765 enum tree_code cond_code;
766 gcc_assert (COMPARISON_CLASS_P (cond));
768 /* Find VAR in the ASSERT_EXPR conditional. */
769 if (var == TREE_OPERAND (cond, 0)
770 || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
771 || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
773 /* If the predicate is of the form VAR COMP LIMIT, then we just
774 take LIMIT from the RHS and use the same comparison code. */
775 cond_code = TREE_CODE (cond);
776 limit = TREE_OPERAND (cond, 1);
777 op = TREE_OPERAND (cond, 0);
779 else
781 /* If the predicate is of the form LIMIT COMP VAR, then we need
782 to flip around the comparison code to create the proper range
783 for VAR. */
784 cond_code = swap_tree_comparison (TREE_CODE (cond));
785 limit = TREE_OPERAND (cond, 0);
786 op = TREE_OPERAND (cond, 1);
788 extract_range_for_var_from_comparison_expr (var, cond_code, op,
789 limit, vr_p);
792 /* Extract range information from SSA name VAR and store it in VR. If
793 VAR has an interesting range, use it. Otherwise, create the
794 range [VAR, VAR] and return it. This is useful in situations where
795 we may have conditionals testing values of VARYING names. For
796 instance,
798 x_3 = y_5;
799 if (x_3 > y_5)
802 Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
803 always false. */
805 void
806 vr_values::extract_range_from_ssa_name (value_range_equiv *vr, tree var)
808 const value_range_equiv *var_vr = get_value_range (var);
810 if (!var_vr->varying_p ())
811 vr->deep_copy (var_vr);
812 else
813 vr->set (var);
815 if (!vr->undefined_p ())
816 vr->equiv_add (var, get_value_range (var), &vrp_equiv_obstack);
819 /* Extract range information from a binary expression OP0 CODE OP1 based on
820 the ranges of each of its operands with resulting type EXPR_TYPE.
821 The resulting range is stored in *VR. */
823 void
824 vr_values::extract_range_from_binary_expr (value_range_equiv *vr,
825 enum tree_code code,
826 tree expr_type, tree op0, tree op1)
828 /* Get value ranges for each operand. For constant operands, create
829 a new value range with the operand to simplify processing. */
830 value_range vr0, vr1;
831 if (TREE_CODE (op0) == SSA_NAME)
832 vr0 = *(get_value_range (op0));
833 else if (is_gimple_min_invariant (op0))
834 vr0.set (op0, op0);
835 else
836 vr0.set_varying (TREE_TYPE (op0));
838 if (TREE_CODE (op1) == SSA_NAME)
839 vr1 = *(get_value_range (op1));
840 else if (is_gimple_min_invariant (op1))
841 vr1.set (op1, op1);
842 else
843 vr1.set_varying (TREE_TYPE (op1));
845 /* If one argument is varying, we can sometimes still deduce a
846 range for the output: any + [3, +INF] is in [MIN+3, +INF]. */
847 if (INTEGRAL_TYPE_P (TREE_TYPE (op0))
848 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0)))
850 if (vr0.varying_p () && !vr1.varying_p ())
851 vr0 = value_range (vrp_val_min (expr_type), vrp_val_max (expr_type));
852 else if (vr1.varying_p () && !vr0.varying_p ())
853 vr1 = value_range (vrp_val_min (expr_type), vrp_val_max (expr_type));
856 range_fold_binary_expr (vr, code, expr_type, &vr0, &vr1);
858 /* Set value_range for n in following sequence:
859 def = __builtin_memchr (arg, 0, sz)
860 n = def - arg
861 Here the range for n can be set to [0, PTRDIFF_MAX - 1]. */
863 if (vr->varying_p ()
864 && code == POINTER_DIFF_EXPR
865 && TREE_CODE (op0) == SSA_NAME
866 && TREE_CODE (op1) == SSA_NAME)
868 tree op0_ptype = TREE_TYPE (TREE_TYPE (op0));
869 tree op1_ptype = TREE_TYPE (TREE_TYPE (op1));
870 gcall *call_stmt = NULL;
872 if (TYPE_MODE (op0_ptype) == TYPE_MODE (char_type_node)
873 && TYPE_PRECISION (op0_ptype) == TYPE_PRECISION (char_type_node)
874 && TYPE_MODE (op1_ptype) == TYPE_MODE (char_type_node)
875 && TYPE_PRECISION (op1_ptype) == TYPE_PRECISION (char_type_node)
876 && (call_stmt = dyn_cast<gcall *>(SSA_NAME_DEF_STMT (op0)))
877 && gimple_call_builtin_p (call_stmt, BUILT_IN_MEMCHR)
878 && operand_equal_p (op0, gimple_call_lhs (call_stmt), 0)
879 && operand_equal_p (op1, gimple_call_arg (call_stmt, 0), 0)
880 && integer_zerop (gimple_call_arg (call_stmt, 1)))
882 tree max = vrp_val_max (ptrdiff_type_node);
883 wide_int wmax = wi::to_wide (max, TYPE_PRECISION (TREE_TYPE (max)));
884 tree range_min = build_zero_cst (expr_type);
885 tree range_max = wide_int_to_tree (expr_type, wmax - 1);
886 vr->set (range_min, range_max, NULL);
887 return;
891 /* Try harder for PLUS and MINUS if the range of one operand is symbolic
892 and based on the other operand, for example if it was deduced from a
893 symbolic comparison. When a bound of the range of the first operand
894 is invariant, we set the corresponding bound of the new range to INF
895 in order to avoid recursing on the range of the second operand. */
896 if (vr->varying_p ()
897 && (code == PLUS_EXPR || code == MINUS_EXPR)
898 && TREE_CODE (op1) == SSA_NAME
899 && vr0.kind () == VR_RANGE
900 && symbolic_range_based_on_p (&vr0, op1))
902 const bool minus_p = (code == MINUS_EXPR);
903 value_range n_vr1;
905 /* Try with VR0 and [-INF, OP1]. */
906 if (is_gimple_min_invariant (minus_p ? vr0.max () : vr0.min ()))
907 n_vr1.set (vrp_val_min (expr_type), op1);
909 /* Try with VR0 and [OP1, +INF]. */
910 else if (is_gimple_min_invariant (minus_p ? vr0.min () : vr0.max ()))
911 n_vr1.set (op1, vrp_val_max (expr_type));
913 /* Try with VR0 and [OP1, OP1]. */
914 else
915 n_vr1.set (op1, op1);
917 range_fold_binary_expr (vr, code, expr_type, &vr0, &n_vr1);
920 if (vr->varying_p ()
921 && (code == PLUS_EXPR || code == MINUS_EXPR)
922 && TREE_CODE (op0) == SSA_NAME
923 && vr1.kind () == VR_RANGE
924 && symbolic_range_based_on_p (&vr1, op0))
926 const bool minus_p = (code == MINUS_EXPR);
927 value_range n_vr0;
929 /* Try with [-INF, OP0] and VR1. */
930 if (is_gimple_min_invariant (minus_p ? vr1.max () : vr1.min ()))
931 n_vr0.set (vrp_val_min (expr_type), op0);
933 /* Try with [OP0, +INF] and VR1. */
934 else if (is_gimple_min_invariant (minus_p ? vr1.min (): vr1.max ()))
935 n_vr0.set (op0, vrp_val_max (expr_type));
937 /* Try with [OP0, OP0] and VR1. */
938 else
939 n_vr0.set (op0, op0);
941 range_fold_binary_expr (vr, code, expr_type, &n_vr0, &vr1);
944 /* If we didn't derive a range for MINUS_EXPR, and
945 op1's range is ~[op0,op0] or vice-versa, then we
946 can derive a non-null range. This happens often for
947 pointer subtraction. */
948 if (vr->varying_p ()
949 && (code == MINUS_EXPR || code == POINTER_DIFF_EXPR)
950 && TREE_CODE (op0) == SSA_NAME
951 && ((vr0.kind () == VR_ANTI_RANGE
952 && vr0.min () == op1
953 && vr0.min () == vr0.max ())
954 || (vr1.kind () == VR_ANTI_RANGE
955 && vr1.min () == op0
956 && vr1.min () == vr1.max ())))
958 vr->set_nonzero (expr_type);
959 vr->equiv_clear ();
963 /* Extract range information from a unary expression CODE OP0 based on
964 the range of its operand with resulting type TYPE.
965 The resulting range is stored in *VR. */
967 void
968 vr_values::extract_range_from_unary_expr (value_range_equiv *vr,
969 enum tree_code code,
970 tree type, tree op0)
972 value_range vr0;
974 /* Get value ranges for the operand. For constant operands, create
975 a new value range with the operand to simplify processing. */
976 if (TREE_CODE (op0) == SSA_NAME)
977 vr0 = *(get_value_range (op0));
978 else if (is_gimple_min_invariant (op0))
979 vr0.set (op0, op0);
980 else
981 vr0.set_varying (type);
983 range_fold_unary_expr (vr, code, type, &vr0, TREE_TYPE (op0));
987 /* Extract range information from a conditional expression STMT based on
988 the ranges of each of its operands and the expression code. */
990 void
991 vr_values::extract_range_from_cond_expr (value_range_equiv *vr, gassign *stmt)
993 /* Get value ranges for each operand. For constant operands, create
994 a new value range with the operand to simplify processing. */
995 tree op0 = gimple_assign_rhs2 (stmt);
996 value_range_equiv tem0;
997 const value_range_equiv *vr0 = &tem0;
998 if (TREE_CODE (op0) == SSA_NAME)
999 vr0 = get_value_range (op0);
1000 else if (is_gimple_min_invariant (op0))
1001 tem0.set (op0);
1002 else
1003 tem0.set_varying (TREE_TYPE (op0));
1005 tree op1 = gimple_assign_rhs3 (stmt);
1006 value_range_equiv tem1;
1007 const value_range_equiv *vr1 = &tem1;
1008 if (TREE_CODE (op1) == SSA_NAME)
1009 vr1 = get_value_range (op1);
1010 else if (is_gimple_min_invariant (op1))
1011 tem1.set (op1);
1012 else
1013 tem1.set_varying (TREE_TYPE (op1));
1015 /* The resulting value range is the union of the operand ranges */
1016 vr->deep_copy (vr0);
1017 vr->legacy_verbose_union_ (vr1);
1021 /* Extract range information from a comparison expression EXPR based
1022 on the range of its operand and the expression code. */
1024 void
1025 vr_values::extract_range_from_comparison (value_range_equiv *vr,
1026 gimple *stmt)
1028 enum tree_code code = gimple_assign_rhs_code (stmt);
1029 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1030 tree op0 = gimple_assign_rhs1 (stmt);
1031 tree op1 = gimple_assign_rhs2 (stmt);
1032 bool sop;
1033 tree val
1034 = simplifier.vrp_evaluate_conditional_warnv_with_ops (stmt, code, op0, op1,
1035 false, &sop, NULL);
1036 if (val)
1038 /* Since this expression was found on the RHS of an assignment,
1039 its type may be different from _Bool. Convert VAL to EXPR's
1040 type. */
1041 val = fold_convert (type, val);
1042 if (is_gimple_min_invariant (val))
1043 vr->set (val);
1044 else
1045 vr->update (val, val);
1047 else
1048 /* The result of a comparison is always true or false. */
1049 set_value_range_to_truthvalue (vr, type);
1052 /* Helper function for simplify_internal_call_using_ranges and
1053 extract_range_basic. Return true if OP0 SUBCODE OP1 for
1054 SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
1055 always overflow. Set *OVF to true if it is known to always
1056 overflow. */
1058 static bool
1059 check_for_binary_op_overflow (range_query *query,
1060 enum tree_code subcode, tree type,
1061 tree op0, tree op1, bool *ovf, gimple *s = NULL)
1063 value_range vr0, vr1;
1064 if (TREE_CODE (op0) == SSA_NAME)
1065 vr0 = *query->get_value_range (op0, s);
1066 else if (TREE_CODE (op0) == INTEGER_CST)
1067 vr0.set (op0, op0);
1068 else
1069 vr0.set_varying (TREE_TYPE (op0));
1071 if (TREE_CODE (op1) == SSA_NAME)
1072 vr1 = *query->get_value_range (op1, s);
1073 else if (TREE_CODE (op1) == INTEGER_CST)
1074 vr1.set (op1, op1);
1075 else
1076 vr1.set_varying (TREE_TYPE (op1));
1078 tree vr0min = vr0.min (), vr0max = vr0.max ();
1079 tree vr1min = vr1.min (), vr1max = vr1.max ();
1080 if (!range_int_cst_p (&vr0)
1081 || TREE_OVERFLOW (vr0min)
1082 || TREE_OVERFLOW (vr0max))
1084 vr0min = vrp_val_min (TREE_TYPE (op0));
1085 vr0max = vrp_val_max (TREE_TYPE (op0));
1087 if (!range_int_cst_p (&vr1)
1088 || TREE_OVERFLOW (vr1min)
1089 || TREE_OVERFLOW (vr1max))
1091 vr1min = vrp_val_min (TREE_TYPE (op1));
1092 vr1max = vrp_val_max (TREE_TYPE (op1));
1094 *ovf = arith_overflowed_p (subcode, type, vr0min,
1095 subcode == MINUS_EXPR ? vr1max : vr1min);
1096 if (arith_overflowed_p (subcode, type, vr0max,
1097 subcode == MINUS_EXPR ? vr1min : vr1max) != *ovf)
1098 return false;
1099 if (subcode == MULT_EXPR)
1101 if (arith_overflowed_p (subcode, type, vr0min, vr1max) != *ovf
1102 || arith_overflowed_p (subcode, type, vr0max, vr1min) != *ovf)
1103 return false;
1105 if (*ovf)
1107 /* So far we found that there is an overflow on the boundaries.
1108 That doesn't prove that there is an overflow even for all values
1109 in between the boundaries. For that compute widest_int range
1110 of the result and see if it doesn't overlap the range of
1111 type. */
1112 widest_int wmin, wmax;
1113 widest_int w[4];
1114 int i;
1115 w[0] = wi::to_widest (vr0min);
1116 w[1] = wi::to_widest (vr0max);
1117 w[2] = wi::to_widest (vr1min);
1118 w[3] = wi::to_widest (vr1max);
1119 for (i = 0; i < 4; i++)
1121 widest_int wt;
1122 switch (subcode)
1124 case PLUS_EXPR:
1125 wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
1126 break;
1127 case MINUS_EXPR:
1128 wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
1129 break;
1130 case MULT_EXPR:
1131 wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
1132 break;
1133 default:
1134 gcc_unreachable ();
1136 if (i == 0)
1138 wmin = wt;
1139 wmax = wt;
1141 else
1143 wmin = wi::smin (wmin, wt);
1144 wmax = wi::smax (wmax, wt);
1147 /* The result of op0 CODE op1 is known to be in range
1148 [wmin, wmax]. */
1149 widest_int wtmin = wi::to_widest (vrp_val_min (type));
1150 widest_int wtmax = wi::to_widest (vrp_val_max (type));
1151 /* If all values in [wmin, wmax] are smaller than
1152 [wtmin, wtmax] or all are larger than [wtmin, wtmax],
1153 the arithmetic operation will always overflow. */
1154 if (wmax < wtmin || wmin > wtmax)
1155 return true;
1156 return false;
1158 return true;
1161 /* Derive a range from a builtin. Set range in VR and return TRUE if
1162 successful. */
1164 bool
1165 vr_values::extract_range_from_ubsan_builtin (value_range_equiv *vr, gimple *stmt)
1167 gcc_assert (is_gimple_call (stmt));
1168 enum tree_code subcode = ERROR_MARK;
1169 combined_fn cfn = gimple_call_combined_fn (stmt);
1170 scalar_int_mode mode;
1172 switch (cfn)
1174 case CFN_UBSAN_CHECK_ADD:
1175 subcode = PLUS_EXPR;
1176 break;
1177 case CFN_UBSAN_CHECK_SUB:
1178 subcode = MINUS_EXPR;
1179 break;
1180 case CFN_UBSAN_CHECK_MUL:
1181 subcode = MULT_EXPR;
1182 break;
1183 default:
1184 break;
1186 if (subcode != ERROR_MARK)
1188 bool saved_flag_wrapv = flag_wrapv;
1189 /* Pretend the arithmetics is wrapping. If there is
1190 any overflow, we'll complain, but will actually do
1191 wrapping operation. */
1192 flag_wrapv = 1;
1193 extract_range_from_binary_expr (vr, subcode,
1194 TREE_TYPE (gimple_call_arg (stmt, 0)),
1195 gimple_call_arg (stmt, 0),
1196 gimple_call_arg (stmt, 1));
1197 flag_wrapv = saved_flag_wrapv;
1199 /* If for both arguments vrp_valueize returned non-NULL,
1200 this should have been already folded and if not, it
1201 wasn't folded because of overflow. Avoid removing the
1202 UBSAN_CHECK_* calls in that case. */
1203 if (vr->kind () == VR_RANGE
1204 && (vr->min () == vr->max ()
1205 || operand_equal_p (vr->min (), vr->max (), 0)))
1206 vr->set_varying (vr->type ());
1208 return !vr->varying_p ();
1210 return false;
1213 /* Try to derive a nonnegative or nonzero range out of STMT relying
1214 primarily on generic routines in fold in conjunction with range data.
1215 Store the result in *VR */
1217 void
1218 vr_values::extract_range_basic (value_range_equiv *vr, gimple *stmt)
1220 bool sop;
1222 if (is_gimple_call (stmt))
1224 combined_fn cfn = gimple_call_combined_fn (stmt);
1225 switch (cfn)
1227 case CFN_UBSAN_CHECK_ADD:
1228 case CFN_UBSAN_CHECK_SUB:
1229 case CFN_UBSAN_CHECK_MUL:
1230 if (extract_range_from_ubsan_builtin (vr, stmt))
1231 return;
1232 break;
1233 default:
1234 if (fold_range (*vr, stmt, this))
1236 /* The original code nuked equivalences every time a
1237 range was found, so do the same here. */
1238 vr->equiv_clear ();
1239 return;
1241 break;
1244 /* Handle extraction of the two results (result of arithmetics and
1245 a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
1246 internal function. Similarly from ATOMIC_COMPARE_EXCHANGE. */
1247 if (is_gimple_assign (stmt)
1248 && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
1249 || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
1250 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt))))
1252 enum tree_code code = gimple_assign_rhs_code (stmt);
1253 tree op = gimple_assign_rhs1 (stmt);
1254 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1255 if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
1257 gimple *g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
1258 if (is_gimple_call (g) && gimple_call_internal_p (g))
1260 enum tree_code subcode = ERROR_MARK;
1261 switch (gimple_call_internal_fn (g))
1263 case IFN_ADD_OVERFLOW:
1264 subcode = PLUS_EXPR;
1265 break;
1266 case IFN_SUB_OVERFLOW:
1267 subcode = MINUS_EXPR;
1268 break;
1269 case IFN_MUL_OVERFLOW:
1270 subcode = MULT_EXPR;
1271 break;
1272 case IFN_ATOMIC_COMPARE_EXCHANGE:
1273 if (code == IMAGPART_EXPR)
1275 /* This is the boolean return value whether compare and
1276 exchange changed anything or not. */
1277 vr->set (build_int_cst (type, 0),
1278 build_int_cst (type, 1), NULL);
1279 return;
1281 break;
1282 default:
1283 break;
1285 if (subcode != ERROR_MARK)
1287 tree op0 = gimple_call_arg (g, 0);
1288 tree op1 = gimple_call_arg (g, 1);
1289 if (code == IMAGPART_EXPR)
1291 bool ovf = false;
1292 if (check_for_binary_op_overflow (this, subcode, type,
1293 op0, op1, &ovf))
1294 vr->set (build_int_cst (type, ovf));
1295 else if (TYPE_PRECISION (type) == 1
1296 && !TYPE_UNSIGNED (type))
1297 vr->set_varying (type);
1298 else
1299 vr->set (build_int_cst (type, 0),
1300 build_int_cst (type, 1), NULL);
1302 else if (types_compatible_p (type, TREE_TYPE (op0))
1303 && types_compatible_p (type, TREE_TYPE (op1)))
1305 bool saved_flag_wrapv = flag_wrapv;
1306 /* Pretend the arithmetics is wrapping. If there is
1307 any overflow, IMAGPART_EXPR will be set. */
1308 flag_wrapv = 1;
1309 extract_range_from_binary_expr (vr, subcode, type,
1310 op0, op1);
1311 flag_wrapv = saved_flag_wrapv;
1313 else
1315 value_range_equiv vr0, vr1;
1316 bool saved_flag_wrapv = flag_wrapv;
1317 /* Pretend the arithmetics is wrapping. If there is
1318 any overflow, IMAGPART_EXPR will be set. */
1319 flag_wrapv = 1;
1320 extract_range_from_unary_expr (&vr0, NOP_EXPR,
1321 type, op0);
1322 extract_range_from_unary_expr (&vr1, NOP_EXPR,
1323 type, op1);
1324 range_fold_binary_expr (vr, subcode, type, &vr0, &vr1);
1325 flag_wrapv = saved_flag_wrapv;
1327 return;
1332 /* None of the below should need a 'type', but we are only called
1333 for assignments and calls with a LHS. */
1334 tree type = TREE_TYPE (gimple_get_lhs (stmt));
1335 if (INTEGRAL_TYPE_P (type)
1336 && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
1337 set_value_range_to_nonnegative (vr, type);
1338 else if (vrp_stmt_computes_nonzero (stmt))
1340 vr->set_nonzero (type);
1341 vr->equiv_clear ();
1343 else
1344 vr->set_varying (type);
1348 /* Try to compute a useful range out of assignment STMT and store it
1349 in *VR. */
1351 void
1352 vr_values::extract_range_from_assignment (value_range_equiv *vr, gassign *stmt)
1354 enum tree_code code = gimple_assign_rhs_code (stmt);
1356 if (code == ASSERT_EXPR)
1357 extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
1358 else if (code == SSA_NAME)
1359 extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
1360 else if (TREE_CODE_CLASS (code) == tcc_binary)
1361 extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
1362 TREE_TYPE (gimple_assign_lhs (stmt)),
1363 gimple_assign_rhs1 (stmt),
1364 gimple_assign_rhs2 (stmt));
1365 else if (TREE_CODE_CLASS (code) == tcc_unary)
1366 extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
1367 TREE_TYPE (gimple_assign_lhs (stmt)),
1368 gimple_assign_rhs1 (stmt));
1369 else if (code == COND_EXPR)
1370 extract_range_from_cond_expr (vr, stmt);
1371 else if (TREE_CODE_CLASS (code) == tcc_comparison)
1372 extract_range_from_comparison (vr, stmt);
1373 else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
1374 && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
1375 vr->set (gimple_assign_rhs1 (stmt));
1376 else
1377 vr->set_varying (TREE_TYPE (gimple_assign_lhs (stmt)));
1379 if (vr->varying_p ())
1380 extract_range_basic (vr, stmt);
1383 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
1385 - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
1386 all the values in the ranges.
1388 - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
1390 - Return NULL_TREE if it is not always possible to determine the
1391 value of the comparison.
1393 Also set *STRICT_OVERFLOW_P to indicate whether comparision evaluation
1394 assumed signed overflow is undefined. */
1397 static tree
1398 compare_ranges (enum tree_code comp, const value_range_equiv *vr0,
1399 const value_range_equiv *vr1, bool *strict_overflow_p)
1401 /* VARYING or UNDEFINED ranges cannot be compared. */
1402 if (vr0->varying_p ()
1403 || vr0->undefined_p ()
1404 || vr1->varying_p ()
1405 || vr1->undefined_p ())
1406 return NULL_TREE;
1408 /* Anti-ranges need to be handled separately. */
1409 if (vr0->kind () == VR_ANTI_RANGE || vr1->kind () == VR_ANTI_RANGE)
1411 /* If both are anti-ranges, then we cannot compute any
1412 comparison. */
1413 if (vr0->kind () == VR_ANTI_RANGE && vr1->kind () == VR_ANTI_RANGE)
1414 return NULL_TREE;
1416 /* These comparisons are never statically computable. */
1417 if (comp == GT_EXPR
1418 || comp == GE_EXPR
1419 || comp == LT_EXPR
1420 || comp == LE_EXPR)
1421 return NULL_TREE;
1423 /* Equality can be computed only between a range and an
1424 anti-range. ~[VAL1, VAL2] == [VAL1, VAL2] is always false. */
1425 if (vr0->kind () == VR_RANGE)
1426 /* To simplify processing, make VR0 the anti-range. */
1427 std::swap (vr0, vr1);
1429 gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
1431 if (compare_values_warnv (vr0->min (), vr1->min (), strict_overflow_p) == 0
1432 && compare_values_warnv (vr0->max (), vr1->max (), strict_overflow_p) == 0)
1433 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1435 return NULL_TREE;
1438 /* Simplify processing. If COMP is GT_EXPR or GE_EXPR, switch the
1439 operands around and change the comparison code. */
1440 if (comp == GT_EXPR || comp == GE_EXPR)
1442 comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
1443 std::swap (vr0, vr1);
1446 if (comp == EQ_EXPR)
1448 /* Equality may only be computed if both ranges represent
1449 exactly one value. */
1450 if (compare_values_warnv (vr0->min (), vr0->max (), strict_overflow_p) == 0
1451 && compare_values_warnv (vr1->min (), vr1->max (), strict_overflow_p) == 0)
1453 int cmp_min = compare_values_warnv (vr0->min (), vr1->min (),
1454 strict_overflow_p);
1455 int cmp_max = compare_values_warnv (vr0->max (), vr1->max (),
1456 strict_overflow_p);
1457 if (cmp_min == 0 && cmp_max == 0)
1458 return boolean_true_node;
1459 else if (cmp_min != -2 && cmp_max != -2)
1460 return boolean_false_node;
1462 /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1. */
1463 else if (compare_values_warnv (vr0->min (), vr1->max (),
1464 strict_overflow_p) == 1
1465 || compare_values_warnv (vr1->min (), vr0->max (),
1466 strict_overflow_p) == 1)
1467 return boolean_false_node;
1469 return NULL_TREE;
1471 else if (comp == NE_EXPR)
1473 int cmp1, cmp2;
1475 /* If VR0 is completely to the left or completely to the right
1476 of VR1, they are always different. Notice that we need to
1477 make sure that both comparisons yield similar results to
1478 avoid comparing values that cannot be compared at
1479 compile-time. */
1480 cmp1 = compare_values_warnv (vr0->max (), vr1->min (), strict_overflow_p);
1481 cmp2 = compare_values_warnv (vr0->min (), vr1->max (), strict_overflow_p);
1482 if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
1483 return boolean_true_node;
1485 /* If VR0 and VR1 represent a single value and are identical,
1486 return false. */
1487 else if (compare_values_warnv (vr0->min (), vr0->max (),
1488 strict_overflow_p) == 0
1489 && compare_values_warnv (vr1->min (), vr1->max (),
1490 strict_overflow_p) == 0
1491 && compare_values_warnv (vr0->min (), vr1->min (),
1492 strict_overflow_p) == 0
1493 && compare_values_warnv (vr0->max (), vr1->max (),
1494 strict_overflow_p) == 0)
1495 return boolean_false_node;
1497 /* Otherwise, they may or may not be different. */
1498 else
1499 return NULL_TREE;
1501 else if (comp == LT_EXPR || comp == LE_EXPR)
1503 int tst;
1505 /* If VR0 is to the left of VR1, return true. */
1506 tst = compare_values_warnv (vr0->max (), vr1->min (), strict_overflow_p);
1507 if ((comp == LT_EXPR && tst == -1)
1508 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1509 return boolean_true_node;
1511 /* If VR0 is to the right of VR1, return false. */
1512 tst = compare_values_warnv (vr0->min (), vr1->max (), strict_overflow_p);
1513 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1514 || (comp == LE_EXPR && tst == 1))
1515 return boolean_false_node;
1517 /* Otherwise, we don't know. */
1518 return NULL_TREE;
1521 gcc_unreachable ();
1524 /* Given a value range VR, a value VAL and a comparison code COMP, return
1525 BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
1526 values in VR. Return BOOLEAN_FALSE_NODE if the comparison
1527 always returns false. Return NULL_TREE if it is not always
1528 possible to determine the value of the comparison. Also set
1529 *STRICT_OVERFLOW_P to indicate whether comparision evaluation
1530 assumed signed overflow is undefined. */
1532 static tree
1533 compare_range_with_value (enum tree_code comp, const value_range *vr,
1534 tree val, bool *strict_overflow_p)
1536 if (vr->varying_p () || vr->undefined_p ())
1537 return NULL_TREE;
1539 /* Anti-ranges need to be handled separately. */
1540 if (vr->kind () == VR_ANTI_RANGE)
1542 /* For anti-ranges, the only predicates that we can compute at
1543 compile time are equality and inequality. */
1544 if (comp == GT_EXPR
1545 || comp == GE_EXPR
1546 || comp == LT_EXPR
1547 || comp == LE_EXPR)
1548 return NULL_TREE;
1550 /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2. */
1551 if (!vr->may_contain_p (val))
1552 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1554 return NULL_TREE;
1557 if (comp == EQ_EXPR)
1559 /* EQ_EXPR may only be computed if VR represents exactly
1560 one value. */
1561 if (compare_values_warnv (vr->min (), vr->max (), strict_overflow_p) == 0)
1563 int cmp = compare_values_warnv (vr->min (), val, strict_overflow_p);
1564 if (cmp == 0)
1565 return boolean_true_node;
1566 else if (cmp == -1 || cmp == 1 || cmp == 2)
1567 return boolean_false_node;
1569 else if (compare_values_warnv (val, vr->min (), strict_overflow_p) == -1
1570 || compare_values_warnv (vr->max (), val, strict_overflow_p) == -1)
1571 return boolean_false_node;
1573 return NULL_TREE;
1575 else if (comp == NE_EXPR)
1577 /* If VAL is not inside VR, then they are always different. */
1578 if (compare_values_warnv (vr->max (), val, strict_overflow_p) == -1
1579 || compare_values_warnv (vr->min (), val, strict_overflow_p) == 1)
1580 return boolean_true_node;
1582 /* If VR represents exactly one value equal to VAL, then return
1583 false. */
1584 if (compare_values_warnv (vr->min (), vr->max (), strict_overflow_p) == 0
1585 && compare_values_warnv (vr->min (), val, strict_overflow_p) == 0)
1586 return boolean_false_node;
1588 /* Otherwise, they may or may not be different. */
1589 return NULL_TREE;
1591 else if (comp == LT_EXPR || comp == LE_EXPR)
1593 int tst;
1595 /* If VR is to the left of VAL, return true. */
1596 tst = compare_values_warnv (vr->max (), val, strict_overflow_p);
1597 if ((comp == LT_EXPR && tst == -1)
1598 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1599 return boolean_true_node;
1601 /* If VR is to the right of VAL, return false. */
1602 tst = compare_values_warnv (vr->min (), val, strict_overflow_p);
1603 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1604 || (comp == LE_EXPR && tst == 1))
1605 return boolean_false_node;
1607 /* Otherwise, we don't know. */
1608 return NULL_TREE;
1610 else if (comp == GT_EXPR || comp == GE_EXPR)
1612 int tst;
1614 /* If VR is to the right of VAL, return true. */
1615 tst = compare_values_warnv (vr->min (), val, strict_overflow_p);
1616 if ((comp == GT_EXPR && tst == 1)
1617 || (comp == GE_EXPR && (tst == 0 || tst == 1)))
1618 return boolean_true_node;
1620 /* If VR is to the left of VAL, return false. */
1621 tst = compare_values_warnv (vr->max (), val, strict_overflow_p);
1622 if ((comp == GT_EXPR && (tst == -1 || tst == 0))
1623 || (comp == GE_EXPR && tst == -1))
1624 return boolean_false_node;
1626 /* Otherwise, we don't know. */
1627 return NULL_TREE;
1630 gcc_unreachable ();
1633 static inline void
1634 fix_overflow (tree *min, tree *max)
1636 /* Even for valid range info, sometimes overflow flag will leak in.
1637 As GIMPLE IL should have no constants with TREE_OVERFLOW set, we
1638 drop them. */
1639 if (TREE_OVERFLOW_P (*min))
1640 *min = drop_tree_overflow (*min);
1641 if (TREE_OVERFLOW_P (*max))
1642 *max = drop_tree_overflow (*max);
1644 gcc_checking_assert (compare_values (*min, *max) != 1);
1647 /* Given a VAR in STMT within LOOP, determine the bounds of the
1648 variable and store it in MIN/MAX and return TRUE. If no bounds
1649 could be determined, return FALSE. */
1651 bool
1652 bounds_of_var_in_loop (tree *min, tree *max, range_query *query,
1653 class loop *loop, gimple *stmt, tree var)
1655 tree init, step, chrec, tmin, tmax, type = TREE_TYPE (var);
1656 enum ev_direction dir;
1657 int_range<2> r;
1659 chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
1661 /* Like in PR19590, scev can return a constant function. */
1662 if (is_gimple_min_invariant (chrec))
1664 *min = *max = chrec;
1665 fix_overflow (min, max);
1666 return true;
1669 if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
1670 return false;
1672 init = initial_condition_in_loop_num (chrec, loop->num);
1673 step = evolution_part_in_loop_num (chrec, loop->num);
1675 if (!init || !step)
1676 return false;
1678 Value_Range rinit (TREE_TYPE (init));
1679 Value_Range rstep (TREE_TYPE (step));
1680 /* If INIT is an SSA with a singleton range, set INIT to said
1681 singleton, otherwise leave INIT alone. */
1682 if (TREE_CODE (init) == SSA_NAME
1683 && query->range_of_expr (rinit, init, stmt))
1684 rinit.singleton_p (&init);
1685 /* Likewise for step. */
1686 if (TREE_CODE (step) == SSA_NAME
1687 && query->range_of_expr (rstep, step, stmt))
1688 rstep.singleton_p (&step);
1690 /* If STEP is symbolic, we can't know whether INIT will be the
1691 minimum or maximum value in the range. Also, unless INIT is
1692 a simple expression, compare_values and possibly other functions
1693 in tree-vrp won't be able to handle it. */
1694 if (step == NULL_TREE
1695 || !is_gimple_min_invariant (step)
1696 || !valid_value_p (init))
1697 return false;
1699 dir = scev_direction (chrec);
1700 if (/* Do not adjust ranges if we do not know whether the iv increases
1701 or decreases, ... */
1702 dir == EV_DIR_UNKNOWN
1703 /* ... or if it may wrap. */
1704 || scev_probably_wraps_p (NULL_TREE, init, step, stmt,
1705 get_chrec_loop (chrec), true))
1706 return false;
1708 if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
1709 tmin = lower_bound_in_type (type, type);
1710 else
1711 tmin = TYPE_MIN_VALUE (type);
1712 if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
1713 tmax = upper_bound_in_type (type, type);
1714 else
1715 tmax = TYPE_MAX_VALUE (type);
1717 /* Try to use estimated number of iterations for the loop to constrain the
1718 final value in the evolution. */
1719 if (TREE_CODE (step) == INTEGER_CST
1720 && is_gimple_val (init)
1721 && (TREE_CODE (init) != SSA_NAME
1722 || (query->range_of_expr (r, init, stmt)
1723 && r.kind () == VR_RANGE)))
1725 widest_int nit;
1727 /* We are only entering here for loop header PHI nodes, so using
1728 the number of latch executions is the correct thing to use. */
1729 if (max_loop_iterations (loop, &nit))
1731 signop sgn = TYPE_SIGN (TREE_TYPE (step));
1732 wi::overflow_type overflow;
1734 widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
1735 &overflow);
1736 /* If the multiplication overflowed we can't do a meaningful
1737 adjustment. Likewise if the result doesn't fit in the type
1738 of the induction variable. For a signed type we have to
1739 check whether the result has the expected signedness which
1740 is that of the step as number of iterations is unsigned. */
1741 if (!overflow
1742 && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
1743 && (sgn == UNSIGNED
1744 || wi::gts_p (wtmp, 0) == wi::gts_p (wi::to_wide (step), 0)))
1746 value_range maxvr, vr0, vr1;
1747 if (TREE_CODE (init) == SSA_NAME)
1748 query->range_of_expr (vr0, init, stmt);
1749 else if (is_gimple_min_invariant (init))
1750 vr0.set (init, init);
1751 else
1752 vr0.set_varying (TREE_TYPE (init));
1753 tree tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
1754 vr1.set (tem, tem);
1755 range_fold_binary_expr (&maxvr, PLUS_EXPR,
1756 TREE_TYPE (init), &vr0, &vr1);
1758 /* Likewise if the addition did. */
1759 if (maxvr.kind () == VR_RANGE)
1761 int_range<2> initvr;
1763 if (TREE_CODE (init) == SSA_NAME)
1764 query->range_of_expr (initvr, init, stmt);
1765 else if (is_gimple_min_invariant (init))
1766 initvr.set (init, init);
1767 else
1768 return false;
1770 /* Check if init + nit * step overflows. Though we checked
1771 scev {init, step}_loop doesn't wrap, it is not enough
1772 because the loop may exit immediately. Overflow could
1773 happen in the plus expression in this case. */
1774 if ((dir == EV_DIR_DECREASES
1775 && compare_values (maxvr.min (), initvr.min ()) != -1)
1776 || (dir == EV_DIR_GROWS
1777 && compare_values (maxvr.max (), initvr.max ()) != 1))
1778 return false;
1780 tmin = maxvr.min ();
1781 tmax = maxvr.max ();
1787 *min = tmin;
1788 *max = tmax;
1789 if (dir == EV_DIR_DECREASES)
1790 *max = init;
1791 else
1792 *min = init;
1794 fix_overflow (min, max);
1795 return true;
1798 /* Given a range VR, a LOOP and a variable VAR, determine whether it
1799 would be profitable to adjust VR using scalar evolution information
1800 for VAR. If so, update VR with the new limits. */
1802 void
1803 vr_values::adjust_range_with_scev (value_range_equiv *vr, class loop *loop,
1804 gimple *stmt, tree var)
1806 tree min, max;
1807 if (bounds_of_var_in_loop (&min, &max, this, loop, stmt, var))
1809 if (vr->undefined_p () || vr->varying_p ())
1811 /* For VARYING or UNDEFINED ranges, just about anything we get
1812 from scalar evolutions should be better. */
1813 vr->update (min, max);
1815 else if (vr->kind () == VR_RANGE)
1817 /* Start with the input range... */
1818 tree vrmin = vr->min ();
1819 tree vrmax = vr->max ();
1821 /* ...and narrow it down with what we got from SCEV. */
1822 if (compare_values (min, vrmin) == 1)
1823 vrmin = min;
1824 if (compare_values (max, vrmax) == -1)
1825 vrmax = max;
1827 vr->update (vrmin, vrmax);
1829 else if (vr->kind () == VR_ANTI_RANGE)
1831 /* ?? As an enhancement, if VR, MIN, and MAX are constants, one
1832 could just intersect VR with a range of [MIN,MAX]. */
1837 /* Dump value ranges of all SSA_NAMEs to FILE. */
1839 void
1840 vr_values::dump (FILE *file)
1842 size_t i;
1844 for (i = 0; i < num_vr_values; i++)
1846 if (vr_value[i] && ssa_name (i))
1848 print_generic_expr (file, ssa_name (i));
1849 fprintf (file, ": ");
1850 dump_value_range (file, vr_value[i]);
1851 fprintf (file, "\n");
1855 fprintf (file, "\n");
1858 /* Initialize VRP lattice. */
1860 vr_values::vr_values () : simplifier (this)
1862 values_propagated = false;
1863 num_vr_values = num_ssa_names * 2;
1864 vr_value = XCNEWVEC (value_range_equiv *, num_vr_values);
1865 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
1866 bitmap_obstack_initialize (&vrp_equiv_obstack);
1869 /* Free VRP lattice. */
1871 vr_values::~vr_values ()
1873 /* Free allocated memory. */
1874 free (vr_value);
1875 free (vr_phi_edge_counts);
1876 bitmap_obstack_release (&vrp_equiv_obstack);
1878 /* So that we can distinguish between VRP data being available
1879 and not available. */
1880 vr_value = NULL;
1881 vr_phi_edge_counts = NULL;
1885 /* A hack. */
1886 static class vr_values *x_vr_values;
1888 /* Return the singleton value-range for NAME or NAME. */
1890 static inline tree
1891 vrp_valueize (tree name)
1893 if (TREE_CODE (name) == SSA_NAME)
1895 const value_range_equiv *vr = x_vr_values->get_value_range (name);
1896 if (vr->kind () == VR_RANGE
1897 && (TREE_CODE (vr->min ()) == SSA_NAME
1898 || is_gimple_min_invariant (vr->min ()))
1899 && vrp_operand_equal_p (vr->min (), vr->max ()))
1900 return vr->min ();
1902 return name;
1905 /* Return the singleton value-range for NAME if that is a constant
1906 but signal to not follow SSA edges. */
1908 static inline tree
1909 vrp_valueize_1 (tree name)
1911 if (TREE_CODE (name) == SSA_NAME)
1913 /* If the definition may be simulated again we cannot follow
1914 this SSA edge as the SSA propagator does not necessarily
1915 re-visit the use. */
1916 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1917 if (!gimple_nop_p (def_stmt)
1918 && prop_simulate_again_p (def_stmt))
1919 return NULL_TREE;
1920 const value_range_equiv *vr = x_vr_values->get_value_range (name);
1921 tree singleton;
1922 if (vr->singleton_p (&singleton))
1923 return singleton;
1925 return name;
1928 /* Given STMT, an assignment or call, return its LHS if the type
1929 of the LHS is suitable for VRP analysis, else return NULL_TREE. */
1931 tree
1932 get_output_for_vrp (gimple *stmt)
1934 if (!is_gimple_assign (stmt) && !is_gimple_call (stmt))
1935 return NULL_TREE;
1937 /* We only keep track of ranges in integral and pointer types. */
1938 tree lhs = gimple_get_lhs (stmt);
1939 if (TREE_CODE (lhs) == SSA_NAME
1940 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
1941 /* It is valid to have NULL MIN/MAX values on a type. See
1942 build_range_type. */
1943 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
1944 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
1945 || POINTER_TYPE_P (TREE_TYPE (lhs))))
1946 return lhs;
1948 return NULL_TREE;
1951 /* Visit assignment STMT. If it produces an interesting range, record
1952 the range in VR and set LHS to OUTPUT_P. */
1954 void
1955 vr_values::vrp_visit_assignment_or_call (gimple *stmt, tree *output_p,
1956 value_range_equiv *vr)
1958 tree lhs = get_output_for_vrp (stmt);
1959 *output_p = lhs;
1961 /* We only keep track of ranges in integral and pointer types. */
1962 if (lhs)
1964 enum gimple_code code = gimple_code (stmt);
1966 /* Try folding the statement to a constant first. */
1967 x_vr_values = this;
1968 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
1969 vrp_valueize_1);
1970 x_vr_values = NULL;
1971 if (tem)
1973 if (TREE_CODE (tem) == SSA_NAME
1974 && (SSA_NAME_IS_DEFAULT_DEF (tem)
1975 || ! prop_simulate_again_p (SSA_NAME_DEF_STMT (tem))))
1977 extract_range_from_ssa_name (vr, tem);
1978 return;
1980 else if (is_gimple_min_invariant (tem))
1982 vr->set (tem);
1983 return;
1986 /* Then dispatch to value-range extracting functions. */
1987 if (code == GIMPLE_CALL)
1988 extract_range_basic (vr, stmt);
1989 else
1990 extract_range_from_assignment (vr, as_a <gassign *> (stmt));
1994 /* Helper that gets the value range of the SSA_NAME with version I
1995 or a symbolic range containing the SSA_NAME only if the value range
1996 is varying or undefined. Uses TEM as storage for the alternate range. */
1998 const value_range_equiv *
1999 simplify_using_ranges::get_vr_for_comparison (int i, value_range_equiv *tem,
2000 gimple *s)
2002 /* Shallow-copy equiv bitmap. */
2003 const value_range_equiv *vr = query->get_value_range (ssa_name (i), s);
2005 /* If name N_i does not have a valid range, use N_i as its own
2006 range. This allows us to compare against names that may
2007 have N_i in their ranges. */
2008 if (vr->varying_p () || vr->undefined_p ())
2010 tem->set (ssa_name (i));
2011 return tem;
2014 return vr;
2017 /* Compare all the value ranges for names equivalent to VAR with VAL
2018 using comparison code COMP. Return the same value returned by
2019 compare_range_with_value, including the setting of
2020 *STRICT_OVERFLOW_P. */
2022 tree
2023 simplify_using_ranges::compare_name_with_value
2024 (enum tree_code comp, tree var, tree val,
2025 bool *strict_overflow_p, bool use_equiv_p,
2026 gimple *s)
2028 /* Get the set of equivalences for VAR. */
2029 bitmap e = query->get_value_range (var, s)->equiv ();
2031 /* Start at -1. Set it to 0 if we do a comparison without relying
2032 on overflow, or 1 if all comparisons rely on overflow. */
2033 int used_strict_overflow = -1;
2035 /* Compare vars' value range with val. */
2036 value_range_equiv tem_vr;
2037 const value_range_equiv *equiv_vr
2038 = get_vr_for_comparison (SSA_NAME_VERSION (var), &tem_vr, s);
2039 bool sop = false;
2040 tree retval = compare_range_with_value (comp, equiv_vr, val, &sop);
2041 if (retval)
2042 used_strict_overflow = sop ? 1 : 0;
2044 /* If the equiv set is empty we have done all work we need to do. */
2045 if (e == NULL)
2047 if (retval && used_strict_overflow > 0)
2048 *strict_overflow_p = true;
2049 return retval;
2052 unsigned i;
2053 bitmap_iterator bi;
2054 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
2056 tree name = ssa_name (i);
2057 if (!name)
2058 continue;
2060 if (!use_equiv_p
2061 && !SSA_NAME_IS_DEFAULT_DEF (name)
2062 && prop_simulate_again_p (SSA_NAME_DEF_STMT (name)))
2063 continue;
2065 equiv_vr = get_vr_for_comparison (i, &tem_vr, s);
2066 sop = false;
2067 tree t = compare_range_with_value (comp, equiv_vr, val, &sop);
2068 if (t)
2070 /* If we get different answers from different members
2071 of the equivalence set this check must be in a dead
2072 code region. Folding it to a trap representation
2073 would be correct here. For now just return don't-know. */
2074 if (retval != NULL
2075 && t != retval)
2077 retval = NULL_TREE;
2078 break;
2080 retval = t;
2082 if (!sop)
2083 used_strict_overflow = 0;
2084 else if (used_strict_overflow < 0)
2085 used_strict_overflow = 1;
2089 if (retval && used_strict_overflow > 0)
2090 *strict_overflow_p = true;
2092 return retval;
2096 /* Given a comparison code COMP and names N1 and N2, compare all the
2097 ranges equivalent to N1 against all the ranges equivalent to N2
2098 to determine the value of N1 COMP N2. Return the same value
2099 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
2100 whether we relied on undefined signed overflow in the comparison. */
2103 tree
2104 simplify_using_ranges::compare_names (enum tree_code comp, tree n1, tree n2,
2105 bool *strict_overflow_p, gimple *s)
2107 /* Compare the ranges of every name equivalent to N1 against the
2108 ranges of every name equivalent to N2. */
2109 bitmap e1 = query->get_value_range (n1, s)->equiv ();
2110 bitmap e2 = query->get_value_range (n2, s)->equiv ();
2112 /* Use the fake bitmaps if e1 or e2 are not available. */
2113 static bitmap s_e1 = NULL, s_e2 = NULL;
2114 static bitmap_obstack *s_obstack = NULL;
2115 if (s_obstack == NULL)
2117 s_obstack = XNEW (bitmap_obstack);
2118 bitmap_obstack_initialize (s_obstack);
2119 s_e1 = BITMAP_ALLOC (s_obstack);
2120 s_e2 = BITMAP_ALLOC (s_obstack);
2122 if (e1 == NULL)
2123 e1 = s_e1;
2124 if (e2 == NULL)
2125 e2 = s_e2;
2127 /* Add N1 and N2 to their own set of equivalences to avoid
2128 duplicating the body of the loop just to check N1 and N2
2129 ranges. */
2130 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
2131 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
2133 /* If the equivalence sets have a common intersection, then the two
2134 names can be compared without checking their ranges. */
2135 if (bitmap_intersect_p (e1, e2))
2137 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2138 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2140 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
2141 ? boolean_true_node
2142 : boolean_false_node;
2145 /* Start at -1. Set it to 0 if we do a comparison without relying
2146 on overflow, or 1 if all comparisons rely on overflow. */
2147 int used_strict_overflow = -1;
2149 /* Otherwise, compare all the equivalent ranges. First, add N1 and
2150 N2 to their own set of equivalences to avoid duplicating the body
2151 of the loop just to check N1 and N2 ranges. */
2152 bitmap_iterator bi1;
2153 unsigned i1;
2154 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
2156 if (!ssa_name (i1))
2157 continue;
2159 value_range_equiv tem_vr1;
2160 const value_range_equiv *vr1 = get_vr_for_comparison (i1, &tem_vr1, s);
2162 tree t = NULL_TREE, retval = NULL_TREE;
2163 bitmap_iterator bi2;
2164 unsigned i2;
2165 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
2167 if (!ssa_name (i2))
2168 continue;
2170 bool sop = false;
2172 value_range_equiv tem_vr2;
2173 const value_range_equiv *vr2 = get_vr_for_comparison (i2, &tem_vr2,
2176 t = compare_ranges (comp, vr1, vr2, &sop);
2177 if (t)
2179 /* If we get different answers from different members
2180 of the equivalence set this check must be in a dead
2181 code region. Folding it to a trap representation
2182 would be correct here. For now just return don't-know. */
2183 if (retval != NULL && t != retval)
2185 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2186 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2187 return NULL_TREE;
2189 retval = t;
2191 if (!sop)
2192 used_strict_overflow = 0;
2193 else if (used_strict_overflow < 0)
2194 used_strict_overflow = 1;
2198 if (retval)
2200 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2201 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2202 if (used_strict_overflow > 0)
2203 *strict_overflow_p = true;
2204 return retval;
2208 /* None of the equivalent ranges are useful in computing this
2209 comparison. */
2210 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2211 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2212 return NULL_TREE;
2215 /* Helper function for vrp_evaluate_conditional_warnv & other
2216 optimizers. */
2218 tree
2219 simplify_using_ranges::vrp_evaluate_conditional_warnv_with_ops_using_ranges
2220 (enum tree_code code, tree op0, tree op1, bool * strict_overflow_p,
2221 gimple *s)
2223 const value_range_equiv *vr0, *vr1;
2224 vr0 = (TREE_CODE (op0) == SSA_NAME) ? query->get_value_range (op0, s) : NULL;
2225 vr1 = (TREE_CODE (op1) == SSA_NAME) ? query->get_value_range (op1, s) : NULL;
2227 tree res = NULL_TREE;
2228 if (vr0 && vr1)
2229 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
2230 if (!res && vr0)
2231 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
2232 if (!res && vr1)
2233 res = (compare_range_with_value
2234 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
2235 return res;
2238 /* Helper function for vrp_evaluate_conditional_warnv. */
2240 tree
2241 simplify_using_ranges::vrp_evaluate_conditional_warnv_with_ops
2242 (gimple *stmt,
2243 enum tree_code code,
2244 tree op0, tree op1,
2245 bool use_equiv_p,
2246 bool *strict_overflow_p,
2247 bool *only_ranges)
2249 tree ret;
2250 if (only_ranges)
2251 *only_ranges = true;
2253 /* We only deal with integral and pointer types. */
2254 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
2255 && !POINTER_TYPE_P (TREE_TYPE (op0)))
2256 return NULL_TREE;
2258 /* If OP0 CODE OP1 is an overflow comparison, if it can be expressed
2259 as a simple equality test, then prefer that over its current form
2260 for evaluation.
2262 An overflow test which collapses to an equality test can always be
2263 expressed as a comparison of one argument against zero. Overflow
2264 occurs when the chosen argument is zero and does not occur if the
2265 chosen argument is not zero. */
2266 tree x;
2267 if (overflow_comparison_p (code, op0, op1, use_equiv_p, &x))
2269 wide_int max = wi::max_value (TYPE_PRECISION (TREE_TYPE (op0)), UNSIGNED);
2270 /* B = A - 1; if (A < B) -> B = A - 1; if (A == 0)
2271 B = A - 1; if (A > B) -> B = A - 1; if (A != 0)
2272 B = A + 1; if (B < A) -> B = A + 1; if (B == 0)
2273 B = A + 1; if (B > A) -> B = A + 1; if (B != 0) */
2274 if (integer_zerop (x))
2276 op1 = x;
2277 code = (code == LT_EXPR || code == LE_EXPR) ? EQ_EXPR : NE_EXPR;
2279 /* B = A + 1; if (A > B) -> B = A + 1; if (B == 0)
2280 B = A + 1; if (A < B) -> B = A + 1; if (B != 0)
2281 B = A - 1; if (B > A) -> B = A - 1; if (A == 0)
2282 B = A - 1; if (B < A) -> B = A - 1; if (A != 0) */
2283 else if (wi::to_wide (x) == max - 1)
2285 op0 = op1;
2286 op1 = wide_int_to_tree (TREE_TYPE (op0), 0);
2287 code = (code == GT_EXPR || code == GE_EXPR) ? EQ_EXPR : NE_EXPR;
2289 else
2291 value_range vro, vri;
2292 if (code == GT_EXPR || code == GE_EXPR)
2294 vro.set (TYPE_MIN_VALUE (TREE_TYPE (op0)), x, VR_ANTI_RANGE);
2295 vri.set (TYPE_MIN_VALUE (TREE_TYPE (op0)), x);
2297 else if (code == LT_EXPR || code == LE_EXPR)
2299 vro.set (TYPE_MIN_VALUE (TREE_TYPE (op0)), x);
2300 vri.set (TYPE_MIN_VALUE (TREE_TYPE (op0)), x, VR_ANTI_RANGE);
2302 else
2303 gcc_unreachable ();
2304 const value_range_equiv *vr0 = query->get_value_range (op0, stmt);
2305 /* If vro, the range for OP0 to pass the overflow test, has
2306 no intersection with *vr0, OP0's known range, then the
2307 overflow test can't pass, so return the node for false.
2308 If it is the inverted range, vri, that has no
2309 intersection, then the overflow test must pass, so return
2310 the node for true. In other cases, we could proceed with
2311 a simplified condition comparing OP0 and X, with LE_EXPR
2312 for previously LE_ or LT_EXPR and GT_EXPR otherwise, but
2313 the comments next to the enclosing if suggest it's not
2314 generally profitable to do so. */
2315 vro.legacy_verbose_intersect (vr0);
2316 if (vro.undefined_p ())
2317 return boolean_false_node;
2318 vri.legacy_verbose_intersect (vr0);
2319 if (vri.undefined_p ())
2320 return boolean_true_node;
2324 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
2325 (code, op0, op1, strict_overflow_p, stmt)))
2326 return ret;
2327 if (only_ranges)
2328 *only_ranges = false;
2329 /* Do not use compare_names during propagation, it's quadratic. */
2330 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
2331 && use_equiv_p)
2332 return compare_names (code, op0, op1, strict_overflow_p, stmt);
2333 else if (TREE_CODE (op0) == SSA_NAME)
2334 return compare_name_with_value (code, op0, op1,
2335 strict_overflow_p, use_equiv_p, stmt);
2336 else if (TREE_CODE (op1) == SSA_NAME)
2337 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
2338 strict_overflow_p, use_equiv_p, stmt);
2339 return NULL_TREE;
2342 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
2343 information. Return NULL if the conditional cannot be evaluated.
2344 The ranges of all the names equivalent with the operands in COND
2345 will be used when trying to compute the value. If the result is
2346 based on undefined signed overflow, issue a warning if
2347 appropriate. */
2349 tree
2350 simplify_using_ranges::vrp_evaluate_conditional (tree_code code, tree op0,
2351 tree op1, gimple *stmt)
2353 bool sop;
2354 tree ret;
2355 bool only_ranges;
2357 /* Some passes and foldings leak constants with overflow flag set
2358 into the IL. Avoid doing wrong things with these and bail out. */
2359 if ((TREE_CODE (op0) == INTEGER_CST
2360 && TREE_OVERFLOW (op0))
2361 || (TREE_CODE (op1) == INTEGER_CST
2362 && TREE_OVERFLOW (op1)))
2363 return NULL_TREE;
2365 sop = false;
2366 ret = vrp_evaluate_conditional_warnv_with_ops (stmt, code, op0, op1, true,
2367 &sop, &only_ranges);
2369 if (ret && sop)
2371 enum warn_strict_overflow_code wc;
2372 const char* warnmsg;
2374 if (is_gimple_min_invariant (ret))
2376 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
2377 warnmsg = G_("assuming signed overflow does not occur when "
2378 "simplifying conditional to constant");
2380 else
2382 wc = WARN_STRICT_OVERFLOW_COMPARISON;
2383 warnmsg = G_("assuming signed overflow does not occur when "
2384 "simplifying conditional");
2387 if (issue_strict_overflow_warning (wc))
2389 location_t location;
2391 if (!gimple_has_location (stmt))
2392 location = input_location;
2393 else
2394 location = gimple_location (stmt);
2395 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
2399 if (warn_type_limits
2400 && ret && only_ranges
2401 && TREE_CODE_CLASS (code) == tcc_comparison
2402 && TREE_CODE (op0) == SSA_NAME)
2404 /* If the comparison is being folded and the operand on the LHS
2405 is being compared against a constant value that is outside of
2406 the natural range of OP0's type, then the predicate will
2407 always fold regardless of the value of OP0. If -Wtype-limits
2408 was specified, emit a warning. */
2409 tree type = TREE_TYPE (op0);
2410 const value_range_equiv *vr0 = query->get_value_range (op0, stmt);
2412 if (vr0->varying_p ()
2413 && INTEGRAL_TYPE_P (type)
2414 && is_gimple_min_invariant (op1))
2416 location_t location;
2418 if (!gimple_has_location (stmt))
2419 location = input_location;
2420 else
2421 location = gimple_location (stmt);
2423 warning_at (location, OPT_Wtype_limits,
2424 integer_zerop (ret)
2425 ? G_("comparison always false "
2426 "due to limited range of data type")
2427 : G_("comparison always true "
2428 "due to limited range of data type"));
2432 return ret;
2436 /* Visit conditional statement STMT. If we can determine which edge
2437 will be taken out of STMT's basic block, record it in
2438 *TAKEN_EDGE_P. Otherwise, set *TAKEN_EDGE_P to NULL. */
2440 void
2441 simplify_using_ranges::vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
2443 tree val;
2445 *taken_edge_p = NULL;
2447 if (dump_file && (dump_flags & TDF_DETAILS))
2449 tree use;
2450 ssa_op_iter i;
2452 fprintf (dump_file, "\nVisiting conditional with predicate: ");
2453 print_gimple_stmt (dump_file, stmt, 0);
2454 fprintf (dump_file, "\nWith known ranges\n");
2456 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
2458 fprintf (dump_file, "\t");
2459 print_generic_expr (dump_file, use);
2460 fprintf (dump_file, ": ");
2461 Value_Range r (TREE_TYPE (use));
2462 query->range_of_expr (r, use, stmt);
2463 r.dump (dump_file);
2466 fprintf (dump_file, "\n");
2469 /* Compute the value of the predicate COND by checking the known
2470 ranges of each of its operands.
2472 Note that we cannot evaluate all the equivalent ranges here
2473 because those ranges may not yet be final and with the current
2474 propagation strategy, we cannot determine when the value ranges
2475 of the names in the equivalence set have changed.
2477 For instance, given the following code fragment
2479 i_5 = PHI <8, i_13>
2481 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
2482 if (i_14 == 1)
2485 Assume that on the first visit to i_14, i_5 has the temporary
2486 range [8, 8] because the second argument to the PHI function is
2487 not yet executable. We derive the range ~[0, 0] for i_14 and the
2488 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
2489 the first time, since i_14 is equivalent to the range [8, 8], we
2490 determine that the predicate is always false.
2492 On the next round of propagation, i_13 is determined to be
2493 VARYING, which causes i_5 to drop down to VARYING. So, another
2494 visit to i_14 is scheduled. In this second visit, we compute the
2495 exact same range and equivalence set for i_14, namely ~[0, 0] and
2496 { i_5 }. But we did not have the previous range for i_5
2497 registered, so vrp_visit_assignment thinks that the range for
2498 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
2499 is not visited again, which stops propagation from visiting
2500 statements in the THEN clause of that if().
2502 To properly fix this we would need to keep the previous range
2503 value for the names in the equivalence set. This way we would've
2504 discovered that from one visit to the other i_5 changed from
2505 range [8, 8] to VR_VARYING.
2507 However, fixing this apparent limitation may not be worth the
2508 additional checking. Testing on several code bases (GCC, DLV,
2509 MICO, TRAMP3D and SPEC2000) showed that doing this results in
2510 4 more predicates folded in SPEC. */
2512 bool sop;
2513 val = vrp_evaluate_conditional_warnv_with_ops (stmt,
2514 gimple_cond_code (stmt),
2515 gimple_cond_lhs (stmt),
2516 gimple_cond_rhs (stmt),
2517 false, &sop, NULL);
2518 if (val)
2519 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
2521 if (dump_file && (dump_flags & TDF_DETAILS))
2523 fprintf (dump_file, "\nPredicate evaluates to: ");
2524 if (val == NULL_TREE)
2525 fprintf (dump_file, "DON'T KNOW\n");
2526 else
2527 print_generic_stmt (dump_file, val);
2531 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
2532 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
2533 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
2534 Returns true if the default label is not needed. */
2536 static bool
2537 find_case_label_ranges (gswitch *stmt, const value_range *vr,
2538 size_t *min_idx1, size_t *max_idx1,
2539 size_t *min_idx2, size_t *max_idx2)
2541 size_t i, j, k, l;
2542 unsigned int n = gimple_switch_num_labels (stmt);
2543 bool take_default;
2544 tree case_low, case_high;
2545 tree min = vr->min (), max = vr->max ();
2547 gcc_checking_assert (!vr->varying_p () && !vr->undefined_p ());
2549 take_default = !find_case_label_range (stmt, min, max, &i, &j);
2551 /* Set second range to empty. */
2552 *min_idx2 = 1;
2553 *max_idx2 = 0;
2555 if (vr->kind () == VR_RANGE)
2557 *min_idx1 = i;
2558 *max_idx1 = j;
2559 return !take_default;
2562 /* Set first range to all case labels. */
2563 *min_idx1 = 1;
2564 *max_idx1 = n - 1;
2566 if (i > j)
2567 return false;
2569 /* Make sure all the values of case labels [i , j] are contained in
2570 range [MIN, MAX]. */
2571 case_low = CASE_LOW (gimple_switch_label (stmt, i));
2572 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
2573 if (tree_int_cst_compare (case_low, min) < 0)
2574 i += 1;
2575 if (case_high != NULL_TREE
2576 && tree_int_cst_compare (max, case_high) < 0)
2577 j -= 1;
2579 if (i > j)
2580 return false;
2582 /* If the range spans case labels [i, j], the corresponding anti-range spans
2583 the labels [1, i - 1] and [j + 1, n - 1]. */
2584 k = j + 1;
2585 l = n - 1;
2586 if (k > l)
2588 k = 1;
2589 l = 0;
2592 j = i - 1;
2593 i = 1;
2594 if (i > j)
2596 i = k;
2597 j = l;
2598 k = 1;
2599 l = 0;
2602 *min_idx1 = i;
2603 *max_idx1 = j;
2604 *min_idx2 = k;
2605 *max_idx2 = l;
2606 return false;
2609 /* Visit switch statement STMT. If we can determine which edge
2610 will be taken out of STMT's basic block, record it in
2611 *TAKEN_EDGE_P. Otherwise, *TAKEN_EDGE_P set to NULL. */
2613 void
2614 vr_values::vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
2616 tree op, val;
2617 const value_range_equiv *vr;
2618 size_t i = 0, j = 0, k, l;
2619 bool take_default;
2621 *taken_edge_p = NULL;
2622 op = gimple_switch_index (stmt);
2623 if (TREE_CODE (op) != SSA_NAME)
2624 return;
2626 vr = get_value_range (op);
2627 if (dump_file && (dump_flags & TDF_DETAILS))
2629 fprintf (dump_file, "\nVisiting switch expression with operand ");
2630 print_generic_expr (dump_file, op);
2631 fprintf (dump_file, " with known range ");
2632 dump_value_range (dump_file, vr);
2633 fprintf (dump_file, "\n");
2636 if (vr->undefined_p ()
2637 || vr->varying_p ()
2638 || vr->symbolic_p ())
2639 return;
2641 /* Find the single edge that is taken from the switch expression. */
2642 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
2644 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
2645 label */
2646 if (j < i)
2648 gcc_assert (take_default);
2649 val = gimple_switch_default_label (stmt);
2651 else
2653 /* Check if labels with index i to j and maybe the default label
2654 are all reaching the same label. */
2656 val = gimple_switch_label (stmt, i);
2657 if (take_default
2658 && CASE_LABEL (gimple_switch_default_label (stmt))
2659 != CASE_LABEL (val))
2661 if (dump_file && (dump_flags & TDF_DETAILS))
2662 fprintf (dump_file, " not a single destination for this "
2663 "range\n");
2664 return;
2666 for (++i; i <= j; ++i)
2668 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
2670 if (dump_file && (dump_flags & TDF_DETAILS))
2671 fprintf (dump_file, " not a single destination for this "
2672 "range\n");
2673 return;
2676 for (; k <= l; ++k)
2678 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
2680 if (dump_file && (dump_flags & TDF_DETAILS))
2681 fprintf (dump_file, " not a single destination for this "
2682 "range\n");
2683 return;
2688 *taken_edge_p = find_edge (gimple_bb (stmt),
2689 label_to_block (cfun, CASE_LABEL (val)));
2691 if (dump_file && (dump_flags & TDF_DETAILS))
2693 fprintf (dump_file, " will take edge to ");
2694 print_generic_stmt (dump_file, CASE_LABEL (val));
2699 /* Evaluate statement STMT. If the statement produces a useful range,
2700 set VR and corepsponding OUTPUT_P.
2702 If STMT is a conditional branch and we can determine its truth
2703 value, the taken edge is recorded in *TAKEN_EDGE_P. */
2705 void
2706 vr_values::extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
2707 tree *output_p, value_range_equiv *vr)
2710 if (dump_file && (dump_flags & TDF_DETAILS))
2712 fprintf (dump_file, "\nextract_range_from_stmt visiting:\n");
2713 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
2716 if (!stmt_interesting_for_vrp (stmt))
2717 gcc_assert (stmt_ends_bb_p (stmt));
2718 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
2719 vrp_visit_assignment_or_call (stmt, output_p, vr);
2720 else if (gimple_code (stmt) == GIMPLE_COND)
2721 simplifier.vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
2722 else if (gimple_code (stmt) == GIMPLE_SWITCH)
2723 vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
2726 /* Visit all arguments for PHI node PHI that flow through executable
2727 edges. If a valid value range can be derived from all the incoming
2728 value ranges, set a new range in VR_RESULT. */
2730 void
2731 vr_values::extract_range_from_phi_node (gphi *phi,
2732 value_range_equiv *vr_result)
2734 tree lhs = PHI_RESULT (phi);
2735 const value_range_equiv *lhs_vr = get_value_range (lhs);
2736 bool first = true;
2737 int old_edges;
2738 class loop *l;
2740 if (dump_file && (dump_flags & TDF_DETAILS))
2742 fprintf (dump_file, "\nVisiting PHI node: ");
2743 print_gimple_stmt (dump_file, phi, 0, dump_flags);
2746 bool may_simulate_backedge_again = false;
2747 int edges = 0;
2748 for (size_t i = 0; i < gimple_phi_num_args (phi); i++)
2750 edge e = gimple_phi_arg_edge (phi, i);
2752 if (dump_file && (dump_flags & TDF_DETAILS))
2754 fprintf (dump_file,
2755 " Argument #%d (%d -> %d %sexecutable)\n",
2756 (int) i, e->src->index, e->dest->index,
2757 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
2760 if (e->flags & EDGE_EXECUTABLE)
2762 value_range_equiv vr_arg_tem;
2763 const value_range_equiv *vr_arg = &vr_arg_tem;
2765 ++edges;
2767 tree arg = PHI_ARG_DEF (phi, i);
2768 if (TREE_CODE (arg) == SSA_NAME)
2770 /* See if we are eventually going to change one of the args. */
2771 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
2772 if (! gimple_nop_p (def_stmt)
2773 && prop_simulate_again_p (def_stmt)
2774 && e->flags & EDGE_DFS_BACK)
2775 may_simulate_backedge_again = true;
2777 const value_range_equiv *vr_arg_ = get_value_range (arg);
2778 /* Do not allow equivalences or symbolic ranges to leak in from
2779 backedges. That creates invalid equivalencies.
2780 See PR53465 and PR54767. */
2781 if (e->flags & EDGE_DFS_BACK)
2783 if (!vr_arg_->varying_p () && !vr_arg_->undefined_p ())
2785 vr_arg_tem.set (vr_arg_->min (), vr_arg_->max (), NULL,
2786 vr_arg_->kind ());
2787 if (vr_arg_tem.symbolic_p ())
2788 vr_arg_tem.set_varying (TREE_TYPE (arg));
2790 else
2791 vr_arg = vr_arg_;
2793 /* If the non-backedge arguments range is VR_VARYING then
2794 we can still try recording a simple equivalence. */
2795 else if (vr_arg_->varying_p ())
2796 vr_arg_tem.set (arg);
2797 else
2798 vr_arg = vr_arg_;
2800 else
2802 if (TREE_OVERFLOW_P (arg))
2803 arg = drop_tree_overflow (arg);
2805 vr_arg_tem.set (arg);
2808 if (dump_file && (dump_flags & TDF_DETAILS))
2810 fprintf (dump_file, "\t");
2811 print_generic_expr (dump_file, arg, dump_flags);
2812 fprintf (dump_file, ": ");
2813 dump_value_range (dump_file, vr_arg);
2814 fprintf (dump_file, "\n");
2817 if (first)
2818 vr_result->deep_copy (vr_arg);
2819 else
2820 vr_result->legacy_verbose_union_ (vr_arg);
2821 first = false;
2823 if (vr_result->varying_p ())
2824 break;
2828 if (vr_result->varying_p ())
2829 goto varying;
2830 else if (vr_result->undefined_p ())
2831 goto update_range;
2833 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
2834 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
2836 /* To prevent infinite iterations in the algorithm, derive ranges
2837 when the new value is slightly bigger or smaller than the
2838 previous one. We don't do this if we have seen a new executable
2839 edge; this helps us avoid an infinity for conditionals
2840 which are not in a loop. If the old value-range was VR_UNDEFINED
2841 use the updated range and iterate one more time. If we will not
2842 simulate this PHI again via the backedge allow us to iterate. */
2843 if (edges > 0
2844 && gimple_phi_num_args (phi) > 1
2845 && edges == old_edges
2846 && !lhs_vr->undefined_p ()
2847 && may_simulate_backedge_again)
2849 /* Compare old and new ranges, fall back to varying if the
2850 values are not comparable. */
2851 int cmp_min = compare_values (lhs_vr->min (), vr_result->min ());
2852 if (cmp_min == -2)
2853 goto varying;
2854 int cmp_max = compare_values (lhs_vr->max (), vr_result->max ());
2855 if (cmp_max == -2)
2856 goto varying;
2858 /* For non VR_RANGE or for pointers fall back to varying if
2859 the range changed. */
2860 if ((lhs_vr->kind () != VR_RANGE || vr_result->kind () != VR_RANGE
2861 || POINTER_TYPE_P (TREE_TYPE (lhs)))
2862 && (cmp_min != 0 || cmp_max != 0))
2863 goto varying;
2865 /* If the new minimum is larger than the previous one
2866 retain the old value. If the new minimum value is smaller
2867 than the previous one and not -INF go all the way to -INF + 1.
2868 In the first case, to avoid infinite bouncing between different
2869 minimums, and in the other case to avoid iterating millions of
2870 times to reach -INF. Going to -INF + 1 also lets the following
2871 iteration compute whether there will be any overflow, at the
2872 expense of one additional iteration. */
2873 tree new_min = vr_result->min ();
2874 tree new_max = vr_result->max ();
2875 if (cmp_min < 0)
2876 new_min = lhs_vr->min ();
2877 else if (cmp_min > 0
2878 && (TREE_CODE (vr_result->min ()) != INTEGER_CST
2879 || tree_int_cst_lt (vrp_val_min (vr_result->type ()),
2880 vr_result->min ())))
2881 new_min = int_const_binop (PLUS_EXPR,
2882 vrp_val_min (vr_result->type ()),
2883 build_int_cst (vr_result->type (), 1));
2885 /* Similarly for the maximum value. */
2886 if (cmp_max > 0)
2887 new_max = lhs_vr->max ();
2888 else if (cmp_max < 0
2889 && (TREE_CODE (vr_result->max ()) != INTEGER_CST
2890 || tree_int_cst_lt (vr_result->max (),
2891 vrp_val_max (vr_result->type ()))))
2892 new_max = int_const_binop (MINUS_EXPR,
2893 vrp_val_max (vr_result->type ()),
2894 build_int_cst (vr_result->type (), 1));
2896 vr_result->update (new_min, new_max, vr_result->kind ());
2898 /* If we dropped either bound to +-INF then if this is a loop
2899 PHI node SCEV may known more about its value-range. */
2900 if (cmp_min > 0 || cmp_min < 0
2901 || cmp_max < 0 || cmp_max > 0)
2902 goto scev_check;
2904 goto infinite_check;
2907 goto update_range;
2909 varying:
2910 vr_result->set_varying (TREE_TYPE (lhs));
2912 scev_check:
2913 /* If this is a loop PHI node SCEV may known more about its value-range.
2914 scev_check can be reached from two paths, one is a fall through from above
2915 "varying" label, the other is direct goto from code block which tries to
2916 avoid infinite simulation. */
2917 if (scev_initialized_p ()
2918 && (l = loop_containing_stmt (phi))
2919 && l->header == gimple_bb (phi))
2920 adjust_range_with_scev (vr_result, l, phi, lhs);
2922 infinite_check:
2923 /* If we will end up with a (-INF, +INF) range, set it to
2924 VARYING. Same if the previous max value was invalid for
2925 the type and we end up with vr_result.min > vr_result.max. */
2926 if ((!vr_result->varying_p () && !vr_result->undefined_p ())
2927 && !((vrp_val_is_max (vr_result->max ()) && vrp_val_is_min (vr_result->min ()))
2928 || compare_values (vr_result->min (), vr_result->max ()) > 0))
2930 else
2931 vr_result->set_varying (TREE_TYPE (lhs));
2933 /* If the new range is different than the previous value, keep
2934 iterating. */
2935 update_range:
2936 return;
2939 /* Simplify boolean operations if the source is known
2940 to be already a boolean. */
2941 bool
2942 simplify_using_ranges::simplify_truth_ops_using_ranges
2943 (gimple_stmt_iterator *gsi,
2944 gimple *stmt)
2946 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
2947 tree lhs, op0, op1;
2948 bool need_conversion;
2950 /* We handle only !=/== case here. */
2951 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
2953 op0 = gimple_assign_rhs1 (stmt);
2954 if (!op_with_boolean_value_range_p (op0, stmt))
2955 return false;
2957 op1 = gimple_assign_rhs2 (stmt);
2958 if (!op_with_boolean_value_range_p (op1, stmt))
2959 return false;
2961 /* Reduce number of cases to handle to NE_EXPR. As there is no
2962 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
2963 if (rhs_code == EQ_EXPR)
2965 if (TREE_CODE (op1) == INTEGER_CST)
2966 op1 = int_const_binop (BIT_XOR_EXPR, op1,
2967 build_int_cst (TREE_TYPE (op1), 1));
2968 else
2969 return false;
2972 lhs = gimple_assign_lhs (stmt);
2973 need_conversion
2974 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
2976 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
2977 if (need_conversion
2978 && !TYPE_UNSIGNED (TREE_TYPE (op0))
2979 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
2980 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
2981 return false;
2983 /* For A != 0 we can substitute A itself. */
2984 if (integer_zerop (op1))
2985 gimple_assign_set_rhs_with_ops (gsi,
2986 need_conversion
2987 ? NOP_EXPR : TREE_CODE (op0), op0);
2988 /* For A != B we substitute A ^ B. Either with conversion. */
2989 else if (need_conversion)
2991 tree tem = make_ssa_name (TREE_TYPE (op0));
2992 gassign *newop
2993 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
2994 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
2995 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
2996 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
2998 value_range vr (TREE_TYPE (tem),
2999 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
3000 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
3001 set_range_info (tem, vr);
3003 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
3005 /* Or without. */
3006 else
3007 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
3008 update_stmt (gsi_stmt (*gsi));
3009 fold_stmt (gsi, follow_single_use_edges);
3011 return true;
3014 /* Simplify a division or modulo operator to a right shift or bitwise and
3015 if the first operand is unsigned or is greater than zero and the second
3016 operand is an exact power of two. For TRUNC_MOD_EXPR op0 % op1 with
3017 constant op1 (op1min = op1) or with op1 in [op1min, op1max] range,
3018 optimize it into just op0 if op0's range is known to be a subset of
3019 [-op1min + 1, op1min - 1] for signed and [0, op1min - 1] for unsigned
3020 modulo. */
3022 bool
3023 simplify_using_ranges::simplify_div_or_mod_using_ranges
3024 (gimple_stmt_iterator *gsi,
3025 gimple *stmt)
3027 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
3028 tree val = NULL;
3029 tree op0 = gimple_assign_rhs1 (stmt);
3030 tree op1 = gimple_assign_rhs2 (stmt);
3031 tree op0min = NULL_TREE, op0max = NULL_TREE;
3032 tree op1min = op1;
3033 const value_range *vr = NULL;
3035 if (TREE_CODE (op0) == INTEGER_CST)
3037 op0min = op0;
3038 op0max = op0;
3040 else
3042 vr = query->get_value_range (op0, stmt);
3043 if (range_int_cst_p (vr))
3045 op0min = vr->min ();
3046 op0max = vr->max ();
3050 if (rhs_code == TRUNC_MOD_EXPR
3051 && TREE_CODE (op1) == SSA_NAME)
3053 const value_range_equiv *vr1 = query->get_value_range (op1, stmt);
3054 if (range_int_cst_p (vr1))
3055 op1min = vr1->min ();
3057 if (rhs_code == TRUNC_MOD_EXPR
3058 && TREE_CODE (op1min) == INTEGER_CST
3059 && tree_int_cst_sgn (op1min) == 1
3060 && op0max
3061 && tree_int_cst_lt (op0max, op1min))
3063 if (TYPE_UNSIGNED (TREE_TYPE (op0))
3064 || tree_int_cst_sgn (op0min) >= 0
3065 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1min), op1min),
3066 op0min))
3068 /* If op0 already has the range op0 % op1 has,
3069 then TRUNC_MOD_EXPR won't change anything. */
3070 gimple_assign_set_rhs_from_tree (gsi, op0);
3071 return true;
3075 if (TREE_CODE (op0) != SSA_NAME)
3076 return false;
3078 if (!integer_pow2p (op1))
3080 /* X % -Y can be only optimized into X % Y either if
3081 X is not INT_MIN, or Y is not -1. Fold it now, as after
3082 remove_range_assertions the range info might be not available
3083 anymore. */
3084 if (rhs_code == TRUNC_MOD_EXPR
3085 && fold_stmt (gsi, follow_single_use_edges))
3086 return true;
3087 return false;
3090 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
3091 val = integer_one_node;
3092 else
3094 bool sop = false;
3096 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
3098 if (val
3099 && sop
3100 && integer_onep (val)
3101 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
3103 location_t location;
3105 if (!gimple_has_location (stmt))
3106 location = input_location;
3107 else
3108 location = gimple_location (stmt);
3109 warning_at (location, OPT_Wstrict_overflow,
3110 "assuming signed overflow does not occur when "
3111 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
3115 if (val && integer_onep (val))
3117 tree t;
3119 if (rhs_code == TRUNC_DIV_EXPR)
3121 t = build_int_cst (integer_type_node, tree_log2 (op1));
3122 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
3123 gimple_assign_set_rhs1 (stmt, op0);
3124 gimple_assign_set_rhs2 (stmt, t);
3126 else
3128 t = build_int_cst (TREE_TYPE (op1), 1);
3129 t = int_const_binop (MINUS_EXPR, op1, t);
3130 t = fold_convert (TREE_TYPE (op0), t);
3132 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
3133 gimple_assign_set_rhs1 (stmt, op0);
3134 gimple_assign_set_rhs2 (stmt, t);
3137 update_stmt (stmt);
3138 fold_stmt (gsi, follow_single_use_edges);
3139 return true;
3142 return false;
3145 /* Simplify a min or max if the ranges of the two operands are
3146 disjoint. Return true if we do simplify. */
3148 bool
3149 simplify_using_ranges::simplify_min_or_max_using_ranges
3150 (gimple_stmt_iterator *gsi,
3151 gimple *stmt)
3153 tree op0 = gimple_assign_rhs1 (stmt);
3154 tree op1 = gimple_assign_rhs2 (stmt);
3155 bool sop = false;
3156 tree val;
3158 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
3159 (LE_EXPR, op0, op1, &sop, stmt));
3160 if (!val)
3162 sop = false;
3163 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
3164 (LT_EXPR, op0, op1, &sop, stmt));
3167 if (val)
3169 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
3171 location_t location;
3173 if (!gimple_has_location (stmt))
3174 location = input_location;
3175 else
3176 location = gimple_location (stmt);
3177 warning_at (location, OPT_Wstrict_overflow,
3178 "assuming signed overflow does not occur when "
3179 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
3182 /* VAL == TRUE -> OP0 < or <= op1
3183 VAL == FALSE -> OP0 > or >= op1. */
3184 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
3185 == integer_zerop (val)) ? op0 : op1;
3186 gimple_assign_set_rhs_from_tree (gsi, res);
3187 return true;
3190 return false;
3193 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
3194 ABS_EXPR. If the operand is <= 0, then simplify the
3195 ABS_EXPR into a NEGATE_EXPR. */
3197 bool
3198 simplify_using_ranges::simplify_abs_using_ranges (gimple_stmt_iterator *gsi,
3199 gimple *stmt)
3201 tree op = gimple_assign_rhs1 (stmt);
3202 const value_range *vr = query->get_value_range (op, stmt);
3204 if (vr)
3206 tree val = NULL;
3207 bool sop = false;
3209 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
3210 if (!val)
3212 /* The range is neither <= 0 nor > 0. Now see if it is
3213 either < 0 or >= 0. */
3214 sop = false;
3215 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
3216 &sop);
3219 if (val)
3221 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
3223 location_t location;
3225 if (!gimple_has_location (stmt))
3226 location = input_location;
3227 else
3228 location = gimple_location (stmt);
3229 warning_at (location, OPT_Wstrict_overflow,
3230 "assuming signed overflow does not occur when "
3231 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
3234 gimple_assign_set_rhs1 (stmt, op);
3235 if (integer_zerop (val))
3236 gimple_assign_set_rhs_code (stmt, SSA_NAME);
3237 else
3238 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
3239 update_stmt (stmt);
3240 fold_stmt (gsi, follow_single_use_edges);
3241 return true;
3245 return false;
3248 /* value_range wrapper for wi_set_zero_nonzero_bits.
3250 Return TRUE if VR was a constant range and we were able to compute
3251 the bit masks. */
3253 static bool
3254 vr_set_zero_nonzero_bits (const tree expr_type,
3255 const value_range *vr,
3256 wide_int *may_be_nonzero,
3257 wide_int *must_be_nonzero)
3259 if (range_int_cst_p (vr))
3261 wi_set_zero_nonzero_bits (expr_type,
3262 wi::to_wide (vr->min ()),
3263 wi::to_wide (vr->max ()),
3264 *may_be_nonzero, *must_be_nonzero);
3265 return true;
3267 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
3268 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
3269 return false;
3272 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
3273 If all the bits that are being cleared by & are already
3274 known to be zero from VR, or all the bits that are being
3275 set by | are already known to be one from VR, the bit
3276 operation is redundant. */
3278 bool
3279 simplify_using_ranges::simplify_bit_ops_using_ranges
3280 (gimple_stmt_iterator *gsi,
3281 gimple *stmt)
3283 tree op0 = gimple_assign_rhs1 (stmt);
3284 tree op1 = gimple_assign_rhs2 (stmt);
3285 tree op = NULL_TREE;
3286 value_range vr0, vr1;
3287 wide_int may_be_nonzero0, may_be_nonzero1;
3288 wide_int must_be_nonzero0, must_be_nonzero1;
3289 wide_int mask;
3291 if (TREE_CODE (op0) == SSA_NAME)
3292 vr0 = *(query->get_value_range (op0, stmt));
3293 else if (is_gimple_min_invariant (op0))
3294 vr0.set (op0, op0);
3295 else
3296 return false;
3298 if (TREE_CODE (op1) == SSA_NAME)
3299 vr1 = *(query->get_value_range (op1, stmt));
3300 else if (is_gimple_min_invariant (op1))
3301 vr1.set (op1, op1);
3302 else
3303 return false;
3305 if (!vr_set_zero_nonzero_bits (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
3306 &must_be_nonzero0))
3307 return false;
3308 if (!vr_set_zero_nonzero_bits (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
3309 &must_be_nonzero1))
3310 return false;
3312 switch (gimple_assign_rhs_code (stmt))
3314 case BIT_AND_EXPR:
3315 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
3316 if (mask == 0)
3318 op = op0;
3319 break;
3321 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
3322 if (mask == 0)
3324 op = op1;
3325 break;
3327 break;
3328 case BIT_IOR_EXPR:
3329 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
3330 if (mask == 0)
3332 op = op1;
3333 break;
3335 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
3336 if (mask == 0)
3338 op = op0;
3339 break;
3341 break;
3342 default:
3343 gcc_unreachable ();
3346 if (op == NULL_TREE)
3347 return false;
3349 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
3350 update_stmt (gsi_stmt (*gsi));
3351 return true;
3354 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
3355 a known value range VR.
3357 If there is one and only one value which will satisfy the
3358 conditional, then return that value. Else return NULL.
3360 If signed overflow must be undefined for the value to satisfy
3361 the conditional, then set *STRICT_OVERFLOW_P to true. */
3363 static tree
3364 test_for_singularity (enum tree_code cond_code, tree op0,
3365 tree op1, const value_range *vr)
3367 tree min = NULL;
3368 tree max = NULL;
3370 /* Extract minimum/maximum values which satisfy the conditional as it was
3371 written. */
3372 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
3374 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
3376 max = op1;
3377 if (cond_code == LT_EXPR)
3379 tree one = build_int_cst (TREE_TYPE (op0), 1);
3380 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
3381 /* Signal to compare_values_warnv this expr doesn't overflow. */
3382 if (EXPR_P (max))
3383 suppress_warning (max, OPT_Woverflow);
3386 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
3388 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
3390 min = op1;
3391 if (cond_code == GT_EXPR)
3393 tree one = build_int_cst (TREE_TYPE (op0), 1);
3394 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
3395 /* Signal to compare_values_warnv this expr doesn't overflow. */
3396 if (EXPR_P (min))
3397 suppress_warning (min, OPT_Woverflow);
3401 /* Now refine the minimum and maximum values using any
3402 value range information we have for op0. */
3403 if (min && max)
3405 tree type = TREE_TYPE (op0);
3406 tree tmin = wide_int_to_tree (type, vr->lower_bound ());
3407 tree tmax = wide_int_to_tree (type, vr->upper_bound ());
3408 if (compare_values (tmin, min) == 1)
3409 min = tmin;
3410 if (compare_values (tmax, max) == -1)
3411 max = tmax;
3413 /* If the new min/max values have converged to a single value,
3414 then there is only one value which can satisfy the condition,
3415 return that value. */
3416 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
3417 return min;
3419 return NULL;
3422 /* Return whether the value range *VR fits in an integer type specified
3423 by PRECISION and UNSIGNED_P. */
3425 bool
3426 range_fits_type_p (const value_range *vr,
3427 unsigned dest_precision, signop dest_sgn)
3429 tree src_type;
3430 unsigned src_precision;
3431 widest_int tem;
3432 signop src_sgn;
3434 /* We can only handle integral and pointer types. */
3435 src_type = vr->type ();
3436 if (!INTEGRAL_TYPE_P (src_type)
3437 && !POINTER_TYPE_P (src_type))
3438 return false;
3440 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
3441 and so is an identity transform. */
3442 src_precision = TYPE_PRECISION (vr->type ());
3443 src_sgn = TYPE_SIGN (src_type);
3444 if ((src_precision < dest_precision
3445 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
3446 || (src_precision == dest_precision && src_sgn == dest_sgn))
3447 return true;
3449 /* Now we can only handle ranges with constant bounds. */
3450 if (!range_int_cst_p (vr))
3451 return false;
3453 /* For sign changes, the MSB of the wide_int has to be clear.
3454 An unsigned value with its MSB set cannot be represented by
3455 a signed wide_int, while a negative value cannot be represented
3456 by an unsigned wide_int. */
3457 if (src_sgn != dest_sgn
3458 && (wi::lts_p (wi::to_wide (vr->min ()), 0)
3459 || wi::lts_p (wi::to_wide (vr->max ()), 0)))
3460 return false;
3462 /* Then we can perform the conversion on both ends and compare
3463 the result for equality. */
3464 tem = wi::ext (wi::to_widest (vr->min ()), dest_precision, dest_sgn);
3465 if (tem != wi::to_widest (vr->min ()))
3466 return false;
3467 tem = wi::ext (wi::to_widest (vr->max ()), dest_precision, dest_sgn);
3468 if (tem != wi::to_widest (vr->max ()))
3469 return false;
3471 return true;
3474 // Clear edge E of EDGE_EXECUTABLE (it is unexecutable). If it wasn't
3475 // previously clear, propagate to successor blocks if appropriate.
3477 void
3478 simplify_using_ranges::set_and_propagate_unexecutable (edge e)
3480 // If not_executable is already set, we're done.
3481 // This works in the absence of a flag as well.
3482 if ((e->flags & m_not_executable_flag) == m_not_executable_flag)
3483 return;
3485 e->flags |= m_not_executable_flag;
3486 m_flag_set_edges.safe_push (e);
3488 // Check if the destination block needs to propagate the property.
3489 basic_block bb = e->dest;
3491 // If any incoming edge is executable, we are done.
3492 edge_iterator ei;
3493 FOR_EACH_EDGE (e, ei, bb->preds)
3494 if ((e->flags & m_not_executable_flag) == 0)
3495 return;
3497 // This block is also unexecutable, propagate to all exit edges as well.
3498 FOR_EACH_EDGE (e, ei, bb->succs)
3499 set_and_propagate_unexecutable (e);
3502 /* If COND can be folded entirely as TRUE or FALSE, rewrite the
3503 conditional as such, and return TRUE. */
3505 bool
3506 simplify_using_ranges::fold_cond (gcond *cond)
3508 int_range_max r;
3509 if (query->range_of_stmt (r, cond) && r.singleton_p ())
3511 // COND has already been folded if arguments are constant.
3512 if (TREE_CODE (gimple_cond_lhs (cond)) != SSA_NAME
3513 && TREE_CODE (gimple_cond_rhs (cond)) != SSA_NAME)
3514 return false;
3515 if (dump_file)
3517 fprintf (dump_file, "Folding predicate ");
3518 print_gimple_expr (dump_file, cond, 0);
3519 fprintf (dump_file, " to ");
3521 edge e0 = EDGE_SUCC (gimple_bb (cond), 0);
3522 edge e1 = EDGE_SUCC (gimple_bb (cond), 1);
3523 if (r.zero_p ())
3525 if (dump_file)
3526 fprintf (dump_file, "0\n");
3527 gimple_cond_make_false (cond);
3528 if (e0->flags & EDGE_TRUE_VALUE)
3529 set_and_propagate_unexecutable (e0);
3530 else
3531 set_and_propagate_unexecutable (e1);
3533 else
3535 if (dump_file)
3536 fprintf (dump_file, "1\n");
3537 gimple_cond_make_true (cond);
3538 if (e0->flags & EDGE_FALSE_VALUE)
3539 set_and_propagate_unexecutable (e0);
3540 else
3541 set_and_propagate_unexecutable (e1);
3543 update_stmt (cond);
3544 return true;
3547 /* ?? vrp_folder::fold_predicate_in() is a superset of this. At
3548 some point we should merge all variants of this code. */
3549 edge taken_edge;
3550 vrp_visit_cond_stmt (cond, &taken_edge);
3552 if (taken_edge)
3554 if (taken_edge->flags & EDGE_TRUE_VALUE)
3556 if (dump_file && (dump_flags & TDF_DETAILS))
3557 fprintf (dump_file, "\nVRP Predicate evaluates to: 1\n");
3558 gimple_cond_make_true (cond);
3560 else if (taken_edge->flags & EDGE_FALSE_VALUE)
3562 if (dump_file && (dump_flags & TDF_DETAILS))
3563 fprintf (dump_file, "\nVRP Predicate evaluates to: 0\n");
3564 gimple_cond_make_false (cond);
3566 else
3567 gcc_unreachable ();
3568 update_stmt (cond);
3569 return true;
3571 return false;
3574 /* Simplify a conditional using a relational operator to an equality
3575 test if the range information indicates only one value can satisfy
3576 the original conditional. */
3578 bool
3579 simplify_using_ranges::simplify_cond_using_ranges_1 (gcond *stmt)
3581 tree op0 = gimple_cond_lhs (stmt);
3582 tree op1 = gimple_cond_rhs (stmt);
3583 enum tree_code cond_code = gimple_cond_code (stmt);
3585 if (fold_cond (stmt))
3586 return true;
3588 if (cond_code != NE_EXPR
3589 && cond_code != EQ_EXPR
3590 && TREE_CODE (op0) == SSA_NAME
3591 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
3592 && is_gimple_min_invariant (op1))
3594 const value_range *vr = query->get_value_range (op0, stmt);
3596 /* If we have range information for OP0, then we might be
3597 able to simplify this conditional. */
3598 if (!vr->undefined_p () && !vr->varying_p ())
3600 tree new_tree = test_for_singularity (cond_code, op0, op1, vr);
3601 if (new_tree)
3603 if (dump_file)
3605 fprintf (dump_file, "Simplified relational ");
3606 print_gimple_stmt (dump_file, stmt, 0);
3607 fprintf (dump_file, " into ");
3610 gimple_cond_set_code (stmt, EQ_EXPR);
3611 gimple_cond_set_lhs (stmt, op0);
3612 gimple_cond_set_rhs (stmt, new_tree);
3614 update_stmt (stmt);
3616 if (dump_file)
3618 print_gimple_stmt (dump_file, stmt, 0);
3619 fprintf (dump_file, "\n");
3622 return true;
3625 /* Try again after inverting the condition. We only deal
3626 with integral types here, so no need to worry about
3627 issues with inverting FP comparisons. */
3628 new_tree = test_for_singularity
3629 (invert_tree_comparison (cond_code, false),
3630 op0, op1, vr);
3631 if (new_tree)
3633 if (dump_file)
3635 fprintf (dump_file, "Simplified relational ");
3636 print_gimple_stmt (dump_file, stmt, 0);
3637 fprintf (dump_file, " into ");
3640 gimple_cond_set_code (stmt, NE_EXPR);
3641 gimple_cond_set_lhs (stmt, op0);
3642 gimple_cond_set_rhs (stmt, new_tree);
3644 update_stmt (stmt);
3646 if (dump_file)
3648 print_gimple_stmt (dump_file, stmt, 0);
3649 fprintf (dump_file, "\n");
3652 return true;
3656 // Try to simplify casted conditions.
3657 return simplify_casted_cond (stmt);
3660 /* STMT is a conditional at the end of a basic block.
3662 If the conditional is of the form SSA_NAME op constant and the SSA_NAME
3663 was set via a type conversion, try to replace the SSA_NAME with the RHS
3664 of the type conversion. Doing so makes the conversion dead which helps
3665 subsequent passes. */
3667 bool
3668 simplify_using_ranges::simplify_casted_cond (gcond *stmt)
3670 tree op0 = gimple_cond_lhs (stmt);
3671 tree op1 = gimple_cond_rhs (stmt);
3673 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
3674 see if OP0 was set by a type conversion where the source of
3675 the conversion is another SSA_NAME with a range that fits
3676 into the range of OP0's type.
3678 If so, the conversion is redundant as the earlier SSA_NAME can be
3679 used for the comparison directly if we just massage the constant in the
3680 comparison. */
3681 if (TREE_CODE (op0) == SSA_NAME
3682 && TREE_CODE (op1) == INTEGER_CST)
3684 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
3685 tree innerop;
3687 if (!is_gimple_assign (def_stmt))
3688 return false;
3690 switch (gimple_assign_rhs_code (def_stmt))
3692 CASE_CONVERT:
3693 innerop = gimple_assign_rhs1 (def_stmt);
3694 break;
3695 case VIEW_CONVERT_EXPR:
3696 innerop = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), 0);
3697 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop)))
3698 return false;
3699 break;
3700 default:
3701 return false;
3704 if (TREE_CODE (innerop) == SSA_NAME
3705 && !POINTER_TYPE_P (TREE_TYPE (innerop))
3706 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
3707 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
3709 const value_range *vr = query->get_value_range (innerop);
3711 if (range_int_cst_p (vr)
3712 && range_fits_type_p (vr,
3713 TYPE_PRECISION (TREE_TYPE (op0)),
3714 TYPE_SIGN (TREE_TYPE (op0)))
3715 && int_fits_type_p (op1, TREE_TYPE (innerop)))
3717 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
3718 gimple_cond_set_lhs (stmt, innerop);
3719 gimple_cond_set_rhs (stmt, newconst);
3720 update_stmt (stmt);
3721 return true;
3725 return false;
3728 /* Simplify a switch statement using the value range of the switch
3729 argument. */
3731 bool
3732 simplify_using_ranges::simplify_switch_using_ranges (gswitch *stmt)
3734 tree op = gimple_switch_index (stmt);
3735 const value_range *vr = NULL;
3736 bool take_default;
3737 edge e;
3738 edge_iterator ei;
3739 size_t i = 0, j = 0, n, n2;
3740 tree vec2;
3741 switch_update su;
3742 size_t k = 1, l = 0;
3744 if (TREE_CODE (op) == SSA_NAME)
3746 vr = query->get_value_range (op, stmt);
3748 /* We can only handle integer ranges. */
3749 if (vr->varying_p ()
3750 || vr->undefined_p ()
3751 || vr->symbolic_p ())
3752 return false;
3754 /* Find case label for min/max of the value range. */
3755 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
3757 else if (TREE_CODE (op) == INTEGER_CST)
3759 take_default = !find_case_label_index (stmt, 1, op, &i);
3760 if (take_default)
3762 i = 1;
3763 j = 0;
3765 else
3767 j = i;
3770 else
3771 return false;
3773 n = gimple_switch_num_labels (stmt);
3775 /* We can truncate the case label ranges that partially overlap with OP's
3776 value range. */
3777 size_t min_idx = 1, max_idx = 0;
3778 if (vr != NULL)
3779 find_case_label_range (stmt, vr->min (), vr->max (), &min_idx, &max_idx);
3780 if (min_idx <= max_idx)
3782 tree min_label = gimple_switch_label (stmt, min_idx);
3783 tree max_label = gimple_switch_label (stmt, max_idx);
3785 /* Avoid changing the type of the case labels when truncating. */
3786 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
3787 tree vr_min = fold_convert (case_label_type, vr->min ());
3788 tree vr_max = fold_convert (case_label_type, vr->max ());
3790 if (vr->kind () == VR_RANGE)
3792 /* If OP's value range is [2,8] and the low label range is
3793 0 ... 3, truncate the label's range to 2 .. 3. */
3794 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
3795 && CASE_HIGH (min_label) != NULL_TREE
3796 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
3797 CASE_LOW (min_label) = vr_min;
3799 /* If OP's value range is [2,8] and the high label range is
3800 7 ... 10, truncate the label's range to 7 .. 8. */
3801 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
3802 && CASE_HIGH (max_label) != NULL_TREE
3803 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
3804 CASE_HIGH (max_label) = vr_max;
3806 else if (vr->kind () == VR_ANTI_RANGE)
3808 tree one_cst = build_one_cst (case_label_type);
3810 if (min_label == max_label)
3812 /* If OP's value range is ~[7,8] and the label's range is
3813 7 ... 10, truncate the label's range to 9 ... 10. */
3814 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
3815 && CASE_HIGH (min_label) != NULL_TREE
3816 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
3817 CASE_LOW (min_label)
3818 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
3820 /* If OP's value range is ~[7,8] and the label's range is
3821 5 ... 8, truncate the label's range to 5 ... 6. */
3822 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
3823 && CASE_HIGH (min_label) != NULL_TREE
3824 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
3825 CASE_HIGH (min_label)
3826 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
3828 else
3830 /* If OP's value range is ~[2,8] and the low label range is
3831 0 ... 3, truncate the label's range to 0 ... 1. */
3832 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
3833 && CASE_HIGH (min_label) != NULL_TREE
3834 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
3835 CASE_HIGH (min_label)
3836 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
3838 /* If OP's value range is ~[2,8] and the high label range is
3839 7 ... 10, truncate the label's range to 9 ... 10. */
3840 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
3841 && CASE_HIGH (max_label) != NULL_TREE
3842 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
3843 CASE_LOW (max_label)
3844 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
3848 /* Canonicalize singleton case ranges. */
3849 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
3850 CASE_HIGH (min_label) = NULL_TREE;
3851 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
3852 CASE_HIGH (max_label) = NULL_TREE;
3855 /* We can also eliminate case labels that lie completely outside OP's value
3856 range. */
3858 /* Bail out if this is just all edges taken. */
3859 if (i == 1
3860 && j == n - 1
3861 && take_default)
3862 return false;
3864 /* Build a new vector of taken case labels. */
3865 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
3866 n2 = 0;
3868 /* Add the default edge, if necessary. */
3869 if (take_default)
3870 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
3872 for (; i <= j; ++i, ++n2)
3873 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
3875 for (; k <= l; ++k, ++n2)
3876 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
3878 /* Mark needed edges. */
3879 for (i = 0; i < n2; ++i)
3881 e = find_edge (gimple_bb (stmt),
3882 label_to_block (cfun,
3883 CASE_LABEL (TREE_VEC_ELT (vec2, i))));
3884 e->aux = (void *)-1;
3887 /* Queue not needed edges for later removal. */
3888 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
3890 if (e->aux == (void *)-1)
3892 e->aux = NULL;
3893 continue;
3896 if (dump_file && (dump_flags & TDF_DETAILS))
3898 fprintf (dump_file, "removing unreachable case label\n");
3900 to_remove_edges.safe_push (e);
3901 set_and_propagate_unexecutable (e);
3902 e->flags &= ~EDGE_EXECUTABLE;
3903 e->flags |= EDGE_IGNORE;
3906 /* And queue an update for the stmt. */
3907 su.stmt = stmt;
3908 su.vec = vec2;
3909 to_update_switch_stmts.safe_push (su);
3910 return true;
3913 void
3914 simplify_using_ranges::cleanup_edges_and_switches (void)
3916 int i;
3917 edge e;
3918 switch_update *su;
3920 /* Clear any edges marked as not executable. */
3921 if (m_not_executable_flag)
3923 FOR_EACH_VEC_ELT (m_flag_set_edges, i, e)
3924 e->flags &= ~m_not_executable_flag;
3926 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
3927 CFG in a broken state and requires a cfg_cleanup run. */
3928 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
3929 remove_edge (e);
3931 /* Update SWITCH_EXPR case label vector. */
3932 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
3934 size_t j;
3935 size_t n = TREE_VEC_LENGTH (su->vec);
3936 tree label;
3937 gimple_switch_set_num_labels (su->stmt, n);
3938 for (j = 0; j < n; j++)
3939 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
3940 /* As we may have replaced the default label with a regular one
3941 make sure to make it a real default label again. This ensures
3942 optimal expansion. */
3943 label = gimple_switch_label (su->stmt, 0);
3944 CASE_LOW (label) = NULL_TREE;
3945 CASE_HIGH (label) = NULL_TREE;
3948 if (!to_remove_edges.is_empty ())
3950 free_dominance_info (CDI_DOMINATORS);
3951 loops_state_set (LOOPS_NEED_FIXUP);
3954 to_remove_edges.release ();
3955 to_update_switch_stmts.release ();
3958 /* Simplify an integral conversion from an SSA name in STMT. */
3960 static bool
3961 simplify_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
3963 tree innerop, middleop, finaltype;
3964 gimple *def_stmt;
3965 signop inner_sgn, middle_sgn, final_sgn;
3966 unsigned inner_prec, middle_prec, final_prec;
3967 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
3969 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
3970 if (!INTEGRAL_TYPE_P (finaltype))
3971 return false;
3972 middleop = gimple_assign_rhs1 (stmt);
3973 def_stmt = SSA_NAME_DEF_STMT (middleop);
3974 if (!is_gimple_assign (def_stmt)
3975 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
3976 return false;
3977 innerop = gimple_assign_rhs1 (def_stmt);
3978 if (TREE_CODE (innerop) != SSA_NAME
3979 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
3980 return false;
3982 /* Get the value-range of the inner operand. Use global ranges in
3983 case innerop was created during substitute-and-fold. */
3984 wide_int imin, imax;
3985 value_range vr;
3986 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop)))
3987 return false;
3988 get_range_query (cfun)->range_of_expr (vr, innerop, stmt);
3989 if (vr.undefined_p () || vr.varying_p ())
3990 return false;
3991 innermin = widest_int::from (vr.lower_bound (), TYPE_SIGN (TREE_TYPE (innerop)));
3992 innermax = widest_int::from (vr.upper_bound (), TYPE_SIGN (TREE_TYPE (innerop)));
3994 /* Simulate the conversion chain to check if the result is equal if
3995 the middle conversion is removed. */
3996 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
3997 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
3998 final_prec = TYPE_PRECISION (finaltype);
4000 /* If the first conversion is not injective, the second must not
4001 be widening. */
4002 if (wi::gtu_p (innermax - innermin,
4003 wi::mask <widest_int> (middle_prec, false))
4004 && middle_prec < final_prec)
4005 return false;
4006 /* We also want a medium value so that we can track the effect that
4007 narrowing conversions with sign change have. */
4008 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
4009 if (inner_sgn == UNSIGNED)
4010 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
4011 else
4012 innermed = 0;
4013 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
4014 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
4015 innermed = innermin;
4017 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
4018 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
4019 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
4020 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
4022 /* Require that the final conversion applied to both the original
4023 and the intermediate range produces the same result. */
4024 final_sgn = TYPE_SIGN (finaltype);
4025 if (wi::ext (middlemin, final_prec, final_sgn)
4026 != wi::ext (innermin, final_prec, final_sgn)
4027 || wi::ext (middlemed, final_prec, final_sgn)
4028 != wi::ext (innermed, final_prec, final_sgn)
4029 || wi::ext (middlemax, final_prec, final_sgn)
4030 != wi::ext (innermax, final_prec, final_sgn))
4031 return false;
4033 gimple_assign_set_rhs1 (stmt, innerop);
4034 fold_stmt (gsi, follow_single_use_edges);
4035 return true;
4038 /* Simplify a conversion from integral SSA name to float in STMT. */
4040 bool
4041 simplify_using_ranges::simplify_float_conversion_using_ranges
4042 (gimple_stmt_iterator *gsi,
4043 gimple *stmt)
4045 tree rhs1 = gimple_assign_rhs1 (stmt);
4046 const value_range *vr = query->get_value_range (rhs1, stmt);
4047 scalar_float_mode fltmode
4048 = SCALAR_FLOAT_TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
4049 scalar_int_mode mode;
4050 tree tem;
4051 gassign *conv;
4053 /* We can only handle constant ranges. */
4054 if (!range_int_cst_p (vr))
4055 return false;
4057 /* First check if we can use a signed type in place of an unsigned. */
4058 scalar_int_mode rhs_mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (rhs1));
4059 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
4060 && can_float_p (fltmode, rhs_mode, 0) != CODE_FOR_nothing
4061 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
4062 mode = rhs_mode;
4063 /* If we can do the conversion in the current input mode do nothing. */
4064 else if (can_float_p (fltmode, rhs_mode,
4065 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
4066 return false;
4067 /* Otherwise search for a mode we can use, starting from the narrowest
4068 integer mode available. */
4069 else
4071 mode = NARROWEST_INT_MODE;
4072 for (;;)
4074 /* If we cannot do a signed conversion to float from mode
4075 or if the value-range does not fit in the signed type
4076 try with a wider mode. */
4077 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
4078 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
4079 break;
4081 /* But do not widen the input. Instead leave that to the
4082 optabs expansion code. */
4083 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
4084 || GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
4085 return false;
4089 /* It works, insert a truncation or sign-change before the
4090 float conversion. */
4091 tem = make_ssa_name (build_nonstandard_integer_type
4092 (GET_MODE_PRECISION (mode), 0));
4093 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
4094 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
4095 gimple_assign_set_rhs1 (stmt, tem);
4096 fold_stmt (gsi, follow_single_use_edges);
4098 return true;
4101 /* Simplify an internal fn call using ranges if possible. */
4103 bool
4104 simplify_using_ranges::simplify_internal_call_using_ranges
4105 (gimple_stmt_iterator *gsi,
4106 gimple *stmt)
4108 enum tree_code subcode;
4109 bool is_ubsan = false;
4110 bool ovf = false;
4111 switch (gimple_call_internal_fn (stmt))
4113 case IFN_UBSAN_CHECK_ADD:
4114 subcode = PLUS_EXPR;
4115 is_ubsan = true;
4116 break;
4117 case IFN_UBSAN_CHECK_SUB:
4118 subcode = MINUS_EXPR;
4119 is_ubsan = true;
4120 break;
4121 case IFN_UBSAN_CHECK_MUL:
4122 subcode = MULT_EXPR;
4123 is_ubsan = true;
4124 break;
4125 case IFN_ADD_OVERFLOW:
4126 subcode = PLUS_EXPR;
4127 break;
4128 case IFN_SUB_OVERFLOW:
4129 subcode = MINUS_EXPR;
4130 break;
4131 case IFN_MUL_OVERFLOW:
4132 subcode = MULT_EXPR;
4133 break;
4134 default:
4135 return false;
4138 tree op0 = gimple_call_arg (stmt, 0);
4139 tree op1 = gimple_call_arg (stmt, 1);
4140 tree type;
4141 if (is_ubsan)
4143 type = TREE_TYPE (op0);
4144 if (VECTOR_TYPE_P (type))
4145 return false;
4147 else if (gimple_call_lhs (stmt) == NULL_TREE)
4148 return false;
4149 else
4150 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
4151 if (!check_for_binary_op_overflow (query, subcode, type, op0, op1, &ovf, stmt)
4152 || (is_ubsan && ovf))
4153 return false;
4155 gimple *g;
4156 location_t loc = gimple_location (stmt);
4157 if (is_ubsan)
4158 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
4159 else
4161 int prec = TYPE_PRECISION (type);
4162 tree utype = type;
4163 if (ovf
4164 || !useless_type_conversion_p (type, TREE_TYPE (op0))
4165 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
4166 utype = build_nonstandard_integer_type (prec, 1);
4167 if (TREE_CODE (op0) == INTEGER_CST)
4168 op0 = fold_convert (utype, op0);
4169 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
4171 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
4172 gimple_set_location (g, loc);
4173 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4174 op0 = gimple_assign_lhs (g);
4176 if (TREE_CODE (op1) == INTEGER_CST)
4177 op1 = fold_convert (utype, op1);
4178 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
4180 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
4181 gimple_set_location (g, loc);
4182 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4183 op1 = gimple_assign_lhs (g);
4185 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
4186 gimple_set_location (g, loc);
4187 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4188 if (utype != type)
4190 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
4191 gimple_assign_lhs (g));
4192 gimple_set_location (g, loc);
4193 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4195 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
4196 gimple_assign_lhs (g),
4197 build_int_cst (type, ovf));
4199 gimple_set_location (g, loc);
4200 gsi_replace (gsi, g, false);
4201 return true;
4204 /* Return true if VAR is a two-valued variable. Set a and b with the
4205 two-values when it is true. Return false otherwise. */
4207 bool
4208 simplify_using_ranges::two_valued_val_range_p (tree var, tree *a, tree *b,
4209 gimple *s)
4211 value_range vr = *query->get_value_range (var, s);
4212 vr.normalize_symbolics ();
4213 if (vr.varying_p () || vr.undefined_p ())
4214 return false;
4216 if ((vr.num_pairs () == 1 && vr.upper_bound () - vr.lower_bound () == 1)
4217 || (vr.num_pairs () == 2
4218 && vr.lower_bound (0) == vr.upper_bound (0)
4219 && vr.lower_bound (1) == vr.upper_bound (1)))
4221 *a = wide_int_to_tree (TREE_TYPE (var), vr.lower_bound ());
4222 *b = wide_int_to_tree (TREE_TYPE (var), vr.upper_bound ());
4223 return true;
4225 return false;
4228 simplify_using_ranges::simplify_using_ranges (range_query *query,
4229 int not_executable_flag)
4230 : query (query)
4232 to_remove_edges = vNULL;
4233 to_update_switch_stmts = vNULL;
4234 m_not_executable_flag = not_executable_flag;
4235 m_flag_set_edges = vNULL;
4238 simplify_using_ranges::~simplify_using_ranges ()
4240 cleanup_edges_and_switches ();
4241 m_flag_set_edges.release ();
4244 /* Simplify STMT using ranges if possible. */
4246 bool
4247 simplify_using_ranges::simplify (gimple_stmt_iterator *gsi)
4249 gcc_checking_assert (query);
4251 gimple *stmt = gsi_stmt (*gsi);
4252 if (is_gimple_assign (stmt))
4254 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
4255 tree rhs1 = gimple_assign_rhs1 (stmt);
4256 tree rhs2 = gimple_assign_rhs2 (stmt);
4257 tree lhs = gimple_assign_lhs (stmt);
4258 tree val1 = NULL_TREE, val2 = NULL_TREE;
4259 use_operand_p use_p;
4260 gimple *use_stmt;
4262 /* Convert:
4263 LHS = CST BINOP VAR
4264 Where VAR is two-valued and LHS is used in GIMPLE_COND only
4266 LHS = VAR == VAL1 ? (CST BINOP VAL1) : (CST BINOP VAL2)
4268 Also handles:
4269 LHS = VAR BINOP CST
4270 Where VAR is two-valued and LHS is used in GIMPLE_COND only
4272 LHS = VAR == VAL1 ? (VAL1 BINOP CST) : (VAL2 BINOP CST) */
4274 if (TREE_CODE_CLASS (rhs_code) == tcc_binary
4275 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
4276 && ((TREE_CODE (rhs1) == INTEGER_CST
4277 && TREE_CODE (rhs2) == SSA_NAME)
4278 || (TREE_CODE (rhs2) == INTEGER_CST
4279 && TREE_CODE (rhs1) == SSA_NAME))
4280 && single_imm_use (lhs, &use_p, &use_stmt)
4281 && gimple_code (use_stmt) == GIMPLE_COND)
4284 tree new_rhs1 = NULL_TREE;
4285 tree new_rhs2 = NULL_TREE;
4286 tree cmp_var = NULL_TREE;
4288 if (TREE_CODE (rhs2) == SSA_NAME
4289 && two_valued_val_range_p (rhs2, &val1, &val2, stmt))
4291 /* Optimize RHS1 OP [VAL1, VAL2]. */
4292 new_rhs1 = int_const_binop (rhs_code, rhs1, val1);
4293 new_rhs2 = int_const_binop (rhs_code, rhs1, val2);
4294 cmp_var = rhs2;
4296 else if (TREE_CODE (rhs1) == SSA_NAME
4297 && two_valued_val_range_p (rhs1, &val1, &val2, stmt))
4299 /* Optimize [VAL1, VAL2] OP RHS2. */
4300 new_rhs1 = int_const_binop (rhs_code, val1, rhs2);
4301 new_rhs2 = int_const_binop (rhs_code, val2, rhs2);
4302 cmp_var = rhs1;
4305 /* If we could not find two-vals or the optimzation is invalid as
4306 in divide by zero, new_rhs1 / new_rhs will be NULL_TREE. */
4307 if (new_rhs1 && new_rhs2)
4309 tree cond = gimple_build (gsi, true, GSI_SAME_STMT,
4310 UNKNOWN_LOCATION,
4311 EQ_EXPR, boolean_type_node,
4312 cmp_var, val1);
4313 gimple_assign_set_rhs_with_ops (gsi,
4314 COND_EXPR, cond,
4315 new_rhs1,
4316 new_rhs2);
4317 update_stmt (gsi_stmt (*gsi));
4318 fold_stmt (gsi, follow_single_use_edges);
4319 return true;
4323 switch (rhs_code)
4325 case EQ_EXPR:
4326 case NE_EXPR:
4327 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
4328 if the RHS is zero or one, and the LHS are known to be boolean
4329 values. */
4330 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4331 return simplify_truth_ops_using_ranges (gsi, stmt);
4332 break;
4334 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
4335 and BIT_AND_EXPR respectively if the first operand is greater
4336 than zero and the second operand is an exact power of two.
4337 Also optimize TRUNC_MOD_EXPR away if the second operand is
4338 constant and the first operand already has the right value
4339 range. */
4340 case TRUNC_DIV_EXPR:
4341 case TRUNC_MOD_EXPR:
4342 if ((TREE_CODE (rhs1) == SSA_NAME
4343 || TREE_CODE (rhs1) == INTEGER_CST)
4344 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4345 return simplify_div_or_mod_using_ranges (gsi, stmt);
4346 break;
4348 /* Transform ABS (X) into X or -X as appropriate. */
4349 case ABS_EXPR:
4350 if (TREE_CODE (rhs1) == SSA_NAME
4351 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4352 return simplify_abs_using_ranges (gsi, stmt);
4353 break;
4355 case BIT_AND_EXPR:
4356 case BIT_IOR_EXPR:
4357 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
4358 if all the bits being cleared are already cleared or
4359 all the bits being set are already set. */
4360 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4361 return simplify_bit_ops_using_ranges (gsi, stmt);
4362 break;
4364 CASE_CONVERT:
4365 if (TREE_CODE (rhs1) == SSA_NAME
4366 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4367 return simplify_conversion_using_ranges (gsi, stmt);
4368 break;
4370 case FLOAT_EXPR:
4371 if (TREE_CODE (rhs1) == SSA_NAME
4372 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4373 return simplify_float_conversion_using_ranges (gsi, stmt);
4374 break;
4376 case MIN_EXPR:
4377 case MAX_EXPR:
4378 return simplify_min_or_max_using_ranges (gsi, stmt);
4380 case RSHIFT_EXPR:
4382 tree op0 = gimple_assign_rhs1 (stmt);
4383 tree type = TREE_TYPE (op0);
4384 int_range_max range;
4385 if (TYPE_SIGN (type) == SIGNED
4386 && query->range_of_expr (range, op0, stmt))
4388 unsigned prec = TYPE_PRECISION (TREE_TYPE (op0));
4389 int_range<2> nzm1 (type, wi::minus_one (prec), wi::zero (prec),
4390 VR_ANTI_RANGE);
4391 range.intersect (nzm1);
4392 // If there are no ranges other than [-1, 0] remove the shift.
4393 if (range.undefined_p ())
4395 gimple_assign_set_rhs_from_tree (gsi, op0);
4396 return true;
4398 return false;
4400 break;
4402 default:
4403 break;
4406 else if (gimple_code (stmt) == GIMPLE_COND)
4407 return simplify_cond_using_ranges_1 (as_a <gcond *> (stmt));
4408 else if (gimple_code (stmt) == GIMPLE_SWITCH)
4409 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
4410 else if (is_gimple_call (stmt)
4411 && gimple_call_internal_p (stmt))
4412 return simplify_internal_call_using_ranges (gsi, stmt);
4414 return false;
4417 /* Set the lattice entry for VAR to VR. */
4419 void
4420 vr_values::set_vr_value (tree var, value_range_equiv *vr)
4422 if (SSA_NAME_VERSION (var) >= num_vr_values)
4423 return;
4424 vr_value[SSA_NAME_VERSION (var)] = vr;
4427 /* Swap the lattice entry for VAR with VR and return the old entry. */
4429 value_range_equiv *
4430 vr_values::swap_vr_value (tree var, value_range_equiv *vr)
4432 if (SSA_NAME_VERSION (var) >= num_vr_values)
4433 return NULL;
4434 std::swap (vr_value[SSA_NAME_VERSION (var)], vr);
4435 return vr;