Daily bump.
[official-gcc.git] / gcc / tree-vrp.c
blob5380508a9ec316f399b307c719484d122411a0c2
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2021 Free Software Foundation, Inc.
3 Contributed by Diego Novillo <dnovillo@redhat.com>.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "basic-block.h"
25 #include "bitmap.h"
26 #include "sbitmap.h"
27 #include "options.h"
28 #include "dominance.h"
29 #include "function.h"
30 #include "cfg.h"
31 #include "tree.h"
32 #include "gimple.h"
33 #include "tree-pass.h"
34 #include "ssa.h"
35 #include "gimple-pretty-print.h"
36 #include "fold-const.h"
37 #include "cfganal.h"
38 #include "gimple-iterator.h"
39 #include "tree-cfg.h"
40 #include "tree-ssa-loop-manip.h"
41 #include "tree-ssa-loop-niter.h"
42 #include "tree-into-ssa.h"
43 #include "cfgloop.h"
44 #include "tree-scalar-evolution.h"
45 #include "tree-ssa-propagate.h"
46 #include "tree-ssa-threadedge.h"
47 #include "domwalk.h"
48 #include "vr-values.h"
49 #include "gimple-array-bounds.h"
50 #include "gimple-range.h"
51 #include "gimple-range-path.h"
52 #include "value-pointer-equiv.h"
53 #include "gimple-fold.h"
55 /* Set of SSA names found live during the RPO traversal of the function
56 for still active basic-blocks. */
57 class live_names
59 public:
60 live_names ();
61 ~live_names ();
62 void set (tree, basic_block);
63 void clear (tree, basic_block);
64 void merge (basic_block dest, basic_block src);
65 bool live_on_block_p (tree, basic_block);
66 bool live_on_edge_p (tree, edge);
67 bool block_has_live_names_p (basic_block);
68 void clear_block (basic_block);
70 private:
71 sbitmap *live;
72 unsigned num_blocks;
73 void init_bitmap_if_needed (basic_block);
76 void
77 live_names::init_bitmap_if_needed (basic_block bb)
79 unsigned i = bb->index;
80 if (!live[i])
82 live[i] = sbitmap_alloc (num_ssa_names);
83 bitmap_clear (live[i]);
87 bool
88 live_names::block_has_live_names_p (basic_block bb)
90 unsigned i = bb->index;
91 return live[i] && bitmap_empty_p (live[i]);
94 void
95 live_names::clear_block (basic_block bb)
97 unsigned i = bb->index;
98 if (live[i])
100 sbitmap_free (live[i]);
101 live[i] = NULL;
105 void
106 live_names::merge (basic_block dest, basic_block src)
108 init_bitmap_if_needed (dest);
109 init_bitmap_if_needed (src);
110 bitmap_ior (live[dest->index], live[dest->index], live[src->index]);
113 void
114 live_names::set (tree name, basic_block bb)
116 init_bitmap_if_needed (bb);
117 bitmap_set_bit (live[bb->index], SSA_NAME_VERSION (name));
120 void
121 live_names::clear (tree name, basic_block bb)
123 unsigned i = bb->index;
124 if (live[i])
125 bitmap_clear_bit (live[i], SSA_NAME_VERSION (name));
128 live_names::live_names ()
130 num_blocks = last_basic_block_for_fn (cfun);
131 live = XCNEWVEC (sbitmap, num_blocks);
134 live_names::~live_names ()
136 for (unsigned i = 0; i < num_blocks; ++i)
137 if (live[i])
138 sbitmap_free (live[i]);
139 XDELETEVEC (live);
142 bool
143 live_names::live_on_block_p (tree name, basic_block bb)
145 return (live[bb->index]
146 && bitmap_bit_p (live[bb->index], SSA_NAME_VERSION (name)));
149 /* Return true if the SSA name NAME is live on the edge E. */
151 bool
152 live_names::live_on_edge_p (tree name, edge e)
154 return live_on_block_p (name, e->dest);
158 /* VR_TYPE describes a range with mininum value *MIN and maximum
159 value *MAX. Restrict the range to the set of values that have
160 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
161 return the new range type.
163 SGN gives the sign of the values described by the range. */
165 enum value_range_kind
166 intersect_range_with_nonzero_bits (enum value_range_kind vr_type,
167 wide_int *min, wide_int *max,
168 const wide_int &nonzero_bits,
169 signop sgn)
171 if (vr_type == VR_ANTI_RANGE)
173 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
174 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
175 to create an inclusive upper bound for A and an inclusive lower
176 bound for B. */
177 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
178 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
180 /* If the calculation of A_MAX wrapped, A is effectively empty
181 and A_MAX is the highest value that satisfies NONZERO_BITS.
182 Likewise if the calculation of B_MIN wrapped, B is effectively
183 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
184 bool a_empty = wi::ge_p (a_max, *min, sgn);
185 bool b_empty = wi::le_p (b_min, *max, sgn);
187 /* If both A and B are empty, there are no valid values. */
188 if (a_empty && b_empty)
189 return VR_UNDEFINED;
191 /* If exactly one of A or B is empty, return a VR_RANGE for the
192 other one. */
193 if (a_empty || b_empty)
195 *min = b_min;
196 *max = a_max;
197 gcc_checking_assert (wi::le_p (*min, *max, sgn));
198 return VR_RANGE;
201 /* Update the VR_ANTI_RANGE bounds. */
202 *min = a_max + 1;
203 *max = b_min - 1;
204 gcc_checking_assert (wi::le_p (*min, *max, sgn));
206 /* Now check whether the excluded range includes any values that
207 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
208 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
210 unsigned int precision = min->get_precision ();
211 *min = wi::min_value (precision, sgn);
212 *max = wi::max_value (precision, sgn);
213 vr_type = VR_RANGE;
216 if (vr_type == VR_RANGE || vr_type == VR_VARYING)
218 *max = wi::round_down_for_mask (*max, nonzero_bits);
220 /* Check that the range contains at least one valid value. */
221 if (wi::gt_p (*min, *max, sgn))
222 return VR_UNDEFINED;
224 *min = wi::round_up_for_mask (*min, nonzero_bits);
225 gcc_checking_assert (wi::le_p (*min, *max, sgn));
227 return vr_type;
230 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
231 a singleton. */
233 bool
234 range_int_cst_p (const value_range *vr)
236 return (vr->kind () == VR_RANGE && range_has_numeric_bounds_p (vr));
239 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
240 otherwise. We only handle additive operations and set NEG to true if the
241 symbol is negated and INV to the invariant part, if any. */
243 tree
244 get_single_symbol (tree t, bool *neg, tree *inv)
246 bool neg_;
247 tree inv_;
249 *inv = NULL_TREE;
250 *neg = false;
252 if (TREE_CODE (t) == PLUS_EXPR
253 || TREE_CODE (t) == POINTER_PLUS_EXPR
254 || TREE_CODE (t) == MINUS_EXPR)
256 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
258 neg_ = (TREE_CODE (t) == MINUS_EXPR);
259 inv_ = TREE_OPERAND (t, 0);
260 t = TREE_OPERAND (t, 1);
262 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
264 neg_ = false;
265 inv_ = TREE_OPERAND (t, 1);
266 t = TREE_OPERAND (t, 0);
268 else
269 return NULL_TREE;
271 else
273 neg_ = false;
274 inv_ = NULL_TREE;
277 if (TREE_CODE (t) == NEGATE_EXPR)
279 t = TREE_OPERAND (t, 0);
280 neg_ = !neg_;
283 if (TREE_CODE (t) != SSA_NAME)
284 return NULL_TREE;
286 if (inv_ && TREE_OVERFLOW_P (inv_))
287 inv_ = drop_tree_overflow (inv_);
289 *neg = neg_;
290 *inv = inv_;
291 return t;
294 /* The reverse operation: build a symbolic expression with TYPE
295 from symbol SYM, negated according to NEG, and invariant INV. */
297 static tree
298 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
300 const bool pointer_p = POINTER_TYPE_P (type);
301 tree t = sym;
303 if (neg)
304 t = build1 (NEGATE_EXPR, type, t);
306 if (integer_zerop (inv))
307 return t;
309 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
312 /* Return
313 1 if VAL < VAL2
314 0 if !(VAL < VAL2)
315 -2 if those are incomparable. */
317 operand_less_p (tree val, tree val2)
319 /* LT is folded faster than GE and others. Inline the common case. */
320 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
321 return tree_int_cst_lt (val, val2);
322 else if (TREE_CODE (val) == SSA_NAME && TREE_CODE (val2) == SSA_NAME)
323 return val == val2 ? 0 : -2;
324 else
326 int cmp = compare_values (val, val2);
327 if (cmp == -1)
328 return 1;
329 else if (cmp == 0 || cmp == 1)
330 return 0;
331 else
332 return -2;
335 return 0;
338 /* Compare two values VAL1 and VAL2. Return
340 -2 if VAL1 and VAL2 cannot be compared at compile-time,
341 -1 if VAL1 < VAL2,
342 0 if VAL1 == VAL2,
343 +1 if VAL1 > VAL2, and
344 +2 if VAL1 != VAL2
346 This is similar to tree_int_cst_compare but supports pointer values
347 and values that cannot be compared at compile time.
349 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
350 true if the return value is only valid if we assume that signed
351 overflow is undefined. */
354 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
356 if (val1 == val2)
357 return 0;
359 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
360 both integers. */
361 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
362 == POINTER_TYPE_P (TREE_TYPE (val2)));
364 /* Convert the two values into the same type. This is needed because
365 sizetype causes sign extension even for unsigned types. */
366 if (!useless_type_conversion_p (TREE_TYPE (val1), TREE_TYPE (val2)))
367 val2 = fold_convert (TREE_TYPE (val1), val2);
369 const bool overflow_undefined
370 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
371 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
372 tree inv1, inv2;
373 bool neg1, neg2;
374 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
375 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
377 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
378 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
379 if (sym1 && sym2)
381 /* Both values must use the same name with the same sign. */
382 if (sym1 != sym2 || neg1 != neg2)
383 return -2;
385 /* [-]NAME + CST == [-]NAME + CST. */
386 if (inv1 == inv2)
387 return 0;
389 /* If overflow is defined we cannot simplify more. */
390 if (!overflow_undefined)
391 return -2;
393 if (strict_overflow_p != NULL
394 /* Symbolic range building sets the no-warning bit to declare
395 that overflow doesn't happen. */
396 && (!inv1 || !warning_suppressed_p (val1, OPT_Woverflow))
397 && (!inv2 || !warning_suppressed_p (val2, OPT_Woverflow)))
398 *strict_overflow_p = true;
400 if (!inv1)
401 inv1 = build_int_cst (TREE_TYPE (val1), 0);
402 if (!inv2)
403 inv2 = build_int_cst (TREE_TYPE (val2), 0);
405 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
406 TYPE_SIGN (TREE_TYPE (val1)));
409 const bool cst1 = is_gimple_min_invariant (val1);
410 const bool cst2 = is_gimple_min_invariant (val2);
412 /* If one is of the form '[-]NAME + CST' and the other is constant, then
413 it might be possible to say something depending on the constants. */
414 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
416 if (!overflow_undefined)
417 return -2;
419 if (strict_overflow_p != NULL
420 /* Symbolic range building sets the no-warning bit to declare
421 that overflow doesn't happen. */
422 && (!sym1 || !warning_suppressed_p (val1, OPT_Woverflow))
423 && (!sym2 || !warning_suppressed_p (val2, OPT_Woverflow)))
424 *strict_overflow_p = true;
426 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
427 tree cst = cst1 ? val1 : val2;
428 tree inv = cst1 ? inv2 : inv1;
430 /* Compute the difference between the constants. If it overflows or
431 underflows, this means that we can trivially compare the NAME with
432 it and, consequently, the two values with each other. */
433 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
434 if (wi::cmp (0, wi::to_wide (inv), sgn)
435 != wi::cmp (diff, wi::to_wide (cst), sgn))
437 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
438 return cst1 ? res : -res;
441 return -2;
444 /* We cannot say anything more for non-constants. */
445 if (!cst1 || !cst2)
446 return -2;
448 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
450 /* We cannot compare overflowed values. */
451 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
452 return -2;
454 if (TREE_CODE (val1) == INTEGER_CST
455 && TREE_CODE (val2) == INTEGER_CST)
456 return tree_int_cst_compare (val1, val2);
458 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
460 if (known_eq (wi::to_poly_widest (val1),
461 wi::to_poly_widest (val2)))
462 return 0;
463 if (known_lt (wi::to_poly_widest (val1),
464 wi::to_poly_widest (val2)))
465 return -1;
466 if (known_gt (wi::to_poly_widest (val1),
467 wi::to_poly_widest (val2)))
468 return 1;
471 return -2;
473 else
475 if (TREE_CODE (val1) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
477 /* We cannot compare overflowed values. */
478 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
479 return -2;
481 return tree_int_cst_compare (val1, val2);
484 /* First see if VAL1 and VAL2 are not the same. */
485 if (operand_equal_p (val1, val2, 0))
486 return 0;
488 fold_defer_overflow_warnings ();
490 /* If VAL1 is a lower address than VAL2, return -1. */
491 tree t = fold_binary_to_constant (LT_EXPR, boolean_type_node, val1, val2);
492 if (t && integer_onep (t))
494 fold_undefer_and_ignore_overflow_warnings ();
495 return -1;
498 /* If VAL1 is a higher address than VAL2, return +1. */
499 t = fold_binary_to_constant (LT_EXPR, boolean_type_node, val2, val1);
500 if (t && integer_onep (t))
502 fold_undefer_and_ignore_overflow_warnings ();
503 return 1;
506 /* If VAL1 is different than VAL2, return +2. */
507 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
508 fold_undefer_and_ignore_overflow_warnings ();
509 if (t && integer_onep (t))
510 return 2;
512 return -2;
516 /* Compare values like compare_values_warnv. */
519 compare_values (tree val1, tree val2)
521 bool sop;
522 return compare_values_warnv (val1, val2, &sop);
525 /* If BOUND will include a symbolic bound, adjust it accordingly,
526 otherwise leave it as is.
528 CODE is the original operation that combined the bounds (PLUS_EXPR
529 or MINUS_EXPR).
531 TYPE is the type of the original operation.
533 SYM_OPn is the symbolic for OPn if it has a symbolic.
535 NEG_OPn is TRUE if the OPn was negated. */
537 static void
538 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
539 tree sym_op0, tree sym_op1,
540 bool neg_op0, bool neg_op1)
542 bool minus_p = (code == MINUS_EXPR);
543 /* If the result bound is constant, we're done; otherwise, build the
544 symbolic lower bound. */
545 if (sym_op0 == sym_op1)
547 else if (sym_op0)
548 bound = build_symbolic_expr (type, sym_op0,
549 neg_op0, bound);
550 else if (sym_op1)
552 /* We may not negate if that might introduce
553 undefined overflow. */
554 if (!minus_p
555 || neg_op1
556 || TYPE_OVERFLOW_WRAPS (type))
557 bound = build_symbolic_expr (type, sym_op1,
558 neg_op1 ^ minus_p, bound);
559 else
560 bound = NULL_TREE;
564 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
565 int bound according to CODE. CODE is the operation combining the
566 bound (either a PLUS_EXPR or a MINUS_EXPR).
568 TYPE is the type of the combine operation.
570 WI is the wide int to store the result.
572 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
573 if over/underflow occurred. */
575 static void
576 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
577 tree type, tree op0, tree op1)
579 bool minus_p = (code == MINUS_EXPR);
580 const signop sgn = TYPE_SIGN (type);
581 const unsigned int prec = TYPE_PRECISION (type);
583 /* Combine the bounds, if any. */
584 if (op0 && op1)
586 if (minus_p)
587 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
588 else
589 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
591 else if (op0)
592 wi = wi::to_wide (op0);
593 else if (op1)
595 if (minus_p)
596 wi = wi::neg (wi::to_wide (op1), &ovf);
597 else
598 wi = wi::to_wide (op1);
600 else
601 wi = wi::shwi (0, prec);
604 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
605 put the result in VR.
607 TYPE is the type of the range.
609 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
610 occurred while originally calculating WMIN or WMAX. -1 indicates
611 underflow. +1 indicates overflow. 0 indicates neither. */
613 static void
614 set_value_range_with_overflow (value_range_kind &kind, tree &min, tree &max,
615 tree type,
616 const wide_int &wmin, const wide_int &wmax,
617 wi::overflow_type min_ovf,
618 wi::overflow_type max_ovf)
620 const signop sgn = TYPE_SIGN (type);
621 const unsigned int prec = TYPE_PRECISION (type);
623 /* For one bit precision if max < min, then the swapped
624 range covers all values. */
625 if (prec == 1 && wi::lt_p (wmax, wmin, sgn))
627 kind = VR_VARYING;
628 return;
631 if (TYPE_OVERFLOW_WRAPS (type))
633 /* If overflow wraps, truncate the values and adjust the
634 range kind and bounds appropriately. */
635 wide_int tmin = wide_int::from (wmin, prec, sgn);
636 wide_int tmax = wide_int::from (wmax, prec, sgn);
637 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
639 /* If the limits are swapped, we wrapped around and cover
640 the entire range. */
641 if (wi::gt_p (tmin, tmax, sgn))
642 kind = VR_VARYING;
643 else
645 kind = VR_RANGE;
646 /* No overflow or both overflow or underflow. The
647 range kind stays VR_RANGE. */
648 min = wide_int_to_tree (type, tmin);
649 max = wide_int_to_tree (type, tmax);
651 return;
653 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
654 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
656 /* Min underflow or max overflow. The range kind
657 changes to VR_ANTI_RANGE. */
658 bool covers = false;
659 wide_int tem = tmin;
660 tmin = tmax + 1;
661 if (wi::cmp (tmin, tmax, sgn) < 0)
662 covers = true;
663 tmax = tem - 1;
664 if (wi::cmp (tmax, tem, sgn) > 0)
665 covers = true;
666 /* If the anti-range would cover nothing, drop to varying.
667 Likewise if the anti-range bounds are outside of the
668 types values. */
669 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
671 kind = VR_VARYING;
672 return;
674 kind = VR_ANTI_RANGE;
675 min = wide_int_to_tree (type, tmin);
676 max = wide_int_to_tree (type, tmax);
677 return;
679 else
681 /* Other underflow and/or overflow, drop to VR_VARYING. */
682 kind = VR_VARYING;
683 return;
686 else
688 /* If overflow does not wrap, saturate to the types min/max
689 value. */
690 wide_int type_min = wi::min_value (prec, sgn);
691 wide_int type_max = wi::max_value (prec, sgn);
692 kind = VR_RANGE;
693 if (min_ovf == wi::OVF_UNDERFLOW)
694 min = wide_int_to_tree (type, type_min);
695 else if (min_ovf == wi::OVF_OVERFLOW)
696 min = wide_int_to_tree (type, type_max);
697 else
698 min = wide_int_to_tree (type, wmin);
700 if (max_ovf == wi::OVF_UNDERFLOW)
701 max = wide_int_to_tree (type, type_min);
702 else if (max_ovf == wi::OVF_OVERFLOW)
703 max = wide_int_to_tree (type, type_max);
704 else
705 max = wide_int_to_tree (type, wmax);
709 /* Fold two value range's of a POINTER_PLUS_EXPR into VR. */
711 static void
712 extract_range_from_pointer_plus_expr (value_range *vr,
713 enum tree_code code,
714 tree expr_type,
715 const value_range *vr0,
716 const value_range *vr1)
718 gcc_checking_assert (POINTER_TYPE_P (expr_type)
719 && code == POINTER_PLUS_EXPR);
720 /* For pointer types, we are really only interested in asserting
721 whether the expression evaluates to non-NULL.
722 With -fno-delete-null-pointer-checks we need to be more
723 conservative. As some object might reside at address 0,
724 then some offset could be added to it and the same offset
725 subtracted again and the result would be NULL.
726 E.g.
727 static int a[12]; where &a[0] is NULL and
728 ptr = &a[6];
729 ptr -= 6;
730 ptr will be NULL here, even when there is POINTER_PLUS_EXPR
731 where the first range doesn't include zero and the second one
732 doesn't either. As the second operand is sizetype (unsigned),
733 consider all ranges where the MSB could be set as possible
734 subtractions where the result might be NULL. */
735 if ((!range_includes_zero_p (vr0)
736 || !range_includes_zero_p (vr1))
737 && !TYPE_OVERFLOW_WRAPS (expr_type)
738 && (flag_delete_null_pointer_checks
739 || (range_int_cst_p (vr1)
740 && !tree_int_cst_sign_bit (vr1->max ()))))
741 vr->set_nonzero (expr_type);
742 else if (vr0->zero_p () && vr1->zero_p ())
743 vr->set_zero (expr_type);
744 else
745 vr->set_varying (expr_type);
748 /* Extract range information from a PLUS/MINUS_EXPR and store the
749 result in *VR. */
751 static void
752 extract_range_from_plus_minus_expr (value_range *vr,
753 enum tree_code code,
754 tree expr_type,
755 const value_range *vr0_,
756 const value_range *vr1_)
758 gcc_checking_assert (code == PLUS_EXPR || code == MINUS_EXPR);
760 value_range vr0 = *vr0_, vr1 = *vr1_;
761 value_range vrtem0, vrtem1;
763 /* Now canonicalize anti-ranges to ranges when they are not symbolic
764 and express ~[] op X as ([]' op X) U ([]'' op X). */
765 if (vr0.kind () == VR_ANTI_RANGE
766 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
768 extract_range_from_plus_minus_expr (vr, code, expr_type, &vrtem0, vr1_);
769 if (!vrtem1.undefined_p ())
771 value_range vrres;
772 extract_range_from_plus_minus_expr (&vrres, code, expr_type,
773 &vrtem1, vr1_);
774 vr->union_ (&vrres);
776 return;
778 /* Likewise for X op ~[]. */
779 if (vr1.kind () == VR_ANTI_RANGE
780 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
782 extract_range_from_plus_minus_expr (vr, code, expr_type, vr0_, &vrtem0);
783 if (!vrtem1.undefined_p ())
785 value_range vrres;
786 extract_range_from_plus_minus_expr (&vrres, code, expr_type,
787 vr0_, &vrtem1);
788 vr->union_ (&vrres);
790 return;
793 value_range_kind kind;
794 value_range_kind vr0_kind = vr0.kind (), vr1_kind = vr1.kind ();
795 tree vr0_min = vr0.min (), vr0_max = vr0.max ();
796 tree vr1_min = vr1.min (), vr1_max = vr1.max ();
797 tree min = NULL_TREE, max = NULL_TREE;
799 /* This will normalize things such that calculating
800 [0,0] - VR_VARYING is not dropped to varying, but is
801 calculated as [MIN+1, MAX]. */
802 if (vr0.varying_p ())
804 vr0_kind = VR_RANGE;
805 vr0_min = vrp_val_min (expr_type);
806 vr0_max = vrp_val_max (expr_type);
808 if (vr1.varying_p ())
810 vr1_kind = VR_RANGE;
811 vr1_min = vrp_val_min (expr_type);
812 vr1_max = vrp_val_max (expr_type);
815 const bool minus_p = (code == MINUS_EXPR);
816 tree min_op0 = vr0_min;
817 tree min_op1 = minus_p ? vr1_max : vr1_min;
818 tree max_op0 = vr0_max;
819 tree max_op1 = minus_p ? vr1_min : vr1_max;
820 tree sym_min_op0 = NULL_TREE;
821 tree sym_min_op1 = NULL_TREE;
822 tree sym_max_op0 = NULL_TREE;
823 tree sym_max_op1 = NULL_TREE;
824 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
826 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
828 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
829 single-symbolic ranges, try to compute the precise resulting range,
830 but only if we know that this resulting range will also be constant
831 or single-symbolic. */
832 if (vr0_kind == VR_RANGE && vr1_kind == VR_RANGE
833 && (TREE_CODE (min_op0) == INTEGER_CST
834 || (sym_min_op0
835 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
836 && (TREE_CODE (min_op1) == INTEGER_CST
837 || (sym_min_op1
838 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
839 && (!(sym_min_op0 && sym_min_op1)
840 || (sym_min_op0 == sym_min_op1
841 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
842 && (TREE_CODE (max_op0) == INTEGER_CST
843 || (sym_max_op0
844 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
845 && (TREE_CODE (max_op1) == INTEGER_CST
846 || (sym_max_op1
847 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
848 && (!(sym_max_op0 && sym_max_op1)
849 || (sym_max_op0 == sym_max_op1
850 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
852 wide_int wmin, wmax;
853 wi::overflow_type min_ovf = wi::OVF_NONE;
854 wi::overflow_type max_ovf = wi::OVF_NONE;
856 /* Build the bounds. */
857 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
858 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
860 /* If the resulting range will be symbolic, we need to eliminate any
861 explicit or implicit overflow introduced in the above computation
862 because compare_values could make an incorrect use of it. That's
863 why we require one of the ranges to be a singleton. */
864 if ((sym_min_op0 != sym_min_op1 || sym_max_op0 != sym_max_op1)
865 && ((bool)min_ovf || (bool)max_ovf
866 || (min_op0 != max_op0 && min_op1 != max_op1)))
868 vr->set_varying (expr_type);
869 return;
872 /* Adjust the range for possible overflow. */
873 set_value_range_with_overflow (kind, min, max, expr_type,
874 wmin, wmax, min_ovf, max_ovf);
875 if (kind == VR_VARYING)
877 vr->set_varying (expr_type);
878 return;
881 /* Build the symbolic bounds if needed. */
882 adjust_symbolic_bound (min, code, expr_type,
883 sym_min_op0, sym_min_op1,
884 neg_min_op0, neg_min_op1);
885 adjust_symbolic_bound (max, code, expr_type,
886 sym_max_op0, sym_max_op1,
887 neg_max_op0, neg_max_op1);
889 else
891 /* For other cases, for example if we have a PLUS_EXPR with two
892 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
893 to compute a precise range for such a case.
894 ??? General even mixed range kind operations can be expressed
895 by for example transforming ~[3, 5] + [1, 2] to range-only
896 operations and a union primitive:
897 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
898 [-INF+1, 4] U [6, +INF(OVF)]
899 though usually the union is not exactly representable with
900 a single range or anti-range as the above is
901 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
902 but one could use a scheme similar to equivalences for this. */
903 vr->set_varying (expr_type);
904 return;
907 /* If either MIN or MAX overflowed, then set the resulting range to
908 VARYING. */
909 if (min == NULL_TREE
910 || TREE_OVERFLOW_P (min)
911 || max == NULL_TREE
912 || TREE_OVERFLOW_P (max))
914 vr->set_varying (expr_type);
915 return;
918 int cmp = compare_values (min, max);
919 if (cmp == -2 || cmp == 1)
921 /* If the new range has its limits swapped around (MIN > MAX),
922 then the operation caused one of them to wrap around, mark
923 the new range VARYING. */
924 vr->set_varying (expr_type);
926 else
927 vr->set (min, max, kind);
930 /* Return the range-ops handler for CODE and EXPR_TYPE. If no
931 suitable operator is found, return NULL and set VR to VARYING. */
933 static const range_operator *
934 get_range_op_handler (value_range *vr,
935 enum tree_code code,
936 tree expr_type)
938 const range_operator *op = range_op_handler (code, expr_type);
939 if (!op)
940 vr->set_varying (expr_type);
941 return op;
944 /* If the types passed are supported, return TRUE, otherwise set VR to
945 VARYING and return FALSE. */
947 static bool
948 supported_types_p (value_range *vr,
949 tree type0,
950 tree type1 = NULL)
952 if (!value_range::supports_type_p (type0)
953 || (type1 && !value_range::supports_type_p (type1)))
955 vr->set_varying (type0);
956 return false;
958 return true;
961 /* If any of the ranges passed are defined, return TRUE, otherwise set
962 VR to UNDEFINED and return FALSE. */
964 static bool
965 defined_ranges_p (value_range *vr,
966 const value_range *vr0, const value_range *vr1 = NULL)
968 if (vr0->undefined_p () && (!vr1 || vr1->undefined_p ()))
970 vr->set_undefined ();
971 return false;
973 return true;
976 static value_range
977 drop_undefines_to_varying (const value_range *vr, tree expr_type)
979 if (vr->undefined_p ())
980 return value_range (expr_type);
981 else
982 return *vr;
985 /* If any operand is symbolic, perform a binary operation on them and
986 return TRUE, otherwise return FALSE. */
988 static bool
989 range_fold_binary_symbolics_p (value_range *vr,
990 tree_code code,
991 tree expr_type,
992 const value_range *vr0_,
993 const value_range *vr1_)
995 if (vr0_->symbolic_p () || vr1_->symbolic_p ())
997 value_range vr0 = drop_undefines_to_varying (vr0_, expr_type);
998 value_range vr1 = drop_undefines_to_varying (vr1_, expr_type);
999 if ((code == PLUS_EXPR || code == MINUS_EXPR))
1001 extract_range_from_plus_minus_expr (vr, code, expr_type,
1002 &vr0, &vr1);
1003 return true;
1005 if (POINTER_TYPE_P (expr_type) && code == POINTER_PLUS_EXPR)
1007 extract_range_from_pointer_plus_expr (vr, code, expr_type,
1008 &vr0, &vr1);
1009 return true;
1011 const range_operator *op = get_range_op_handler (vr, code, expr_type);
1012 vr0.normalize_symbolics ();
1013 vr1.normalize_symbolics ();
1014 return op->fold_range (*vr, expr_type, vr0, vr1);
1016 return false;
1019 /* If operand is symbolic, perform a unary operation on it and return
1020 TRUE, otherwise return FALSE. */
1022 static bool
1023 range_fold_unary_symbolics_p (value_range *vr,
1024 tree_code code,
1025 tree expr_type,
1026 const value_range *vr0)
1028 if (vr0->symbolic_p ())
1030 if (code == NEGATE_EXPR)
1032 /* -X is simply 0 - X. */
1033 value_range zero;
1034 zero.set_zero (vr0->type ());
1035 range_fold_binary_expr (vr, MINUS_EXPR, expr_type, &zero, vr0);
1036 return true;
1038 if (code == BIT_NOT_EXPR)
1040 /* ~X is simply -1 - X. */
1041 value_range minusone;
1042 minusone.set (build_int_cst (vr0->type (), -1));
1043 range_fold_binary_expr (vr, MINUS_EXPR, expr_type, &minusone, vr0);
1044 return true;
1046 const range_operator *op = get_range_op_handler (vr, code, expr_type);
1047 value_range vr0_cst (*vr0);
1048 vr0_cst.normalize_symbolics ();
1049 return op->fold_range (*vr, expr_type, vr0_cst, value_range (expr_type));
1051 return false;
1054 /* Perform a binary operation on a pair of ranges. */
1056 void
1057 range_fold_binary_expr (value_range *vr,
1058 enum tree_code code,
1059 tree expr_type,
1060 const value_range *vr0_,
1061 const value_range *vr1_)
1063 if (!supported_types_p (vr, expr_type)
1064 || !defined_ranges_p (vr, vr0_, vr1_))
1065 return;
1066 const range_operator *op = get_range_op_handler (vr, code, expr_type);
1067 if (!op)
1068 return;
1070 if (range_fold_binary_symbolics_p (vr, code, expr_type, vr0_, vr1_))
1071 return;
1073 value_range vr0 (*vr0_);
1074 value_range vr1 (*vr1_);
1075 if (vr0.undefined_p ())
1076 vr0.set_varying (expr_type);
1077 if (vr1.undefined_p ())
1078 vr1.set_varying (expr_type);
1079 vr0.normalize_addresses ();
1080 vr1.normalize_addresses ();
1081 op->fold_range (*vr, expr_type, vr0, vr1);
1084 /* Perform a unary operation on a range. */
1086 void
1087 range_fold_unary_expr (value_range *vr,
1088 enum tree_code code, tree expr_type,
1089 const value_range *vr0,
1090 tree vr0_type)
1092 if (!supported_types_p (vr, expr_type, vr0_type)
1093 || !defined_ranges_p (vr, vr0))
1094 return;
1095 const range_operator *op = get_range_op_handler (vr, code, expr_type);
1096 if (!op)
1097 return;
1099 if (range_fold_unary_symbolics_p (vr, code, expr_type, vr0))
1100 return;
1102 value_range vr0_cst (*vr0);
1103 vr0_cst.normalize_addresses ();
1104 op->fold_range (*vr, expr_type, vr0_cst, value_range (expr_type));
1107 /* If the range of values taken by OP can be inferred after STMT executes,
1108 return the comparison code (COMP_CODE_P) and value (VAL_P) that
1109 describes the inferred range. Return true if a range could be
1110 inferred. */
1112 bool
1113 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
1115 *val_p = NULL_TREE;
1116 *comp_code_p = ERROR_MARK;
1118 /* Do not attempt to infer anything in names that flow through
1119 abnormal edges. */
1120 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
1121 return false;
1123 /* If STMT is the last statement of a basic block with no normal
1124 successors, there is no point inferring anything about any of its
1125 operands. We would not be able to find a proper insertion point
1126 for the assertion, anyway. */
1127 if (stmt_ends_bb_p (stmt))
1129 edge_iterator ei;
1130 edge e;
1132 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
1133 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
1134 break;
1135 if (e == NULL)
1136 return false;
1139 if (infer_nonnull_range (stmt, op))
1141 *val_p = build_int_cst (TREE_TYPE (op), 0);
1142 *comp_code_p = NE_EXPR;
1143 return true;
1146 return false;
1149 /* Dump assert_info structure. */
1151 void
1152 dump_assert_info (FILE *file, const assert_info &assert)
1154 fprintf (file, "Assert for: ");
1155 print_generic_expr (file, assert.name);
1156 fprintf (file, "\n\tPREDICATE: expr=[");
1157 print_generic_expr (file, assert.expr);
1158 fprintf (file, "] %s ", get_tree_code_name (assert.comp_code));
1159 fprintf (file, "val=[");
1160 print_generic_expr (file, assert.val);
1161 fprintf (file, "]\n\n");
1164 DEBUG_FUNCTION void
1165 debug (const assert_info &assert)
1167 dump_assert_info (stderr, assert);
1170 /* Dump a vector of assert_info's. */
1172 void
1173 dump_asserts_info (FILE *file, const vec<assert_info> &asserts)
1175 for (unsigned i = 0; i < asserts.length (); ++i)
1177 dump_assert_info (file, asserts[i]);
1178 fprintf (file, "\n");
1182 DEBUG_FUNCTION void
1183 debug (const vec<assert_info> &asserts)
1185 dump_asserts_info (stderr, asserts);
1188 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
1190 static void
1191 add_assert_info (vec<assert_info> &asserts,
1192 tree name, tree expr, enum tree_code comp_code, tree val)
1194 assert_info info;
1195 info.comp_code = comp_code;
1196 info.name = name;
1197 if (TREE_OVERFLOW_P (val))
1198 val = drop_tree_overflow (val);
1199 info.val = val;
1200 info.expr = expr;
1201 asserts.safe_push (info);
1202 if (dump_enabled_p ())
1203 dump_printf (MSG_NOTE | MSG_PRIORITY_INTERNALS,
1204 "Adding assert for %T from %T %s %T\n",
1205 name, expr, op_symbol_code (comp_code), val);
1208 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
1209 Extract a suitable test code and value and store them into *CODE_P and
1210 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
1212 If no extraction was possible, return FALSE, otherwise return TRUE.
1214 If INVERT is true, then we invert the result stored into *CODE_P. */
1216 static bool
1217 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
1218 tree cond_op0, tree cond_op1,
1219 bool invert, enum tree_code *code_p,
1220 tree *val_p)
1222 enum tree_code comp_code;
1223 tree val;
1225 /* Otherwise, we have a comparison of the form NAME COMP VAL
1226 or VAL COMP NAME. */
1227 if (name == cond_op1)
1229 /* If the predicate is of the form VAL COMP NAME, flip
1230 COMP around because we need to register NAME as the
1231 first operand in the predicate. */
1232 comp_code = swap_tree_comparison (cond_code);
1233 val = cond_op0;
1235 else if (name == cond_op0)
1237 /* The comparison is of the form NAME COMP VAL, so the
1238 comparison code remains unchanged. */
1239 comp_code = cond_code;
1240 val = cond_op1;
1242 else
1243 gcc_unreachable ();
1245 /* Invert the comparison code as necessary. */
1246 if (invert)
1247 comp_code = invert_tree_comparison (comp_code, 0);
1249 /* VRP only handles integral and pointer types. */
1250 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
1251 && ! POINTER_TYPE_P (TREE_TYPE (val)))
1252 return false;
1254 /* Do not register always-false predicates.
1255 FIXME: this works around a limitation in fold() when dealing with
1256 enumerations. Given 'enum { N1, N2 } x;', fold will not
1257 fold 'if (x > N2)' to 'if (0)'. */
1258 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
1259 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
1261 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
1262 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
1264 if (comp_code == GT_EXPR
1265 && (!max
1266 || compare_values (val, max) == 0))
1267 return false;
1269 if (comp_code == LT_EXPR
1270 && (!min
1271 || compare_values (val, min) == 0))
1272 return false;
1274 *code_p = comp_code;
1275 *val_p = val;
1276 return true;
1279 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
1280 (otherwise return VAL). VAL and MASK must be zero-extended for
1281 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
1282 (to transform signed values into unsigned) and at the end xor
1283 SGNBIT back. */
1285 wide_int
1286 masked_increment (const wide_int &val_in, const wide_int &mask,
1287 const wide_int &sgnbit, unsigned int prec)
1289 wide_int bit = wi::one (prec), res;
1290 unsigned int i;
1292 wide_int val = val_in ^ sgnbit;
1293 for (i = 0; i < prec; i++, bit += bit)
1295 res = mask;
1296 if ((res & bit) == 0)
1297 continue;
1298 res = bit - 1;
1299 res = wi::bit_and_not (val + bit, res);
1300 res &= mask;
1301 if (wi::gtu_p (res, val))
1302 return res ^ sgnbit;
1304 return val ^ sgnbit;
1307 /* Helper for overflow_comparison_p
1309 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
1310 OP1's defining statement to see if it ultimately has the form
1311 OP0 CODE (OP0 PLUS INTEGER_CST)
1313 If so, return TRUE indicating this is an overflow test and store into
1314 *NEW_CST an updated constant that can be used in a narrowed range test.
1316 REVERSED indicates if the comparison was originally:
1318 OP1 CODE' OP0.
1320 This affects how we build the updated constant. */
1322 static bool
1323 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
1324 bool follow_assert_exprs, bool reversed, tree *new_cst)
1326 /* See if this is a relational operation between two SSA_NAMES with
1327 unsigned, overflow wrapping values. If so, check it more deeply. */
1328 if ((code == LT_EXPR || code == LE_EXPR
1329 || code == GE_EXPR || code == GT_EXPR)
1330 && TREE_CODE (op0) == SSA_NAME
1331 && TREE_CODE (op1) == SSA_NAME
1332 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
1333 && TYPE_UNSIGNED (TREE_TYPE (op0))
1334 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
1336 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
1338 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
1339 if (follow_assert_exprs)
1341 while (gimple_assign_single_p (op1_def)
1342 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
1344 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
1345 if (TREE_CODE (op1) != SSA_NAME)
1346 break;
1347 op1_def = SSA_NAME_DEF_STMT (op1);
1351 /* Now look at the defining statement of OP1 to see if it adds
1352 or subtracts a nonzero constant from another operand. */
1353 if (op1_def
1354 && is_gimple_assign (op1_def)
1355 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
1356 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
1357 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
1359 tree target = gimple_assign_rhs1 (op1_def);
1361 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
1362 for one where TARGET appears on the RHS. */
1363 if (follow_assert_exprs)
1365 /* Now see if that "other operand" is op0, following the chain
1366 of ASSERT_EXPRs if necessary. */
1367 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
1368 while (op0 != target
1369 && gimple_assign_single_p (op0_def)
1370 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
1372 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
1373 if (TREE_CODE (op0) != SSA_NAME)
1374 break;
1375 op0_def = SSA_NAME_DEF_STMT (op0);
1379 /* If we did not find our target SSA_NAME, then this is not
1380 an overflow test. */
1381 if (op0 != target)
1382 return false;
1384 tree type = TREE_TYPE (op0);
1385 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
1386 tree inc = gimple_assign_rhs2 (op1_def);
1387 if (reversed)
1388 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
1389 else
1390 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
1391 return true;
1394 return false;
1397 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
1398 OP1's defining statement to see if it ultimately has the form
1399 OP0 CODE (OP0 PLUS INTEGER_CST)
1401 If so, return TRUE indicating this is an overflow test and store into
1402 *NEW_CST an updated constant that can be used in a narrowed range test.
1404 These statements are left as-is in the IL to facilitate discovery of
1405 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
1406 the alternate range representation is often useful within VRP. */
1408 bool
1409 overflow_comparison_p (tree_code code, tree name, tree val,
1410 bool use_equiv_p, tree *new_cst)
1412 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
1413 return true;
1414 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
1415 use_equiv_p, true, new_cst);
1419 /* Try to register an edge assertion for SSA name NAME on edge E for
1420 the condition COND contributing to the conditional jump pointed to by BSI.
1421 Invert the condition COND if INVERT is true. */
1423 static void
1424 register_edge_assert_for_2 (tree name, edge e,
1425 enum tree_code cond_code,
1426 tree cond_op0, tree cond_op1, bool invert,
1427 vec<assert_info> &asserts)
1429 tree val;
1430 enum tree_code comp_code;
1432 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
1433 cond_op0,
1434 cond_op1,
1435 invert, &comp_code, &val))
1436 return;
1438 /* Queue the assert. */
1439 tree x;
1440 if (overflow_comparison_p (comp_code, name, val, false, &x))
1442 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
1443 ? GT_EXPR : LE_EXPR);
1444 add_assert_info (asserts, name, name, new_code, x);
1446 add_assert_info (asserts, name, name, comp_code, val);
1448 /* In the case of NAME <= CST and NAME being defined as
1449 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
1450 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
1451 This catches range and anti-range tests. */
1452 if ((comp_code == LE_EXPR
1453 || comp_code == GT_EXPR)
1454 && TREE_CODE (val) == INTEGER_CST
1455 && TYPE_UNSIGNED (TREE_TYPE (val)))
1457 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1458 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
1460 /* Extract CST2 from the (optional) addition. */
1461 if (is_gimple_assign (def_stmt)
1462 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
1464 name2 = gimple_assign_rhs1 (def_stmt);
1465 cst2 = gimple_assign_rhs2 (def_stmt);
1466 if (TREE_CODE (name2) == SSA_NAME
1467 && TREE_CODE (cst2) == INTEGER_CST)
1468 def_stmt = SSA_NAME_DEF_STMT (name2);
1471 /* Extract NAME2 from the (optional) sign-changing cast. */
1472 if (gassign *ass = dyn_cast <gassign *> (def_stmt))
1474 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (ass))
1475 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (ass)))
1476 && (TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (ass)))
1477 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (ass)))))
1478 name3 = gimple_assign_rhs1 (ass);
1481 /* If name3 is used later, create an ASSERT_EXPR for it. */
1482 if (name3 != NULL_TREE
1483 && TREE_CODE (name3) == SSA_NAME
1484 && (cst2 == NULL_TREE
1485 || TREE_CODE (cst2) == INTEGER_CST)
1486 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
1488 tree tmp;
1490 /* Build an expression for the range test. */
1491 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
1492 if (cst2 != NULL_TREE)
1493 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
1494 add_assert_info (asserts, name3, tmp, comp_code, val);
1497 /* If name2 is used later, create an ASSERT_EXPR for it. */
1498 if (name2 != NULL_TREE
1499 && TREE_CODE (name2) == SSA_NAME
1500 && TREE_CODE (cst2) == INTEGER_CST
1501 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
1503 tree tmp;
1505 /* Build an expression for the range test. */
1506 tmp = name2;
1507 if (TREE_TYPE (name) != TREE_TYPE (name2))
1508 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
1509 if (cst2 != NULL_TREE)
1510 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
1511 add_assert_info (asserts, name2, tmp, comp_code, val);
1515 /* In the case of post-in/decrement tests like if (i++) ... and uses
1516 of the in/decremented value on the edge the extra name we want to
1517 assert for is not on the def chain of the name compared. Instead
1518 it is in the set of use stmts.
1519 Similar cases happen for conversions that were simplified through
1520 fold_{sign_changed,widened}_comparison. */
1521 if ((comp_code == NE_EXPR
1522 || comp_code == EQ_EXPR)
1523 && TREE_CODE (val) == INTEGER_CST)
1525 imm_use_iterator ui;
1526 gimple *use_stmt;
1527 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
1529 if (!is_gimple_assign (use_stmt))
1530 continue;
1532 /* Cut off to use-stmts that are dominating the predecessor. */
1533 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
1534 continue;
1536 tree name2 = gimple_assign_lhs (use_stmt);
1537 if (TREE_CODE (name2) != SSA_NAME)
1538 continue;
1540 enum tree_code code = gimple_assign_rhs_code (use_stmt);
1541 tree cst;
1542 if (code == PLUS_EXPR
1543 || code == MINUS_EXPR)
1545 cst = gimple_assign_rhs2 (use_stmt);
1546 if (TREE_CODE (cst) != INTEGER_CST)
1547 continue;
1548 cst = int_const_binop (code, val, cst);
1550 else if (CONVERT_EXPR_CODE_P (code))
1552 /* For truncating conversions we cannot record
1553 an inequality. */
1554 if (comp_code == NE_EXPR
1555 && (TYPE_PRECISION (TREE_TYPE (name2))
1556 < TYPE_PRECISION (TREE_TYPE (name))))
1557 continue;
1558 cst = fold_convert (TREE_TYPE (name2), val);
1560 else
1561 continue;
1563 if (TREE_OVERFLOW_P (cst))
1564 cst = drop_tree_overflow (cst);
1565 add_assert_info (asserts, name2, name2, comp_code, cst);
1569 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
1570 && TREE_CODE (val) == INTEGER_CST)
1572 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1573 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
1574 tree val2 = NULL_TREE;
1575 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
1576 wide_int mask = wi::zero (prec);
1577 unsigned int nprec = prec;
1578 enum tree_code rhs_code = ERROR_MARK;
1580 if (is_gimple_assign (def_stmt))
1581 rhs_code = gimple_assign_rhs_code (def_stmt);
1583 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
1584 assert that A != CST1 -+ CST2. */
1585 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
1586 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
1588 tree op0 = gimple_assign_rhs1 (def_stmt);
1589 tree op1 = gimple_assign_rhs2 (def_stmt);
1590 if (TREE_CODE (op0) == SSA_NAME
1591 && TREE_CODE (op1) == INTEGER_CST)
1593 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
1594 ? MINUS_EXPR : PLUS_EXPR);
1595 op1 = int_const_binop (reverse_op, val, op1);
1596 if (TREE_OVERFLOW (op1))
1597 op1 = drop_tree_overflow (op1);
1598 add_assert_info (asserts, op0, op0, comp_code, op1);
1602 /* Add asserts for NAME cmp CST and NAME being defined
1603 as NAME = (int) NAME2. */
1604 if (!TYPE_UNSIGNED (TREE_TYPE (val))
1605 && (comp_code == LE_EXPR || comp_code == LT_EXPR
1606 || comp_code == GT_EXPR || comp_code == GE_EXPR)
1607 && gimple_assign_cast_p (def_stmt))
1609 name2 = gimple_assign_rhs1 (def_stmt);
1610 if (CONVERT_EXPR_CODE_P (rhs_code)
1611 && TREE_CODE (name2) == SSA_NAME
1612 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
1613 && TYPE_UNSIGNED (TREE_TYPE (name2))
1614 && prec == TYPE_PRECISION (TREE_TYPE (name2))
1615 && (comp_code == LE_EXPR || comp_code == GT_EXPR
1616 || !tree_int_cst_equal (val,
1617 TYPE_MIN_VALUE (TREE_TYPE (val)))))
1619 tree tmp, cst;
1620 enum tree_code new_comp_code = comp_code;
1622 cst = fold_convert (TREE_TYPE (name2),
1623 TYPE_MIN_VALUE (TREE_TYPE (val)));
1624 /* Build an expression for the range test. */
1625 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
1626 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
1627 fold_convert (TREE_TYPE (name2), val));
1628 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
1630 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
1631 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
1632 build_int_cst (TREE_TYPE (name2), 1));
1634 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
1638 /* Add asserts for NAME cmp CST and NAME being defined as
1639 NAME = NAME2 >> CST2.
1641 Extract CST2 from the right shift. */
1642 if (rhs_code == RSHIFT_EXPR)
1644 name2 = gimple_assign_rhs1 (def_stmt);
1645 cst2 = gimple_assign_rhs2 (def_stmt);
1646 if (TREE_CODE (name2) == SSA_NAME
1647 && tree_fits_uhwi_p (cst2)
1648 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
1649 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
1650 && type_has_mode_precision_p (TREE_TYPE (val)))
1652 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
1653 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
1656 if (val2 != NULL_TREE
1657 && TREE_CODE (val2) == INTEGER_CST
1658 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
1659 TREE_TYPE (val),
1660 val2, cst2), val))
1662 enum tree_code new_comp_code = comp_code;
1663 tree tmp, new_val;
1665 tmp = name2;
1666 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
1668 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
1670 tree type = build_nonstandard_integer_type (prec, 1);
1671 tmp = build1 (NOP_EXPR, type, name2);
1672 val2 = fold_convert (type, val2);
1674 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
1675 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
1676 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
1678 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
1680 wide_int minval
1681 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
1682 new_val = val2;
1683 if (minval == wi::to_wide (new_val))
1684 new_val = NULL_TREE;
1686 else
1688 wide_int maxval
1689 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
1690 mask |= wi::to_wide (val2);
1691 if (wi::eq_p (mask, maxval))
1692 new_val = NULL_TREE;
1693 else
1694 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
1697 if (new_val)
1698 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
1701 /* If we have a conversion that doesn't change the value of the source
1702 simply register the same assert for it. */
1703 if (CONVERT_EXPR_CODE_P (rhs_code))
1705 value_range vr;
1706 tree rhs1 = gimple_assign_rhs1 (def_stmt);
1707 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
1708 && TREE_CODE (rhs1) == SSA_NAME
1709 /* Make sure the relation preserves the upper/lower boundary of
1710 the range conservatively. */
1711 && (comp_code == NE_EXPR
1712 || comp_code == EQ_EXPR
1713 || (TYPE_SIGN (TREE_TYPE (name))
1714 == TYPE_SIGN (TREE_TYPE (rhs1)))
1715 || ((comp_code == LE_EXPR
1716 || comp_code == LT_EXPR)
1717 && !TYPE_UNSIGNED (TREE_TYPE (rhs1)))
1718 || ((comp_code == GE_EXPR
1719 || comp_code == GT_EXPR)
1720 && TYPE_UNSIGNED (TREE_TYPE (rhs1))))
1721 /* And the conversion does not alter the value we compare
1722 against and all values in rhs1 can be represented in
1723 the converted to type. */
1724 && int_fits_type_p (val, TREE_TYPE (rhs1))
1725 && ((TYPE_PRECISION (TREE_TYPE (name))
1726 > TYPE_PRECISION (TREE_TYPE (rhs1)))
1727 || ((get_range_query (cfun)->range_of_expr (vr, rhs1)
1728 && vr.kind () == VR_RANGE)
1729 && wi::fits_to_tree_p
1730 (widest_int::from (vr.lower_bound (),
1731 TYPE_SIGN (TREE_TYPE (rhs1))),
1732 TREE_TYPE (name))
1733 && wi::fits_to_tree_p
1734 (widest_int::from (vr.upper_bound (),
1735 TYPE_SIGN (TREE_TYPE (rhs1))),
1736 TREE_TYPE (name)))))
1737 add_assert_info (asserts, rhs1, rhs1,
1738 comp_code, fold_convert (TREE_TYPE (rhs1), val));
1741 /* Add asserts for NAME cmp CST and NAME being defined as
1742 NAME = NAME2 & CST2.
1744 Extract CST2 from the and.
1746 Also handle
1747 NAME = (unsigned) NAME2;
1748 casts where NAME's type is unsigned and has smaller precision
1749 than NAME2's type as if it was NAME = NAME2 & MASK. */
1750 names[0] = NULL_TREE;
1751 names[1] = NULL_TREE;
1752 cst2 = NULL_TREE;
1753 if (rhs_code == BIT_AND_EXPR
1754 || (CONVERT_EXPR_CODE_P (rhs_code)
1755 && INTEGRAL_TYPE_P (TREE_TYPE (val))
1756 && TYPE_UNSIGNED (TREE_TYPE (val))
1757 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
1758 > prec))
1760 name2 = gimple_assign_rhs1 (def_stmt);
1761 if (rhs_code == BIT_AND_EXPR)
1762 cst2 = gimple_assign_rhs2 (def_stmt);
1763 else
1765 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
1766 nprec = TYPE_PRECISION (TREE_TYPE (name2));
1768 if (TREE_CODE (name2) == SSA_NAME
1769 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
1770 && TREE_CODE (cst2) == INTEGER_CST
1771 && !integer_zerop (cst2)
1772 && (nprec > 1
1773 || TYPE_UNSIGNED (TREE_TYPE (val))))
1775 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
1776 if (gimple_assign_cast_p (def_stmt2))
1778 names[1] = gimple_assign_rhs1 (def_stmt2);
1779 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
1780 || TREE_CODE (names[1]) != SSA_NAME
1781 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
1782 || (TYPE_PRECISION (TREE_TYPE (name2))
1783 != TYPE_PRECISION (TREE_TYPE (names[1]))))
1784 names[1] = NULL_TREE;
1786 names[0] = name2;
1789 if (names[0] || names[1])
1791 wide_int minv, maxv, valv, cst2v;
1792 wide_int tem, sgnbit;
1793 bool valid_p = false, valn, cst2n;
1794 enum tree_code ccode = comp_code;
1796 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
1797 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
1798 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
1799 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
1800 /* If CST2 doesn't have most significant bit set,
1801 but VAL is negative, we have comparison like
1802 if ((x & 0x123) > -4) (always true). Just give up. */
1803 if (!cst2n && valn)
1804 ccode = ERROR_MARK;
1805 if (cst2n)
1806 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
1807 else
1808 sgnbit = wi::zero (nprec);
1809 minv = valv & cst2v;
1810 switch (ccode)
1812 case EQ_EXPR:
1813 /* Minimum unsigned value for equality is VAL & CST2
1814 (should be equal to VAL, otherwise we probably should
1815 have folded the comparison into false) and
1816 maximum unsigned value is VAL | ~CST2. */
1817 maxv = valv | ~cst2v;
1818 valid_p = true;
1819 break;
1821 case NE_EXPR:
1822 tem = valv | ~cst2v;
1823 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
1824 if (valv == 0)
1826 cst2n = false;
1827 sgnbit = wi::zero (nprec);
1828 goto gt_expr;
1830 /* If (VAL | ~CST2) is all ones, handle it as
1831 (X & CST2) < VAL. */
1832 if (tem == -1)
1834 cst2n = false;
1835 valn = false;
1836 sgnbit = wi::zero (nprec);
1837 goto lt_expr;
1839 if (!cst2n && wi::neg_p (cst2v))
1840 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
1841 if (sgnbit != 0)
1843 if (valv == sgnbit)
1845 cst2n = true;
1846 valn = true;
1847 goto gt_expr;
1849 if (tem == wi::mask (nprec - 1, false, nprec))
1851 cst2n = true;
1852 goto lt_expr;
1854 if (!cst2n)
1855 sgnbit = wi::zero (nprec);
1857 break;
1859 case GE_EXPR:
1860 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
1861 is VAL and maximum unsigned value is ~0. For signed
1862 comparison, if CST2 doesn't have most significant bit
1863 set, handle it similarly. If CST2 has MSB set,
1864 the minimum is the same, and maximum is ~0U/2. */
1865 if (minv != valv)
1867 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
1868 VAL. */
1869 minv = masked_increment (valv, cst2v, sgnbit, nprec);
1870 if (minv == valv)
1871 break;
1873 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
1874 valid_p = true;
1875 break;
1877 case GT_EXPR:
1878 gt_expr:
1879 /* Find out smallest MINV where MINV > VAL
1880 && (MINV & CST2) == MINV, if any. If VAL is signed and
1881 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
1882 minv = masked_increment (valv, cst2v, sgnbit, nprec);
1883 if (minv == valv)
1884 break;
1885 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
1886 valid_p = true;
1887 break;
1889 case LE_EXPR:
1890 /* Minimum unsigned value for <= is 0 and maximum
1891 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
1892 Otherwise, find smallest VAL2 where VAL2 > VAL
1893 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
1894 as maximum.
1895 For signed comparison, if CST2 doesn't have most
1896 significant bit set, handle it similarly. If CST2 has
1897 MSB set, the maximum is the same and minimum is INT_MIN. */
1898 if (minv == valv)
1899 maxv = valv;
1900 else
1902 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
1903 if (maxv == valv)
1904 break;
1905 maxv -= 1;
1907 maxv |= ~cst2v;
1908 minv = sgnbit;
1909 valid_p = true;
1910 break;
1912 case LT_EXPR:
1913 lt_expr:
1914 /* Minimum unsigned value for < is 0 and maximum
1915 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
1916 Otherwise, find smallest VAL2 where VAL2 > VAL
1917 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
1918 as maximum.
1919 For signed comparison, if CST2 doesn't have most
1920 significant bit set, handle it similarly. If CST2 has
1921 MSB set, the maximum is the same and minimum is INT_MIN. */
1922 if (minv == valv)
1924 if (valv == sgnbit)
1925 break;
1926 maxv = valv;
1928 else
1930 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
1931 if (maxv == valv)
1932 break;
1934 maxv -= 1;
1935 maxv |= ~cst2v;
1936 minv = sgnbit;
1937 valid_p = true;
1938 break;
1940 default:
1941 break;
1943 if (valid_p
1944 && (maxv - minv) != -1)
1946 tree tmp, new_val, type;
1947 int i;
1949 for (i = 0; i < 2; i++)
1950 if (names[i])
1952 wide_int maxv2 = maxv;
1953 tmp = names[i];
1954 type = TREE_TYPE (names[i]);
1955 if (!TYPE_UNSIGNED (type))
1957 type = build_nonstandard_integer_type (nprec, 1);
1958 tmp = build1 (NOP_EXPR, type, names[i]);
1960 if (minv != 0)
1962 tmp = build2 (PLUS_EXPR, type, tmp,
1963 wide_int_to_tree (type, -minv));
1964 maxv2 = maxv - minv;
1966 new_val = wide_int_to_tree (type, maxv2);
1967 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
1974 /* OP is an operand of a truth value expression which is known to have
1975 a particular value. Register any asserts for OP and for any
1976 operands in OP's defining statement.
1978 If CODE is EQ_EXPR, then we want to register OP is zero (false),
1979 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
1981 static void
1982 register_edge_assert_for_1 (tree op, enum tree_code code,
1983 edge e, vec<assert_info> &asserts)
1985 gimple *op_def;
1986 tree val;
1987 enum tree_code rhs_code;
1989 /* We only care about SSA_NAMEs. */
1990 if (TREE_CODE (op) != SSA_NAME)
1991 return;
1993 /* We know that OP will have a zero or nonzero value. */
1994 val = build_int_cst (TREE_TYPE (op), 0);
1995 add_assert_info (asserts, op, op, code, val);
1997 /* Now look at how OP is set. If it's set from a comparison,
1998 a truth operation or some bit operations, then we may be able
1999 to register information about the operands of that assignment. */
2000 op_def = SSA_NAME_DEF_STMT (op);
2001 if (gimple_code (op_def) != GIMPLE_ASSIGN)
2002 return;
2004 rhs_code = gimple_assign_rhs_code (op_def);
2006 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
2008 bool invert = (code == EQ_EXPR ? true : false);
2009 tree op0 = gimple_assign_rhs1 (op_def);
2010 tree op1 = gimple_assign_rhs2 (op_def);
2012 if (TREE_CODE (op0) == SSA_NAME)
2013 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
2014 if (TREE_CODE (op1) == SSA_NAME)
2015 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
2017 else if ((code == NE_EXPR
2018 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
2019 || (code == EQ_EXPR
2020 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
2022 /* Recurse on each operand. */
2023 tree op0 = gimple_assign_rhs1 (op_def);
2024 tree op1 = gimple_assign_rhs2 (op_def);
2025 if (TREE_CODE (op0) == SSA_NAME
2026 && has_single_use (op0))
2027 register_edge_assert_for_1 (op0, code, e, asserts);
2028 if (TREE_CODE (op1) == SSA_NAME
2029 && has_single_use (op1))
2030 register_edge_assert_for_1 (op1, code, e, asserts);
2032 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
2033 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
2035 /* Recurse, flipping CODE. */
2036 code = invert_tree_comparison (code, false);
2037 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
2039 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
2041 /* Recurse through the copy. */
2042 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
2044 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
2046 /* Recurse through the type conversion, unless it is a narrowing
2047 conversion or conversion from non-integral type. */
2048 tree rhs = gimple_assign_rhs1 (op_def);
2049 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
2050 && (TYPE_PRECISION (TREE_TYPE (rhs))
2051 <= TYPE_PRECISION (TREE_TYPE (op))))
2052 register_edge_assert_for_1 (rhs, code, e, asserts);
2056 /* Check if comparison
2057 NAME COND_OP INTEGER_CST
2058 has a form of
2059 (X & 11...100..0) COND_OP XX...X00...0
2060 Such comparison can yield assertions like
2061 X >= XX...X00...0
2062 X <= XX...X11...1
2063 in case of COND_OP being EQ_EXPR or
2064 X < XX...X00...0
2065 X > XX...X11...1
2066 in case of NE_EXPR. */
2068 static bool
2069 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
2070 tree *new_name, tree *low, enum tree_code *low_code,
2071 tree *high, enum tree_code *high_code)
2073 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2075 if (!is_gimple_assign (def_stmt)
2076 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
2077 return false;
2079 tree t = gimple_assign_rhs1 (def_stmt);
2080 tree maskt = gimple_assign_rhs2 (def_stmt);
2081 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
2082 return false;
2084 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
2085 wide_int inv_mask = ~mask;
2086 /* Must have been removed by now so don't bother optimizing. */
2087 if (mask == 0 || inv_mask == 0)
2088 return false;
2090 /* Assume VALT is INTEGER_CST. */
2091 wi::tree_to_wide_ref val = wi::to_wide (valt);
2093 if ((inv_mask & (inv_mask + 1)) != 0
2094 || (val & mask) != val)
2095 return false;
2097 bool is_range = cond_code == EQ_EXPR;
2099 tree type = TREE_TYPE (t);
2100 wide_int min = wi::min_value (type),
2101 max = wi::max_value (type);
2103 if (is_range)
2105 *low_code = val == min ? ERROR_MARK : GE_EXPR;
2106 *high_code = val == max ? ERROR_MARK : LE_EXPR;
2108 else
2110 /* We can still generate assertion if one of alternatives
2111 is known to always be false. */
2112 if (val == min)
2114 *low_code = (enum tree_code) 0;
2115 *high_code = GT_EXPR;
2117 else if ((val | inv_mask) == max)
2119 *low_code = LT_EXPR;
2120 *high_code = (enum tree_code) 0;
2122 else
2123 return false;
2126 *new_name = t;
2127 *low = wide_int_to_tree (type, val);
2128 *high = wide_int_to_tree (type, val | inv_mask);
2130 return true;
2133 /* Try to register an edge assertion for SSA name NAME on edge E for
2134 the condition COND contributing to the conditional jump pointed to by
2135 SI. */
2137 void
2138 register_edge_assert_for (tree name, edge e,
2139 enum tree_code cond_code, tree cond_op0,
2140 tree cond_op1, vec<assert_info> &asserts)
2142 tree val;
2143 enum tree_code comp_code;
2144 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
2146 /* Do not attempt to infer anything in names that flow through
2147 abnormal edges. */
2148 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
2149 return;
2151 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2152 cond_op0, cond_op1,
2153 is_else_edge,
2154 &comp_code, &val))
2155 return;
2157 /* Register ASSERT_EXPRs for name. */
2158 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
2159 cond_op1, is_else_edge, asserts);
2162 /* If COND is effectively an equality test of an SSA_NAME against
2163 the value zero or one, then we may be able to assert values
2164 for SSA_NAMEs which flow into COND. */
2166 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
2167 statement of NAME we can assert both operands of the BIT_AND_EXPR
2168 have nonzero value. */
2169 if ((comp_code == EQ_EXPR && integer_onep (val))
2170 || (comp_code == NE_EXPR && integer_zerop (val)))
2172 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2174 if (is_gimple_assign (def_stmt)
2175 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
2177 tree op0 = gimple_assign_rhs1 (def_stmt);
2178 tree op1 = gimple_assign_rhs2 (def_stmt);
2179 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
2180 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
2182 else if (is_gimple_assign (def_stmt)
2183 && (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt))
2184 == tcc_comparison))
2185 register_edge_assert_for_1 (name, NE_EXPR, e, asserts);
2188 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
2189 statement of NAME we can assert both operands of the BIT_IOR_EXPR
2190 have zero value. */
2191 if ((comp_code == EQ_EXPR && integer_zerop (val))
2192 || (comp_code == NE_EXPR
2193 && integer_onep (val)
2194 && TYPE_PRECISION (TREE_TYPE (name)) == 1))
2196 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2198 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
2199 necessarily zero value, or if type-precision is one. */
2200 if (is_gimple_assign (def_stmt)
2201 && gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR)
2203 tree op0 = gimple_assign_rhs1 (def_stmt);
2204 tree op1 = gimple_assign_rhs2 (def_stmt);
2205 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
2206 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
2208 else if (is_gimple_assign (def_stmt)
2209 && (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt))
2210 == tcc_comparison))
2211 register_edge_assert_for_1 (name, EQ_EXPR, e, asserts);
2214 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
2215 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2216 && TREE_CODE (val) == INTEGER_CST)
2218 enum tree_code low_code, high_code;
2219 tree low, high;
2220 if (is_masked_range_test (name, val, comp_code, &name, &low,
2221 &low_code, &high, &high_code))
2223 if (low_code != ERROR_MARK)
2224 register_edge_assert_for_2 (name, e, low_code, name,
2225 low, /*invert*/false, asserts);
2226 if (high_code != ERROR_MARK)
2227 register_edge_assert_for_2 (name, e, high_code, name,
2228 high, /*invert*/false, asserts);
2233 /* Handle
2234 _4 = x_3 & 31;
2235 if (_4 != 0)
2236 goto <bb 6>;
2237 else
2238 goto <bb 7>;
2239 <bb 6>:
2240 __builtin_unreachable ();
2241 <bb 7>:
2242 x_5 = ASSERT_EXPR <x_3, ...>;
2243 If x_3 has no other immediate uses (checked by caller),
2244 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
2245 from the non-zero bitmask. */
2247 void
2248 maybe_set_nonzero_bits (edge e, tree var)
2250 basic_block cond_bb = e->src;
2251 gimple *stmt = last_stmt (cond_bb);
2252 tree cst;
2254 if (stmt == NULL
2255 || gimple_code (stmt) != GIMPLE_COND
2256 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
2257 ? EQ_EXPR : NE_EXPR)
2258 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
2259 || !integer_zerop (gimple_cond_rhs (stmt)))
2260 return;
2262 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
2263 if (!is_gimple_assign (stmt)
2264 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
2265 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
2266 return;
2267 if (gimple_assign_rhs1 (stmt) != var)
2269 gimple *stmt2;
2271 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
2272 return;
2273 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
2274 if (!gimple_assign_cast_p (stmt2)
2275 || gimple_assign_rhs1 (stmt2) != var
2276 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
2277 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
2278 != TYPE_PRECISION (TREE_TYPE (var))))
2279 return;
2281 cst = gimple_assign_rhs2 (stmt);
2282 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
2283 wi::to_wide (cst)));
2286 /* Return true if STMT is interesting for VRP. */
2288 bool
2289 stmt_interesting_for_vrp (gimple *stmt)
2291 if (gimple_code (stmt) == GIMPLE_PHI)
2293 tree res = gimple_phi_result (stmt);
2294 return (!virtual_operand_p (res)
2295 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
2296 || POINTER_TYPE_P (TREE_TYPE (res))));
2298 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
2300 tree lhs = gimple_get_lhs (stmt);
2302 /* In general, assignments with virtual operands are not useful
2303 for deriving ranges, with the obvious exception of calls to
2304 builtin functions. */
2305 if (lhs && TREE_CODE (lhs) == SSA_NAME
2306 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
2307 || POINTER_TYPE_P (TREE_TYPE (lhs)))
2308 && (is_gimple_call (stmt)
2309 || !gimple_vuse (stmt)))
2310 return true;
2311 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
2312 switch (gimple_call_internal_fn (stmt))
2314 case IFN_ADD_OVERFLOW:
2315 case IFN_SUB_OVERFLOW:
2316 case IFN_MUL_OVERFLOW:
2317 case IFN_ATOMIC_COMPARE_EXCHANGE:
2318 /* These internal calls return _Complex integer type,
2319 but are interesting to VRP nevertheless. */
2320 if (lhs && TREE_CODE (lhs) == SSA_NAME)
2321 return true;
2322 break;
2323 default:
2324 break;
2327 else if (gimple_code (stmt) == GIMPLE_COND
2328 || gimple_code (stmt) == GIMPLE_SWITCH)
2329 return true;
2331 return false;
2334 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
2335 that includes the value VAL. The search is restricted to the range
2336 [START_IDX, n - 1] where n is the size of VEC.
2338 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
2339 returned.
2341 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
2342 it is placed in IDX and false is returned.
2344 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
2345 returned. */
2347 bool
2348 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
2350 size_t n = gimple_switch_num_labels (stmt);
2351 size_t low, high;
2353 /* Find case label for minimum of the value range or the next one.
2354 At each iteration we are searching in [low, high - 1]. */
2356 for (low = start_idx, high = n; high != low; )
2358 tree t;
2359 int cmp;
2360 /* Note that i != high, so we never ask for n. */
2361 size_t i = (high + low) / 2;
2362 t = gimple_switch_label (stmt, i);
2364 /* Cache the result of comparing CASE_LOW and val. */
2365 cmp = tree_int_cst_compare (CASE_LOW (t), val);
2367 if (cmp == 0)
2369 /* Ranges cannot be empty. */
2370 *idx = i;
2371 return true;
2373 else if (cmp > 0)
2374 high = i;
2375 else
2377 low = i + 1;
2378 if (CASE_HIGH (t) != NULL
2379 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
2381 *idx = i;
2382 return true;
2387 *idx = high;
2388 return false;
2391 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
2392 for values between MIN and MAX. The first index is placed in MIN_IDX. The
2393 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
2394 then MAX_IDX < MIN_IDX.
2395 Returns true if the default label is not needed. */
2397 bool
2398 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
2399 size_t *max_idx)
2401 size_t i, j;
2402 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
2403 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
2405 if (i == j
2406 && min_take_default
2407 && max_take_default)
2409 /* Only the default case label reached.
2410 Return an empty range. */
2411 *min_idx = 1;
2412 *max_idx = 0;
2413 return false;
2415 else
2417 bool take_default = min_take_default || max_take_default;
2418 tree low, high;
2419 size_t k;
2421 if (max_take_default)
2422 j--;
2424 /* If the case label range is continuous, we do not need
2425 the default case label. Verify that. */
2426 high = CASE_LOW (gimple_switch_label (stmt, i));
2427 if (CASE_HIGH (gimple_switch_label (stmt, i)))
2428 high = CASE_HIGH (gimple_switch_label (stmt, i));
2429 for (k = i + 1; k <= j; ++k)
2431 low = CASE_LOW (gimple_switch_label (stmt, k));
2432 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
2434 take_default = true;
2435 break;
2437 high = low;
2438 if (CASE_HIGH (gimple_switch_label (stmt, k)))
2439 high = CASE_HIGH (gimple_switch_label (stmt, k));
2442 *min_idx = i;
2443 *max_idx = j;
2444 return !take_default;
2448 /* Given a SWITCH_STMT, return the case label that encompasses the
2449 known possible values for the switch operand. RANGE_OF_OP is a
2450 range for the known values of the switch operand. */
2452 tree
2453 find_case_label_range (gswitch *switch_stmt, const irange *range_of_op)
2455 if (range_of_op->undefined_p ()
2456 || range_of_op->varying_p ()
2457 || range_of_op->symbolic_p ())
2458 return NULL_TREE;
2460 size_t i, j;
2461 tree op = gimple_switch_index (switch_stmt);
2462 tree type = TREE_TYPE (op);
2463 tree tmin = wide_int_to_tree (type, range_of_op->lower_bound ());
2464 tree tmax = wide_int_to_tree (type, range_of_op->upper_bound ());
2465 find_case_label_range (switch_stmt, tmin, tmax, &i, &j);
2466 if (i == j)
2468 /* Look for exactly one label that encompasses the range of
2469 the operand. */
2470 tree label = gimple_switch_label (switch_stmt, i);
2471 tree case_high
2472 = CASE_HIGH (label) ? CASE_HIGH (label) : CASE_LOW (label);
2473 int_range_max label_range (CASE_LOW (label), case_high);
2474 if (!types_compatible_p (label_range.type (), range_of_op->type ()))
2475 range_cast (label_range, range_of_op->type ());
2476 label_range.intersect (range_of_op);
2477 if (label_range == *range_of_op)
2478 return label;
2480 else if (i > j)
2482 /* If there are no labels at all, take the default. */
2483 return gimple_switch_label (switch_stmt, 0);
2485 else
2487 /* Otherwise, there are various labels that can encompass
2488 the range of operand. In which case, see if the range of
2489 the operand is entirely *outside* the bounds of all the
2490 (non-default) case labels. If so, take the default. */
2491 unsigned n = gimple_switch_num_labels (switch_stmt);
2492 tree min_label = gimple_switch_label (switch_stmt, 1);
2493 tree max_label = gimple_switch_label (switch_stmt, n - 1);
2494 tree case_high = CASE_HIGH (max_label);
2495 if (!case_high)
2496 case_high = CASE_LOW (max_label);
2497 int_range_max label_range (CASE_LOW (min_label), case_high);
2498 if (!types_compatible_p (label_range.type (), range_of_op->type ()))
2499 range_cast (label_range, range_of_op->type ());
2500 label_range.intersect (range_of_op);
2501 if (label_range.undefined_p ())
2502 return gimple_switch_label (switch_stmt, 0);
2504 return NULL_TREE;
2507 struct case_info
2509 tree expr;
2510 basic_block bb;
2513 /* Location information for ASSERT_EXPRs. Each instance of this
2514 structure describes an ASSERT_EXPR for an SSA name. Since a single
2515 SSA name may have more than one assertion associated with it, these
2516 locations are kept in a linked list attached to the corresponding
2517 SSA name. */
2518 struct assert_locus
2520 /* Basic block where the assertion would be inserted. */
2521 basic_block bb;
2523 /* Some assertions need to be inserted on an edge (e.g., assertions
2524 generated by COND_EXPRs). In those cases, BB will be NULL. */
2525 edge e;
2527 /* Pointer to the statement that generated this assertion. */
2528 gimple_stmt_iterator si;
2530 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
2531 enum tree_code comp_code;
2533 /* Value being compared against. */
2534 tree val;
2536 /* Expression to compare. */
2537 tree expr;
2539 /* Next node in the linked list. */
2540 assert_locus *next;
2543 /* Class to traverse the flowgraph looking for conditional jumps to
2544 insert ASSERT_EXPR range expressions. These range expressions are
2545 meant to provide information to optimizations that need to reason
2546 in terms of value ranges. They will not be expanded into RTL. */
2548 class vrp_asserts
2550 public:
2551 vrp_asserts (struct function *fn) : fun (fn) { }
2553 void insert_range_assertions ();
2555 /* Convert range assertion expressions into the implied copies and
2556 copy propagate away the copies. */
2557 void remove_range_assertions ();
2559 /* Dump all the registered assertions for all the names to FILE. */
2560 void dump (FILE *);
2562 /* Dump all the registered assertions for NAME to FILE. */
2563 void dump (FILE *file, tree name);
2565 /* Dump all the registered assertions for NAME to stderr. */
2566 void debug (tree name)
2568 dump (stderr, name);
2571 /* Dump all the registered assertions for all the names to stderr. */
2572 void debug ()
2574 dump (stderr);
2577 private:
2578 /* Set of SSA names found live during the RPO traversal of the function
2579 for still active basic-blocks. */
2580 live_names live;
2582 /* Function to work on. */
2583 struct function *fun;
2585 /* If bit I is present, it means that SSA name N_i has a list of
2586 assertions that should be inserted in the IL. */
2587 bitmap need_assert_for;
2589 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
2590 holds a list of ASSERT_LOCUS_T nodes that describe where
2591 ASSERT_EXPRs for SSA name N_I should be inserted. */
2592 assert_locus **asserts_for;
2594 /* Finish found ASSERTS for E and register them at GSI. */
2595 void finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
2596 vec<assert_info> &asserts);
2598 /* Determine whether the outgoing edges of BB should receive an
2599 ASSERT_EXPR for each of the operands of BB's LAST statement. The
2600 last statement of BB must be a SWITCH_EXPR.
2602 If any of the sub-graphs rooted at BB have an interesting use of
2603 the predicate operands, an assert location node is added to the
2604 list of assertions for the corresponding operands. */
2605 void find_switch_asserts (basic_block bb, gswitch *last);
2607 /* Do an RPO walk over the function computing SSA name liveness
2608 on-the-fly and deciding on assert expressions to insert. */
2609 void find_assert_locations ();
2611 /* Traverse all the statements in block BB looking for statements that
2612 may generate useful assertions for the SSA names in their operand.
2613 See method implementation comentary for more information. */
2614 void find_assert_locations_in_bb (basic_block bb);
2616 /* Determine whether the outgoing edges of BB should receive an
2617 ASSERT_EXPR for each of the operands of BB's LAST statement.
2618 The last statement of BB must be a COND_EXPR.
2620 If any of the sub-graphs rooted at BB have an interesting use of
2621 the predicate operands, an assert location node is added to the
2622 list of assertions for the corresponding operands. */
2623 void find_conditional_asserts (basic_block bb, gcond *last);
2625 /* Process all the insertions registered for every name N_i registered
2626 in NEED_ASSERT_FOR. The list of assertions to be inserted are
2627 found in ASSERTS_FOR[i]. */
2628 void process_assert_insertions ();
2630 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2631 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2632 E->DEST, then register this location as a possible insertion point
2633 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2635 BB, E and SI provide the exact insertion point for the new
2636 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2637 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2638 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2639 must not be NULL. */
2640 void register_new_assert_for (tree name, tree expr,
2641 enum tree_code comp_code,
2642 tree val, basic_block bb,
2643 edge e, gimple_stmt_iterator si);
2645 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2646 create a new SSA name N and return the assertion assignment
2647 'N = ASSERT_EXPR <V, V OP W>'. */
2648 gimple *build_assert_expr_for (tree cond, tree v);
2650 /* Create an ASSERT_EXPR for NAME and insert it in the location
2651 indicated by LOC. Return true if we made any edge insertions. */
2652 bool process_assert_insertions_for (tree name, assert_locus *loc);
2654 /* Qsort callback for sorting assert locations. */
2655 template <bool stable> static int compare_assert_loc (const void *,
2656 const void *);
2658 /* Return false if EXPR is a predicate expression involving floating
2659 point values. */
2660 bool fp_predicate (gimple *stmt)
2662 GIMPLE_CHECK (stmt, GIMPLE_COND);
2663 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2666 bool all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt,
2667 basic_block cond_bb);
2669 static int compare_case_labels (const void *, const void *);
2672 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2673 create a new SSA name N and return the assertion assignment
2674 'N = ASSERT_EXPR <V, V OP W>'. */
2676 gimple *
2677 vrp_asserts::build_assert_expr_for (tree cond, tree v)
2679 tree a;
2680 gassign *assertion;
2682 gcc_assert (TREE_CODE (v) == SSA_NAME
2683 && COMPARISON_CLASS_P (cond));
2685 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2686 assertion = gimple_build_assign (NULL_TREE, a);
2688 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2689 operand of the ASSERT_EXPR. Create it so the new name and the old one
2690 are registered in the replacement table so that we can fix the SSA web
2691 after adding all the ASSERT_EXPRs. */
2692 tree new_def = create_new_def_for (v, assertion, NULL);
2693 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2694 given we have to be able to fully propagate those out to re-create
2695 valid SSA when removing the asserts. */
2696 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2697 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2699 return assertion;
2702 /* Dump all the registered assertions for NAME to FILE. */
2704 void
2705 vrp_asserts::dump (FILE *file, tree name)
2707 assert_locus *loc;
2709 fprintf (file, "Assertions to be inserted for ");
2710 print_generic_expr (file, name);
2711 fprintf (file, "\n");
2713 loc = asserts_for[SSA_NAME_VERSION (name)];
2714 while (loc)
2716 fprintf (file, "\t");
2717 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2718 fprintf (file, "\n\tBB #%d", loc->bb->index);
2719 if (loc->e)
2721 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2722 loc->e->dest->index);
2723 dump_edge_info (file, loc->e, dump_flags, 0);
2725 fprintf (file, "\n\tPREDICATE: ");
2726 print_generic_expr (file, loc->expr);
2727 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2728 print_generic_expr (file, loc->val);
2729 fprintf (file, "\n\n");
2730 loc = loc->next;
2733 fprintf (file, "\n");
2736 /* Dump all the registered assertions for all the names to FILE. */
2738 void
2739 vrp_asserts::dump (FILE *file)
2741 unsigned i;
2742 bitmap_iterator bi;
2744 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2745 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2746 dump (file, ssa_name (i));
2747 fprintf (file, "\n");
2750 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2751 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2752 E->DEST, then register this location as a possible insertion point
2753 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2755 BB, E and SI provide the exact insertion point for the new
2756 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2757 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2758 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2759 must not be NULL. */
2761 void
2762 vrp_asserts::register_new_assert_for (tree name, tree expr,
2763 enum tree_code comp_code,
2764 tree val,
2765 basic_block bb,
2766 edge e,
2767 gimple_stmt_iterator si)
2769 assert_locus *n, *loc, *last_loc;
2770 basic_block dest_bb;
2772 gcc_checking_assert (bb == NULL || e == NULL);
2774 if (e == NULL)
2775 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2776 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2778 /* Never build an assert comparing against an integer constant with
2779 TREE_OVERFLOW set. This confuses our undefined overflow warning
2780 machinery. */
2781 if (TREE_OVERFLOW_P (val))
2782 val = drop_tree_overflow (val);
2784 /* The new assertion A will be inserted at BB or E. We need to
2785 determine if the new location is dominated by a previously
2786 registered location for A. If we are doing an edge insertion,
2787 assume that A will be inserted at E->DEST. Note that this is not
2788 necessarily true.
2790 If E is a critical edge, it will be split. But even if E is
2791 split, the new block will dominate the same set of blocks that
2792 E->DEST dominates.
2794 The reverse, however, is not true, blocks dominated by E->DEST
2795 will not be dominated by the new block created to split E. So,
2796 if the insertion location is on a critical edge, we will not use
2797 the new location to move another assertion previously registered
2798 at a block dominated by E->DEST. */
2799 dest_bb = (bb) ? bb : e->dest;
2801 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2802 VAL at a block dominating DEST_BB, then we don't need to insert a new
2803 one. Similarly, if the same assertion already exists at a block
2804 dominated by DEST_BB and the new location is not on a critical
2805 edge, then update the existing location for the assertion (i.e.,
2806 move the assertion up in the dominance tree).
2808 Note, this is implemented as a simple linked list because there
2809 should not be more than a handful of assertions registered per
2810 name. If this becomes a performance problem, a table hashed by
2811 COMP_CODE and VAL could be implemented. */
2812 loc = asserts_for[SSA_NAME_VERSION (name)];
2813 last_loc = loc;
2814 while (loc)
2816 if (loc->comp_code == comp_code
2817 && (loc->val == val
2818 || operand_equal_p (loc->val, val, 0))
2819 && (loc->expr == expr
2820 || operand_equal_p (loc->expr, expr, 0)))
2822 /* If E is not a critical edge and DEST_BB
2823 dominates the existing location for the assertion, move
2824 the assertion up in the dominance tree by updating its
2825 location information. */
2826 if ((e == NULL || !EDGE_CRITICAL_P (e))
2827 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2829 loc->bb = dest_bb;
2830 loc->e = e;
2831 loc->si = si;
2832 return;
2836 /* Update the last node of the list and move to the next one. */
2837 last_loc = loc;
2838 loc = loc->next;
2841 /* If we didn't find an assertion already registered for
2842 NAME COMP_CODE VAL, add a new one at the end of the list of
2843 assertions associated with NAME. */
2844 n = XNEW (struct assert_locus);
2845 n->bb = dest_bb;
2846 n->e = e;
2847 n->si = si;
2848 n->comp_code = comp_code;
2849 n->val = val;
2850 n->expr = expr;
2851 n->next = NULL;
2853 if (last_loc)
2854 last_loc->next = n;
2855 else
2856 asserts_for[SSA_NAME_VERSION (name)] = n;
2858 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2861 /* Finish found ASSERTS for E and register them at GSI. */
2863 void
2864 vrp_asserts::finish_register_edge_assert_for (edge e,
2865 gimple_stmt_iterator gsi,
2866 vec<assert_info> &asserts)
2868 for (unsigned i = 0; i < asserts.length (); ++i)
2869 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
2870 reachable from E. */
2871 if (live.live_on_edge_p (asserts[i].name, e))
2872 register_new_assert_for (asserts[i].name, asserts[i].expr,
2873 asserts[i].comp_code, asserts[i].val,
2874 NULL, e, gsi);
2877 /* Determine whether the outgoing edges of BB should receive an
2878 ASSERT_EXPR for each of the operands of BB's LAST statement.
2879 The last statement of BB must be a COND_EXPR.
2881 If any of the sub-graphs rooted at BB have an interesting use of
2882 the predicate operands, an assert location node is added to the
2883 list of assertions for the corresponding operands. */
2885 void
2886 vrp_asserts::find_conditional_asserts (basic_block bb, gcond *last)
2888 gimple_stmt_iterator bsi;
2889 tree op;
2890 edge_iterator ei;
2891 edge e;
2892 ssa_op_iter iter;
2894 bsi = gsi_for_stmt (last);
2896 /* Look for uses of the operands in each of the sub-graphs
2897 rooted at BB. We need to check each of the outgoing edges
2898 separately, so that we know what kind of ASSERT_EXPR to
2899 insert. */
2900 FOR_EACH_EDGE (e, ei, bb->succs)
2902 if (e->dest == bb)
2903 continue;
2905 /* Register the necessary assertions for each operand in the
2906 conditional predicate. */
2907 auto_vec<assert_info, 8> asserts;
2908 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2909 register_edge_assert_for (op, e,
2910 gimple_cond_code (last),
2911 gimple_cond_lhs (last),
2912 gimple_cond_rhs (last), asserts);
2913 finish_register_edge_assert_for (e, bsi, asserts);
2917 /* Compare two case labels sorting first by the destination bb index
2918 and then by the case value. */
2921 vrp_asserts::compare_case_labels (const void *p1, const void *p2)
2923 const struct case_info *ci1 = (const struct case_info *) p1;
2924 const struct case_info *ci2 = (const struct case_info *) p2;
2925 int idx1 = ci1->bb->index;
2926 int idx2 = ci2->bb->index;
2928 if (idx1 < idx2)
2929 return -1;
2930 else if (idx1 == idx2)
2932 /* Make sure the default label is first in a group. */
2933 if (!CASE_LOW (ci1->expr))
2934 return -1;
2935 else if (!CASE_LOW (ci2->expr))
2936 return 1;
2937 else
2938 return tree_int_cst_compare (CASE_LOW (ci1->expr),
2939 CASE_LOW (ci2->expr));
2941 else
2942 return 1;
2945 /* Determine whether the outgoing edges of BB should receive an
2946 ASSERT_EXPR for each of the operands of BB's LAST statement.
2947 The last statement of BB must be a SWITCH_EXPR.
2949 If any of the sub-graphs rooted at BB have an interesting use of
2950 the predicate operands, an assert location node is added to the
2951 list of assertions for the corresponding operands. */
2953 void
2954 vrp_asserts::find_switch_asserts (basic_block bb, gswitch *last)
2956 gimple_stmt_iterator bsi;
2957 tree op;
2958 edge e;
2959 struct case_info *ci;
2960 size_t n = gimple_switch_num_labels (last);
2961 #if GCC_VERSION >= 4000
2962 unsigned int idx;
2963 #else
2964 /* Work around GCC 3.4 bug (PR 37086). */
2965 volatile unsigned int idx;
2966 #endif
2968 bsi = gsi_for_stmt (last);
2969 op = gimple_switch_index (last);
2970 if (TREE_CODE (op) != SSA_NAME)
2971 return;
2973 /* Build a vector of case labels sorted by destination label. */
2974 ci = XNEWVEC (struct case_info, n);
2975 for (idx = 0; idx < n; ++idx)
2977 ci[idx].expr = gimple_switch_label (last, idx);
2978 ci[idx].bb = label_to_block (fun, CASE_LABEL (ci[idx].expr));
2980 edge default_edge = find_edge (bb, ci[0].bb);
2981 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
2983 for (idx = 0; idx < n; ++idx)
2985 tree min, max;
2986 tree cl = ci[idx].expr;
2987 basic_block cbb = ci[idx].bb;
2989 min = CASE_LOW (cl);
2990 max = CASE_HIGH (cl);
2992 /* If there are multiple case labels with the same destination
2993 we need to combine them to a single value range for the edge. */
2994 if (idx + 1 < n && cbb == ci[idx + 1].bb)
2996 /* Skip labels until the last of the group. */
2997 do {
2998 ++idx;
2999 } while (idx < n && cbb == ci[idx].bb);
3000 --idx;
3002 /* Pick up the maximum of the case label range. */
3003 if (CASE_HIGH (ci[idx].expr))
3004 max = CASE_HIGH (ci[idx].expr);
3005 else
3006 max = CASE_LOW (ci[idx].expr);
3009 /* Can't extract a useful assertion out of a range that includes the
3010 default label. */
3011 if (min == NULL_TREE)
3012 continue;
3014 /* Find the edge to register the assert expr on. */
3015 e = find_edge (bb, cbb);
3017 /* Register the necessary assertions for the operand in the
3018 SWITCH_EXPR. */
3019 auto_vec<assert_info, 8> asserts;
3020 register_edge_assert_for (op, e,
3021 max ? GE_EXPR : EQ_EXPR,
3022 op, fold_convert (TREE_TYPE (op), min),
3023 asserts);
3024 if (max)
3025 register_edge_assert_for (op, e, LE_EXPR, op,
3026 fold_convert (TREE_TYPE (op), max),
3027 asserts);
3028 finish_register_edge_assert_for (e, bsi, asserts);
3031 XDELETEVEC (ci);
3033 if (!live.live_on_edge_p (op, default_edge))
3034 return;
3036 /* Now register along the default label assertions that correspond to the
3037 anti-range of each label. */
3038 int insertion_limit = param_max_vrp_switch_assertions;
3039 if (insertion_limit == 0)
3040 return;
3042 /* We can't do this if the default case shares a label with another case. */
3043 tree default_cl = gimple_switch_default_label (last);
3044 for (idx = 1; idx < n; idx++)
3046 tree min, max;
3047 tree cl = gimple_switch_label (last, idx);
3048 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3049 continue;
3051 min = CASE_LOW (cl);
3052 max = CASE_HIGH (cl);
3054 /* Combine contiguous case ranges to reduce the number of assertions
3055 to insert. */
3056 for (idx = idx + 1; idx < n; idx++)
3058 tree next_min, next_max;
3059 tree next_cl = gimple_switch_label (last, idx);
3060 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3061 break;
3063 next_min = CASE_LOW (next_cl);
3064 next_max = CASE_HIGH (next_cl);
3066 wide_int difference = (wi::to_wide (next_min)
3067 - wi::to_wide (max ? max : min));
3068 if (wi::eq_p (difference, 1))
3069 max = next_max ? next_max : next_min;
3070 else
3071 break;
3073 idx--;
3075 if (max == NULL_TREE)
3077 /* Register the assertion OP != MIN. */
3078 auto_vec<assert_info, 8> asserts;
3079 min = fold_convert (TREE_TYPE (op), min);
3080 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3081 asserts);
3082 finish_register_edge_assert_for (default_edge, bsi, asserts);
3084 else
3086 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3087 which will give OP the anti-range ~[MIN,MAX]. */
3088 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3089 min = fold_convert (TREE_TYPE (uop), min);
3090 max = fold_convert (TREE_TYPE (uop), max);
3092 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3093 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3094 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3095 NULL, default_edge, bsi);
3098 if (--insertion_limit == 0)
3099 break;
3103 /* Traverse all the statements in block BB looking for statements that
3104 may generate useful assertions for the SSA names in their operand.
3105 If a statement produces a useful assertion A for name N_i, then the
3106 list of assertions already generated for N_i is scanned to
3107 determine if A is actually needed.
3109 If N_i already had the assertion A at a location dominating the
3110 current location, then nothing needs to be done. Otherwise, the
3111 new location for A is recorded instead.
3113 1- For every statement S in BB, all the variables used by S are
3114 added to bitmap FOUND_IN_SUBGRAPH.
3116 2- If statement S uses an operand N in a way that exposes a known
3117 value range for N, then if N was not already generated by an
3118 ASSERT_EXPR, create a new assert location for N. For instance,
3119 if N is a pointer and the statement dereferences it, we can
3120 assume that N is not NULL.
3122 3- COND_EXPRs are a special case of #2. We can derive range
3123 information from the predicate but need to insert different
3124 ASSERT_EXPRs for each of the sub-graphs rooted at the
3125 conditional block. If the last statement of BB is a conditional
3126 expression of the form 'X op Y', then
3128 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3130 b) If the conditional is the only entry point to the sub-graph
3131 corresponding to the THEN_CLAUSE, recurse into it. On
3132 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3133 an ASSERT_EXPR is added for the corresponding variable.
3135 c) Repeat step (b) on the ELSE_CLAUSE.
3137 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3139 For instance,
3141 if (a == 9)
3142 b = a;
3143 else
3144 b = c + 1;
3146 In this case, an assertion on the THEN clause is useful to
3147 determine that 'a' is always 9 on that edge. However, an assertion
3148 on the ELSE clause would be unnecessary.
3150 4- If BB does not end in a conditional expression, then we recurse
3151 into BB's dominator children.
3153 At the end of the recursive traversal, every SSA name will have a
3154 list of locations where ASSERT_EXPRs should be added. When a new
3155 location for name N is found, it is registered by calling
3156 register_new_assert_for. That function keeps track of all the
3157 registered assertions to prevent adding unnecessary assertions.
3158 For instance, if a pointer P_4 is dereferenced more than once in a
3159 dominator tree, only the location dominating all the dereference of
3160 P_4 will receive an ASSERT_EXPR. */
3162 void
3163 vrp_asserts::find_assert_locations_in_bb (basic_block bb)
3165 gimple *last;
3167 last = last_stmt (bb);
3169 /* If BB's last statement is a conditional statement involving integer
3170 operands, determine if we need to add ASSERT_EXPRs. */
3171 if (last
3172 && gimple_code (last) == GIMPLE_COND
3173 && !fp_predicate (last)
3174 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3175 find_conditional_asserts (bb, as_a <gcond *> (last));
3177 /* If BB's last statement is a switch statement involving integer
3178 operands, determine if we need to add ASSERT_EXPRs. */
3179 if (last
3180 && gimple_code (last) == GIMPLE_SWITCH
3181 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3182 find_switch_asserts (bb, as_a <gswitch *> (last));
3184 /* Traverse all the statements in BB marking used names and looking
3185 for statements that may infer assertions for their used operands. */
3186 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3187 gsi_prev (&si))
3189 gimple *stmt;
3190 tree op;
3191 ssa_op_iter i;
3193 stmt = gsi_stmt (si);
3195 if (is_gimple_debug (stmt))
3196 continue;
3198 /* See if we can derive an assertion for any of STMT's operands. */
3199 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3201 tree value;
3202 enum tree_code comp_code;
3204 /* If op is not live beyond this stmt, do not bother to insert
3205 asserts for it. */
3206 if (!live.live_on_block_p (op, bb))
3207 continue;
3209 /* If OP is used in such a way that we can infer a value
3210 range for it, and we don't find a previous assertion for
3211 it, create a new assertion location node for OP. */
3212 if (infer_value_range (stmt, op, &comp_code, &value))
3214 /* If we are able to infer a nonzero value range for OP,
3215 then walk backwards through the use-def chain to see if OP
3216 was set via a typecast.
3218 If so, then we can also infer a nonzero value range
3219 for the operand of the NOP_EXPR. */
3220 if (comp_code == NE_EXPR && integer_zerop (value))
3222 tree t = op;
3223 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3225 while (is_gimple_assign (def_stmt)
3226 && CONVERT_EXPR_CODE_P
3227 (gimple_assign_rhs_code (def_stmt))
3228 && TREE_CODE
3229 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3230 && POINTER_TYPE_P
3231 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3233 t = gimple_assign_rhs1 (def_stmt);
3234 def_stmt = SSA_NAME_DEF_STMT (t);
3236 /* Note we want to register the assert for the
3237 operand of the NOP_EXPR after SI, not after the
3238 conversion. */
3239 if (live.live_on_block_p (t, bb))
3240 register_new_assert_for (t, t, comp_code, value,
3241 bb, NULL, si);
3245 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3249 /* Update live. */
3250 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3251 live.set (op, bb);
3252 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3253 live.clear (op, bb);
3256 /* Traverse all PHI nodes in BB, updating live. */
3257 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3258 gsi_next (&si))
3260 use_operand_p arg_p;
3261 ssa_op_iter i;
3262 gphi *phi = si.phi ();
3263 tree res = gimple_phi_result (phi);
3265 if (virtual_operand_p (res))
3266 continue;
3268 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3270 tree arg = USE_FROM_PTR (arg_p);
3271 if (TREE_CODE (arg) == SSA_NAME)
3272 live.set (arg, bb);
3275 live.clear (res, bb);
3279 /* Do an RPO walk over the function computing SSA name liveness
3280 on-the-fly and deciding on assert expressions to insert. */
3282 void
3283 vrp_asserts::find_assert_locations (void)
3285 int *rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
3286 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
3287 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (fun));
3288 int rpo_cnt, i;
3290 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3291 for (i = 0; i < rpo_cnt; ++i)
3292 bb_rpo[rpo[i]] = i;
3294 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3295 the order we compute liveness and insert asserts we otherwise
3296 fail to insert asserts into the loop latch. */
3297 for (auto loop : loops_list (cfun, 0))
3299 i = loop->latch->index;
3300 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3301 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3302 !gsi_end_p (gsi); gsi_next (&gsi))
3304 gphi *phi = gsi.phi ();
3305 if (virtual_operand_p (gimple_phi_result (phi)))
3306 continue;
3307 tree arg = gimple_phi_arg_def (phi, j);
3308 if (TREE_CODE (arg) == SSA_NAME)
3309 live.set (arg, loop->latch);
3313 for (i = rpo_cnt - 1; i >= 0; --i)
3315 basic_block bb = BASIC_BLOCK_FOR_FN (fun, rpo[i]);
3316 edge e;
3317 edge_iterator ei;
3319 /* Process BB and update the live information with uses in
3320 this block. */
3321 find_assert_locations_in_bb (bb);
3323 /* Merge liveness into the predecessor blocks and free it. */
3324 if (!live.block_has_live_names_p (bb))
3326 int pred_rpo = i;
3327 FOR_EACH_EDGE (e, ei, bb->preds)
3329 int pred = e->src->index;
3330 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
3331 continue;
3333 live.merge (e->src, bb);
3335 if (bb_rpo[pred] < pred_rpo)
3336 pred_rpo = bb_rpo[pred];
3339 /* Record the RPO number of the last visited block that needs
3340 live information from this block. */
3341 last_rpo[rpo[i]] = pred_rpo;
3343 else
3344 live.clear_block (bb);
3346 /* We can free all successors live bitmaps if all their
3347 predecessors have been visited already. */
3348 FOR_EACH_EDGE (e, ei, bb->succs)
3349 if (last_rpo[e->dest->index] == i)
3350 live.clear_block (e->dest);
3353 XDELETEVEC (rpo);
3354 XDELETEVEC (bb_rpo);
3355 XDELETEVEC (last_rpo);
3358 /* Create an ASSERT_EXPR for NAME and insert it in the location
3359 indicated by LOC. Return true if we made any edge insertions. */
3361 bool
3362 vrp_asserts::process_assert_insertions_for (tree name, assert_locus *loc)
3364 /* Build the comparison expression NAME_i COMP_CODE VAL. */
3365 gimple *stmt;
3366 tree cond;
3367 gimple *assert_stmt;
3368 edge_iterator ei;
3369 edge e;
3371 /* If we have X <=> X do not insert an assert expr for that. */
3372 if (loc->expr == loc->val)
3373 return false;
3375 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
3376 assert_stmt = build_assert_expr_for (cond, name);
3377 if (loc->e)
3379 /* We have been asked to insert the assertion on an edge. This
3380 is used only by COND_EXPR and SWITCH_EXPR assertions. */
3381 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
3382 || (gimple_code (gsi_stmt (loc->si))
3383 == GIMPLE_SWITCH));
3385 gsi_insert_on_edge (loc->e, assert_stmt);
3386 return true;
3389 /* If the stmt iterator points at the end then this is an insertion
3390 at the beginning of a block. */
3391 if (gsi_end_p (loc->si))
3393 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
3394 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
3395 return false;
3398 /* Otherwise, we can insert right after LOC->SI iff the
3399 statement must not be the last statement in the block. */
3400 stmt = gsi_stmt (loc->si);
3401 if (!stmt_ends_bb_p (stmt))
3403 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
3404 return false;
3407 /* If STMT must be the last statement in BB, we can only insert new
3408 assertions on the non-abnormal edge out of BB. Note that since
3409 STMT is not control flow, there may only be one non-abnormal/eh edge
3410 out of BB. */
3411 FOR_EACH_EDGE (e, ei, loc->bb->succs)
3412 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
3414 gsi_insert_on_edge (e, assert_stmt);
3415 return true;
3418 gcc_unreachable ();
3421 /* Qsort helper for sorting assert locations. If stable is true, don't
3422 use iterative_hash_expr because it can be unstable for -fcompare-debug,
3423 on the other side some pointers might be NULL. */
3425 template <bool stable>
3427 vrp_asserts::compare_assert_loc (const void *pa, const void *pb)
3429 assert_locus * const a = *(assert_locus * const *)pa;
3430 assert_locus * const b = *(assert_locus * const *)pb;
3432 /* If stable, some asserts might be optimized away already, sort
3433 them last. */
3434 if (stable)
3436 if (a == NULL)
3437 return b != NULL;
3438 else if (b == NULL)
3439 return -1;
3442 if (a->e == NULL && b->e != NULL)
3443 return 1;
3444 else if (a->e != NULL && b->e == NULL)
3445 return -1;
3447 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
3448 no need to test both a->e and b->e. */
3450 /* Sort after destination index. */
3451 if (a->e == NULL)
3453 else if (a->e->dest->index > b->e->dest->index)
3454 return 1;
3455 else if (a->e->dest->index < b->e->dest->index)
3456 return -1;
3458 /* Sort after comp_code. */
3459 if (a->comp_code > b->comp_code)
3460 return 1;
3461 else if (a->comp_code < b->comp_code)
3462 return -1;
3464 hashval_t ha, hb;
3466 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
3467 uses DECL_UID of the VAR_DECL, so sorting might differ between
3468 -g and -g0. When doing the removal of redundant assert exprs
3469 and commonization to successors, this does not matter, but for
3470 the final sort needs to be stable. */
3471 if (stable)
3473 ha = 0;
3474 hb = 0;
3476 else
3478 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
3479 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
3482 /* Break the tie using hashing and source/bb index. */
3483 if (ha == hb)
3484 return (a->e != NULL
3485 ? a->e->src->index - b->e->src->index
3486 : a->bb->index - b->bb->index);
3487 return ha > hb ? 1 : -1;
3490 /* Process all the insertions registered for every name N_i registered
3491 in NEED_ASSERT_FOR. The list of assertions to be inserted are
3492 found in ASSERTS_FOR[i]. */
3494 void
3495 vrp_asserts::process_assert_insertions ()
3497 unsigned i;
3498 bitmap_iterator bi;
3499 bool update_edges_p = false;
3500 int num_asserts = 0;
3502 if (dump_file && (dump_flags & TDF_DETAILS))
3503 dump (dump_file);
3505 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
3507 assert_locus *loc = asserts_for[i];
3508 gcc_assert (loc);
3510 auto_vec<assert_locus *, 16> asserts;
3511 for (; loc; loc = loc->next)
3512 asserts.safe_push (loc);
3513 asserts.qsort (compare_assert_loc<false>);
3515 /* Push down common asserts to successors and remove redundant ones. */
3516 unsigned ecnt = 0;
3517 assert_locus *common = NULL;
3518 unsigned commonj = 0;
3519 for (unsigned j = 0; j < asserts.length (); ++j)
3521 loc = asserts[j];
3522 if (! loc->e)
3523 common = NULL;
3524 else if (! common
3525 || loc->e->dest != common->e->dest
3526 || loc->comp_code != common->comp_code
3527 || ! operand_equal_p (loc->val, common->val, 0)
3528 || ! operand_equal_p (loc->expr, common->expr, 0))
3530 commonj = j;
3531 common = loc;
3532 ecnt = 1;
3534 else if (loc->e == asserts[j-1]->e)
3536 /* Remove duplicate asserts. */
3537 if (commonj == j - 1)
3539 commonj = j;
3540 common = loc;
3542 free (asserts[j-1]);
3543 asserts[j-1] = NULL;
3545 else
3547 ecnt++;
3548 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
3550 /* We have the same assertion on all incoming edges of a BB.
3551 Insert it at the beginning of that block. */
3552 loc->bb = loc->e->dest;
3553 loc->e = NULL;
3554 loc->si = gsi_none ();
3555 common = NULL;
3556 /* Clear asserts commoned. */
3557 for (; commonj != j; ++commonj)
3558 if (asserts[commonj])
3560 free (asserts[commonj]);
3561 asserts[commonj] = NULL;
3567 /* The asserts vector sorting above might be unstable for
3568 -fcompare-debug, sort again to ensure a stable sort. */
3569 asserts.qsort (compare_assert_loc<true>);
3570 for (unsigned j = 0; j < asserts.length (); ++j)
3572 loc = asserts[j];
3573 if (! loc)
3574 break;
3575 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
3576 num_asserts++;
3577 free (loc);
3581 if (update_edges_p)
3582 gsi_commit_edge_inserts ();
3584 statistics_counter_event (fun, "Number of ASSERT_EXPR expressions inserted",
3585 num_asserts);
3588 /* Traverse the flowgraph looking for conditional jumps to insert range
3589 expressions. These range expressions are meant to provide information
3590 to optimizations that need to reason in terms of value ranges. They
3591 will not be expanded into RTL. For instance, given:
3593 x = ...
3594 y = ...
3595 if (x < y)
3596 y = x - 2;
3597 else
3598 x = y + 3;
3600 this pass will transform the code into:
3602 x = ...
3603 y = ...
3604 if (x < y)
3606 x = ASSERT_EXPR <x, x < y>
3607 y = x - 2
3609 else
3611 y = ASSERT_EXPR <y, x >= y>
3612 x = y + 3
3615 The idea is that once copy and constant propagation have run, other
3616 optimizations will be able to determine what ranges of values can 'x'
3617 take in different paths of the code, simply by checking the reaching
3618 definition of 'x'. */
3620 void
3621 vrp_asserts::insert_range_assertions (void)
3623 need_assert_for = BITMAP_ALLOC (NULL);
3624 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
3626 calculate_dominance_info (CDI_DOMINATORS);
3628 find_assert_locations ();
3629 if (!bitmap_empty_p (need_assert_for))
3631 process_assert_insertions ();
3632 update_ssa (TODO_update_ssa_no_phi);
3635 if (dump_file && (dump_flags & TDF_DETAILS))
3637 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
3638 dump_function_to_file (current_function_decl, dump_file, dump_flags);
3641 free (asserts_for);
3642 BITMAP_FREE (need_assert_for);
3645 /* Return true if all imm uses of VAR are either in STMT, or
3646 feed (optionally through a chain of single imm uses) GIMPLE_COND
3647 in basic block COND_BB. */
3649 bool
3650 vrp_asserts::all_imm_uses_in_stmt_or_feed_cond (tree var,
3651 gimple *stmt,
3652 basic_block cond_bb)
3654 use_operand_p use_p, use2_p;
3655 imm_use_iterator iter;
3657 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
3658 if (USE_STMT (use_p) != stmt)
3660 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
3661 if (is_gimple_debug (use_stmt))
3662 continue;
3663 while (is_gimple_assign (use_stmt)
3664 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
3665 && single_imm_use (gimple_assign_lhs (use_stmt),
3666 &use2_p, &use_stmt2))
3667 use_stmt = use_stmt2;
3668 if (gimple_code (use_stmt) != GIMPLE_COND
3669 || gimple_bb (use_stmt) != cond_bb)
3670 return false;
3672 return true;
3675 /* Convert range assertion expressions into the implied copies and
3676 copy propagate away the copies. Doing the trivial copy propagation
3677 here avoids the need to run the full copy propagation pass after
3678 VRP.
3680 FIXME, this will eventually lead to copy propagation removing the
3681 names that had useful range information attached to them. For
3682 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
3683 then N_i will have the range [3, +INF].
3685 However, by converting the assertion into the implied copy
3686 operation N_i = N_j, we will then copy-propagate N_j into the uses
3687 of N_i and lose the range information. We may want to hold on to
3688 ASSERT_EXPRs a little while longer as the ranges could be used in
3689 things like jump threading.
3691 The problem with keeping ASSERT_EXPRs around is that passes after
3692 VRP need to handle them appropriately.
3694 Another approach would be to make the range information a first
3695 class property of the SSA_NAME so that it can be queried from
3696 any pass. This is made somewhat more complex by the need for
3697 multiple ranges to be associated with one SSA_NAME. */
3699 void
3700 vrp_asserts::remove_range_assertions ()
3702 basic_block bb;
3703 gimple_stmt_iterator si;
3704 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
3705 a basic block preceeded by GIMPLE_COND branching to it and
3706 __builtin_trap, -1 if not yet checked, 0 otherwise. */
3707 int is_unreachable;
3709 /* Note that the BSI iterator bump happens at the bottom of the
3710 loop and no bump is necessary if we're removing the statement
3711 referenced by the current BSI. */
3712 FOR_EACH_BB_FN (bb, fun)
3713 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
3715 gimple *stmt = gsi_stmt (si);
3717 if (is_gimple_assign (stmt)
3718 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
3720 tree lhs = gimple_assign_lhs (stmt);
3721 tree rhs = gimple_assign_rhs1 (stmt);
3722 tree var;
3724 var = ASSERT_EXPR_VAR (rhs);
3726 if (TREE_CODE (var) == SSA_NAME
3727 && !POINTER_TYPE_P (TREE_TYPE (lhs))
3728 && SSA_NAME_RANGE_INFO (lhs))
3730 if (is_unreachable == -1)
3732 is_unreachable = 0;
3733 if (single_pred_p (bb)
3734 && assert_unreachable_fallthru_edge_p
3735 (single_pred_edge (bb)))
3736 is_unreachable = 1;
3738 /* Handle
3739 if (x_7 >= 10 && x_7 < 20)
3740 __builtin_unreachable ();
3741 x_8 = ASSERT_EXPR <x_7, ...>;
3742 if the only uses of x_7 are in the ASSERT_EXPR and
3743 in the condition. In that case, we can copy the
3744 range info from x_8 computed in this pass also
3745 for x_7. */
3746 if (is_unreachable
3747 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
3748 single_pred (bb)))
3750 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
3751 SSA_NAME_RANGE_INFO (lhs)->get_min (),
3752 SSA_NAME_RANGE_INFO (lhs)->get_max ());
3753 maybe_set_nonzero_bits (single_pred_edge (bb), var);
3757 /* Propagate the RHS into every use of the LHS. For SSA names
3758 also propagate abnormals as it merely restores the original
3759 IL in this case (an replace_uses_by would assert). */
3760 if (TREE_CODE (var) == SSA_NAME)
3762 imm_use_iterator iter;
3763 use_operand_p use_p;
3764 gimple *use_stmt;
3765 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
3766 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
3767 SET_USE (use_p, var);
3769 else
3770 replace_uses_by (lhs, var);
3772 /* And finally, remove the copy, it is not needed. */
3773 gsi_remove (&si, true);
3774 release_defs (stmt);
3776 else
3778 if (!is_gimple_debug (gsi_stmt (si)))
3779 is_unreachable = 0;
3780 gsi_next (&si);
3785 class vrp_prop : public ssa_propagation_engine
3787 public:
3788 vrp_prop (vr_values *v)
3789 : ssa_propagation_engine (),
3790 m_vr_values (v) { }
3792 void initialize (struct function *);
3793 void finalize ();
3795 private:
3796 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
3797 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
3799 struct function *fun;
3800 vr_values *m_vr_values;
3803 /* Initialization required by ssa_propagate engine. */
3805 void
3806 vrp_prop::initialize (struct function *fn)
3808 basic_block bb;
3809 fun = fn;
3811 FOR_EACH_BB_FN (bb, fun)
3813 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3814 gsi_next (&si))
3816 gphi *phi = si.phi ();
3817 if (!stmt_interesting_for_vrp (phi))
3819 tree lhs = PHI_RESULT (phi);
3820 m_vr_values->set_def_to_varying (lhs);
3821 prop_set_simulate_again (phi, false);
3823 else
3824 prop_set_simulate_again (phi, true);
3827 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
3828 gsi_next (&si))
3830 gimple *stmt = gsi_stmt (si);
3832 /* If the statement is a control insn, then we do not
3833 want to avoid simulating the statement once. Failure
3834 to do so means that those edges will never get added. */
3835 if (stmt_ends_bb_p (stmt))
3836 prop_set_simulate_again (stmt, true);
3837 else if (!stmt_interesting_for_vrp (stmt))
3839 m_vr_values->set_defs_to_varying (stmt);
3840 prop_set_simulate_again (stmt, false);
3842 else
3843 prop_set_simulate_again (stmt, true);
3848 /* Evaluate statement STMT. If the statement produces a useful range,
3849 return SSA_PROP_INTERESTING and record the SSA name with the
3850 interesting range into *OUTPUT_P.
3852 If STMT is a conditional branch and we can determine its truth
3853 value, the taken edge is recorded in *TAKEN_EDGE_P.
3855 If STMT produces a varying value, return SSA_PROP_VARYING. */
3857 enum ssa_prop_result
3858 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
3860 tree lhs = gimple_get_lhs (stmt);
3861 value_range_equiv vr;
3862 m_vr_values->extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
3864 if (*output_p)
3866 if (m_vr_values->update_value_range (*output_p, &vr))
3868 if (dump_file && (dump_flags & TDF_DETAILS))
3870 fprintf (dump_file, "Found new range for ");
3871 print_generic_expr (dump_file, *output_p);
3872 fprintf (dump_file, ": ");
3873 dump_value_range (dump_file, &vr);
3874 fprintf (dump_file, "\n");
3877 if (vr.varying_p ())
3878 return SSA_PROP_VARYING;
3880 return SSA_PROP_INTERESTING;
3882 return SSA_PROP_NOT_INTERESTING;
3885 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
3886 switch (gimple_call_internal_fn (stmt))
3888 case IFN_ADD_OVERFLOW:
3889 case IFN_SUB_OVERFLOW:
3890 case IFN_MUL_OVERFLOW:
3891 case IFN_ATOMIC_COMPARE_EXCHANGE:
3892 /* These internal calls return _Complex integer type,
3893 which VRP does not track, but the immediate uses
3894 thereof might be interesting. */
3895 if (lhs && TREE_CODE (lhs) == SSA_NAME)
3897 imm_use_iterator iter;
3898 use_operand_p use_p;
3899 enum ssa_prop_result res = SSA_PROP_VARYING;
3901 m_vr_values->set_def_to_varying (lhs);
3903 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
3905 gimple *use_stmt = USE_STMT (use_p);
3906 if (!is_gimple_assign (use_stmt))
3907 continue;
3908 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
3909 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
3910 continue;
3911 tree rhs1 = gimple_assign_rhs1 (use_stmt);
3912 tree use_lhs = gimple_assign_lhs (use_stmt);
3913 if (TREE_CODE (rhs1) != rhs_code
3914 || TREE_OPERAND (rhs1, 0) != lhs
3915 || TREE_CODE (use_lhs) != SSA_NAME
3916 || !stmt_interesting_for_vrp (use_stmt)
3917 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
3918 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
3919 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
3920 continue;
3922 /* If there is a change in the value range for any of the
3923 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
3924 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
3925 or IMAGPART_EXPR immediate uses, but none of them have
3926 a change in their value ranges, return
3927 SSA_PROP_NOT_INTERESTING. If there are no
3928 {REAL,IMAG}PART_EXPR uses at all,
3929 return SSA_PROP_VARYING. */
3930 value_range_equiv new_vr;
3931 m_vr_values->extract_range_basic (&new_vr, use_stmt);
3932 const value_range_equiv *old_vr
3933 = m_vr_values->get_value_range (use_lhs);
3934 if (!old_vr->equal_p (new_vr, /*ignore_equivs=*/false))
3935 res = SSA_PROP_INTERESTING;
3936 else
3937 res = SSA_PROP_NOT_INTERESTING;
3938 new_vr.equiv_clear ();
3939 if (res == SSA_PROP_INTERESTING)
3941 *output_p = lhs;
3942 return res;
3946 return res;
3948 break;
3949 default:
3950 break;
3953 /* All other statements produce nothing of interest for VRP, so mark
3954 their outputs varying and prevent further simulation. */
3955 m_vr_values->set_defs_to_varying (stmt);
3957 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
3960 /* Visit all arguments for PHI node PHI that flow through executable
3961 edges. If a valid value range can be derived from all the incoming
3962 value ranges, set a new range for the LHS of PHI. */
3964 enum ssa_prop_result
3965 vrp_prop::visit_phi (gphi *phi)
3967 tree lhs = PHI_RESULT (phi);
3968 value_range_equiv vr_result;
3969 m_vr_values->extract_range_from_phi_node (phi, &vr_result);
3970 if (m_vr_values->update_value_range (lhs, &vr_result))
3972 if (dump_file && (dump_flags & TDF_DETAILS))
3974 fprintf (dump_file, "Found new range for ");
3975 print_generic_expr (dump_file, lhs);
3976 fprintf (dump_file, ": ");
3977 dump_value_range (dump_file, &vr_result);
3978 fprintf (dump_file, "\n");
3981 if (vr_result.varying_p ())
3982 return SSA_PROP_VARYING;
3984 return SSA_PROP_INTERESTING;
3987 /* Nothing changed, don't add outgoing edges. */
3988 return SSA_PROP_NOT_INTERESTING;
3991 /* Traverse all the blocks folding conditionals with known ranges. */
3993 void
3994 vrp_prop::finalize ()
3996 size_t i;
3998 /* We have completed propagating through the lattice. */
3999 m_vr_values->set_lattice_propagation_complete ();
4001 if (dump_file)
4003 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
4004 m_vr_values->dump (dump_file);
4005 fprintf (dump_file, "\n");
4008 /* Set value range to non pointer SSA_NAMEs. */
4009 for (i = 0; i < num_ssa_names; i++)
4011 tree name = ssa_name (i);
4012 if (!name)
4013 continue;
4015 const value_range_equiv *vr = m_vr_values->get_value_range (name);
4016 if (!name || vr->varying_p () || !vr->constant_p ())
4017 continue;
4019 if (POINTER_TYPE_P (TREE_TYPE (name))
4020 && range_includes_zero_p (vr) == 0)
4021 set_ptr_nonnull (name);
4022 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
4023 set_range_info (name, *vr);
4027 class vrp_folder : public substitute_and_fold_engine
4029 public:
4030 vrp_folder (vr_values *v)
4031 : substitute_and_fold_engine (/* Fold all stmts. */ true),
4032 m_vr_values (v), simplifier (v)
4034 void simplify_casted_conds (function *fun);
4036 private:
4037 tree value_of_expr (tree name, gimple *stmt) OVERRIDE
4039 return m_vr_values->value_of_expr (name, stmt);
4041 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
4042 bool fold_predicate_in (gimple_stmt_iterator *);
4044 vr_values *m_vr_values;
4045 simplify_using_ranges simplifier;
4048 /* If the statement pointed by SI has a predicate whose value can be
4049 computed using the value range information computed by VRP, compute
4050 its value and return true. Otherwise, return false. */
4052 bool
4053 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
4055 bool assignment_p = false;
4056 tree val;
4057 gimple *stmt = gsi_stmt (*si);
4059 if (is_gimple_assign (stmt)
4060 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
4062 assignment_p = true;
4063 val = simplifier.vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
4064 gimple_assign_rhs1 (stmt),
4065 gimple_assign_rhs2 (stmt),
4066 stmt);
4068 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
4069 val = simplifier.vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
4070 gimple_cond_lhs (cond_stmt),
4071 gimple_cond_rhs (cond_stmt),
4072 stmt);
4073 else
4074 return false;
4076 if (val)
4078 if (assignment_p)
4079 val = fold_convert (TREE_TYPE (gimple_assign_lhs (stmt)), val);
4081 if (dump_file)
4083 fprintf (dump_file, "Folding predicate ");
4084 print_gimple_expr (dump_file, stmt, 0);
4085 fprintf (dump_file, " to ");
4086 print_generic_expr (dump_file, val);
4087 fprintf (dump_file, "\n");
4090 if (is_gimple_assign (stmt))
4091 gimple_assign_set_rhs_from_tree (si, val);
4092 else
4094 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
4095 gcond *cond_stmt = as_a <gcond *> (stmt);
4096 if (integer_zerop (val))
4097 gimple_cond_make_false (cond_stmt);
4098 else if (integer_onep (val))
4099 gimple_cond_make_true (cond_stmt);
4100 else
4101 gcc_unreachable ();
4104 return true;
4107 return false;
4110 /* Callback for substitute_and_fold folding the stmt at *SI. */
4112 bool
4113 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
4115 if (fold_predicate_in (si))
4116 return true;
4118 return simplifier.simplify (si);
4121 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
4122 was set by a type conversion can often be rewritten to use the RHS
4123 of the type conversion. Do this optimization for all conditionals
4124 in FUN.
4126 However, doing so inhibits jump threading through the comparison.
4127 So that transformation is not performed until after jump threading
4128 is complete. */
4130 void
4131 vrp_folder::simplify_casted_conds (function *fun)
4133 basic_block bb;
4134 FOR_EACH_BB_FN (bb, fun)
4136 gimple *last = last_stmt (bb);
4137 if (last && gimple_code (last) == GIMPLE_COND)
4139 if (simplifier.simplify_casted_cond (as_a <gcond *> (last)))
4141 if (dump_file && (dump_flags & TDF_DETAILS))
4143 fprintf (dump_file, "Folded into: ");
4144 print_gimple_stmt (dump_file, last, 0, TDF_SLIM);
4145 fprintf (dump_file, "\n");
4152 /* Main entry point to VRP (Value Range Propagation). This pass is
4153 loosely based on J. R. C. Patterson, ``Accurate Static Branch
4154 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
4155 Programming Language Design and Implementation, pp. 67-78, 1995.
4156 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
4158 This is essentially an SSA-CCP pass modified to deal with ranges
4159 instead of constants.
4161 While propagating ranges, we may find that two or more SSA name
4162 have equivalent, though distinct ranges. For instance,
4164 1 x_9 = p_3->a;
4165 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
4166 3 if (p_4 == q_2)
4167 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
4168 5 endif
4169 6 if (q_2)
4171 In the code above, pointer p_5 has range [q_2, q_2], but from the
4172 code we can also determine that p_5 cannot be NULL and, if q_2 had
4173 a non-varying range, p_5's range should also be compatible with it.
4175 These equivalences are created by two expressions: ASSERT_EXPR and
4176 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
4177 result of another assertion, then we can use the fact that p_5 and
4178 p_4 are equivalent when evaluating p_5's range.
4180 Together with value ranges, we also propagate these equivalences
4181 between names so that we can take advantage of information from
4182 multiple ranges when doing final replacement. Note that this
4183 equivalency relation is transitive but not symmetric.
4185 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
4186 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
4187 in contexts where that assertion does not hold (e.g., in line 6).
4189 TODO, the main difference between this pass and Patterson's is that
4190 we do not propagate edge probabilities. We only compute whether
4191 edges can be taken or not. That is, instead of having a spectrum
4192 of jump probabilities between 0 and 1, we only deal with 0, 1 and
4193 DON'T KNOW. In the future, it may be worthwhile to propagate
4194 probabilities to aid branch prediction. */
4196 static unsigned int
4197 execute_vrp (struct function *fun, bool warn_array_bounds_p)
4199 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
4200 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
4201 scev_initialize ();
4203 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
4204 Inserting assertions may split edges which will invalidate
4205 EDGE_DFS_BACK. */
4206 vrp_asserts assert_engine (fun);
4207 assert_engine.insert_range_assertions ();
4209 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
4210 mark_dfs_back_edges ();
4212 vr_values vrp_vr_values;
4214 class vrp_prop vrp_prop (&vrp_vr_values);
4215 vrp_prop.initialize (fun);
4216 vrp_prop.ssa_propagate ();
4218 /* Instantiate the folder here, so that edge cleanups happen at the
4219 end of this function. */
4220 vrp_folder folder (&vrp_vr_values);
4221 vrp_prop.finalize ();
4223 /* If we're checking array refs, we want to merge information on
4224 the executability of each edge between vrp_folder and the
4225 check_array_bounds_dom_walker: each can clear the
4226 EDGE_EXECUTABLE flag on edges, in different ways.
4228 Hence, if we're going to call check_all_array_refs, set
4229 the flag on every edge now, rather than in
4230 check_array_bounds_dom_walker's ctor; vrp_folder may clear
4231 it from some edges. */
4232 if (warn_array_bounds && warn_array_bounds_p)
4233 set_all_edges_as_executable (fun);
4235 folder.substitute_and_fold ();
4237 if (warn_array_bounds && warn_array_bounds_p)
4239 array_bounds_checker array_checker (fun, &vrp_vr_values);
4240 array_checker.check ();
4243 folder.simplify_casted_conds (fun);
4245 free_numbers_of_iterations_estimates (fun);
4247 /* ASSERT_EXPRs must be removed before finalizing jump threads
4248 as finalizing jump threads calls the CFG cleanup code which
4249 does not properly handle ASSERT_EXPRs. */
4250 assert_engine.remove_range_assertions ();
4252 scev_finalize ();
4253 loop_optimizer_finalize ();
4254 return 0;
4257 // This is a ranger based folder which continues to use the dominator
4258 // walk to access the substitute and fold machinery. Ranges are calculated
4259 // on demand.
4261 class rvrp_folder : public substitute_and_fold_engine
4263 public:
4265 rvrp_folder (gimple_ranger *r) : substitute_and_fold_engine (),
4266 m_simplifier (r, r->non_executable_edge_flag)
4268 m_ranger = r;
4269 m_pta = new pointer_equiv_analyzer (m_ranger);
4272 ~rvrp_folder ()
4274 delete m_pta;
4277 tree value_of_expr (tree name, gimple *s = NULL) OVERRIDE
4279 // Shortcircuit subst_and_fold callbacks for abnormal ssa_names.
4280 if (TREE_CODE (name) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
4281 return NULL;
4282 tree ret = m_ranger->value_of_expr (name, s);
4283 if (!ret && supported_pointer_equiv_p (name))
4284 ret = m_pta->get_equiv (name);
4285 return ret;
4288 tree value_on_edge (edge e, tree name) OVERRIDE
4290 // Shortcircuit subst_and_fold callbacks for abnormal ssa_names.
4291 if (TREE_CODE (name) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
4292 return NULL;
4293 tree ret = m_ranger->value_on_edge (e, name);
4294 if (!ret && supported_pointer_equiv_p (name))
4295 ret = m_pta->get_equiv (name);
4296 return ret;
4299 tree value_of_stmt (gimple *s, tree name = NULL) OVERRIDE
4301 // Shortcircuit subst_and_fold callbacks for abnormal ssa_names.
4302 if (TREE_CODE (name) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
4303 return NULL;
4304 return m_ranger->value_of_stmt (s, name);
4307 void pre_fold_bb (basic_block bb) OVERRIDE
4309 m_pta->enter (bb);
4312 void post_fold_bb (basic_block bb) OVERRIDE
4314 m_pta->leave (bb);
4317 void pre_fold_stmt (gimple *stmt) OVERRIDE
4319 m_pta->visit_stmt (stmt);
4322 bool fold_stmt (gimple_stmt_iterator *gsi) OVERRIDE
4324 if (m_simplifier.simplify (gsi))
4325 return true;
4326 return m_ranger->fold_stmt (gsi, follow_single_use_edges);
4329 private:
4330 DISABLE_COPY_AND_ASSIGN (rvrp_folder);
4331 gimple_ranger *m_ranger;
4332 simplify_using_ranges m_simplifier;
4333 pointer_equiv_analyzer *m_pta;
4336 /* Main entry point for a VRP pass using just ranger. This can be called
4337 from anywhere to perform a VRP pass, including from EVRP. */
4339 unsigned int
4340 execute_ranger_vrp (struct function *fun, bool warn_array_bounds_p)
4342 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
4343 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
4344 scev_initialize ();
4345 calculate_dominance_info (CDI_DOMINATORS);
4347 gimple_ranger *ranger = enable_ranger (fun);
4348 rvrp_folder folder (ranger);
4349 folder.substitute_and_fold ();
4350 ranger->export_global_ranges ();
4351 if (dump_file && (dump_flags & TDF_DETAILS))
4352 ranger->dump (dump_file);
4354 if (warn_array_bounds && warn_array_bounds_p)
4356 // Set all edges as executable, except those ranger says aren't.
4357 int non_exec_flag = ranger->non_executable_edge_flag;
4358 basic_block bb;
4359 FOR_ALL_BB_FN (bb, fun)
4361 edge_iterator ei;
4362 edge e;
4363 FOR_EACH_EDGE (e, ei, bb->succs)
4364 if (e->flags & non_exec_flag)
4365 e->flags &= ~EDGE_EXECUTABLE;
4366 else
4367 e->flags |= EDGE_EXECUTABLE;
4369 scev_reset ();
4370 array_bounds_checker array_checker (fun, ranger);
4371 array_checker.check ();
4374 disable_ranger (fun);
4375 scev_finalize ();
4376 loop_optimizer_finalize ();
4377 return 0;
4380 namespace {
4382 const pass_data pass_data_vrp =
4384 GIMPLE_PASS, /* type */
4385 "vrp", /* name */
4386 OPTGROUP_NONE, /* optinfo_flags */
4387 TV_TREE_VRP, /* tv_id */
4388 PROP_ssa, /* properties_required */
4389 0, /* properties_provided */
4390 0, /* properties_destroyed */
4391 0, /* todo_flags_start */
4392 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
4395 static int vrp_pass_num = 0;
4396 class pass_vrp : public gimple_opt_pass
4398 public:
4399 pass_vrp (gcc::context *ctxt)
4400 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false),
4401 my_pass (++vrp_pass_num)
4404 /* opt_pass methods: */
4405 opt_pass * clone () { return new pass_vrp (m_ctxt); }
4406 void set_pass_param (unsigned int n, bool param)
4408 gcc_assert (n == 0);
4409 warn_array_bounds_p = param;
4411 virtual bool gate (function *) { return flag_tree_vrp != 0; }
4412 virtual unsigned int execute (function *fun)
4414 if ((my_pass == 1 && param_vrp1_mode == VRP_MODE_RANGER)
4415 || (my_pass == 2 && param_vrp2_mode == VRP_MODE_RANGER))
4416 return execute_ranger_vrp (fun, warn_array_bounds_p);
4417 return execute_vrp (fun, warn_array_bounds_p);
4420 private:
4421 bool warn_array_bounds_p;
4422 int my_pass;
4423 }; // class pass_vrp
4425 } // anon namespace
4427 gimple_opt_pass *
4428 make_pass_vrp (gcc::context *ctxt)
4430 return new pass_vrp (ctxt);
4433 // This is the dom walker for the hybrid threader. The reason this is
4434 // here, as opposed to the generic threading files, is because the
4435 // other client would be DOM, and they have their own custom walker.
4437 class hybrid_threader : public dom_walker
4439 public:
4440 hybrid_threader ();
4441 ~hybrid_threader ();
4443 void thread_jumps (function *fun)
4445 walk (fun->cfg->x_entry_block_ptr);
4447 bool thread_through_all_blocks ()
4449 return m_threader->thread_through_all_blocks (false);
4452 private:
4453 edge before_dom_children (basic_block) override;
4454 void after_dom_children (basic_block bb) override;
4456 hybrid_jt_simplifier *m_simplifier;
4457 jump_threader *m_threader;
4458 jt_state *m_state;
4459 gimple_ranger *m_ranger;
4460 path_range_query *m_query;
4463 hybrid_threader::hybrid_threader () : dom_walker (CDI_DOMINATORS, REACHABLE_BLOCKS)
4465 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
4466 scev_initialize ();
4467 calculate_dominance_info (CDI_DOMINATORS);
4468 mark_dfs_back_edges ();
4470 m_ranger = new gimple_ranger;
4471 m_query = new path_range_query (*m_ranger, /*resolve=*/true);
4472 m_simplifier = new hybrid_jt_simplifier (m_ranger, m_query);
4473 m_state = new hybrid_jt_state;
4474 m_threader = new jump_threader (m_simplifier, m_state);
4477 hybrid_threader::~hybrid_threader ()
4479 delete m_simplifier;
4480 delete m_threader;
4481 delete m_state;
4482 delete m_ranger;
4483 delete m_query;
4485 scev_finalize ();
4486 loop_optimizer_finalize ();
4489 edge
4490 hybrid_threader::before_dom_children (basic_block bb)
4492 gimple_stmt_iterator gsi;
4493 int_range<2> r;
4495 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4497 gimple *stmt = gsi_stmt (gsi);
4498 m_ranger->range_of_stmt (r, stmt);
4500 return NULL;
4503 void
4504 hybrid_threader::after_dom_children (basic_block bb)
4506 m_threader->thread_outgoing_edges (bb);
4509 static unsigned int
4510 execute_vrp_threader (function *fun)
4512 hybrid_threader threader;
4513 threader.thread_jumps (fun);
4514 if (threader.thread_through_all_blocks ())
4515 return (TODO_cleanup_cfg | TODO_update_ssa);
4516 return 0;
4519 namespace {
4521 const pass_data pass_data_vrp_threader =
4523 GIMPLE_PASS, /* type */
4524 "vrp-thread", /* name */
4525 OPTGROUP_NONE, /* optinfo_flags */
4526 TV_TREE_VRP_THREADER, /* tv_id */
4527 PROP_ssa, /* properties_required */
4528 0, /* properties_provided */
4529 0, /* properties_destroyed */
4530 0, /* todo_flags_start */
4531 0 /* todo_flags_finish */
4534 class pass_vrp_threader : public gimple_opt_pass
4536 public:
4537 pass_vrp_threader (gcc::context *ctxt)
4538 : gimple_opt_pass (pass_data_vrp_threader, ctxt)
4541 /* opt_pass methods: */
4542 opt_pass * clone () { return new pass_vrp_threader (m_ctxt); }
4543 virtual bool gate (function *) { return flag_tree_vrp != 0; }
4544 virtual unsigned int execute (function *fun)
4545 { return execute_vrp_threader (fun); }
4548 } // namespace {
4550 gimple_opt_pass *
4551 make_pass_vrp_threader (gcc::context *ctxt)
4553 return new pass_vrp_threader (ctxt);