]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/tree-vrp.c
Enforce canonicalization in value_range.
[thirdparty/gcc.git] / gcc / tree-vrp.c
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2019 Free Software Foundation, Inc.
3 Contributed by Diego Novillo <dnovillo@redhat.com>.
4
5 This file is part of GCC.
6
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.
11
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.
16
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/>. */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "insn-codes.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "cfghooks.h"
30 #include "tree-pass.h"
31 #include "ssa.h"
32 #include "optabs-tree.h"
33 #include "gimple-pretty-print.h"
34 #include "diagnostic-core.h"
35 #include "flags.h"
36 #include "fold-const.h"
37 #include "stor-layout.h"
38 #include "calls.h"
39 #include "cfganal.h"
40 #include "gimple-fold.h"
41 #include "tree-eh.h"
42 #include "gimple-iterator.h"
43 #include "gimple-walk.h"
44 #include "tree-cfg.h"
45 #include "tree-dfa.h"
46 #include "tree-ssa-loop-manip.h"
47 #include "tree-ssa-loop-niter.h"
48 #include "tree-ssa-loop.h"
49 #include "tree-into-ssa.h"
50 #include "tree-ssa.h"
51 #include "intl.h"
52 #include "cfgloop.h"
53 #include "tree-scalar-evolution.h"
54 #include "tree-ssa-propagate.h"
55 #include "tree-chrec.h"
56 #include "tree-ssa-threadupdate.h"
57 #include "tree-ssa-scopedtables.h"
58 #include "tree-ssa-threadedge.h"
59 #include "omp-general.h"
60 #include "target.h"
61 #include "case-cfn-macros.h"
62 #include "params.h"
63 #include "alloc-pool.h"
64 #include "domwalk.h"
65 #include "tree-cfgcleanup.h"
66 #include "stringpool.h"
67 #include "attribs.h"
68 #include "vr-values.h"
69 #include "builtins.h"
70 #include "wide-int-range.h"
71
72 static bool
73 ranges_from_anti_range (const value_range_base *ar,
74 value_range_base *vr0, value_range_base *vr1,
75 bool handle_pointers = false);
76
77 /* Set of SSA names found live during the RPO traversal of the function
78 for still active basic-blocks. */
79 static sbitmap *live;
80
81 void
82 value_range::set_equiv (bitmap equiv)
83 {
84 if (undefined_p () || varying_p ())
85 equiv = NULL;
86 /* Since updating the equivalence set involves deep copying the
87 bitmaps, only do it if absolutely necessary.
88
89 All equivalence bitmaps are allocated from the same obstack. So
90 we can use the obstack associated with EQUIV to allocate vr->equiv. */
91 if (m_equiv == NULL
92 && equiv != NULL)
93 m_equiv = BITMAP_ALLOC (equiv->obstack);
94
95 if (equiv != m_equiv)
96 {
97 if (equiv && !bitmap_empty_p (equiv))
98 bitmap_copy (m_equiv, equiv);
99 else
100 bitmap_clear (m_equiv);
101 }
102 }
103
104 /* Initialize value_range. */
105
106 void
107 value_range::set (enum value_range_kind kind, tree min, tree max,
108 bitmap equiv)
109 {
110 value_range_base::set (kind, min, max);
111 set_equiv (equiv);
112 if (flag_checking)
113 check ();
114 }
115
116 value_range_base::value_range_base (value_range_kind kind, tree min, tree max)
117 {
118 set (kind, min, max);
119 }
120
121 value_range::value_range (value_range_kind kind, tree min, tree max,
122 bitmap equiv)
123 {
124 m_equiv = NULL;
125 set (kind, min, max, equiv);
126 }
127
128 value_range::value_range (const value_range_base &other)
129 {
130 m_equiv = NULL;
131 set (other.kind (), other.min(), other.max (), NULL);
132 }
133
134 /* Like set, but keep the equivalences in place. */
135
136 void
137 value_range::update (value_range_kind kind, tree min, tree max)
138 {
139 set (kind, min, max,
140 (kind != VR_UNDEFINED && kind != VR_VARYING) ? m_equiv : NULL);
141 }
142
143 /* Copy value_range in FROM into THIS while avoiding bitmap sharing.
144
145 Note: The code that avoids the bitmap sharing looks at the existing
146 this->m_equiv, so this function cannot be used to initalize an
147 object. Use the constructors for initialization. */
148
149 void
150 value_range::deep_copy (const value_range *from)
151 {
152 set (from->m_kind, from->min (), from->max (), from->m_equiv);
153 }
154
155 void
156 value_range::move (value_range *from)
157 {
158 set (from->m_kind, from->min (), from->max ());
159 m_equiv = from->m_equiv;
160 from->m_equiv = NULL;
161 }
162
163 /* Check the validity of the range. */
164
165 void
166 value_range_base::check ()
167 {
168 switch (m_kind)
169 {
170 case VR_RANGE:
171 case VR_ANTI_RANGE:
172 {
173 int cmp;
174
175 gcc_assert (m_min && m_max);
176
177 gcc_assert (!TREE_OVERFLOW_P (m_min) && !TREE_OVERFLOW_P (m_max));
178
179 /* Creating ~[-MIN, +MAX] is stupid because that would be
180 the empty set. */
181 if (INTEGRAL_TYPE_P (TREE_TYPE (m_min)) && m_kind == VR_ANTI_RANGE)
182 gcc_assert (!vrp_val_is_min (m_min) || !vrp_val_is_max (m_max));
183
184 cmp = compare_values (m_min, m_max);
185 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
186 break;
187 }
188 case VR_UNDEFINED:
189 case VR_VARYING:
190 gcc_assert (!min () && !max ());
191 break;
192 default:
193 gcc_unreachable ();
194 }
195 }
196
197 void
198 value_range::check ()
199 {
200 value_range_base::check ();
201 switch (m_kind)
202 {
203 case VR_UNDEFINED:
204 case VR_VARYING:
205 gcc_assert (!m_equiv || bitmap_empty_p (m_equiv));
206 default:;
207 }
208 }
209
210 /* Equality operator. We purposely do not overload ==, to avoid
211 confusion with the equality bitmap in the derived value_range
212 class. */
213
214 bool
215 value_range_base::equal_p (const value_range_base &other) const
216 {
217 return (m_kind == other.m_kind
218 && vrp_operand_equal_p (m_min, other.m_min)
219 && vrp_operand_equal_p (m_max, other.m_max));
220 }
221
222 /* Returns TRUE if THIS == OTHER. Ignores the equivalence bitmap if
223 IGNORE_EQUIVS is TRUE. */
224
225 bool
226 value_range::equal_p (const value_range &other, bool ignore_equivs) const
227 {
228 return (value_range_base::equal_p (other)
229 && (ignore_equivs
230 || vrp_bitmap_equal_p (m_equiv, other.m_equiv)));
231 }
232
233 /* Return TRUE if this is a symbolic range. */
234
235 bool
236 value_range_base::symbolic_p () const
237 {
238 return (!varying_p ()
239 && !undefined_p ()
240 && (!is_gimple_min_invariant (m_min)
241 || !is_gimple_min_invariant (m_max)));
242 }
243
244 /* NOTE: This is not the inverse of symbolic_p because the range
245 could also be varying or undefined. Ideally they should be inverse
246 of each other, with varying only applying to symbolics. Varying of
247 constants would be represented as [-MIN, +MAX]. */
248
249 bool
250 value_range_base::constant_p () const
251 {
252 return (!varying_p ()
253 && !undefined_p ()
254 && TREE_CODE (m_min) == INTEGER_CST
255 && TREE_CODE (m_max) == INTEGER_CST);
256 }
257
258 void
259 value_range_base::set_undefined ()
260 {
261 m_kind = VR_UNDEFINED;
262 m_min = m_max = NULL;
263 }
264
265 void
266 value_range::set_undefined ()
267 {
268 set (VR_UNDEFINED, NULL, NULL, NULL);
269 }
270
271 void
272 value_range_base::set_varying ()
273 {
274 m_kind = VR_VARYING;
275 m_min = m_max = NULL;
276 }
277
278 void
279 value_range::set_varying ()
280 {
281 set (VR_VARYING, NULL, NULL, NULL);
282 }
283
284 /* Return TRUE if it is possible that range contains VAL. */
285
286 bool
287 value_range_base::may_contain_p (tree val) const
288 {
289 return value_inside_range (val) != 0;
290 }
291
292 void
293 value_range::equiv_clear ()
294 {
295 if (m_equiv)
296 bitmap_clear (m_equiv);
297 }
298
299 /* Add VAR and VAR's equivalence set (VAR_VR) to the equivalence
300 bitmap. If no equivalence table has been created, OBSTACK is the
301 obstack to use (NULL for the default obstack).
302
303 This is the central point where equivalence processing can be
304 turned on/off. */
305
306 void
307 value_range::equiv_add (const_tree var,
308 const value_range *var_vr,
309 bitmap_obstack *obstack)
310 {
311 if (!m_equiv)
312 m_equiv = BITMAP_ALLOC (obstack);
313 unsigned ver = SSA_NAME_VERSION (var);
314 bitmap_set_bit (m_equiv, ver);
315 if (var_vr && var_vr->m_equiv)
316 bitmap_ior_into (m_equiv, var_vr->m_equiv);
317 }
318
319 /* If range is a singleton, place it in RESULT and return TRUE.
320 Note: A singleton can be any gimple invariant, not just constants.
321 So, [&x, &x] counts as a singleton. */
322
323 bool
324 value_range_base::singleton_p (tree *result) const
325 {
326 if (m_kind == VR_ANTI_RANGE)
327 {
328 if (nonzero_p ())
329 {
330 if (TYPE_PRECISION (type ()) == 1)
331 {
332 if (result)
333 *result = m_max;
334 return true;
335 }
336 return false;
337 }
338
339 value_range_base vr0, vr1;
340 return (ranges_from_anti_range (this, &vr0, &vr1, true)
341 && vr1.undefined_p ()
342 && vr0.singleton_p (result));
343 }
344 if (m_kind == VR_RANGE
345 && vrp_operand_equal_p (min (), max ())
346 && is_gimple_min_invariant (min ()))
347 {
348 if (result)
349 *result = min ();
350 return true;
351 }
352 return false;
353 }
354
355 tree
356 value_range_base::type () const
357 {
358 /* Types are only valid for VR_RANGE and VR_ANTI_RANGE, which are
359 known to have non-zero min/max. */
360 gcc_assert (min ());
361 return TREE_TYPE (min ());
362 }
363
364 void
365 value_range_base::dump (FILE *file) const
366 {
367 if (undefined_p ())
368 fprintf (file, "UNDEFINED");
369 else if (m_kind == VR_RANGE || m_kind == VR_ANTI_RANGE)
370 {
371 tree ttype = type ();
372
373 print_generic_expr (file, ttype);
374 fprintf (file, " ");
375
376 fprintf (file, "%s[", (m_kind == VR_ANTI_RANGE) ? "~" : "");
377
378 if (INTEGRAL_TYPE_P (ttype)
379 && !TYPE_UNSIGNED (ttype)
380 && vrp_val_is_min (min ())
381 && TYPE_PRECISION (ttype) != 1)
382 fprintf (file, "-INF");
383 else
384 print_generic_expr (file, min ());
385
386 fprintf (file, ", ");
387
388 if (INTEGRAL_TYPE_P (ttype)
389 && vrp_val_is_max (max ())
390 && TYPE_PRECISION (ttype) != 1)
391 fprintf (file, "+INF");
392 else
393 print_generic_expr (file, max ());
394
395 fprintf (file, "]");
396 }
397 else if (varying_p ())
398 fprintf (file, "VARYING");
399 else
400 gcc_unreachable ();
401 }
402
403 void
404 value_range::dump (FILE *file) const
405 {
406 value_range_base::dump (file);
407 if ((m_kind == VR_RANGE || m_kind == VR_ANTI_RANGE)
408 && m_equiv)
409 {
410 bitmap_iterator bi;
411 unsigned i, c = 0;
412
413 fprintf (file, " EQUIVALENCES: { ");
414
415 EXECUTE_IF_SET_IN_BITMAP (m_equiv, 0, i, bi)
416 {
417 print_generic_expr (file, ssa_name (i));
418 fprintf (file, " ");
419 c++;
420 }
421
422 fprintf (file, "} (%u elements)", c);
423 }
424 }
425
426 void
427 dump_value_range (FILE *file, const value_range *vr)
428 {
429 if (!vr)
430 fprintf (file, "[]");
431 else
432 vr->dump (file);
433 }
434
435 void
436 dump_value_range (FILE *file, const value_range_base *vr)
437 {
438 if (!vr)
439 fprintf (file, "[]");
440 else
441 vr->dump (file);
442 }
443
444 DEBUG_FUNCTION void
445 debug (const value_range_base *vr)
446 {
447 dump_value_range (stderr, vr);
448 }
449
450 DEBUG_FUNCTION void
451 debug (const value_range_base &vr)
452 {
453 dump_value_range (stderr, &vr);
454 }
455
456 DEBUG_FUNCTION void
457 debug (const value_range *vr)
458 {
459 dump_value_range (stderr, vr);
460 }
461
462 DEBUG_FUNCTION void
463 debug (const value_range &vr)
464 {
465 dump_value_range (stderr, &vr);
466 }
467
468 /* Return true if the SSA name NAME is live on the edge E. */
469
470 static bool
471 live_on_edge (edge e, tree name)
472 {
473 return (live[e->dest->index]
474 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
475 }
476
477 /* Location information for ASSERT_EXPRs. Each instance of this
478 structure describes an ASSERT_EXPR for an SSA name. Since a single
479 SSA name may have more than one assertion associated with it, these
480 locations are kept in a linked list attached to the corresponding
481 SSA name. */
482 struct assert_locus
483 {
484 /* Basic block where the assertion would be inserted. */
485 basic_block bb;
486
487 /* Some assertions need to be inserted on an edge (e.g., assertions
488 generated by COND_EXPRs). In those cases, BB will be NULL. */
489 edge e;
490
491 /* Pointer to the statement that generated this assertion. */
492 gimple_stmt_iterator si;
493
494 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
495 enum tree_code comp_code;
496
497 /* Value being compared against. */
498 tree val;
499
500 /* Expression to compare. */
501 tree expr;
502
503 /* Next node in the linked list. */
504 assert_locus *next;
505 };
506
507 /* If bit I is present, it means that SSA name N_i has a list of
508 assertions that should be inserted in the IL. */
509 static bitmap need_assert_for;
510
511 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
512 holds a list of ASSERT_LOCUS_T nodes that describe where
513 ASSERT_EXPRs for SSA name N_I should be inserted. */
514 static assert_locus **asserts_for;
515
516 /* Return the maximum value for TYPE. */
517
518 tree
519 vrp_val_max (const_tree type, bool handle_pointers)
520 {
521 if (INTEGRAL_TYPE_P (type))
522 return TYPE_MAX_VALUE (type);
523 if (POINTER_TYPE_P (type) && handle_pointers)
524 {
525 wide_int max = wi::max_value (TYPE_PRECISION (type), TYPE_SIGN (type));
526 return wide_int_to_tree (const_cast<tree> (type), max);
527 }
528 return NULL_TREE;
529 }
530
531 /* Return the minimum value for TYPE. */
532
533 tree
534 vrp_val_min (const_tree type, bool handle_pointers)
535 {
536 if (INTEGRAL_TYPE_P (type))
537 return TYPE_MIN_VALUE (type);
538 if (POINTER_TYPE_P (type) && handle_pointers)
539 return build_zero_cst (const_cast<tree> (type));
540 return NULL_TREE;
541 }
542
543 /* Return whether VAL is equal to the maximum value of its type.
544 We can't do a simple equality comparison with TYPE_MAX_VALUE because
545 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
546 is not == to the integer constant with the same value in the type. */
547
548 bool
549 vrp_val_is_max (const_tree val)
550 {
551 tree type_max = vrp_val_max (TREE_TYPE (val));
552 return (val == type_max
553 || (type_max != NULL_TREE
554 && operand_equal_p (val, type_max, 0)));
555 }
556
557 /* Return whether VAL is equal to the minimum value of its type. */
558
559 bool
560 vrp_val_is_min (const_tree val)
561 {
562 tree type_min = vrp_val_min (TREE_TYPE (val));
563 return (val == type_min
564 || (type_min != NULL_TREE
565 && operand_equal_p (val, type_min, 0)));
566 }
567
568 /* VR_TYPE describes a range with mininum value *MIN and maximum
569 value *MAX. Restrict the range to the set of values that have
570 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
571 return the new range type.
572
573 SGN gives the sign of the values described by the range. */
574
575 enum value_range_kind
576 intersect_range_with_nonzero_bits (enum value_range_kind vr_type,
577 wide_int *min, wide_int *max,
578 const wide_int &nonzero_bits,
579 signop sgn)
580 {
581 if (vr_type == VR_ANTI_RANGE)
582 {
583 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
584 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
585 to create an inclusive upper bound for A and an inclusive lower
586 bound for B. */
587 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
588 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
589
590 /* If the calculation of A_MAX wrapped, A is effectively empty
591 and A_MAX is the highest value that satisfies NONZERO_BITS.
592 Likewise if the calculation of B_MIN wrapped, B is effectively
593 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
594 bool a_empty = wi::ge_p (a_max, *min, sgn);
595 bool b_empty = wi::le_p (b_min, *max, sgn);
596
597 /* If both A and B are empty, there are no valid values. */
598 if (a_empty && b_empty)
599 return VR_UNDEFINED;
600
601 /* If exactly one of A or B is empty, return a VR_RANGE for the
602 other one. */
603 if (a_empty || b_empty)
604 {
605 *min = b_min;
606 *max = a_max;
607 gcc_checking_assert (wi::le_p (*min, *max, sgn));
608 return VR_RANGE;
609 }
610
611 /* Update the VR_ANTI_RANGE bounds. */
612 *min = a_max + 1;
613 *max = b_min - 1;
614 gcc_checking_assert (wi::le_p (*min, *max, sgn));
615
616 /* Now check whether the excluded range includes any values that
617 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
618 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
619 {
620 unsigned int precision = min->get_precision ();
621 *min = wi::min_value (precision, sgn);
622 *max = wi::max_value (precision, sgn);
623 vr_type = VR_RANGE;
624 }
625 }
626 if (vr_type == VR_RANGE)
627 {
628 *max = wi::round_down_for_mask (*max, nonzero_bits);
629
630 /* Check that the range contains at least one valid value. */
631 if (wi::gt_p (*min, *max, sgn))
632 return VR_UNDEFINED;
633
634 *min = wi::round_up_for_mask (*min, nonzero_bits);
635 gcc_checking_assert (wi::le_p (*min, *max, sgn));
636 }
637 return vr_type;
638 }
639
640
641 /* Set value range to the canonical form of {VRTYPE, MIN, MAX, EQUIV}.
642 This means adjusting VRTYPE, MIN and MAX representing the case of a
643 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
644 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
645 In corner cases where MAX+1 or MIN-1 wraps this will fall back
646 to varying.
647 This routine exists to ease canonicalization in the case where we
648 extract ranges from var + CST op limit. */
649
650 void
651 value_range_base::set (enum value_range_kind kind, tree min, tree max)
652 {
653 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
654 if (kind == VR_UNDEFINED)
655 {
656 set_undefined ();
657 return;
658 }
659 else if (kind == VR_VARYING)
660 {
661 set_varying ();
662 return;
663 }
664
665 /* Nothing to canonicalize for symbolic ranges. */
666 if (TREE_CODE (min) != INTEGER_CST
667 || TREE_CODE (max) != INTEGER_CST)
668 {
669 m_kind = kind;
670 m_min = min;
671 m_max = max;
672 return;
673 }
674
675 /* Wrong order for min and max, to swap them and the VR type we need
676 to adjust them. */
677 if (tree_int_cst_lt (max, min))
678 {
679 tree one, tmp;
680
681 /* For one bit precision if max < min, then the swapped
682 range covers all values, so for VR_RANGE it is varying and
683 for VR_ANTI_RANGE empty range, so drop to varying as well. */
684 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
685 {
686 set_varying ();
687 return;
688 }
689
690 one = build_int_cst (TREE_TYPE (min), 1);
691 tmp = int_const_binop (PLUS_EXPR, max, one);
692 max = int_const_binop (MINUS_EXPR, min, one);
693 min = tmp;
694
695 /* There's one corner case, if we had [C+1, C] before we now have
696 that again. But this represents an empty value range, so drop
697 to varying in this case. */
698 if (tree_int_cst_lt (max, min))
699 {
700 set_varying ();
701 return;
702 }
703
704 kind = kind == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
705 }
706
707 tree type = TREE_TYPE (min);
708
709 /* Anti-ranges that can be represented as ranges should be so. */
710 if (kind == VR_ANTI_RANGE)
711 {
712 /* For -fstrict-enums we may receive out-of-range ranges so consider
713 values < -INF and values > INF as -INF/INF as well. */
714 bool is_min = (INTEGRAL_TYPE_P (type)
715 && tree_int_cst_compare (min, TYPE_MIN_VALUE (type)) <= 0);
716 bool is_max = (INTEGRAL_TYPE_P (type)
717 && tree_int_cst_compare (max, TYPE_MAX_VALUE (type)) >= 0);
718
719 if (is_min && is_max)
720 {
721 /* We cannot deal with empty ranges, drop to varying.
722 ??? This could be VR_UNDEFINED instead. */
723 set_varying ();
724 return;
725 }
726 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
727 && (is_min || is_max))
728 {
729 /* Non-empty boolean ranges can always be represented
730 as a singleton range. */
731 if (is_min)
732 min = max = vrp_val_max (TREE_TYPE (min));
733 else
734 min = max = vrp_val_min (TREE_TYPE (min));
735 kind = VR_RANGE;
736 }
737 else if (is_min
738 /* As a special exception preserve non-null ranges. */
739 && !(TYPE_UNSIGNED (TREE_TYPE (min))
740 && integer_zerop (max)))
741 {
742 tree one = build_int_cst (TREE_TYPE (max), 1);
743 min = int_const_binop (PLUS_EXPR, max, one);
744 max = vrp_val_max (TREE_TYPE (max));
745 kind = VR_RANGE;
746 }
747 else if (is_max)
748 {
749 tree one = build_int_cst (TREE_TYPE (min), 1);
750 max = int_const_binop (MINUS_EXPR, min, one);
751 min = vrp_val_min (TREE_TYPE (min));
752 kind = VR_RANGE;
753 }
754 }
755
756 /* Normalize [MIN, MAX] into VARYING and ~[MIN, MAX] into UNDEFINED.
757
758 Avoid using TYPE_{MIN,MAX}_VALUE because -fstrict-enums can
759 restrict those to a subset of what actually fits in the type.
760 Instead use the extremes of the type precision which will allow
761 compare_range_with_value() to check if a value is inside a range,
762 whereas if we used TYPE_*_VAL, said function would just punt
763 upon seeing a VARYING. */
764 unsigned prec = TYPE_PRECISION (type);
765 signop sign = TYPE_SIGN (type);
766 if (wi::eq_p (wi::to_wide (min), wi::min_value (prec, sign))
767 && wi::eq_p (wi::to_wide (max), wi::max_value (prec, sign)))
768 {
769 if (kind == VR_RANGE)
770 set_varying ();
771 else if (kind == VR_ANTI_RANGE)
772 set_undefined ();
773 else
774 gcc_unreachable ();
775 return;
776 }
777
778 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
779 to make sure VRP iteration terminates, otherwise we can get into
780 oscillations. */
781
782 m_kind = kind;
783 m_min = min;
784 m_max = max;
785 if (flag_checking)
786 check ();
787 }
788
789 void
790 value_range_base::set (tree val)
791 {
792 gcc_assert (TREE_CODE (val) == SSA_NAME || is_gimple_min_invariant (val));
793 if (TREE_OVERFLOW_P (val))
794 val = drop_tree_overflow (val);
795 set (VR_RANGE, val, val);
796 }
797
798 void
799 value_range::set (tree val)
800 {
801 gcc_assert (TREE_CODE (val) == SSA_NAME || is_gimple_min_invariant (val));
802 if (TREE_OVERFLOW_P (val))
803 val = drop_tree_overflow (val);
804 set (VR_RANGE, val, val, NULL);
805 }
806
807 /* Set value range VR to a nonzero range of type TYPE. */
808
809 void
810 value_range_base::set_nonzero (tree type)
811 {
812 tree zero = build_int_cst (type, 0);
813 set (VR_ANTI_RANGE, zero, zero);
814 }
815
816 /* Set value range VR to a ZERO range of type TYPE. */
817
818 void
819 value_range_base::set_zero (tree type)
820 {
821 set (build_int_cst (type, 0));
822 }
823
824 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
825
826 bool
827 vrp_operand_equal_p (const_tree val1, const_tree val2)
828 {
829 if (val1 == val2)
830 return true;
831 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
832 return false;
833 return true;
834 }
835
836 /* Return true, if the bitmaps B1 and B2 are equal. */
837
838 bool
839 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
840 {
841 return (b1 == b2
842 || ((!b1 || bitmap_empty_p (b1))
843 && (!b2 || bitmap_empty_p (b2)))
844 || (b1 && b2
845 && bitmap_equal_p (b1, b2)));
846 }
847
848 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
849 a singleton. */
850
851 bool
852 range_int_cst_p (const value_range_base *vr)
853 {
854 return (vr->kind () == VR_RANGE
855 && TREE_CODE (vr->min ()) == INTEGER_CST
856 && TREE_CODE (vr->max ()) == INTEGER_CST);
857 }
858
859 /* Return true if VR is a INTEGER_CST singleton. */
860
861 bool
862 range_int_cst_singleton_p (const value_range_base *vr)
863 {
864 return (range_int_cst_p (vr)
865 && tree_int_cst_equal (vr->min (), vr->max ()));
866 }
867
868 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
869 otherwise. We only handle additive operations and set NEG to true if the
870 symbol is negated and INV to the invariant part, if any. */
871
872 tree
873 get_single_symbol (tree t, bool *neg, tree *inv)
874 {
875 bool neg_;
876 tree inv_;
877
878 *inv = NULL_TREE;
879 *neg = false;
880
881 if (TREE_CODE (t) == PLUS_EXPR
882 || TREE_CODE (t) == POINTER_PLUS_EXPR
883 || TREE_CODE (t) == MINUS_EXPR)
884 {
885 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
886 {
887 neg_ = (TREE_CODE (t) == MINUS_EXPR);
888 inv_ = TREE_OPERAND (t, 0);
889 t = TREE_OPERAND (t, 1);
890 }
891 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
892 {
893 neg_ = false;
894 inv_ = TREE_OPERAND (t, 1);
895 t = TREE_OPERAND (t, 0);
896 }
897 else
898 return NULL_TREE;
899 }
900 else
901 {
902 neg_ = false;
903 inv_ = NULL_TREE;
904 }
905
906 if (TREE_CODE (t) == NEGATE_EXPR)
907 {
908 t = TREE_OPERAND (t, 0);
909 neg_ = !neg_;
910 }
911
912 if (TREE_CODE (t) != SSA_NAME)
913 return NULL_TREE;
914
915 if (inv_ && TREE_OVERFLOW_P (inv_))
916 inv_ = drop_tree_overflow (inv_);
917
918 *neg = neg_;
919 *inv = inv_;
920 return t;
921 }
922
923 /* The reverse operation: build a symbolic expression with TYPE
924 from symbol SYM, negated according to NEG, and invariant INV. */
925
926 static tree
927 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
928 {
929 const bool pointer_p = POINTER_TYPE_P (type);
930 tree t = sym;
931
932 if (neg)
933 t = build1 (NEGATE_EXPR, type, t);
934
935 if (integer_zerop (inv))
936 return t;
937
938 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
939 }
940
941 /* Return
942 1 if VAL < VAL2
943 0 if !(VAL < VAL2)
944 -2 if those are incomparable. */
945 int
946 operand_less_p (tree val, tree val2)
947 {
948 /* LT is folded faster than GE and others. Inline the common case. */
949 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
950 return tree_int_cst_lt (val, val2);
951 else if (TREE_CODE (val) == SSA_NAME && TREE_CODE (val2) == SSA_NAME)
952 return val == val2 ? 0 : -2;
953 else
954 {
955 int cmp = compare_values (val, val2);
956 if (cmp == -1)
957 return 1;
958 else if (cmp == 0 || cmp == 1)
959 return 0;
960 else
961 return -2;
962 }
963
964 return 0;
965 }
966
967 /* Compare two values VAL1 and VAL2. Return
968
969 -2 if VAL1 and VAL2 cannot be compared at compile-time,
970 -1 if VAL1 < VAL2,
971 0 if VAL1 == VAL2,
972 +1 if VAL1 > VAL2, and
973 +2 if VAL1 != VAL2
974
975 This is similar to tree_int_cst_compare but supports pointer values
976 and values that cannot be compared at compile time.
977
978 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
979 true if the return value is only valid if we assume that signed
980 overflow is undefined. */
981
982 int
983 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
984 {
985 if (val1 == val2)
986 return 0;
987
988 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
989 both integers. */
990 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
991 == POINTER_TYPE_P (TREE_TYPE (val2)));
992
993 /* Convert the two values into the same type. This is needed because
994 sizetype causes sign extension even for unsigned types. */
995 if (!useless_type_conversion_p (TREE_TYPE (val1), TREE_TYPE (val2)))
996 val2 = fold_convert (TREE_TYPE (val1), val2);
997
998 const bool overflow_undefined
999 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
1000 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
1001 tree inv1, inv2;
1002 bool neg1, neg2;
1003 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
1004 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
1005
1006 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
1007 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
1008 if (sym1 && sym2)
1009 {
1010 /* Both values must use the same name with the same sign. */
1011 if (sym1 != sym2 || neg1 != neg2)
1012 return -2;
1013
1014 /* [-]NAME + CST == [-]NAME + CST. */
1015 if (inv1 == inv2)
1016 return 0;
1017
1018 /* If overflow is defined we cannot simplify more. */
1019 if (!overflow_undefined)
1020 return -2;
1021
1022 if (strict_overflow_p != NULL
1023 /* Symbolic range building sets TREE_NO_WARNING to declare
1024 that overflow doesn't happen. */
1025 && (!inv1 || !TREE_NO_WARNING (val1))
1026 && (!inv2 || !TREE_NO_WARNING (val2)))
1027 *strict_overflow_p = true;
1028
1029 if (!inv1)
1030 inv1 = build_int_cst (TREE_TYPE (val1), 0);
1031 if (!inv2)
1032 inv2 = build_int_cst (TREE_TYPE (val2), 0);
1033
1034 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
1035 TYPE_SIGN (TREE_TYPE (val1)));
1036 }
1037
1038 const bool cst1 = is_gimple_min_invariant (val1);
1039 const bool cst2 = is_gimple_min_invariant (val2);
1040
1041 /* If one is of the form '[-]NAME + CST' and the other is constant, then
1042 it might be possible to say something depending on the constants. */
1043 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
1044 {
1045 if (!overflow_undefined)
1046 return -2;
1047
1048 if (strict_overflow_p != NULL
1049 /* Symbolic range building sets TREE_NO_WARNING to declare
1050 that overflow doesn't happen. */
1051 && (!sym1 || !TREE_NO_WARNING (val1))
1052 && (!sym2 || !TREE_NO_WARNING (val2)))
1053 *strict_overflow_p = true;
1054
1055 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
1056 tree cst = cst1 ? val1 : val2;
1057 tree inv = cst1 ? inv2 : inv1;
1058
1059 /* Compute the difference between the constants. If it overflows or
1060 underflows, this means that we can trivially compare the NAME with
1061 it and, consequently, the two values with each other. */
1062 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
1063 if (wi::cmp (0, wi::to_wide (inv), sgn)
1064 != wi::cmp (diff, wi::to_wide (cst), sgn))
1065 {
1066 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
1067 return cst1 ? res : -res;
1068 }
1069
1070 return -2;
1071 }
1072
1073 /* We cannot say anything more for non-constants. */
1074 if (!cst1 || !cst2)
1075 return -2;
1076
1077 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1078 {
1079 /* We cannot compare overflowed values. */
1080 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1081 return -2;
1082
1083 if (TREE_CODE (val1) == INTEGER_CST
1084 && TREE_CODE (val2) == INTEGER_CST)
1085 return tree_int_cst_compare (val1, val2);
1086
1087 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
1088 {
1089 if (known_eq (wi::to_poly_widest (val1),
1090 wi::to_poly_widest (val2)))
1091 return 0;
1092 if (known_lt (wi::to_poly_widest (val1),
1093 wi::to_poly_widest (val2)))
1094 return -1;
1095 if (known_gt (wi::to_poly_widest (val1),
1096 wi::to_poly_widest (val2)))
1097 return 1;
1098 }
1099
1100 return -2;
1101 }
1102 else
1103 {
1104 if (TREE_CODE (val1) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
1105 {
1106 /* We cannot compare overflowed values. */
1107 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1108 return -2;
1109
1110 return tree_int_cst_compare (val1, val2);
1111 }
1112
1113 /* First see if VAL1 and VAL2 are not the same. */
1114 if (operand_equal_p (val1, val2, 0))
1115 return 0;
1116
1117 fold_defer_overflow_warnings ();
1118
1119 /* If VAL1 is a lower address than VAL2, return -1. */
1120 tree t = fold_binary_to_constant (LT_EXPR, boolean_type_node, val1, val2);
1121 if (t && integer_onep (t))
1122 {
1123 fold_undefer_and_ignore_overflow_warnings ();
1124 return -1;
1125 }
1126
1127 /* If VAL1 is a higher address than VAL2, return +1. */
1128 t = fold_binary_to_constant (LT_EXPR, boolean_type_node, val2, val1);
1129 if (t && integer_onep (t))
1130 {
1131 fold_undefer_and_ignore_overflow_warnings ();
1132 return 1;
1133 }
1134
1135 /* If VAL1 is different than VAL2, return +2. */
1136 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1137 fold_undefer_and_ignore_overflow_warnings ();
1138 if (t && integer_onep (t))
1139 return 2;
1140
1141 return -2;
1142 }
1143 }
1144
1145 /* Compare values like compare_values_warnv. */
1146
1147 int
1148 compare_values (tree val1, tree val2)
1149 {
1150 bool sop;
1151 return compare_values_warnv (val1, val2, &sop);
1152 }
1153
1154
1155 /* Return 1 if VAL is inside value range.
1156 0 if VAL is not inside value range.
1157 -2 if we cannot tell either way.
1158
1159 Benchmark compile/20001226-1.c compilation time after changing this
1160 function. */
1161
1162 int
1163 value_range_base::value_inside_range (tree val) const
1164 {
1165 int cmp1, cmp2;
1166
1167 if (varying_p ())
1168 return 1;
1169
1170 if (undefined_p ())
1171 return 0;
1172
1173 cmp1 = operand_less_p (val, m_min);
1174 if (cmp1 == -2)
1175 return -2;
1176 if (cmp1 == 1)
1177 return m_kind != VR_RANGE;
1178
1179 cmp2 = operand_less_p (m_max, val);
1180 if (cmp2 == -2)
1181 return -2;
1182
1183 if (m_kind == VR_RANGE)
1184 return !cmp2;
1185 else
1186 return !!cmp2;
1187 }
1188
1189 /* Value range wrapper for wide_int_range_set_zero_nonzero_bits.
1190
1191 Compute MAY_BE_NONZERO and MUST_BE_NONZERO bit masks for range in VR.
1192
1193 Return TRUE if VR was a constant range and we were able to compute
1194 the bit masks. */
1195
1196 bool
1197 vrp_set_zero_nonzero_bits (const tree expr_type,
1198 const value_range_base *vr,
1199 wide_int *may_be_nonzero,
1200 wide_int *must_be_nonzero)
1201 {
1202 if (!range_int_cst_p (vr))
1203 {
1204 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1205 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1206 return false;
1207 }
1208 wide_int_range_set_zero_nonzero_bits (TYPE_SIGN (expr_type),
1209 wi::to_wide (vr->min ()),
1210 wi::to_wide (vr->max ()),
1211 *may_be_nonzero, *must_be_nonzero);
1212 return true;
1213 }
1214
1215 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
1216 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
1217 false otherwise. If *AR can be represented with a single range
1218 *VR1 will be VR_UNDEFINED. */
1219
1220 static bool
1221 ranges_from_anti_range (const value_range_base *ar,
1222 value_range_base *vr0, value_range_base *vr1,
1223 bool handle_pointers)
1224 {
1225 tree type = ar->type ();
1226
1227 vr0->set_undefined ();
1228 vr1->set_undefined ();
1229
1230 /* As a future improvement, we could handle ~[0, A] as: [-INF, -1] U
1231 [A+1, +INF]. Not sure if this helps in practice, though. */
1232
1233 if (ar->kind () != VR_ANTI_RANGE
1234 || TREE_CODE (ar->min ()) != INTEGER_CST
1235 || TREE_CODE (ar->max ()) != INTEGER_CST
1236 || !vrp_val_min (type, handle_pointers)
1237 || !vrp_val_max (type, handle_pointers))
1238 return false;
1239
1240 if (tree_int_cst_lt (vrp_val_min (type, handle_pointers), ar->min ()))
1241 vr0->set (VR_RANGE,
1242 vrp_val_min (type, handle_pointers),
1243 wide_int_to_tree (type, wi::to_wide (ar->min ()) - 1));
1244 if (tree_int_cst_lt (ar->max (), vrp_val_max (type, handle_pointers)))
1245 vr1->set (VR_RANGE,
1246 wide_int_to_tree (type, wi::to_wide (ar->max ()) + 1),
1247 vrp_val_max (type, handle_pointers));
1248 if (vr0->undefined_p ())
1249 {
1250 *vr0 = *vr1;
1251 vr1->set_undefined ();
1252 }
1253
1254 return !vr0->undefined_p ();
1255 }
1256
1257 /* Extract the components of a value range into a pair of wide ints in
1258 [WMIN, WMAX], after having normalized any symbolics from the input. */
1259
1260 static void inline
1261 extract_range_into_wide_ints (const value_range_base *vr_,
1262 tree type, wide_int &wmin, wide_int &wmax)
1263 {
1264 signop sign = TYPE_SIGN (type);
1265 unsigned int prec = TYPE_PRECISION (type);
1266 gcc_assert (vr_->kind () != VR_ANTI_RANGE || vr_->symbolic_p ());
1267 value_range vr = vr_->normalize_symbolics ();
1268 if (range_int_cst_p (&vr))
1269 {
1270 wmin = wi::to_wide (vr.min ());
1271 wmax = wi::to_wide (vr.max ());
1272 }
1273 else
1274 {
1275 wmin = wi::min_value (prec, sign);
1276 wmax = wi::max_value (prec, sign);
1277 }
1278 }
1279
1280 /* Value range wrapper for wide_int_range_multiplicative_op:
1281
1282 *VR = *VR0 .CODE. *VR1. */
1283
1284 static void
1285 extract_range_from_multiplicative_op (value_range_base *vr,
1286 enum tree_code code, tree type,
1287 const value_range_base *vr0,
1288 const value_range_base *vr1)
1289 {
1290 gcc_assert (code == MULT_EXPR
1291 || code == TRUNC_DIV_EXPR
1292 || code == FLOOR_DIV_EXPR
1293 || code == CEIL_DIV_EXPR
1294 || code == EXACT_DIV_EXPR
1295 || code == ROUND_DIV_EXPR
1296 || code == RSHIFT_EXPR
1297 || code == LSHIFT_EXPR);
1298 if (!range_int_cst_p (vr1))
1299 {
1300 vr->set_varying ();
1301 return;
1302 }
1303
1304 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1305 useful ranges just from the shift count. E.g.
1306 x >> 63 for signed 64-bit x is always [-1, 0]. */
1307 value_range_base tem = vr0->normalize_symbolics ();
1308 tree vr0_min, vr0_max;
1309 if (tem.kind () == VR_RANGE)
1310 {
1311 vr0_min = tem.min ();
1312 vr0_max = tem.max ();
1313 }
1314 else
1315 {
1316 vr0_min = vrp_val_min (type);
1317 vr0_max = vrp_val_max (type);
1318 }
1319
1320 wide_int res_lb, res_ub;
1321 wide_int vr0_lb = wi::to_wide (vr0_min);
1322 wide_int vr0_ub = wi::to_wide (vr0_max);
1323 wide_int vr1_lb = wi::to_wide (vr1->min ());
1324 wide_int vr1_ub = wi::to_wide (vr1->max ());
1325 bool overflow_undefined = TYPE_OVERFLOW_UNDEFINED (type);
1326 unsigned prec = TYPE_PRECISION (type);
1327
1328 if (wide_int_range_multiplicative_op (res_lb, res_ub,
1329 code, TYPE_SIGN (type), prec,
1330 vr0_lb, vr0_ub, vr1_lb, vr1_ub,
1331 overflow_undefined))
1332 vr->set (VR_RANGE, wide_int_to_tree (type, res_lb),
1333 wide_int_to_tree (type, res_ub));
1334 else
1335 vr->set_varying ();
1336 }
1337
1338 /* If BOUND will include a symbolic bound, adjust it accordingly,
1339 otherwise leave it as is.
1340
1341 CODE is the original operation that combined the bounds (PLUS_EXPR
1342 or MINUS_EXPR).
1343
1344 TYPE is the type of the original operation.
1345
1346 SYM_OPn is the symbolic for OPn if it has a symbolic.
1347
1348 NEG_OPn is TRUE if the OPn was negated. */
1349
1350 static void
1351 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
1352 tree sym_op0, tree sym_op1,
1353 bool neg_op0, bool neg_op1)
1354 {
1355 bool minus_p = (code == MINUS_EXPR);
1356 /* If the result bound is constant, we're done; otherwise, build the
1357 symbolic lower bound. */
1358 if (sym_op0 == sym_op1)
1359 ;
1360 else if (sym_op0)
1361 bound = build_symbolic_expr (type, sym_op0,
1362 neg_op0, bound);
1363 else if (sym_op1)
1364 {
1365 /* We may not negate if that might introduce
1366 undefined overflow. */
1367 if (!minus_p
1368 || neg_op1
1369 || TYPE_OVERFLOW_WRAPS (type))
1370 bound = build_symbolic_expr (type, sym_op1,
1371 neg_op1 ^ minus_p, bound);
1372 else
1373 bound = NULL_TREE;
1374 }
1375 }
1376
1377 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
1378 int bound according to CODE. CODE is the operation combining the
1379 bound (either a PLUS_EXPR or a MINUS_EXPR).
1380
1381 TYPE is the type of the combine operation.
1382
1383 WI is the wide int to store the result.
1384
1385 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
1386 if over/underflow occurred. */
1387
1388 static void
1389 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
1390 tree type, tree op0, tree op1)
1391 {
1392 bool minus_p = (code == MINUS_EXPR);
1393 const signop sgn = TYPE_SIGN (type);
1394 const unsigned int prec = TYPE_PRECISION (type);
1395
1396 /* Combine the bounds, if any. */
1397 if (op0 && op1)
1398 {
1399 if (minus_p)
1400 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1401 else
1402 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1403 }
1404 else if (op0)
1405 wi = wi::to_wide (op0);
1406 else if (op1)
1407 {
1408 if (minus_p)
1409 wi = wi::neg (wi::to_wide (op1), &ovf);
1410 else
1411 wi = wi::to_wide (op1);
1412 }
1413 else
1414 wi = wi::shwi (0, prec);
1415 }
1416
1417 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1418 put the result in VR.
1419
1420 TYPE is the type of the range.
1421
1422 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1423 occurred while originally calculating WMIN or WMAX. -1 indicates
1424 underflow. +1 indicates overflow. 0 indicates neither. */
1425
1426 static void
1427 set_value_range_with_overflow (value_range_kind &kind, tree &min, tree &max,
1428 tree type,
1429 const wide_int &wmin, const wide_int &wmax,
1430 wi::overflow_type min_ovf,
1431 wi::overflow_type max_ovf)
1432 {
1433 const signop sgn = TYPE_SIGN (type);
1434 const unsigned int prec = TYPE_PRECISION (type);
1435
1436 /* For one bit precision if max < min, then the swapped
1437 range covers all values. */
1438 if (prec == 1 && wi::lt_p (wmax, wmin, sgn))
1439 {
1440 kind = VR_VARYING;
1441 return;
1442 }
1443
1444 if (TYPE_OVERFLOW_WRAPS (type))
1445 {
1446 /* If overflow wraps, truncate the values and adjust the
1447 range kind and bounds appropriately. */
1448 wide_int tmin = wide_int::from (wmin, prec, sgn);
1449 wide_int tmax = wide_int::from (wmax, prec, sgn);
1450 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
1451 {
1452 /* If the limits are swapped, we wrapped around and cover
1453 the entire range. We have a similar check at the end of
1454 extract_range_from_binary_expr. */
1455 if (wi::gt_p (tmin, tmax, sgn))
1456 kind = VR_VARYING;
1457 else
1458 {
1459 kind = VR_RANGE;
1460 /* No overflow or both overflow or underflow. The
1461 range kind stays VR_RANGE. */
1462 min = wide_int_to_tree (type, tmin);
1463 max = wide_int_to_tree (type, tmax);
1464 }
1465 return;
1466 }
1467 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
1468 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
1469 {
1470 /* Min underflow or max overflow. The range kind
1471 changes to VR_ANTI_RANGE. */
1472 bool covers = false;
1473 wide_int tem = tmin;
1474 tmin = tmax + 1;
1475 if (wi::cmp (tmin, tmax, sgn) < 0)
1476 covers = true;
1477 tmax = tem - 1;
1478 if (wi::cmp (tmax, tem, sgn) > 0)
1479 covers = true;
1480 /* If the anti-range would cover nothing, drop to varying.
1481 Likewise if the anti-range bounds are outside of the
1482 types values. */
1483 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1484 {
1485 kind = VR_VARYING;
1486 return;
1487 }
1488 kind = VR_ANTI_RANGE;
1489 min = wide_int_to_tree (type, tmin);
1490 max = wide_int_to_tree (type, tmax);
1491 return;
1492 }
1493 else
1494 {
1495 /* Other underflow and/or overflow, drop to VR_VARYING. */
1496 kind = VR_VARYING;
1497 return;
1498 }
1499 }
1500 else
1501 {
1502 /* If overflow does not wrap, saturate to the types min/max
1503 value. */
1504 wide_int type_min = wi::min_value (prec, sgn);
1505 wide_int type_max = wi::max_value (prec, sgn);
1506 kind = VR_RANGE;
1507 if (min_ovf == wi::OVF_UNDERFLOW)
1508 min = wide_int_to_tree (type, type_min);
1509 else if (min_ovf == wi::OVF_OVERFLOW)
1510 min = wide_int_to_tree (type, type_max);
1511 else
1512 min = wide_int_to_tree (type, wmin);
1513
1514 if (max_ovf == wi::OVF_UNDERFLOW)
1515 max = wide_int_to_tree (type, type_min);
1516 else if (max_ovf == wi::OVF_OVERFLOW)
1517 max = wide_int_to_tree (type, type_max);
1518 else
1519 max = wide_int_to_tree (type, wmax);
1520 }
1521 }
1522
1523 /* Extract range information from a binary operation CODE based on
1524 the ranges of each of its operands *VR0 and *VR1 with resulting
1525 type EXPR_TYPE. The resulting range is stored in *VR. */
1526
1527 void
1528 extract_range_from_binary_expr (value_range_base *vr,
1529 enum tree_code code, tree expr_type,
1530 const value_range_base *vr0_,
1531 const value_range_base *vr1_)
1532 {
1533 signop sign = TYPE_SIGN (expr_type);
1534 unsigned int prec = TYPE_PRECISION (expr_type);
1535 value_range_base vr0 = *vr0_, vr1 = *vr1_;
1536 value_range_base vrtem0, vrtem1;
1537 enum value_range_kind type;
1538 tree min = NULL_TREE, max = NULL_TREE;
1539 int cmp;
1540
1541 if (!INTEGRAL_TYPE_P (expr_type)
1542 && !POINTER_TYPE_P (expr_type))
1543 {
1544 vr->set_varying ();
1545 return;
1546 }
1547
1548 /* Not all binary expressions can be applied to ranges in a
1549 meaningful way. Handle only arithmetic operations. */
1550 if (code != PLUS_EXPR
1551 && code != MINUS_EXPR
1552 && code != POINTER_PLUS_EXPR
1553 && code != MULT_EXPR
1554 && code != TRUNC_DIV_EXPR
1555 && code != FLOOR_DIV_EXPR
1556 && code != CEIL_DIV_EXPR
1557 && code != EXACT_DIV_EXPR
1558 && code != ROUND_DIV_EXPR
1559 && code != TRUNC_MOD_EXPR
1560 && code != RSHIFT_EXPR
1561 && code != LSHIFT_EXPR
1562 && code != MIN_EXPR
1563 && code != MAX_EXPR
1564 && code != BIT_AND_EXPR
1565 && code != BIT_IOR_EXPR
1566 && code != BIT_XOR_EXPR)
1567 {
1568 vr->set_varying ();
1569 return;
1570 }
1571
1572 /* If both ranges are UNDEFINED, so is the result. */
1573 if (vr0.undefined_p () && vr1.undefined_p ())
1574 {
1575 vr->set_undefined ();
1576 return;
1577 }
1578 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1579 code. At some point we may want to special-case operations that
1580 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1581 operand. */
1582 else if (vr0.undefined_p ())
1583 vr0.set_varying ();
1584 else if (vr1.undefined_p ())
1585 vr1.set_varying ();
1586
1587 /* We get imprecise results from ranges_from_anti_range when
1588 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1589 range, but then we also need to hack up vrp_union. It's just
1590 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1591 if (code == EXACT_DIV_EXPR && vr0.nonzero_p ())
1592 {
1593 vr->set_nonzero (expr_type);
1594 return;
1595 }
1596
1597 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1598 and express ~[] op X as ([]' op X) U ([]'' op X). */
1599 if (vr0.kind () == VR_ANTI_RANGE
1600 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1601 {
1602 extract_range_from_binary_expr (vr, code, expr_type, &vrtem0, vr1_);
1603 if (!vrtem1.undefined_p ())
1604 {
1605 value_range_base vrres;
1606 extract_range_from_binary_expr (&vrres, code, expr_type,
1607 &vrtem1, vr1_);
1608 vr->union_ (&vrres);
1609 }
1610 return;
1611 }
1612 /* Likewise for X op ~[]. */
1613 if (vr1.kind () == VR_ANTI_RANGE
1614 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1615 {
1616 extract_range_from_binary_expr (vr, code, expr_type, vr0_, &vrtem0);
1617 if (!vrtem1.undefined_p ())
1618 {
1619 value_range_base vrres;
1620 extract_range_from_binary_expr (&vrres, code, expr_type,
1621 vr0_, &vrtem1);
1622 vr->union_ (&vrres);
1623 }
1624 return;
1625 }
1626
1627 /* The type of the resulting value range defaults to VR0.TYPE. */
1628 type = vr0.kind ();
1629
1630 /* Refuse to operate on VARYING ranges, ranges of different kinds
1631 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1632 because we may be able to derive a useful range even if one of
1633 the operands is VR_VARYING or symbolic range. Similarly for
1634 divisions, MIN/MAX and PLUS/MINUS.
1635
1636 TODO, we may be able to derive anti-ranges in some cases. */
1637 if (code != BIT_AND_EXPR
1638 && code != BIT_IOR_EXPR
1639 && code != TRUNC_DIV_EXPR
1640 && code != FLOOR_DIV_EXPR
1641 && code != CEIL_DIV_EXPR
1642 && code != EXACT_DIV_EXPR
1643 && code != ROUND_DIV_EXPR
1644 && code != TRUNC_MOD_EXPR
1645 && code != MIN_EXPR
1646 && code != MAX_EXPR
1647 && code != PLUS_EXPR
1648 && code != MINUS_EXPR
1649 && code != RSHIFT_EXPR
1650 && code != POINTER_PLUS_EXPR
1651 && (vr0.varying_p ()
1652 || vr1.varying_p ()
1653 || vr0.kind () != vr1.kind ()
1654 || vr0.symbolic_p ()
1655 || vr1.symbolic_p ()))
1656 {
1657 vr->set_varying ();
1658 return;
1659 }
1660
1661 /* Now evaluate the expression to determine the new range. */
1662 if (POINTER_TYPE_P (expr_type))
1663 {
1664 if (code == MIN_EXPR || code == MAX_EXPR)
1665 {
1666 /* For MIN/MAX expressions with pointers, we only care about
1667 nullness, if both are non null, then the result is nonnull.
1668 If both are null, then the result is null. Otherwise they
1669 are varying. */
1670 if (!range_includes_zero_p (&vr0) && !range_includes_zero_p (&vr1))
1671 vr->set_nonzero (expr_type);
1672 else if (vr0.zero_p () && vr1.zero_p ())
1673 vr->set_zero (expr_type);
1674 else
1675 vr->set_varying ();
1676 }
1677 else if (code == POINTER_PLUS_EXPR)
1678 {
1679 /* For pointer types, we are really only interested in asserting
1680 whether the expression evaluates to non-NULL.
1681 With -fno-delete-null-pointer-checks we need to be more
1682 conservative. As some object might reside at address 0,
1683 then some offset could be added to it and the same offset
1684 subtracted again and the result would be NULL.
1685 E.g.
1686 static int a[12]; where &a[0] is NULL and
1687 ptr = &a[6];
1688 ptr -= 6;
1689 ptr will be NULL here, even when there is POINTER_PLUS_EXPR
1690 where the first range doesn't include zero and the second one
1691 doesn't either. As the second operand is sizetype (unsigned),
1692 consider all ranges where the MSB could be set as possible
1693 subtractions where the result might be NULL. */
1694 if ((!range_includes_zero_p (&vr0)
1695 || !range_includes_zero_p (&vr1))
1696 && !TYPE_OVERFLOW_WRAPS (expr_type)
1697 && (flag_delete_null_pointer_checks
1698 || (range_int_cst_p (&vr1)
1699 && !tree_int_cst_sign_bit (vr1.max ()))))
1700 vr->set_nonzero (expr_type);
1701 else if (vr0.zero_p () && vr1.zero_p ())
1702 vr->set_zero (expr_type);
1703 else
1704 vr->set_varying ();
1705 }
1706 else if (code == BIT_AND_EXPR)
1707 {
1708 /* For pointer types, we are really only interested in asserting
1709 whether the expression evaluates to non-NULL. */
1710 if (!range_includes_zero_p (&vr0) && !range_includes_zero_p (&vr1))
1711 vr->set_nonzero (expr_type);
1712 else if (vr0.zero_p () || vr1.zero_p ())
1713 vr->set_zero (expr_type);
1714 else
1715 vr->set_varying ();
1716 }
1717 else
1718 vr->set_varying ();
1719
1720 return;
1721 }
1722
1723 /* For integer ranges, apply the operation to each end of the
1724 range and see what we end up with. */
1725 if (code == PLUS_EXPR || code == MINUS_EXPR)
1726 {
1727 value_range_kind vr0_kind = vr0.kind (), vr1_kind = vr1.kind ();
1728 tree vr0_min = vr0.min (), vr0_max = vr0.max ();
1729 tree vr1_min = vr1.min (), vr1_max = vr1.max ();
1730 /* This will normalize things such that calculating
1731 [0,0] - VR_VARYING is not dropped to varying, but is
1732 calculated as [MIN+1, MAX]. */
1733 if (vr0.varying_p ())
1734 {
1735 vr0_kind = VR_RANGE;
1736 vr0_min = vrp_val_min (expr_type);
1737 vr0_max = vrp_val_max (expr_type);
1738 }
1739 if (vr1.varying_p ())
1740 {
1741 vr1_kind = VR_RANGE;
1742 vr1_min = vrp_val_min (expr_type);
1743 vr1_max = vrp_val_max (expr_type);
1744 }
1745
1746 const bool minus_p = (code == MINUS_EXPR);
1747 tree min_op0 = vr0_min;
1748 tree min_op1 = minus_p ? vr1_max : vr1_min;
1749 tree max_op0 = vr0_max;
1750 tree max_op1 = minus_p ? vr1_min : vr1_max;
1751 tree sym_min_op0 = NULL_TREE;
1752 tree sym_min_op1 = NULL_TREE;
1753 tree sym_max_op0 = NULL_TREE;
1754 tree sym_max_op1 = NULL_TREE;
1755 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1756
1757 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1758
1759 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1760 single-symbolic ranges, try to compute the precise resulting range,
1761 but only if we know that this resulting range will also be constant
1762 or single-symbolic. */
1763 if (vr0_kind == VR_RANGE && vr1_kind == VR_RANGE
1764 && (TREE_CODE (min_op0) == INTEGER_CST
1765 || (sym_min_op0
1766 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1767 && (TREE_CODE (min_op1) == INTEGER_CST
1768 || (sym_min_op1
1769 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1770 && (!(sym_min_op0 && sym_min_op1)
1771 || (sym_min_op0 == sym_min_op1
1772 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1773 && (TREE_CODE (max_op0) == INTEGER_CST
1774 || (sym_max_op0
1775 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1776 && (TREE_CODE (max_op1) == INTEGER_CST
1777 || (sym_max_op1
1778 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1779 && (!(sym_max_op0 && sym_max_op1)
1780 || (sym_max_op0 == sym_max_op1
1781 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1782 {
1783 wide_int wmin, wmax;
1784 wi::overflow_type min_ovf = wi::OVF_NONE;
1785 wi::overflow_type max_ovf = wi::OVF_NONE;
1786
1787 /* Build the bounds. */
1788 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1789 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1790
1791 /* If we have overflow for the constant part and the resulting
1792 range will be symbolic, drop to VR_VARYING. */
1793 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1794 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1795 {
1796 vr->set_varying ();
1797 return;
1798 }
1799
1800 /* Adjust the range for possible overflow. */
1801 min = NULL_TREE;
1802 max = NULL_TREE;
1803 set_value_range_with_overflow (type, min, max, expr_type,
1804 wmin, wmax, min_ovf, max_ovf);
1805 if (type == VR_VARYING)
1806 {
1807 vr->set_varying ();
1808 return;
1809 }
1810
1811 /* Build the symbolic bounds if needed. */
1812 adjust_symbolic_bound (min, code, expr_type,
1813 sym_min_op0, sym_min_op1,
1814 neg_min_op0, neg_min_op1);
1815 adjust_symbolic_bound (max, code, expr_type,
1816 sym_max_op0, sym_max_op1,
1817 neg_max_op0, neg_max_op1);
1818 }
1819 else
1820 {
1821 /* For other cases, for example if we have a PLUS_EXPR with two
1822 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1823 to compute a precise range for such a case.
1824 ??? General even mixed range kind operations can be expressed
1825 by for example transforming ~[3, 5] + [1, 2] to range-only
1826 operations and a union primitive:
1827 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1828 [-INF+1, 4] U [6, +INF(OVF)]
1829 though usually the union is not exactly representable with
1830 a single range or anti-range as the above is
1831 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1832 but one could use a scheme similar to equivalences for this. */
1833 vr->set_varying ();
1834 return;
1835 }
1836 }
1837 else if (code == MIN_EXPR
1838 || code == MAX_EXPR)
1839 {
1840 wide_int wmin, wmax;
1841 wide_int vr0_min, vr0_max;
1842 wide_int vr1_min, vr1_max;
1843 extract_range_into_wide_ints (&vr0, expr_type, vr0_min, vr0_max);
1844 extract_range_into_wide_ints (&vr1, expr_type, vr1_min, vr1_max);
1845 if (wide_int_range_min_max (wmin, wmax, code, sign, prec,
1846 vr0_min, vr0_max, vr1_min, vr1_max))
1847 vr->set (VR_RANGE, wide_int_to_tree (expr_type, wmin),
1848 wide_int_to_tree (expr_type, wmax));
1849 else
1850 vr->set_varying ();
1851 return;
1852 }
1853 else if (code == MULT_EXPR)
1854 {
1855 if (!range_int_cst_p (&vr0)
1856 || !range_int_cst_p (&vr1))
1857 {
1858 vr->set_varying ();
1859 return;
1860 }
1861 extract_range_from_multiplicative_op (vr, code, expr_type, &vr0, &vr1);
1862 return;
1863 }
1864 else if (code == RSHIFT_EXPR
1865 || code == LSHIFT_EXPR)
1866 {
1867 if (range_int_cst_p (&vr1)
1868 && !wide_int_range_shift_undefined_p
1869 (TYPE_SIGN (TREE_TYPE (vr1.min ())),
1870 prec,
1871 wi::to_wide (vr1.min ()),
1872 wi::to_wide (vr1.max ())))
1873 {
1874 if (code == RSHIFT_EXPR)
1875 {
1876 extract_range_from_multiplicative_op (vr, code, expr_type,
1877 &vr0, &vr1);
1878 return;
1879 }
1880 else if (code == LSHIFT_EXPR
1881 && range_int_cst_p (&vr0))
1882 {
1883 wide_int res_lb, res_ub;
1884 if (wide_int_range_lshift (res_lb, res_ub, sign, prec,
1885 wi::to_wide (vr0.min ()),
1886 wi::to_wide (vr0.max ()),
1887 wi::to_wide (vr1.min ()),
1888 wi::to_wide (vr1.max ()),
1889 TYPE_OVERFLOW_UNDEFINED (expr_type)))
1890 {
1891 min = wide_int_to_tree (expr_type, res_lb);
1892 max = wide_int_to_tree (expr_type, res_ub);
1893 vr->set (VR_RANGE, min, max);
1894 return;
1895 }
1896 }
1897 }
1898 vr->set_varying ();
1899 return;
1900 }
1901 else if (code == TRUNC_DIV_EXPR
1902 || code == FLOOR_DIV_EXPR
1903 || code == CEIL_DIV_EXPR
1904 || code == EXACT_DIV_EXPR
1905 || code == ROUND_DIV_EXPR)
1906 {
1907 wide_int dividend_min, dividend_max, divisor_min, divisor_max;
1908 wide_int wmin, wmax, extra_min, extra_max;
1909 bool extra_range_p;
1910
1911 /* Special case explicit division by zero as undefined. */
1912 if (vr1.zero_p ())
1913 {
1914 vr->set_undefined ();
1915 return;
1916 }
1917
1918 /* First, normalize ranges into constants we can handle. Note
1919 that VR_ANTI_RANGE's of constants were already normalized
1920 before arriving here.
1921
1922 NOTE: As a future improvement, we may be able to do better
1923 with mixed symbolic (anti-)ranges like [0, A]. See note in
1924 ranges_from_anti_range. */
1925 extract_range_into_wide_ints (&vr0, expr_type,
1926 dividend_min, dividend_max);
1927 extract_range_into_wide_ints (&vr1, expr_type,
1928 divisor_min, divisor_max);
1929 if (!wide_int_range_div (wmin, wmax, code, sign, prec,
1930 dividend_min, dividend_max,
1931 divisor_min, divisor_max,
1932 TYPE_OVERFLOW_UNDEFINED (expr_type),
1933 extra_range_p, extra_min, extra_max))
1934 {
1935 vr->set_varying ();
1936 return;
1937 }
1938 vr->set (VR_RANGE, wide_int_to_tree (expr_type, wmin),
1939 wide_int_to_tree (expr_type, wmax));
1940 if (extra_range_p)
1941 {
1942 value_range_base
1943 extra_range (VR_RANGE, wide_int_to_tree (expr_type, extra_min),
1944 wide_int_to_tree (expr_type, extra_max));
1945 vr->union_ (&extra_range);
1946 }
1947 return;
1948 }
1949 else if (code == TRUNC_MOD_EXPR)
1950 {
1951 if (vr1.zero_p ())
1952 {
1953 vr->set_undefined ();
1954 return;
1955 }
1956 wide_int wmin, wmax, tmp;
1957 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1958 extract_range_into_wide_ints (&vr0, expr_type, vr0_min, vr0_max);
1959 extract_range_into_wide_ints (&vr1, expr_type, vr1_min, vr1_max);
1960 wide_int_range_trunc_mod (wmin, wmax, sign, prec,
1961 vr0_min, vr0_max, vr1_min, vr1_max);
1962 min = wide_int_to_tree (expr_type, wmin);
1963 max = wide_int_to_tree (expr_type, wmax);
1964 vr->set (VR_RANGE, min, max);
1965 return;
1966 }
1967 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
1968 {
1969 wide_int may_be_nonzero0, may_be_nonzero1;
1970 wide_int must_be_nonzero0, must_be_nonzero1;
1971 wide_int wmin, wmax;
1972 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1973 vrp_set_zero_nonzero_bits (expr_type, &vr0,
1974 &may_be_nonzero0, &must_be_nonzero0);
1975 vrp_set_zero_nonzero_bits (expr_type, &vr1,
1976 &may_be_nonzero1, &must_be_nonzero1);
1977 extract_range_into_wide_ints (&vr0, expr_type, vr0_min, vr0_max);
1978 extract_range_into_wide_ints (&vr1, expr_type, vr1_min, vr1_max);
1979 if (code == BIT_AND_EXPR)
1980 {
1981 if (wide_int_range_bit_and (wmin, wmax, sign, prec,
1982 vr0_min, vr0_max,
1983 vr1_min, vr1_max,
1984 must_be_nonzero0,
1985 may_be_nonzero0,
1986 must_be_nonzero1,
1987 may_be_nonzero1))
1988 {
1989 min = wide_int_to_tree (expr_type, wmin);
1990 max = wide_int_to_tree (expr_type, wmax);
1991 vr->set (VR_RANGE, min, max);
1992 }
1993 else
1994 vr->set_varying ();
1995 return;
1996 }
1997 else if (code == BIT_IOR_EXPR)
1998 {
1999 if (wide_int_range_bit_ior (wmin, wmax, sign,
2000 vr0_min, vr0_max,
2001 vr1_min, vr1_max,
2002 must_be_nonzero0,
2003 may_be_nonzero0,
2004 must_be_nonzero1,
2005 may_be_nonzero1))
2006 {
2007 min = wide_int_to_tree (expr_type, wmin);
2008 max = wide_int_to_tree (expr_type, wmax);
2009 vr->set (VR_RANGE, min, max);
2010 }
2011 else
2012 vr->set_varying ();
2013 return;
2014 }
2015 else if (code == BIT_XOR_EXPR)
2016 {
2017 if (wide_int_range_bit_xor (wmin, wmax, sign, prec,
2018 must_be_nonzero0,
2019 may_be_nonzero0,
2020 must_be_nonzero1,
2021 may_be_nonzero1))
2022 {
2023 min = wide_int_to_tree (expr_type, wmin);
2024 max = wide_int_to_tree (expr_type, wmax);
2025 vr->set (VR_RANGE, min, max);
2026 }
2027 else
2028 vr->set_varying ();
2029 return;
2030 }
2031 }
2032 else
2033 gcc_unreachable ();
2034
2035 /* If either MIN or MAX overflowed, then set the resulting range to
2036 VARYING. */
2037 if (min == NULL_TREE
2038 || TREE_OVERFLOW_P (min)
2039 || max == NULL_TREE
2040 || TREE_OVERFLOW_P (max))
2041 {
2042 vr->set_varying ();
2043 return;
2044 }
2045
2046 /* We punt for [-INF, +INF].
2047 We learn nothing when we have INF on both sides.
2048 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
2049 if (vrp_val_is_min (min) && vrp_val_is_max (max))
2050 {
2051 vr->set_varying ();
2052 return;
2053 }
2054
2055 cmp = compare_values (min, max);
2056 if (cmp == -2 || cmp == 1)
2057 {
2058 /* If the new range has its limits swapped around (MIN > MAX),
2059 then the operation caused one of them to wrap around, mark
2060 the new range VARYING. */
2061 vr->set_varying ();
2062 }
2063 else
2064 vr->set (type, min, max);
2065 }
2066
2067 /* Extract range information from a unary operation CODE based on
2068 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
2069 The resulting range is stored in *VR. */
2070
2071 void
2072 extract_range_from_unary_expr (value_range_base *vr,
2073 enum tree_code code, tree type,
2074 const value_range_base *vr0_, tree op0_type)
2075 {
2076 signop sign = TYPE_SIGN (type);
2077 unsigned int prec = TYPE_PRECISION (type);
2078 value_range_base vr0 = *vr0_;
2079 value_range_base vrtem0, vrtem1;
2080
2081 /* VRP only operates on integral and pointer types. */
2082 if (!(INTEGRAL_TYPE_P (op0_type)
2083 || POINTER_TYPE_P (op0_type))
2084 || !(INTEGRAL_TYPE_P (type)
2085 || POINTER_TYPE_P (type)))
2086 {
2087 vr->set_varying ();
2088 return;
2089 }
2090
2091 /* If VR0 is UNDEFINED, so is the result. */
2092 if (vr0.undefined_p ())
2093 {
2094 vr->set_undefined ();
2095 return;
2096 }
2097
2098 /* Handle operations that we express in terms of others. */
2099 if (code == PAREN_EXPR)
2100 {
2101 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
2102 *vr = vr0;
2103 return;
2104 }
2105 else if (code == NEGATE_EXPR)
2106 {
2107 /* -X is simply 0 - X, so re-use existing code that also handles
2108 anti-ranges fine. */
2109 value_range_base zero;
2110 zero.set (build_int_cst (type, 0));
2111 extract_range_from_binary_expr (vr, MINUS_EXPR, type, &zero, &vr0);
2112 return;
2113 }
2114 else if (code == BIT_NOT_EXPR)
2115 {
2116 /* ~X is simply -1 - X, so re-use existing code that also handles
2117 anti-ranges fine. */
2118 value_range_base minusone;
2119 minusone.set (build_int_cst (type, -1));
2120 extract_range_from_binary_expr (vr, MINUS_EXPR, type, &minusone, &vr0);
2121 return;
2122 }
2123
2124 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2125 and express op ~[] as (op []') U (op []''). */
2126 if (vr0.kind () == VR_ANTI_RANGE
2127 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2128 {
2129 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
2130 if (!vrtem1.undefined_p ())
2131 {
2132 value_range_base vrres;
2133 extract_range_from_unary_expr (&vrres, code, type,
2134 &vrtem1, op0_type);
2135 vr->union_ (&vrres);
2136 }
2137 return;
2138 }
2139
2140 if (CONVERT_EXPR_CODE_P (code))
2141 {
2142 tree inner_type = op0_type;
2143 tree outer_type = type;
2144
2145 /* If the expression involves a pointer, we are only interested in
2146 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).
2147
2148 This may lose precision when converting (char *)~[0,2] to
2149 int, because we'll forget that the pointer can also not be 1
2150 or 2. In practice we don't care, as this is some idiot
2151 storing a magic constant to a pointer. */
2152 if (POINTER_TYPE_P (type) || POINTER_TYPE_P (op0_type))
2153 {
2154 if (!range_includes_zero_p (&vr0))
2155 vr->set_nonzero (type);
2156 else if (vr0.zero_p ())
2157 vr->set_zero (type);
2158 else
2159 vr->set_varying ();
2160 return;
2161 }
2162
2163 /* The POINTER_TYPE_P code above will have dealt with all
2164 pointer anti-ranges. Any remaining anti-ranges at this point
2165 will be integer conversions from SSA names that will be
2166 normalized into VARYING. For instance: ~[x_55, x_55]. */
2167 gcc_assert (vr0.kind () != VR_ANTI_RANGE
2168 || TREE_CODE (vr0.min ()) != INTEGER_CST);
2169
2170 /* NOTES: Previously we were returning VARYING for all symbolics, but
2171 we can do better by treating them as [-MIN, +MAX]. For
2172 example, converting [SYM, SYM] from INT to LONG UNSIGNED,
2173 we can return: ~[0x8000000, 0xffffffff7fffffff].
2174
2175 We were also failing to convert ~[0,0] from char* to unsigned,
2176 instead choosing to return VR_VARYING. Now we return ~[0,0]. */
2177 wide_int vr0_min, vr0_max, wmin, wmax;
2178 signop inner_sign = TYPE_SIGN (inner_type);
2179 signop outer_sign = TYPE_SIGN (outer_type);
2180 unsigned inner_prec = TYPE_PRECISION (inner_type);
2181 unsigned outer_prec = TYPE_PRECISION (outer_type);
2182 extract_range_into_wide_ints (&vr0, inner_type, vr0_min, vr0_max);
2183 if (wide_int_range_convert (wmin, wmax,
2184 inner_sign, inner_prec,
2185 outer_sign, outer_prec,
2186 vr0_min, vr0_max))
2187 {
2188 tree min = wide_int_to_tree (outer_type, wmin);
2189 tree max = wide_int_to_tree (outer_type, wmax);
2190 vr->set (VR_RANGE, min, max);
2191 }
2192 else
2193 vr->set_varying ();
2194 return;
2195 }
2196 else if (code == ABS_EXPR)
2197 {
2198 wide_int wmin, wmax;
2199 wide_int vr0_min, vr0_max;
2200 extract_range_into_wide_ints (&vr0, type, vr0_min, vr0_max);
2201 if (wide_int_range_abs (wmin, wmax, sign, prec, vr0_min, vr0_max,
2202 TYPE_OVERFLOW_UNDEFINED (type)))
2203 vr->set (VR_RANGE, wide_int_to_tree (type, wmin),
2204 wide_int_to_tree (type, wmax));
2205 else
2206 vr->set_varying ();
2207 return;
2208 }
2209 else if (code == ABSU_EXPR)
2210 {
2211 wide_int wmin, wmax;
2212 wide_int vr0_min, vr0_max;
2213 tree signed_type = make_signed_type (TYPE_PRECISION (type));
2214 extract_range_into_wide_ints (&vr0, signed_type, vr0_min, vr0_max);
2215 wide_int_range_absu (wmin, wmax, prec, vr0_min, vr0_max);
2216 vr->set (VR_RANGE, wide_int_to_tree (type, wmin),
2217 wide_int_to_tree (type, wmax));
2218 return;
2219 }
2220
2221 /* For unhandled operations fall back to varying. */
2222 vr->set_varying ();
2223 return;
2224 }
2225
2226 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2227 create a new SSA name N and return the assertion assignment
2228 'N = ASSERT_EXPR <V, V OP W>'. */
2229
2230 static gimple *
2231 build_assert_expr_for (tree cond, tree v)
2232 {
2233 tree a;
2234 gassign *assertion;
2235
2236 gcc_assert (TREE_CODE (v) == SSA_NAME
2237 && COMPARISON_CLASS_P (cond));
2238
2239 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2240 assertion = gimple_build_assign (NULL_TREE, a);
2241
2242 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2243 operand of the ASSERT_EXPR. Create it so the new name and the old one
2244 are registered in the replacement table so that we can fix the SSA web
2245 after adding all the ASSERT_EXPRs. */
2246 tree new_def = create_new_def_for (v, assertion, NULL);
2247 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2248 given we have to be able to fully propagate those out to re-create
2249 valid SSA when removing the asserts. */
2250 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2251 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2252
2253 return assertion;
2254 }
2255
2256
2257 /* Return false if EXPR is a predicate expression involving floating
2258 point values. */
2259
2260 static inline bool
2261 fp_predicate (gimple *stmt)
2262 {
2263 GIMPLE_CHECK (stmt, GIMPLE_COND);
2264
2265 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2266 }
2267
2268 /* If the range of values taken by OP can be inferred after STMT executes,
2269 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2270 describes the inferred range. Return true if a range could be
2271 inferred. */
2272
2273 bool
2274 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2275 {
2276 *val_p = NULL_TREE;
2277 *comp_code_p = ERROR_MARK;
2278
2279 /* Do not attempt to infer anything in names that flow through
2280 abnormal edges. */
2281 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2282 return false;
2283
2284 /* If STMT is the last statement of a basic block with no normal
2285 successors, there is no point inferring anything about any of its
2286 operands. We would not be able to find a proper insertion point
2287 for the assertion, anyway. */
2288 if (stmt_ends_bb_p (stmt))
2289 {
2290 edge_iterator ei;
2291 edge e;
2292
2293 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2294 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2295 break;
2296 if (e == NULL)
2297 return false;
2298 }
2299
2300 if (infer_nonnull_range (stmt, op))
2301 {
2302 *val_p = build_int_cst (TREE_TYPE (op), 0);
2303 *comp_code_p = NE_EXPR;
2304 return true;
2305 }
2306
2307 return false;
2308 }
2309
2310
2311 void dump_asserts_for (FILE *, tree);
2312 void debug_asserts_for (tree);
2313 void dump_all_asserts (FILE *);
2314 void debug_all_asserts (void);
2315
2316 /* Dump all the registered assertions for NAME to FILE. */
2317
2318 void
2319 dump_asserts_for (FILE *file, tree name)
2320 {
2321 assert_locus *loc;
2322
2323 fprintf (file, "Assertions to be inserted for ");
2324 print_generic_expr (file, name);
2325 fprintf (file, "\n");
2326
2327 loc = asserts_for[SSA_NAME_VERSION (name)];
2328 while (loc)
2329 {
2330 fprintf (file, "\t");
2331 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2332 fprintf (file, "\n\tBB #%d", loc->bb->index);
2333 if (loc->e)
2334 {
2335 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2336 loc->e->dest->index);
2337 dump_edge_info (file, loc->e, dump_flags, 0);
2338 }
2339 fprintf (file, "\n\tPREDICATE: ");
2340 print_generic_expr (file, loc->expr);
2341 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2342 print_generic_expr (file, loc->val);
2343 fprintf (file, "\n\n");
2344 loc = loc->next;
2345 }
2346
2347 fprintf (file, "\n");
2348 }
2349
2350
2351 /* Dump all the registered assertions for NAME to stderr. */
2352
2353 DEBUG_FUNCTION void
2354 debug_asserts_for (tree name)
2355 {
2356 dump_asserts_for (stderr, name);
2357 }
2358
2359
2360 /* Dump all the registered assertions for all the names to FILE. */
2361
2362 void
2363 dump_all_asserts (FILE *file)
2364 {
2365 unsigned i;
2366 bitmap_iterator bi;
2367
2368 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2369 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2370 dump_asserts_for (file, ssa_name (i));
2371 fprintf (file, "\n");
2372 }
2373
2374
2375 /* Dump all the registered assertions for all the names to stderr. */
2376
2377 DEBUG_FUNCTION void
2378 debug_all_asserts (void)
2379 {
2380 dump_all_asserts (stderr);
2381 }
2382
2383 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2384
2385 static void
2386 add_assert_info (vec<assert_info> &asserts,
2387 tree name, tree expr, enum tree_code comp_code, tree val)
2388 {
2389 assert_info info;
2390 info.comp_code = comp_code;
2391 info.name = name;
2392 if (TREE_OVERFLOW_P (val))
2393 val = drop_tree_overflow (val);
2394 info.val = val;
2395 info.expr = expr;
2396 asserts.safe_push (info);
2397 if (dump_enabled_p ())
2398 dump_printf (MSG_NOTE | MSG_PRIORITY_INTERNALS,
2399 "Adding assert for %T from %T %s %T\n",
2400 name, expr, op_symbol_code (comp_code), val);
2401 }
2402
2403 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2404 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2405 E->DEST, then register this location as a possible insertion point
2406 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2407
2408 BB, E and SI provide the exact insertion point for the new
2409 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2410 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2411 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2412 must not be NULL. */
2413
2414 static void
2415 register_new_assert_for (tree name, tree expr,
2416 enum tree_code comp_code,
2417 tree val,
2418 basic_block bb,
2419 edge e,
2420 gimple_stmt_iterator si)
2421 {
2422 assert_locus *n, *loc, *last_loc;
2423 basic_block dest_bb;
2424
2425 gcc_checking_assert (bb == NULL || e == NULL);
2426
2427 if (e == NULL)
2428 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2429 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2430
2431 /* Never build an assert comparing against an integer constant with
2432 TREE_OVERFLOW set. This confuses our undefined overflow warning
2433 machinery. */
2434 if (TREE_OVERFLOW_P (val))
2435 val = drop_tree_overflow (val);
2436
2437 /* The new assertion A will be inserted at BB or E. We need to
2438 determine if the new location is dominated by a previously
2439 registered location for A. If we are doing an edge insertion,
2440 assume that A will be inserted at E->DEST. Note that this is not
2441 necessarily true.
2442
2443 If E is a critical edge, it will be split. But even if E is
2444 split, the new block will dominate the same set of blocks that
2445 E->DEST dominates.
2446
2447 The reverse, however, is not true, blocks dominated by E->DEST
2448 will not be dominated by the new block created to split E. So,
2449 if the insertion location is on a critical edge, we will not use
2450 the new location to move another assertion previously registered
2451 at a block dominated by E->DEST. */
2452 dest_bb = (bb) ? bb : e->dest;
2453
2454 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2455 VAL at a block dominating DEST_BB, then we don't need to insert a new
2456 one. Similarly, if the same assertion already exists at a block
2457 dominated by DEST_BB and the new location is not on a critical
2458 edge, then update the existing location for the assertion (i.e.,
2459 move the assertion up in the dominance tree).
2460
2461 Note, this is implemented as a simple linked list because there
2462 should not be more than a handful of assertions registered per
2463 name. If this becomes a performance problem, a table hashed by
2464 COMP_CODE and VAL could be implemented. */
2465 loc = asserts_for[SSA_NAME_VERSION (name)];
2466 last_loc = loc;
2467 while (loc)
2468 {
2469 if (loc->comp_code == comp_code
2470 && (loc->val == val
2471 || operand_equal_p (loc->val, val, 0))
2472 && (loc->expr == expr
2473 || operand_equal_p (loc->expr, expr, 0)))
2474 {
2475 /* If E is not a critical edge and DEST_BB
2476 dominates the existing location for the assertion, move
2477 the assertion up in the dominance tree by updating its
2478 location information. */
2479 if ((e == NULL || !EDGE_CRITICAL_P (e))
2480 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2481 {
2482 loc->bb = dest_bb;
2483 loc->e = e;
2484 loc->si = si;
2485 return;
2486 }
2487 }
2488
2489 /* Update the last node of the list and move to the next one. */
2490 last_loc = loc;
2491 loc = loc->next;
2492 }
2493
2494 /* If we didn't find an assertion already registered for
2495 NAME COMP_CODE VAL, add a new one at the end of the list of
2496 assertions associated with NAME. */
2497 n = XNEW (struct assert_locus);
2498 n->bb = dest_bb;
2499 n->e = e;
2500 n->si = si;
2501 n->comp_code = comp_code;
2502 n->val = val;
2503 n->expr = expr;
2504 n->next = NULL;
2505
2506 if (last_loc)
2507 last_loc->next = n;
2508 else
2509 asserts_for[SSA_NAME_VERSION (name)] = n;
2510
2511 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2512 }
2513
2514 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2515 Extract a suitable test code and value and store them into *CODE_P and
2516 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2517
2518 If no extraction was possible, return FALSE, otherwise return TRUE.
2519
2520 If INVERT is true, then we invert the result stored into *CODE_P. */
2521
2522 static bool
2523 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2524 tree cond_op0, tree cond_op1,
2525 bool invert, enum tree_code *code_p,
2526 tree *val_p)
2527 {
2528 enum tree_code comp_code;
2529 tree val;
2530
2531 /* Otherwise, we have a comparison of the form NAME COMP VAL
2532 or VAL COMP NAME. */
2533 if (name == cond_op1)
2534 {
2535 /* If the predicate is of the form VAL COMP NAME, flip
2536 COMP around because we need to register NAME as the
2537 first operand in the predicate. */
2538 comp_code = swap_tree_comparison (cond_code);
2539 val = cond_op0;
2540 }
2541 else if (name == cond_op0)
2542 {
2543 /* The comparison is of the form NAME COMP VAL, so the
2544 comparison code remains unchanged. */
2545 comp_code = cond_code;
2546 val = cond_op1;
2547 }
2548 else
2549 gcc_unreachable ();
2550
2551 /* Invert the comparison code as necessary. */
2552 if (invert)
2553 comp_code = invert_tree_comparison (comp_code, 0);
2554
2555 /* VRP only handles integral and pointer types. */
2556 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2557 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2558 return false;
2559
2560 /* Do not register always-false predicates.
2561 FIXME: this works around a limitation in fold() when dealing with
2562 enumerations. Given 'enum { N1, N2 } x;', fold will not
2563 fold 'if (x > N2)' to 'if (0)'. */
2564 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2565 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2566 {
2567 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2568 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2569
2570 if (comp_code == GT_EXPR
2571 && (!max
2572 || compare_values (val, max) == 0))
2573 return false;
2574
2575 if (comp_code == LT_EXPR
2576 && (!min
2577 || compare_values (val, min) == 0))
2578 return false;
2579 }
2580 *code_p = comp_code;
2581 *val_p = val;
2582 return true;
2583 }
2584
2585 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2586 (otherwise return VAL). VAL and MASK must be zero-extended for
2587 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2588 (to transform signed values into unsigned) and at the end xor
2589 SGNBIT back. */
2590
2591 static wide_int
2592 masked_increment (const wide_int &val_in, const wide_int &mask,
2593 const wide_int &sgnbit, unsigned int prec)
2594 {
2595 wide_int bit = wi::one (prec), res;
2596 unsigned int i;
2597
2598 wide_int val = val_in ^ sgnbit;
2599 for (i = 0; i < prec; i++, bit += bit)
2600 {
2601 res = mask;
2602 if ((res & bit) == 0)
2603 continue;
2604 res = bit - 1;
2605 res = wi::bit_and_not (val + bit, res);
2606 res &= mask;
2607 if (wi::gtu_p (res, val))
2608 return res ^ sgnbit;
2609 }
2610 return val ^ sgnbit;
2611 }
2612
2613 /* Helper for overflow_comparison_p
2614
2615 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2616 OP1's defining statement to see if it ultimately has the form
2617 OP0 CODE (OP0 PLUS INTEGER_CST)
2618
2619 If so, return TRUE indicating this is an overflow test and store into
2620 *NEW_CST an updated constant that can be used in a narrowed range test.
2621
2622 REVERSED indicates if the comparison was originally:
2623
2624 OP1 CODE' OP0.
2625
2626 This affects how we build the updated constant. */
2627
2628 static bool
2629 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
2630 bool follow_assert_exprs, bool reversed, tree *new_cst)
2631 {
2632 /* See if this is a relational operation between two SSA_NAMES with
2633 unsigned, overflow wrapping values. If so, check it more deeply. */
2634 if ((code == LT_EXPR || code == LE_EXPR
2635 || code == GE_EXPR || code == GT_EXPR)
2636 && TREE_CODE (op0) == SSA_NAME
2637 && TREE_CODE (op1) == SSA_NAME
2638 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
2639 && TYPE_UNSIGNED (TREE_TYPE (op0))
2640 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
2641 {
2642 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
2643
2644 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
2645 if (follow_assert_exprs)
2646 {
2647 while (gimple_assign_single_p (op1_def)
2648 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
2649 {
2650 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
2651 if (TREE_CODE (op1) != SSA_NAME)
2652 break;
2653 op1_def = SSA_NAME_DEF_STMT (op1);
2654 }
2655 }
2656
2657 /* Now look at the defining statement of OP1 to see if it adds
2658 or subtracts a nonzero constant from another operand. */
2659 if (op1_def
2660 && is_gimple_assign (op1_def)
2661 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
2662 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
2663 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
2664 {
2665 tree target = gimple_assign_rhs1 (op1_def);
2666
2667 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
2668 for one where TARGET appears on the RHS. */
2669 if (follow_assert_exprs)
2670 {
2671 /* Now see if that "other operand" is op0, following the chain
2672 of ASSERT_EXPRs if necessary. */
2673 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
2674 while (op0 != target
2675 && gimple_assign_single_p (op0_def)
2676 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
2677 {
2678 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
2679 if (TREE_CODE (op0) != SSA_NAME)
2680 break;
2681 op0_def = SSA_NAME_DEF_STMT (op0);
2682 }
2683 }
2684
2685 /* If we did not find our target SSA_NAME, then this is not
2686 an overflow test. */
2687 if (op0 != target)
2688 return false;
2689
2690 tree type = TREE_TYPE (op0);
2691 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
2692 tree inc = gimple_assign_rhs2 (op1_def);
2693 if (reversed)
2694 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
2695 else
2696 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
2697 return true;
2698 }
2699 }
2700 return false;
2701 }
2702
2703 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2704 OP1's defining statement to see if it ultimately has the form
2705 OP0 CODE (OP0 PLUS INTEGER_CST)
2706
2707 If so, return TRUE indicating this is an overflow test and store into
2708 *NEW_CST an updated constant that can be used in a narrowed range test.
2709
2710 These statements are left as-is in the IL to facilitate discovery of
2711 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
2712 the alternate range representation is often useful within VRP. */
2713
2714 bool
2715 overflow_comparison_p (tree_code code, tree name, tree val,
2716 bool use_equiv_p, tree *new_cst)
2717 {
2718 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
2719 return true;
2720 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
2721 use_equiv_p, true, new_cst);
2722 }
2723
2724
2725 /* Try to register an edge assertion for SSA name NAME on edge E for
2726 the condition COND contributing to the conditional jump pointed to by BSI.
2727 Invert the condition COND if INVERT is true. */
2728
2729 static void
2730 register_edge_assert_for_2 (tree name, edge e,
2731 enum tree_code cond_code,
2732 tree cond_op0, tree cond_op1, bool invert,
2733 vec<assert_info> &asserts)
2734 {
2735 tree val;
2736 enum tree_code comp_code;
2737
2738 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2739 cond_op0,
2740 cond_op1,
2741 invert, &comp_code, &val))
2742 return;
2743
2744 /* Queue the assert. */
2745 tree x;
2746 if (overflow_comparison_p (comp_code, name, val, false, &x))
2747 {
2748 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
2749 ? GT_EXPR : LE_EXPR);
2750 add_assert_info (asserts, name, name, new_code, x);
2751 }
2752 add_assert_info (asserts, name, name, comp_code, val);
2753
2754 /* In the case of NAME <= CST and NAME being defined as
2755 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
2756 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
2757 This catches range and anti-range tests. */
2758 if ((comp_code == LE_EXPR
2759 || comp_code == GT_EXPR)
2760 && TREE_CODE (val) == INTEGER_CST
2761 && TYPE_UNSIGNED (TREE_TYPE (val)))
2762 {
2763 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2764 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
2765
2766 /* Extract CST2 from the (optional) addition. */
2767 if (is_gimple_assign (def_stmt)
2768 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
2769 {
2770 name2 = gimple_assign_rhs1 (def_stmt);
2771 cst2 = gimple_assign_rhs2 (def_stmt);
2772 if (TREE_CODE (name2) == SSA_NAME
2773 && TREE_CODE (cst2) == INTEGER_CST)
2774 def_stmt = SSA_NAME_DEF_STMT (name2);
2775 }
2776
2777 /* Extract NAME2 from the (optional) sign-changing cast. */
2778 if (gimple_assign_cast_p (def_stmt))
2779 {
2780 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
2781 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2782 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
2783 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
2784 name3 = gimple_assign_rhs1 (def_stmt);
2785 }
2786
2787 /* If name3 is used later, create an ASSERT_EXPR for it. */
2788 if (name3 != NULL_TREE
2789 && TREE_CODE (name3) == SSA_NAME
2790 && (cst2 == NULL_TREE
2791 || TREE_CODE (cst2) == INTEGER_CST)
2792 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
2793 {
2794 tree tmp;
2795
2796 /* Build an expression for the range test. */
2797 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
2798 if (cst2 != NULL_TREE)
2799 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2800 add_assert_info (asserts, name3, tmp, comp_code, val);
2801 }
2802
2803 /* If name2 is used later, create an ASSERT_EXPR for it. */
2804 if (name2 != NULL_TREE
2805 && TREE_CODE (name2) == SSA_NAME
2806 && TREE_CODE (cst2) == INTEGER_CST
2807 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
2808 {
2809 tree tmp;
2810
2811 /* Build an expression for the range test. */
2812 tmp = name2;
2813 if (TREE_TYPE (name) != TREE_TYPE (name2))
2814 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
2815 if (cst2 != NULL_TREE)
2816 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2817 add_assert_info (asserts, name2, tmp, comp_code, val);
2818 }
2819 }
2820
2821 /* In the case of post-in/decrement tests like if (i++) ... and uses
2822 of the in/decremented value on the edge the extra name we want to
2823 assert for is not on the def chain of the name compared. Instead
2824 it is in the set of use stmts.
2825 Similar cases happen for conversions that were simplified through
2826 fold_{sign_changed,widened}_comparison. */
2827 if ((comp_code == NE_EXPR
2828 || comp_code == EQ_EXPR)
2829 && TREE_CODE (val) == INTEGER_CST)
2830 {
2831 imm_use_iterator ui;
2832 gimple *use_stmt;
2833 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
2834 {
2835 if (!is_gimple_assign (use_stmt))
2836 continue;
2837
2838 /* Cut off to use-stmts that are dominating the predecessor. */
2839 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
2840 continue;
2841
2842 tree name2 = gimple_assign_lhs (use_stmt);
2843 if (TREE_CODE (name2) != SSA_NAME)
2844 continue;
2845
2846 enum tree_code code = gimple_assign_rhs_code (use_stmt);
2847 tree cst;
2848 if (code == PLUS_EXPR
2849 || code == MINUS_EXPR)
2850 {
2851 cst = gimple_assign_rhs2 (use_stmt);
2852 if (TREE_CODE (cst) != INTEGER_CST)
2853 continue;
2854 cst = int_const_binop (code, val, cst);
2855 }
2856 else if (CONVERT_EXPR_CODE_P (code))
2857 {
2858 /* For truncating conversions we cannot record
2859 an inequality. */
2860 if (comp_code == NE_EXPR
2861 && (TYPE_PRECISION (TREE_TYPE (name2))
2862 < TYPE_PRECISION (TREE_TYPE (name))))
2863 continue;
2864 cst = fold_convert (TREE_TYPE (name2), val);
2865 }
2866 else
2867 continue;
2868
2869 if (TREE_OVERFLOW_P (cst))
2870 cst = drop_tree_overflow (cst);
2871 add_assert_info (asserts, name2, name2, comp_code, cst);
2872 }
2873 }
2874
2875 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
2876 && TREE_CODE (val) == INTEGER_CST)
2877 {
2878 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2879 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
2880 tree val2 = NULL_TREE;
2881 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
2882 wide_int mask = wi::zero (prec);
2883 unsigned int nprec = prec;
2884 enum tree_code rhs_code = ERROR_MARK;
2885
2886 if (is_gimple_assign (def_stmt))
2887 rhs_code = gimple_assign_rhs_code (def_stmt);
2888
2889 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
2890 assert that A != CST1 -+ CST2. */
2891 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2892 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
2893 {
2894 tree op0 = gimple_assign_rhs1 (def_stmt);
2895 tree op1 = gimple_assign_rhs2 (def_stmt);
2896 if (TREE_CODE (op0) == SSA_NAME
2897 && TREE_CODE (op1) == INTEGER_CST)
2898 {
2899 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
2900 ? MINUS_EXPR : PLUS_EXPR);
2901 op1 = int_const_binop (reverse_op, val, op1);
2902 if (TREE_OVERFLOW (op1))
2903 op1 = drop_tree_overflow (op1);
2904 add_assert_info (asserts, op0, op0, comp_code, op1);
2905 }
2906 }
2907
2908 /* Add asserts for NAME cmp CST and NAME being defined
2909 as NAME = (int) NAME2. */
2910 if (!TYPE_UNSIGNED (TREE_TYPE (val))
2911 && (comp_code == LE_EXPR || comp_code == LT_EXPR
2912 || comp_code == GT_EXPR || comp_code == GE_EXPR)
2913 && gimple_assign_cast_p (def_stmt))
2914 {
2915 name2 = gimple_assign_rhs1 (def_stmt);
2916 if (CONVERT_EXPR_CODE_P (rhs_code)
2917 && TREE_CODE (name2) == SSA_NAME
2918 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2919 && TYPE_UNSIGNED (TREE_TYPE (name2))
2920 && prec == TYPE_PRECISION (TREE_TYPE (name2))
2921 && (comp_code == LE_EXPR || comp_code == GT_EXPR
2922 || !tree_int_cst_equal (val,
2923 TYPE_MIN_VALUE (TREE_TYPE (val)))))
2924 {
2925 tree tmp, cst;
2926 enum tree_code new_comp_code = comp_code;
2927
2928 cst = fold_convert (TREE_TYPE (name2),
2929 TYPE_MIN_VALUE (TREE_TYPE (val)));
2930 /* Build an expression for the range test. */
2931 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
2932 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
2933 fold_convert (TREE_TYPE (name2), val));
2934 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2935 {
2936 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
2937 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
2938 build_int_cst (TREE_TYPE (name2), 1));
2939 }
2940 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
2941 }
2942 }
2943
2944 /* Add asserts for NAME cmp CST and NAME being defined as
2945 NAME = NAME2 >> CST2.
2946
2947 Extract CST2 from the right shift. */
2948 if (rhs_code == RSHIFT_EXPR)
2949 {
2950 name2 = gimple_assign_rhs1 (def_stmt);
2951 cst2 = gimple_assign_rhs2 (def_stmt);
2952 if (TREE_CODE (name2) == SSA_NAME
2953 && tree_fits_uhwi_p (cst2)
2954 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2955 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
2956 && type_has_mode_precision_p (TREE_TYPE (val)))
2957 {
2958 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
2959 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
2960 }
2961 }
2962 if (val2 != NULL_TREE
2963 && TREE_CODE (val2) == INTEGER_CST
2964 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
2965 TREE_TYPE (val),
2966 val2, cst2), val))
2967 {
2968 enum tree_code new_comp_code = comp_code;
2969 tree tmp, new_val;
2970
2971 tmp = name2;
2972 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
2973 {
2974 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
2975 {
2976 tree type = build_nonstandard_integer_type (prec, 1);
2977 tmp = build1 (NOP_EXPR, type, name2);
2978 val2 = fold_convert (type, val2);
2979 }
2980 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
2981 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
2982 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
2983 }
2984 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2985 {
2986 wide_int minval
2987 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2988 new_val = val2;
2989 if (minval == wi::to_wide (new_val))
2990 new_val = NULL_TREE;
2991 }
2992 else
2993 {
2994 wide_int maxval
2995 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2996 mask |= wi::to_wide (val2);
2997 if (wi::eq_p (mask, maxval))
2998 new_val = NULL_TREE;
2999 else
3000 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
3001 }
3002
3003 if (new_val)
3004 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
3005 }
3006
3007 /* If we have a conversion that doesn't change the value of the source
3008 simply register the same assert for it. */
3009 if (CONVERT_EXPR_CODE_P (rhs_code))
3010 {
3011 wide_int rmin, rmax;
3012 tree rhs1 = gimple_assign_rhs1 (def_stmt);
3013 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
3014 && TREE_CODE (rhs1) == SSA_NAME
3015 /* Make sure the relation preserves the upper/lower boundary of
3016 the range conservatively. */
3017 && (comp_code == NE_EXPR
3018 || comp_code == EQ_EXPR
3019 || (TYPE_SIGN (TREE_TYPE (name))
3020 == TYPE_SIGN (TREE_TYPE (rhs1)))
3021 || ((comp_code == LE_EXPR
3022 || comp_code == LT_EXPR)
3023 && !TYPE_UNSIGNED (TREE_TYPE (rhs1)))
3024 || ((comp_code == GE_EXPR
3025 || comp_code == GT_EXPR)
3026 && TYPE_UNSIGNED (TREE_TYPE (rhs1))))
3027 /* And the conversion does not alter the value we compare
3028 against and all values in rhs1 can be represented in
3029 the converted to type. */
3030 && int_fits_type_p (val, TREE_TYPE (rhs1))
3031 && ((TYPE_PRECISION (TREE_TYPE (name))
3032 > TYPE_PRECISION (TREE_TYPE (rhs1)))
3033 || (get_range_info (rhs1, &rmin, &rmax) == VR_RANGE
3034 && wi::fits_to_tree_p (rmin, TREE_TYPE (name))
3035 && wi::fits_to_tree_p (rmax, TREE_TYPE (name)))))
3036 add_assert_info (asserts, rhs1, rhs1,
3037 comp_code, fold_convert (TREE_TYPE (rhs1), val));
3038 }
3039
3040 /* Add asserts for NAME cmp CST and NAME being defined as
3041 NAME = NAME2 & CST2.
3042
3043 Extract CST2 from the and.
3044
3045 Also handle
3046 NAME = (unsigned) NAME2;
3047 casts where NAME's type is unsigned and has smaller precision
3048 than NAME2's type as if it was NAME = NAME2 & MASK. */
3049 names[0] = NULL_TREE;
3050 names[1] = NULL_TREE;
3051 cst2 = NULL_TREE;
3052 if (rhs_code == BIT_AND_EXPR
3053 || (CONVERT_EXPR_CODE_P (rhs_code)
3054 && INTEGRAL_TYPE_P (TREE_TYPE (val))
3055 && TYPE_UNSIGNED (TREE_TYPE (val))
3056 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
3057 > prec))
3058 {
3059 name2 = gimple_assign_rhs1 (def_stmt);
3060 if (rhs_code == BIT_AND_EXPR)
3061 cst2 = gimple_assign_rhs2 (def_stmt);
3062 else
3063 {
3064 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
3065 nprec = TYPE_PRECISION (TREE_TYPE (name2));
3066 }
3067 if (TREE_CODE (name2) == SSA_NAME
3068 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3069 && TREE_CODE (cst2) == INTEGER_CST
3070 && !integer_zerop (cst2)
3071 && (nprec > 1
3072 || TYPE_UNSIGNED (TREE_TYPE (val))))
3073 {
3074 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
3075 if (gimple_assign_cast_p (def_stmt2))
3076 {
3077 names[1] = gimple_assign_rhs1 (def_stmt2);
3078 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
3079 || TREE_CODE (names[1]) != SSA_NAME
3080 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
3081 || (TYPE_PRECISION (TREE_TYPE (name2))
3082 != TYPE_PRECISION (TREE_TYPE (names[1]))))
3083 names[1] = NULL_TREE;
3084 }
3085 names[0] = name2;
3086 }
3087 }
3088 if (names[0] || names[1])
3089 {
3090 wide_int minv, maxv, valv, cst2v;
3091 wide_int tem, sgnbit;
3092 bool valid_p = false, valn, cst2n;
3093 enum tree_code ccode = comp_code;
3094
3095 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
3096 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
3097 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
3098 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
3099 /* If CST2 doesn't have most significant bit set,
3100 but VAL is negative, we have comparison like
3101 if ((x & 0x123) > -4) (always true). Just give up. */
3102 if (!cst2n && valn)
3103 ccode = ERROR_MARK;
3104 if (cst2n)
3105 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3106 else
3107 sgnbit = wi::zero (nprec);
3108 minv = valv & cst2v;
3109 switch (ccode)
3110 {
3111 case EQ_EXPR:
3112 /* Minimum unsigned value for equality is VAL & CST2
3113 (should be equal to VAL, otherwise we probably should
3114 have folded the comparison into false) and
3115 maximum unsigned value is VAL | ~CST2. */
3116 maxv = valv | ~cst2v;
3117 valid_p = true;
3118 break;
3119
3120 case NE_EXPR:
3121 tem = valv | ~cst2v;
3122 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
3123 if (valv == 0)
3124 {
3125 cst2n = false;
3126 sgnbit = wi::zero (nprec);
3127 goto gt_expr;
3128 }
3129 /* If (VAL | ~CST2) is all ones, handle it as
3130 (X & CST2) < VAL. */
3131 if (tem == -1)
3132 {
3133 cst2n = false;
3134 valn = false;
3135 sgnbit = wi::zero (nprec);
3136 goto lt_expr;
3137 }
3138 if (!cst2n && wi::neg_p (cst2v))
3139 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3140 if (sgnbit != 0)
3141 {
3142 if (valv == sgnbit)
3143 {
3144 cst2n = true;
3145 valn = true;
3146 goto gt_expr;
3147 }
3148 if (tem == wi::mask (nprec - 1, false, nprec))
3149 {
3150 cst2n = true;
3151 goto lt_expr;
3152 }
3153 if (!cst2n)
3154 sgnbit = wi::zero (nprec);
3155 }
3156 break;
3157
3158 case GE_EXPR:
3159 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
3160 is VAL and maximum unsigned value is ~0. For signed
3161 comparison, if CST2 doesn't have most significant bit
3162 set, handle it similarly. If CST2 has MSB set,
3163 the minimum is the same, and maximum is ~0U/2. */
3164 if (minv != valv)
3165 {
3166 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
3167 VAL. */
3168 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3169 if (minv == valv)
3170 break;
3171 }
3172 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3173 valid_p = true;
3174 break;
3175
3176 case GT_EXPR:
3177 gt_expr:
3178 /* Find out smallest MINV where MINV > VAL
3179 && (MINV & CST2) == MINV, if any. If VAL is signed and
3180 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3181 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3182 if (minv == valv)
3183 break;
3184 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3185 valid_p = true;
3186 break;
3187
3188 case LE_EXPR:
3189 /* Minimum unsigned value for <= is 0 and maximum
3190 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3191 Otherwise, find smallest VAL2 where VAL2 > VAL
3192 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3193 as maximum.
3194 For signed comparison, if CST2 doesn't have most
3195 significant bit set, handle it similarly. If CST2 has
3196 MSB set, the maximum is the same and minimum is INT_MIN. */
3197 if (minv == valv)
3198 maxv = valv;
3199 else
3200 {
3201 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3202 if (maxv == valv)
3203 break;
3204 maxv -= 1;
3205 }
3206 maxv |= ~cst2v;
3207 minv = sgnbit;
3208 valid_p = true;
3209 break;
3210
3211 case LT_EXPR:
3212 lt_expr:
3213 /* Minimum unsigned value for < is 0 and maximum
3214 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
3215 Otherwise, find smallest VAL2 where VAL2 > VAL
3216 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3217 as maximum.
3218 For signed comparison, if CST2 doesn't have most
3219 significant bit set, handle it similarly. If CST2 has
3220 MSB set, the maximum is the same and minimum is INT_MIN. */
3221 if (minv == valv)
3222 {
3223 if (valv == sgnbit)
3224 break;
3225 maxv = valv;
3226 }
3227 else
3228 {
3229 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3230 if (maxv == valv)
3231 break;
3232 }
3233 maxv -= 1;
3234 maxv |= ~cst2v;
3235 minv = sgnbit;
3236 valid_p = true;
3237 break;
3238
3239 default:
3240 break;
3241 }
3242 if (valid_p
3243 && (maxv - minv) != -1)
3244 {
3245 tree tmp, new_val, type;
3246 int i;
3247
3248 for (i = 0; i < 2; i++)
3249 if (names[i])
3250 {
3251 wide_int maxv2 = maxv;
3252 tmp = names[i];
3253 type = TREE_TYPE (names[i]);
3254 if (!TYPE_UNSIGNED (type))
3255 {
3256 type = build_nonstandard_integer_type (nprec, 1);
3257 tmp = build1 (NOP_EXPR, type, names[i]);
3258 }
3259 if (minv != 0)
3260 {
3261 tmp = build2 (PLUS_EXPR, type, tmp,
3262 wide_int_to_tree (type, -minv));
3263 maxv2 = maxv - minv;
3264 }
3265 new_val = wide_int_to_tree (type, maxv2);
3266 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3267 }
3268 }
3269 }
3270 }
3271 }
3272
3273 /* OP is an operand of a truth value expression which is known to have
3274 a particular value. Register any asserts for OP and for any
3275 operands in OP's defining statement.
3276
3277 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3278 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3279
3280 static void
3281 register_edge_assert_for_1 (tree op, enum tree_code code,
3282 edge e, vec<assert_info> &asserts)
3283 {
3284 gimple *op_def;
3285 tree val;
3286 enum tree_code rhs_code;
3287
3288 /* We only care about SSA_NAMEs. */
3289 if (TREE_CODE (op) != SSA_NAME)
3290 return;
3291
3292 /* We know that OP will have a zero or nonzero value. */
3293 val = build_int_cst (TREE_TYPE (op), 0);
3294 add_assert_info (asserts, op, op, code, val);
3295
3296 /* Now look at how OP is set. If it's set from a comparison,
3297 a truth operation or some bit operations, then we may be able
3298 to register information about the operands of that assignment. */
3299 op_def = SSA_NAME_DEF_STMT (op);
3300 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3301 return;
3302
3303 rhs_code = gimple_assign_rhs_code (op_def);
3304
3305 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3306 {
3307 bool invert = (code == EQ_EXPR ? true : false);
3308 tree op0 = gimple_assign_rhs1 (op_def);
3309 tree op1 = gimple_assign_rhs2 (op_def);
3310
3311 if (TREE_CODE (op0) == SSA_NAME)
3312 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3313 if (TREE_CODE (op1) == SSA_NAME)
3314 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3315 }
3316 else if ((code == NE_EXPR
3317 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3318 || (code == EQ_EXPR
3319 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3320 {
3321 /* Recurse on each operand. */
3322 tree op0 = gimple_assign_rhs1 (op_def);
3323 tree op1 = gimple_assign_rhs2 (op_def);
3324 if (TREE_CODE (op0) == SSA_NAME
3325 && has_single_use (op0))
3326 register_edge_assert_for_1 (op0, code, e, asserts);
3327 if (TREE_CODE (op1) == SSA_NAME
3328 && has_single_use (op1))
3329 register_edge_assert_for_1 (op1, code, e, asserts);
3330 }
3331 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3332 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3333 {
3334 /* Recurse, flipping CODE. */
3335 code = invert_tree_comparison (code, false);
3336 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3337 }
3338 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3339 {
3340 /* Recurse through the copy. */
3341 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3342 }
3343 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3344 {
3345 /* Recurse through the type conversion, unless it is a narrowing
3346 conversion or conversion from non-integral type. */
3347 tree rhs = gimple_assign_rhs1 (op_def);
3348 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3349 && (TYPE_PRECISION (TREE_TYPE (rhs))
3350 <= TYPE_PRECISION (TREE_TYPE (op))))
3351 register_edge_assert_for_1 (rhs, code, e, asserts);
3352 }
3353 }
3354
3355 /* Check if comparison
3356 NAME COND_OP INTEGER_CST
3357 has a form of
3358 (X & 11...100..0) COND_OP XX...X00...0
3359 Such comparison can yield assertions like
3360 X >= XX...X00...0
3361 X <= XX...X11...1
3362 in case of COND_OP being EQ_EXPR or
3363 X < XX...X00...0
3364 X > XX...X11...1
3365 in case of NE_EXPR. */
3366
3367 static bool
3368 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3369 tree *new_name, tree *low, enum tree_code *low_code,
3370 tree *high, enum tree_code *high_code)
3371 {
3372 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3373
3374 if (!is_gimple_assign (def_stmt)
3375 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3376 return false;
3377
3378 tree t = gimple_assign_rhs1 (def_stmt);
3379 tree maskt = gimple_assign_rhs2 (def_stmt);
3380 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3381 return false;
3382
3383 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3384 wide_int inv_mask = ~mask;
3385 /* Must have been removed by now so don't bother optimizing. */
3386 if (mask == 0 || inv_mask == 0)
3387 return false;
3388
3389 /* Assume VALT is INTEGER_CST. */
3390 wi::tree_to_wide_ref val = wi::to_wide (valt);
3391
3392 if ((inv_mask & (inv_mask + 1)) != 0
3393 || (val & mask) != val)
3394 return false;
3395
3396 bool is_range = cond_code == EQ_EXPR;
3397
3398 tree type = TREE_TYPE (t);
3399 wide_int min = wi::min_value (type),
3400 max = wi::max_value (type);
3401
3402 if (is_range)
3403 {
3404 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3405 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3406 }
3407 else
3408 {
3409 /* We can still generate assertion if one of alternatives
3410 is known to always be false. */
3411 if (val == min)
3412 {
3413 *low_code = (enum tree_code) 0;
3414 *high_code = GT_EXPR;
3415 }
3416 else if ((val | inv_mask) == max)
3417 {
3418 *low_code = LT_EXPR;
3419 *high_code = (enum tree_code) 0;
3420 }
3421 else
3422 return false;
3423 }
3424
3425 *new_name = t;
3426 *low = wide_int_to_tree (type, val);
3427 *high = wide_int_to_tree (type, val | inv_mask);
3428
3429 return true;
3430 }
3431
3432 /* Try to register an edge assertion for SSA name NAME on edge E for
3433 the condition COND contributing to the conditional jump pointed to by
3434 SI. */
3435
3436 void
3437 register_edge_assert_for (tree name, edge e,
3438 enum tree_code cond_code, tree cond_op0,
3439 tree cond_op1, vec<assert_info> &asserts)
3440 {
3441 tree val;
3442 enum tree_code comp_code;
3443 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3444
3445 /* Do not attempt to infer anything in names that flow through
3446 abnormal edges. */
3447 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3448 return;
3449
3450 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3451 cond_op0, cond_op1,
3452 is_else_edge,
3453 &comp_code, &val))
3454 return;
3455
3456 /* Register ASSERT_EXPRs for name. */
3457 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3458 cond_op1, is_else_edge, asserts);
3459
3460
3461 /* If COND is effectively an equality test of an SSA_NAME against
3462 the value zero or one, then we may be able to assert values
3463 for SSA_NAMEs which flow into COND. */
3464
3465 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3466 statement of NAME we can assert both operands of the BIT_AND_EXPR
3467 have nonzero value. */
3468 if (((comp_code == EQ_EXPR && integer_onep (val))
3469 || (comp_code == NE_EXPR && integer_zerop (val))))
3470 {
3471 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3472
3473 if (is_gimple_assign (def_stmt)
3474 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3475 {
3476 tree op0 = gimple_assign_rhs1 (def_stmt);
3477 tree op1 = gimple_assign_rhs2 (def_stmt);
3478 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3479 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3480 }
3481 }
3482
3483 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3484 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3485 have zero value. */
3486 if (((comp_code == EQ_EXPR && integer_zerop (val))
3487 || (comp_code == NE_EXPR && integer_onep (val))))
3488 {
3489 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3490
3491 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3492 necessarily zero value, or if type-precision is one. */
3493 if (is_gimple_assign (def_stmt)
3494 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3495 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3496 || comp_code == EQ_EXPR)))
3497 {
3498 tree op0 = gimple_assign_rhs1 (def_stmt);
3499 tree op1 = gimple_assign_rhs2 (def_stmt);
3500 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3501 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3502 }
3503 }
3504
3505 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3506 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3507 && TREE_CODE (val) == INTEGER_CST)
3508 {
3509 enum tree_code low_code, high_code;
3510 tree low, high;
3511 if (is_masked_range_test (name, val, comp_code, &name, &low,
3512 &low_code, &high, &high_code))
3513 {
3514 if (low_code != ERROR_MARK)
3515 register_edge_assert_for_2 (name, e, low_code, name,
3516 low, /*invert*/false, asserts);
3517 if (high_code != ERROR_MARK)
3518 register_edge_assert_for_2 (name, e, high_code, name,
3519 high, /*invert*/false, asserts);
3520 }
3521 }
3522 }
3523
3524 /* Finish found ASSERTS for E and register them at GSI. */
3525
3526 static void
3527 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3528 vec<assert_info> &asserts)
3529 {
3530 for (unsigned i = 0; i < asserts.length (); ++i)
3531 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3532 reachable from E. */
3533 if (live_on_edge (e, asserts[i].name))
3534 register_new_assert_for (asserts[i].name, asserts[i].expr,
3535 asserts[i].comp_code, asserts[i].val,
3536 NULL, e, gsi);
3537 }
3538
3539
3540
3541 /* Determine whether the outgoing edges of BB should receive an
3542 ASSERT_EXPR for each of the operands of BB's LAST statement.
3543 The last statement of BB must be a COND_EXPR.
3544
3545 If any of the sub-graphs rooted at BB have an interesting use of
3546 the predicate operands, an assert location node is added to the
3547 list of assertions for the corresponding operands. */
3548
3549 static void
3550 find_conditional_asserts (basic_block bb, gcond *last)
3551 {
3552 gimple_stmt_iterator bsi;
3553 tree op;
3554 edge_iterator ei;
3555 edge e;
3556 ssa_op_iter iter;
3557
3558 bsi = gsi_for_stmt (last);
3559
3560 /* Look for uses of the operands in each of the sub-graphs
3561 rooted at BB. We need to check each of the outgoing edges
3562 separately, so that we know what kind of ASSERT_EXPR to
3563 insert. */
3564 FOR_EACH_EDGE (e, ei, bb->succs)
3565 {
3566 if (e->dest == bb)
3567 continue;
3568
3569 /* Register the necessary assertions for each operand in the
3570 conditional predicate. */
3571 auto_vec<assert_info, 8> asserts;
3572 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3573 register_edge_assert_for (op, e,
3574 gimple_cond_code (last),
3575 gimple_cond_lhs (last),
3576 gimple_cond_rhs (last), asserts);
3577 finish_register_edge_assert_for (e, bsi, asserts);
3578 }
3579 }
3580
3581 struct case_info
3582 {
3583 tree expr;
3584 basic_block bb;
3585 };
3586
3587 /* Compare two case labels sorting first by the destination bb index
3588 and then by the case value. */
3589
3590 static int
3591 compare_case_labels (const void *p1, const void *p2)
3592 {
3593 const struct case_info *ci1 = (const struct case_info *) p1;
3594 const struct case_info *ci2 = (const struct case_info *) p2;
3595 int idx1 = ci1->bb->index;
3596 int idx2 = ci2->bb->index;
3597
3598 if (idx1 < idx2)
3599 return -1;
3600 else if (idx1 == idx2)
3601 {
3602 /* Make sure the default label is first in a group. */
3603 if (!CASE_LOW (ci1->expr))
3604 return -1;
3605 else if (!CASE_LOW (ci2->expr))
3606 return 1;
3607 else
3608 return tree_int_cst_compare (CASE_LOW (ci1->expr),
3609 CASE_LOW (ci2->expr));
3610 }
3611 else
3612 return 1;
3613 }
3614
3615 /* Determine whether the outgoing edges of BB should receive an
3616 ASSERT_EXPR for each of the operands of BB's LAST statement.
3617 The last statement of BB must be a SWITCH_EXPR.
3618
3619 If any of the sub-graphs rooted at BB have an interesting use of
3620 the predicate operands, an assert location node is added to the
3621 list of assertions for the corresponding operands. */
3622
3623 static void
3624 find_switch_asserts (basic_block bb, gswitch *last)
3625 {
3626 gimple_stmt_iterator bsi;
3627 tree op;
3628 edge e;
3629 struct case_info *ci;
3630 size_t n = gimple_switch_num_labels (last);
3631 #if GCC_VERSION >= 4000
3632 unsigned int idx;
3633 #else
3634 /* Work around GCC 3.4 bug (PR 37086). */
3635 volatile unsigned int idx;
3636 #endif
3637
3638 bsi = gsi_for_stmt (last);
3639 op = gimple_switch_index (last);
3640 if (TREE_CODE (op) != SSA_NAME)
3641 return;
3642
3643 /* Build a vector of case labels sorted by destination label. */
3644 ci = XNEWVEC (struct case_info, n);
3645 for (idx = 0; idx < n; ++idx)
3646 {
3647 ci[idx].expr = gimple_switch_label (last, idx);
3648 ci[idx].bb = label_to_block (cfun, CASE_LABEL (ci[idx].expr));
3649 }
3650 edge default_edge = find_edge (bb, ci[0].bb);
3651 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
3652
3653 for (idx = 0; idx < n; ++idx)
3654 {
3655 tree min, max;
3656 tree cl = ci[idx].expr;
3657 basic_block cbb = ci[idx].bb;
3658
3659 min = CASE_LOW (cl);
3660 max = CASE_HIGH (cl);
3661
3662 /* If there are multiple case labels with the same destination
3663 we need to combine them to a single value range for the edge. */
3664 if (idx + 1 < n && cbb == ci[idx + 1].bb)
3665 {
3666 /* Skip labels until the last of the group. */
3667 do {
3668 ++idx;
3669 } while (idx < n && cbb == ci[idx].bb);
3670 --idx;
3671
3672 /* Pick up the maximum of the case label range. */
3673 if (CASE_HIGH (ci[idx].expr))
3674 max = CASE_HIGH (ci[idx].expr);
3675 else
3676 max = CASE_LOW (ci[idx].expr);
3677 }
3678
3679 /* Can't extract a useful assertion out of a range that includes the
3680 default label. */
3681 if (min == NULL_TREE)
3682 continue;
3683
3684 /* Find the edge to register the assert expr on. */
3685 e = find_edge (bb, cbb);
3686
3687 /* Register the necessary assertions for the operand in the
3688 SWITCH_EXPR. */
3689 auto_vec<assert_info, 8> asserts;
3690 register_edge_assert_for (op, e,
3691 max ? GE_EXPR : EQ_EXPR,
3692 op, fold_convert (TREE_TYPE (op), min),
3693 asserts);
3694 if (max)
3695 register_edge_assert_for (op, e, LE_EXPR, op,
3696 fold_convert (TREE_TYPE (op), max),
3697 asserts);
3698 finish_register_edge_assert_for (e, bsi, asserts);
3699 }
3700
3701 XDELETEVEC (ci);
3702
3703 if (!live_on_edge (default_edge, op))
3704 return;
3705
3706 /* Now register along the default label assertions that correspond to the
3707 anti-range of each label. */
3708 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
3709 if (insertion_limit == 0)
3710 return;
3711
3712 /* We can't do this if the default case shares a label with another case. */
3713 tree default_cl = gimple_switch_default_label (last);
3714 for (idx = 1; idx < n; idx++)
3715 {
3716 tree min, max;
3717 tree cl = gimple_switch_label (last, idx);
3718 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3719 continue;
3720
3721 min = CASE_LOW (cl);
3722 max = CASE_HIGH (cl);
3723
3724 /* Combine contiguous case ranges to reduce the number of assertions
3725 to insert. */
3726 for (idx = idx + 1; idx < n; idx++)
3727 {
3728 tree next_min, next_max;
3729 tree next_cl = gimple_switch_label (last, idx);
3730 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3731 break;
3732
3733 next_min = CASE_LOW (next_cl);
3734 next_max = CASE_HIGH (next_cl);
3735
3736 wide_int difference = (wi::to_wide (next_min)
3737 - wi::to_wide (max ? max : min));
3738 if (wi::eq_p (difference, 1))
3739 max = next_max ? next_max : next_min;
3740 else
3741 break;
3742 }
3743 idx--;
3744
3745 if (max == NULL_TREE)
3746 {
3747 /* Register the assertion OP != MIN. */
3748 auto_vec<assert_info, 8> asserts;
3749 min = fold_convert (TREE_TYPE (op), min);
3750 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3751 asserts);
3752 finish_register_edge_assert_for (default_edge, bsi, asserts);
3753 }
3754 else
3755 {
3756 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3757 which will give OP the anti-range ~[MIN,MAX]. */
3758 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3759 min = fold_convert (TREE_TYPE (uop), min);
3760 max = fold_convert (TREE_TYPE (uop), max);
3761
3762 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3763 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3764 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3765 NULL, default_edge, bsi);
3766 }
3767
3768 if (--insertion_limit == 0)
3769 break;
3770 }
3771 }
3772
3773
3774 /* Traverse all the statements in block BB looking for statements that
3775 may generate useful assertions for the SSA names in their operand.
3776 If a statement produces a useful assertion A for name N_i, then the
3777 list of assertions already generated for N_i is scanned to
3778 determine if A is actually needed.
3779
3780 If N_i already had the assertion A at a location dominating the
3781 current location, then nothing needs to be done. Otherwise, the
3782 new location for A is recorded instead.
3783
3784 1- For every statement S in BB, all the variables used by S are
3785 added to bitmap FOUND_IN_SUBGRAPH.
3786
3787 2- If statement S uses an operand N in a way that exposes a known
3788 value range for N, then if N was not already generated by an
3789 ASSERT_EXPR, create a new assert location for N. For instance,
3790 if N is a pointer and the statement dereferences it, we can
3791 assume that N is not NULL.
3792
3793 3- COND_EXPRs are a special case of #2. We can derive range
3794 information from the predicate but need to insert different
3795 ASSERT_EXPRs for each of the sub-graphs rooted at the
3796 conditional block. If the last statement of BB is a conditional
3797 expression of the form 'X op Y', then
3798
3799 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3800
3801 b) If the conditional is the only entry point to the sub-graph
3802 corresponding to the THEN_CLAUSE, recurse into it. On
3803 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3804 an ASSERT_EXPR is added for the corresponding variable.
3805
3806 c) Repeat step (b) on the ELSE_CLAUSE.
3807
3808 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3809
3810 For instance,
3811
3812 if (a == 9)
3813 b = a;
3814 else
3815 b = c + 1;
3816
3817 In this case, an assertion on the THEN clause is useful to
3818 determine that 'a' is always 9 on that edge. However, an assertion
3819 on the ELSE clause would be unnecessary.
3820
3821 4- If BB does not end in a conditional expression, then we recurse
3822 into BB's dominator children.
3823
3824 At the end of the recursive traversal, every SSA name will have a
3825 list of locations where ASSERT_EXPRs should be added. When a new
3826 location for name N is found, it is registered by calling
3827 register_new_assert_for. That function keeps track of all the
3828 registered assertions to prevent adding unnecessary assertions.
3829 For instance, if a pointer P_4 is dereferenced more than once in a
3830 dominator tree, only the location dominating all the dereference of
3831 P_4 will receive an ASSERT_EXPR. */
3832
3833 static void
3834 find_assert_locations_1 (basic_block bb, sbitmap live)
3835 {
3836 gimple *last;
3837
3838 last = last_stmt (bb);
3839
3840 /* If BB's last statement is a conditional statement involving integer
3841 operands, determine if we need to add ASSERT_EXPRs. */
3842 if (last
3843 && gimple_code (last) == GIMPLE_COND
3844 && !fp_predicate (last)
3845 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3846 find_conditional_asserts (bb, as_a <gcond *> (last));
3847
3848 /* If BB's last statement is a switch statement involving integer
3849 operands, determine if we need to add ASSERT_EXPRs. */
3850 if (last
3851 && gimple_code (last) == GIMPLE_SWITCH
3852 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3853 find_switch_asserts (bb, as_a <gswitch *> (last));
3854
3855 /* Traverse all the statements in BB marking used names and looking
3856 for statements that may infer assertions for their used operands. */
3857 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3858 gsi_prev (&si))
3859 {
3860 gimple *stmt;
3861 tree op;
3862 ssa_op_iter i;
3863
3864 stmt = gsi_stmt (si);
3865
3866 if (is_gimple_debug (stmt))
3867 continue;
3868
3869 /* See if we can derive an assertion for any of STMT's operands. */
3870 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3871 {
3872 tree value;
3873 enum tree_code comp_code;
3874
3875 /* If op is not live beyond this stmt, do not bother to insert
3876 asserts for it. */
3877 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
3878 continue;
3879
3880 /* If OP is used in such a way that we can infer a value
3881 range for it, and we don't find a previous assertion for
3882 it, create a new assertion location node for OP. */
3883 if (infer_value_range (stmt, op, &comp_code, &value))
3884 {
3885 /* If we are able to infer a nonzero value range for OP,
3886 then walk backwards through the use-def chain to see if OP
3887 was set via a typecast.
3888
3889 If so, then we can also infer a nonzero value range
3890 for the operand of the NOP_EXPR. */
3891 if (comp_code == NE_EXPR && integer_zerop (value))
3892 {
3893 tree t = op;
3894 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3895
3896 while (is_gimple_assign (def_stmt)
3897 && CONVERT_EXPR_CODE_P
3898 (gimple_assign_rhs_code (def_stmt))
3899 && TREE_CODE
3900 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3901 && POINTER_TYPE_P
3902 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3903 {
3904 t = gimple_assign_rhs1 (def_stmt);
3905 def_stmt = SSA_NAME_DEF_STMT (t);
3906
3907 /* Note we want to register the assert for the
3908 operand of the NOP_EXPR after SI, not after the
3909 conversion. */
3910 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
3911 register_new_assert_for (t, t, comp_code, value,
3912 bb, NULL, si);
3913 }
3914 }
3915
3916 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3917 }
3918 }
3919
3920 /* Update live. */
3921 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3922 bitmap_set_bit (live, SSA_NAME_VERSION (op));
3923 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3924 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
3925 }
3926
3927 /* Traverse all PHI nodes in BB, updating live. */
3928 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3929 gsi_next (&si))
3930 {
3931 use_operand_p arg_p;
3932 ssa_op_iter i;
3933 gphi *phi = si.phi ();
3934 tree res = gimple_phi_result (phi);
3935
3936 if (virtual_operand_p (res))
3937 continue;
3938
3939 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3940 {
3941 tree arg = USE_FROM_PTR (arg_p);
3942 if (TREE_CODE (arg) == SSA_NAME)
3943 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
3944 }
3945
3946 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
3947 }
3948 }
3949
3950 /* Do an RPO walk over the function computing SSA name liveness
3951 on-the-fly and deciding on assert expressions to insert. */
3952
3953 static void
3954 find_assert_locations (void)
3955 {
3956 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3957 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3958 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
3959 int rpo_cnt, i;
3960
3961 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
3962 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3963 for (i = 0; i < rpo_cnt; ++i)
3964 bb_rpo[rpo[i]] = i;
3965
3966 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3967 the order we compute liveness and insert asserts we otherwise
3968 fail to insert asserts into the loop latch. */
3969 loop_p loop;
3970 FOR_EACH_LOOP (loop, 0)
3971 {
3972 i = loop->latch->index;
3973 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3974 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3975 !gsi_end_p (gsi); gsi_next (&gsi))
3976 {
3977 gphi *phi = gsi.phi ();
3978 if (virtual_operand_p (gimple_phi_result (phi)))
3979 continue;
3980 tree arg = gimple_phi_arg_def (phi, j);
3981 if (TREE_CODE (arg) == SSA_NAME)
3982 {
3983 if (live[i] == NULL)
3984 {
3985 live[i] = sbitmap_alloc (num_ssa_names);
3986 bitmap_clear (live[i]);
3987 }
3988 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
3989 }
3990 }
3991 }
3992
3993 for (i = rpo_cnt - 1; i >= 0; --i)
3994 {
3995 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
3996 edge e;
3997 edge_iterator ei;
3998
3999 if (!live[rpo[i]])
4000 {
4001 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
4002 bitmap_clear (live[rpo[i]]);
4003 }
4004
4005 /* Process BB and update the live information with uses in
4006 this block. */
4007 find_assert_locations_1 (bb, live[rpo[i]]);
4008
4009 /* Merge liveness into the predecessor blocks and free it. */
4010 if (!bitmap_empty_p (live[rpo[i]]))
4011 {
4012 int pred_rpo = i;
4013 FOR_EACH_EDGE (e, ei, bb->preds)
4014 {
4015 int pred = e->src->index;
4016 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
4017 continue;
4018
4019 if (!live[pred])
4020 {
4021 live[pred] = sbitmap_alloc (num_ssa_names);
4022 bitmap_clear (live[pred]);
4023 }
4024 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
4025
4026 if (bb_rpo[pred] < pred_rpo)
4027 pred_rpo = bb_rpo[pred];
4028 }
4029
4030 /* Record the RPO number of the last visited block that needs
4031 live information from this block. */
4032 last_rpo[rpo[i]] = pred_rpo;
4033 }
4034 else
4035 {
4036 sbitmap_free (live[rpo[i]]);
4037 live[rpo[i]] = NULL;
4038 }
4039
4040 /* We can free all successors live bitmaps if all their
4041 predecessors have been visited already. */
4042 FOR_EACH_EDGE (e, ei, bb->succs)
4043 if (last_rpo[e->dest->index] == i
4044 && live[e->dest->index])
4045 {
4046 sbitmap_free (live[e->dest->index]);
4047 live[e->dest->index] = NULL;
4048 }
4049 }
4050
4051 XDELETEVEC (rpo);
4052 XDELETEVEC (bb_rpo);
4053 XDELETEVEC (last_rpo);
4054 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
4055 if (live[i])
4056 sbitmap_free (live[i]);
4057 XDELETEVEC (live);
4058 }
4059
4060 /* Create an ASSERT_EXPR for NAME and insert it in the location
4061 indicated by LOC. Return true if we made any edge insertions. */
4062
4063 static bool
4064 process_assert_insertions_for (tree name, assert_locus *loc)
4065 {
4066 /* Build the comparison expression NAME_i COMP_CODE VAL. */
4067 gimple *stmt;
4068 tree cond;
4069 gimple *assert_stmt;
4070 edge_iterator ei;
4071 edge e;
4072
4073 /* If we have X <=> X do not insert an assert expr for that. */
4074 if (loc->expr == loc->val)
4075 return false;
4076
4077 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
4078 assert_stmt = build_assert_expr_for (cond, name);
4079 if (loc->e)
4080 {
4081 /* We have been asked to insert the assertion on an edge. This
4082 is used only by COND_EXPR and SWITCH_EXPR assertions. */
4083 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
4084 || (gimple_code (gsi_stmt (loc->si))
4085 == GIMPLE_SWITCH));
4086
4087 gsi_insert_on_edge (loc->e, assert_stmt);
4088 return true;
4089 }
4090
4091 /* If the stmt iterator points at the end then this is an insertion
4092 at the beginning of a block. */
4093 if (gsi_end_p (loc->si))
4094 {
4095 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
4096 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
4097 return false;
4098
4099 }
4100 /* Otherwise, we can insert right after LOC->SI iff the
4101 statement must not be the last statement in the block. */
4102 stmt = gsi_stmt (loc->si);
4103 if (!stmt_ends_bb_p (stmt))
4104 {
4105 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
4106 return false;
4107 }
4108
4109 /* If STMT must be the last statement in BB, we can only insert new
4110 assertions on the non-abnormal edge out of BB. Note that since
4111 STMT is not control flow, there may only be one non-abnormal/eh edge
4112 out of BB. */
4113 FOR_EACH_EDGE (e, ei, loc->bb->succs)
4114 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4115 {
4116 gsi_insert_on_edge (e, assert_stmt);
4117 return true;
4118 }
4119
4120 gcc_unreachable ();
4121 }
4122
4123 /* Qsort helper for sorting assert locations. If stable is true, don't
4124 use iterative_hash_expr because it can be unstable for -fcompare-debug,
4125 on the other side some pointers might be NULL. */
4126
4127 template <bool stable>
4128 static int
4129 compare_assert_loc (const void *pa, const void *pb)
4130 {
4131 assert_locus * const a = *(assert_locus * const *)pa;
4132 assert_locus * const b = *(assert_locus * const *)pb;
4133
4134 /* If stable, some asserts might be optimized away already, sort
4135 them last. */
4136 if (stable)
4137 {
4138 if (a == NULL)
4139 return b != NULL;
4140 else if (b == NULL)
4141 return -1;
4142 }
4143
4144 if (a->e == NULL && b->e != NULL)
4145 return 1;
4146 else if (a->e != NULL && b->e == NULL)
4147 return -1;
4148
4149 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
4150 no need to test both a->e and b->e. */
4151
4152 /* Sort after destination index. */
4153 if (a->e == NULL)
4154 ;
4155 else if (a->e->dest->index > b->e->dest->index)
4156 return 1;
4157 else if (a->e->dest->index < b->e->dest->index)
4158 return -1;
4159
4160 /* Sort after comp_code. */
4161 if (a->comp_code > b->comp_code)
4162 return 1;
4163 else if (a->comp_code < b->comp_code)
4164 return -1;
4165
4166 hashval_t ha, hb;
4167
4168 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
4169 uses DECL_UID of the VAR_DECL, so sorting might differ between
4170 -g and -g0. When doing the removal of redundant assert exprs
4171 and commonization to successors, this does not matter, but for
4172 the final sort needs to be stable. */
4173 if (stable)
4174 {
4175 ha = 0;
4176 hb = 0;
4177 }
4178 else
4179 {
4180 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4181 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4182 }
4183
4184 /* Break the tie using hashing and source/bb index. */
4185 if (ha == hb)
4186 return (a->e != NULL
4187 ? a->e->src->index - b->e->src->index
4188 : a->bb->index - b->bb->index);
4189 return ha > hb ? 1 : -1;
4190 }
4191
4192 /* Process all the insertions registered for every name N_i registered
4193 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4194 found in ASSERTS_FOR[i]. */
4195
4196 static void
4197 process_assert_insertions (void)
4198 {
4199 unsigned i;
4200 bitmap_iterator bi;
4201 bool update_edges_p = false;
4202 int num_asserts = 0;
4203
4204 if (dump_file && (dump_flags & TDF_DETAILS))
4205 dump_all_asserts (dump_file);
4206
4207 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4208 {
4209 assert_locus *loc = asserts_for[i];
4210 gcc_assert (loc);
4211
4212 auto_vec<assert_locus *, 16> asserts;
4213 for (; loc; loc = loc->next)
4214 asserts.safe_push (loc);
4215 asserts.qsort (compare_assert_loc<false>);
4216
4217 /* Push down common asserts to successors and remove redundant ones. */
4218 unsigned ecnt = 0;
4219 assert_locus *common = NULL;
4220 unsigned commonj = 0;
4221 for (unsigned j = 0; j < asserts.length (); ++j)
4222 {
4223 loc = asserts[j];
4224 if (! loc->e)
4225 common = NULL;
4226 else if (! common
4227 || loc->e->dest != common->e->dest
4228 || loc->comp_code != common->comp_code
4229 || ! operand_equal_p (loc->val, common->val, 0)
4230 || ! operand_equal_p (loc->expr, common->expr, 0))
4231 {
4232 commonj = j;
4233 common = loc;
4234 ecnt = 1;
4235 }
4236 else if (loc->e == asserts[j-1]->e)
4237 {
4238 /* Remove duplicate asserts. */
4239 if (commonj == j - 1)
4240 {
4241 commonj = j;
4242 common = loc;
4243 }
4244 free (asserts[j-1]);
4245 asserts[j-1] = NULL;
4246 }
4247 else
4248 {
4249 ecnt++;
4250 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4251 {
4252 /* We have the same assertion on all incoming edges of a BB.
4253 Insert it at the beginning of that block. */
4254 loc->bb = loc->e->dest;
4255 loc->e = NULL;
4256 loc->si = gsi_none ();
4257 common = NULL;
4258 /* Clear asserts commoned. */
4259 for (; commonj != j; ++commonj)
4260 if (asserts[commonj])
4261 {
4262 free (asserts[commonj]);
4263 asserts[commonj] = NULL;
4264 }
4265 }
4266 }
4267 }
4268
4269 /* The asserts vector sorting above might be unstable for
4270 -fcompare-debug, sort again to ensure a stable sort. */
4271 asserts.qsort (compare_assert_loc<true>);
4272 for (unsigned j = 0; j < asserts.length (); ++j)
4273 {
4274 loc = asserts[j];
4275 if (! loc)
4276 break;
4277 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4278 num_asserts++;
4279 free (loc);
4280 }
4281 }
4282
4283 if (update_edges_p)
4284 gsi_commit_edge_inserts ();
4285
4286 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4287 num_asserts);
4288 }
4289
4290
4291 /* Traverse the flowgraph looking for conditional jumps to insert range
4292 expressions. These range expressions are meant to provide information
4293 to optimizations that need to reason in terms of value ranges. They
4294 will not be expanded into RTL. For instance, given:
4295
4296 x = ...
4297 y = ...
4298 if (x < y)
4299 y = x - 2;
4300 else
4301 x = y + 3;
4302
4303 this pass will transform the code into:
4304
4305 x = ...
4306 y = ...
4307 if (x < y)
4308 {
4309 x = ASSERT_EXPR <x, x < y>
4310 y = x - 2
4311 }
4312 else
4313 {
4314 y = ASSERT_EXPR <y, x >= y>
4315 x = y + 3
4316 }
4317
4318 The idea is that once copy and constant propagation have run, other
4319 optimizations will be able to determine what ranges of values can 'x'
4320 take in different paths of the code, simply by checking the reaching
4321 definition of 'x'. */
4322
4323 static void
4324 insert_range_assertions (void)
4325 {
4326 need_assert_for = BITMAP_ALLOC (NULL);
4327 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4328
4329 calculate_dominance_info (CDI_DOMINATORS);
4330
4331 find_assert_locations ();
4332 if (!bitmap_empty_p (need_assert_for))
4333 {
4334 process_assert_insertions ();
4335 update_ssa (TODO_update_ssa_no_phi);
4336 }
4337
4338 if (dump_file && (dump_flags & TDF_DETAILS))
4339 {
4340 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4341 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4342 }
4343
4344 free (asserts_for);
4345 BITMAP_FREE (need_assert_for);
4346 }
4347
4348 class vrp_prop : public ssa_propagation_engine
4349 {
4350 public:
4351 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4352 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4353
4354 void vrp_initialize (void);
4355 void vrp_finalize (bool);
4356 void check_all_array_refs (void);
4357 void check_array_ref (location_t, tree, bool);
4358 void check_mem_ref (location_t, tree, bool);
4359 void search_for_addr_array (tree, location_t);
4360
4361 class vr_values vr_values;
4362 /* Temporary delegator to minimize code churn. */
4363 const value_range *get_value_range (const_tree op)
4364 { return vr_values.get_value_range (op); }
4365 void set_def_to_varying (const_tree def)
4366 { vr_values.set_def_to_varying (def); }
4367 void set_defs_to_varying (gimple *stmt)
4368 { vr_values.set_defs_to_varying (stmt); }
4369 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4370 tree *output_p, value_range *vr)
4371 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4372 bool update_value_range (const_tree op, value_range *vr)
4373 { return vr_values.update_value_range (op, vr); }
4374 void extract_range_basic (value_range *vr, gimple *stmt)
4375 { vr_values.extract_range_basic (vr, stmt); }
4376 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4377 { vr_values.extract_range_from_phi_node (phi, vr); }
4378 };
4379 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4380 and "struct" hacks. If VRP can determine that the
4381 array subscript is a constant, check if it is outside valid
4382 range. If the array subscript is a RANGE, warn if it is
4383 non-overlapping with valid range.
4384 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4385
4386 void
4387 vrp_prop::check_array_ref (location_t location, tree ref,
4388 bool ignore_off_by_one)
4389 {
4390 const value_range *vr = NULL;
4391 tree low_sub, up_sub;
4392 tree low_bound, up_bound, up_bound_p1;
4393
4394 if (TREE_NO_WARNING (ref))
4395 return;
4396
4397 low_sub = up_sub = TREE_OPERAND (ref, 1);
4398 up_bound = array_ref_up_bound (ref);
4399
4400 if (!up_bound
4401 || TREE_CODE (up_bound) != INTEGER_CST
4402 || (warn_array_bounds < 2
4403 && array_at_struct_end_p (ref)))
4404 {
4405 /* Accesses to trailing arrays via pointers may access storage
4406 beyond the types array bounds. For such arrays, or for flexible
4407 array members, as well as for other arrays of an unknown size,
4408 replace the upper bound with a more permissive one that assumes
4409 the size of the largest object is PTRDIFF_MAX. */
4410 tree eltsize = array_ref_element_size (ref);
4411
4412 if (TREE_CODE (eltsize) != INTEGER_CST
4413 || integer_zerop (eltsize))
4414 {
4415 up_bound = NULL_TREE;
4416 up_bound_p1 = NULL_TREE;
4417 }
4418 else
4419 {
4420 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4421 tree arg = TREE_OPERAND (ref, 0);
4422 poly_int64 off;
4423
4424 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4425 maxbound = wide_int_to_tree (sizetype,
4426 wi::sub (wi::to_wide (maxbound),
4427 off));
4428 else
4429 maxbound = fold_convert (sizetype, maxbound);
4430
4431 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4432
4433 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4434 build_int_cst (ptrdiff_type_node, 1));
4435 }
4436 }
4437 else
4438 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4439 build_int_cst (TREE_TYPE (up_bound), 1));
4440
4441 low_bound = array_ref_low_bound (ref);
4442
4443 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4444
4445 bool warned = false;
4446
4447 /* Empty array. */
4448 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4449 warned = warning_at (location, OPT_Warray_bounds,
4450 "array subscript %E is above array bounds of %qT",
4451 low_bound, artype);
4452
4453 if (TREE_CODE (low_sub) == SSA_NAME)
4454 {
4455 vr = get_value_range (low_sub);
4456 if (!vr->undefined_p () && !vr->varying_p ())
4457 {
4458 low_sub = vr->kind () == VR_RANGE ? vr->max () : vr->min ();
4459 up_sub = vr->kind () == VR_RANGE ? vr->min () : vr->max ();
4460 }
4461 }
4462
4463 if (vr && vr->kind () == VR_ANTI_RANGE)
4464 {
4465 if (up_bound
4466 && TREE_CODE (up_sub) == INTEGER_CST
4467 && (ignore_off_by_one
4468 ? tree_int_cst_lt (up_bound, up_sub)
4469 : tree_int_cst_le (up_bound, up_sub))
4470 && TREE_CODE (low_sub) == INTEGER_CST
4471 && tree_int_cst_le (low_sub, low_bound))
4472 warned = warning_at (location, OPT_Warray_bounds,
4473 "array subscript [%E, %E] is outside "
4474 "array bounds of %qT",
4475 low_sub, up_sub, artype);
4476 }
4477 else if (up_bound
4478 && TREE_CODE (up_sub) == INTEGER_CST
4479 && (ignore_off_by_one
4480 ? !tree_int_cst_le (up_sub, up_bound_p1)
4481 : !tree_int_cst_le (up_sub, up_bound)))
4482 {
4483 if (dump_file && (dump_flags & TDF_DETAILS))
4484 {
4485 fprintf (dump_file, "Array bound warning for ");
4486 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4487 fprintf (dump_file, "\n");
4488 }
4489 warned = warning_at (location, OPT_Warray_bounds,
4490 "array subscript %E is above array bounds of %qT",
4491 up_sub, artype);
4492 }
4493 else if (TREE_CODE (low_sub) == INTEGER_CST
4494 && tree_int_cst_lt (low_sub, low_bound))
4495 {
4496 if (dump_file && (dump_flags & TDF_DETAILS))
4497 {
4498 fprintf (dump_file, "Array bound warning for ");
4499 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4500 fprintf (dump_file, "\n");
4501 }
4502 warned = warning_at (location, OPT_Warray_bounds,
4503 "array subscript %E is below array bounds of %qT",
4504 low_sub, artype);
4505 }
4506
4507 if (warned)
4508 {
4509 ref = TREE_OPERAND (ref, 0);
4510
4511 if (DECL_P (ref))
4512 inform (DECL_SOURCE_LOCATION (ref), "while referencing %qD", ref);
4513
4514 TREE_NO_WARNING (ref) = 1;
4515 }
4516 }
4517
4518 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
4519 references to string constants. If VRP can determine that the array
4520 subscript is a constant, check if it is outside valid range.
4521 If the array subscript is a RANGE, warn if it is non-overlapping
4522 with valid range.
4523 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
4524 (used to allow one-past-the-end indices for code that takes
4525 the address of the just-past-the-end element of an array). */
4526
4527 void
4528 vrp_prop::check_mem_ref (location_t location, tree ref,
4529 bool ignore_off_by_one)
4530 {
4531 if (TREE_NO_WARNING (ref))
4532 return;
4533
4534 tree arg = TREE_OPERAND (ref, 0);
4535 /* The constant and variable offset of the reference. */
4536 tree cstoff = TREE_OPERAND (ref, 1);
4537 tree varoff = NULL_TREE;
4538
4539 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
4540
4541 /* The array or string constant bounds in bytes. Initially set
4542 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
4543 determined. */
4544 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
4545
4546 /* The minimum and maximum intermediate offset. For a reference
4547 to be valid, not only does the final offset/subscript must be
4548 in bounds but all intermediate offsets should be as well.
4549 GCC may be able to deal gracefully with such out-of-bounds
4550 offsets so the checking is only enbaled at -Warray-bounds=2
4551 where it may help detect bugs in uses of the intermediate
4552 offsets that could otherwise not be detectable. */
4553 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
4554 offset_int extrema[2] = { 0, wi::abs (ioff) };
4555
4556 /* The range of the byte offset into the reference. */
4557 offset_int offrange[2] = { 0, 0 };
4558
4559 const value_range *vr = NULL;
4560
4561 /* Determine the offsets and increment OFFRANGE for the bounds of each.
4562 The loop computes the range of the final offset for expressions such
4563 as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs in
4564 some range. */
4565 const unsigned limit = PARAM_VALUE (PARAM_SSA_NAME_DEF_CHAIN_LIMIT);
4566 for (unsigned n = 0; TREE_CODE (arg) == SSA_NAME && n < limit; ++n)
4567 {
4568 gimple *def = SSA_NAME_DEF_STMT (arg);
4569 if (!is_gimple_assign (def))
4570 break;
4571
4572 tree_code code = gimple_assign_rhs_code (def);
4573 if (code == POINTER_PLUS_EXPR)
4574 {
4575 arg = gimple_assign_rhs1 (def);
4576 varoff = gimple_assign_rhs2 (def);
4577 }
4578 else if (code == ASSERT_EXPR)
4579 {
4580 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
4581 continue;
4582 }
4583 else
4584 return;
4585
4586 /* VAROFF should always be a SSA_NAME here (and not even
4587 INTEGER_CST) but there's no point in taking chances. */
4588 if (TREE_CODE (varoff) != SSA_NAME)
4589 break;
4590
4591 vr = get_value_range (varoff);
4592 if (!vr || vr->undefined_p () || vr->varying_p ())
4593 break;
4594
4595 if (!vr->constant_p ())
4596 break;
4597
4598 if (vr->kind () == VR_RANGE)
4599 {
4600 offset_int min
4601 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min ()));
4602 offset_int max
4603 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max ()));
4604 if (min < max)
4605 {
4606 offrange[0] += min;
4607 offrange[1] += max;
4608 }
4609 else
4610 {
4611 /* When MIN >= MAX, the offset is effectively in a union
4612 of two ranges: [-MAXOBJSIZE -1, MAX] and [MIN, MAXOBJSIZE].
4613 Since there is no way to represent such a range across
4614 additions, conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
4615 to OFFRANGE. */
4616 offrange[0] += arrbounds[0];
4617 offrange[1] += arrbounds[1];
4618 }
4619 }
4620 else
4621 {
4622 /* For an anti-range, analogously to the above, conservatively
4623 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
4624 offrange[0] += arrbounds[0];
4625 offrange[1] += arrbounds[1];
4626 }
4627
4628 /* Keep track of the minimum and maximum offset. */
4629 if (offrange[1] < 0 && offrange[1] < extrema[0])
4630 extrema[0] = offrange[1];
4631 if (offrange[0] > 0 && offrange[0] > extrema[1])
4632 extrema[1] = offrange[0];
4633
4634 if (offrange[0] < arrbounds[0])
4635 offrange[0] = arrbounds[0];
4636
4637 if (offrange[1] > arrbounds[1])
4638 offrange[1] = arrbounds[1];
4639 }
4640
4641 if (TREE_CODE (arg) == ADDR_EXPR)
4642 {
4643 arg = TREE_OPERAND (arg, 0);
4644 if (TREE_CODE (arg) != STRING_CST
4645 && TREE_CODE (arg) != VAR_DECL)
4646 return;
4647 }
4648 else
4649 return;
4650
4651 /* The type of the object being referred to. It can be an array,
4652 string literal, or a non-array type when the MEM_REF represents
4653 a reference/subscript via a pointer to an object that is not
4654 an element of an array. References to members of structs and
4655 unions are excluded because MEM_REF doesn't make it possible
4656 to identify the member where the reference originated.
4657 Incomplete types are excluded as well because their size is
4658 not known. */
4659 tree reftype = TREE_TYPE (arg);
4660 if (POINTER_TYPE_P (reftype)
4661 || !COMPLETE_TYPE_P (reftype)
4662 || TREE_CODE (TYPE_SIZE_UNIT (reftype)) != INTEGER_CST
4663 || RECORD_OR_UNION_TYPE_P (reftype))
4664 return;
4665
4666 offset_int eltsize;
4667 if (TREE_CODE (reftype) == ARRAY_TYPE)
4668 {
4669 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
4670
4671 if (tree dom = TYPE_DOMAIN (reftype))
4672 {
4673 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
4674 if (array_at_struct_end_p (arg)
4675 || !bnds[0] || !bnds[1])
4676 {
4677 arrbounds[0] = 0;
4678 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4679 }
4680 else
4681 {
4682 arrbounds[0] = wi::to_offset (bnds[0]) * eltsize;
4683 arrbounds[1] = (wi::to_offset (bnds[1]) + 1) * eltsize;
4684 }
4685 }
4686 else
4687 {
4688 arrbounds[0] = 0;
4689 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4690 }
4691
4692 if (TREE_CODE (ref) == MEM_REF)
4693 {
4694 /* For MEM_REF determine a tighter bound of the non-array
4695 element type. */
4696 tree eltype = TREE_TYPE (reftype);
4697 while (TREE_CODE (eltype) == ARRAY_TYPE)
4698 eltype = TREE_TYPE (eltype);
4699 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
4700 }
4701 }
4702 else
4703 {
4704 eltsize = 1;
4705 arrbounds[0] = 0;
4706 arrbounds[1] = wi::to_offset (TYPE_SIZE_UNIT (reftype));
4707 }
4708
4709 offrange[0] += ioff;
4710 offrange[1] += ioff;
4711
4712 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
4713 is set (when taking the address of the one-past-last element
4714 of an array) but always use the stricter bound in diagnostics. */
4715 offset_int ubound = arrbounds[1];
4716 if (ignore_off_by_one)
4717 ubound += 1;
4718
4719 if (offrange[0] >= ubound || offrange[1] < arrbounds[0])
4720 {
4721 /* Treat a reference to a non-array object as one to an array
4722 of a single element. */
4723 if (TREE_CODE (reftype) != ARRAY_TYPE)
4724 reftype = build_array_type_nelts (reftype, 1);
4725
4726 if (TREE_CODE (ref) == MEM_REF)
4727 {
4728 /* Extract the element type out of MEM_REF and use its size
4729 to compute the index to print in the diagnostic; arrays
4730 in MEM_REF don't mean anything. A type with no size like
4731 void is as good as having a size of 1. */
4732 tree type = TREE_TYPE (ref);
4733 while (TREE_CODE (type) == ARRAY_TYPE)
4734 type = TREE_TYPE (type);
4735 if (tree size = TYPE_SIZE_UNIT (type))
4736 {
4737 offrange[0] = offrange[0] / wi::to_offset (size);
4738 offrange[1] = offrange[1] / wi::to_offset (size);
4739 }
4740 }
4741 else
4742 {
4743 /* For anything other than MEM_REF, compute the index to
4744 print in the diagnostic as the offset over element size. */
4745 offrange[0] = offrange[0] / eltsize;
4746 offrange[1] = offrange[1] / eltsize;
4747 }
4748
4749 bool warned;
4750 if (offrange[0] == offrange[1])
4751 warned = warning_at (location, OPT_Warray_bounds,
4752 "array subscript %wi is outside array bounds "
4753 "of %qT",
4754 offrange[0].to_shwi (), reftype);
4755 else
4756 warned = warning_at (location, OPT_Warray_bounds,
4757 "array subscript [%wi, %wi] is outside "
4758 "array bounds of %qT",
4759 offrange[0].to_shwi (),
4760 offrange[1].to_shwi (), reftype);
4761 if (warned && DECL_P (arg))
4762 inform (DECL_SOURCE_LOCATION (arg), "while referencing %qD", arg);
4763
4764 if (warned)
4765 TREE_NO_WARNING (ref) = 1;
4766 return;
4767 }
4768
4769 if (warn_array_bounds < 2)
4770 return;
4771
4772 /* At level 2 check also intermediate offsets. */
4773 int i = 0;
4774 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
4775 {
4776 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
4777
4778 if (warning_at (location, OPT_Warray_bounds,
4779 "intermediate array offset %wi is outside array bounds "
4780 "of %qT", tmpidx, reftype))
4781 TREE_NO_WARNING (ref) = 1;
4782 }
4783 }
4784
4785 /* Searches if the expr T, located at LOCATION computes
4786 address of an ARRAY_REF, and call check_array_ref on it. */
4787
4788 void
4789 vrp_prop::search_for_addr_array (tree t, location_t location)
4790 {
4791 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
4792 do
4793 {
4794 if (TREE_CODE (t) == ARRAY_REF)
4795 check_array_ref (location, t, true /*ignore_off_by_one*/);
4796 else if (TREE_CODE (t) == MEM_REF)
4797 check_mem_ref (location, t, true /*ignore_off_by_one*/);
4798
4799 t = TREE_OPERAND (t, 0);
4800 }
4801 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
4802
4803 if (TREE_CODE (t) != MEM_REF
4804 || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR
4805 || TREE_NO_WARNING (t))
4806 return;
4807
4808 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4809 tree low_bound, up_bound, el_sz;
4810 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4811 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4812 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4813 return;
4814
4815 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4816 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4817 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4818 if (!low_bound
4819 || TREE_CODE (low_bound) != INTEGER_CST
4820 || !up_bound
4821 || TREE_CODE (up_bound) != INTEGER_CST
4822 || !el_sz
4823 || TREE_CODE (el_sz) != INTEGER_CST)
4824 return;
4825
4826 offset_int idx;
4827 if (!mem_ref_offset (t).is_constant (&idx))
4828 return;
4829
4830 bool warned = false;
4831 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
4832 if (idx < 0)
4833 {
4834 if (dump_file && (dump_flags & TDF_DETAILS))
4835 {
4836 fprintf (dump_file, "Array bound warning for ");
4837 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4838 fprintf (dump_file, "\n");
4839 }
4840 warned = warning_at (location, OPT_Warray_bounds,
4841 "array subscript %wi is below "
4842 "array bounds of %qT",
4843 idx.to_shwi (), TREE_TYPE (tem));
4844 }
4845 else if (idx > (wi::to_offset (up_bound)
4846 - wi::to_offset (low_bound) + 1))
4847 {
4848 if (dump_file && (dump_flags & TDF_DETAILS))
4849 {
4850 fprintf (dump_file, "Array bound warning for ");
4851 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4852 fprintf (dump_file, "\n");
4853 }
4854 warned = warning_at (location, OPT_Warray_bounds,
4855 "array subscript %wu is above "
4856 "array bounds of %qT",
4857 idx.to_uhwi (), TREE_TYPE (tem));
4858 }
4859
4860 if (warned)
4861 {
4862 if (DECL_P (t))
4863 inform (DECL_SOURCE_LOCATION (t), "while referencing %qD", t);
4864
4865 TREE_NO_WARNING (t) = 1;
4866 }
4867 }
4868
4869 /* walk_tree() callback that checks if *TP is
4870 an ARRAY_REF inside an ADDR_EXPR (in which an array
4871 subscript one outside the valid range is allowed). Call
4872 check_array_ref for each ARRAY_REF found. The location is
4873 passed in DATA. */
4874
4875 static tree
4876 check_array_bounds (tree *tp, int *walk_subtree, void *data)
4877 {
4878 tree t = *tp;
4879 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
4880 location_t location;
4881
4882 if (EXPR_HAS_LOCATION (t))
4883 location = EXPR_LOCATION (t);
4884 else
4885 location = gimple_location (wi->stmt);
4886
4887 *walk_subtree = TRUE;
4888
4889 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
4890 if (TREE_CODE (t) == ARRAY_REF)
4891 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
4892 else if (TREE_CODE (t) == MEM_REF)
4893 vrp_prop->check_mem_ref (location, t, false /*ignore_off_by_one*/);
4894 else if (TREE_CODE (t) == ADDR_EXPR)
4895 {
4896 vrp_prop->search_for_addr_array (t, location);
4897 *walk_subtree = FALSE;
4898 }
4899
4900 return NULL_TREE;
4901 }
4902
4903 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
4904 to walk over all statements of all reachable BBs and call
4905 check_array_bounds on them. */
4906
4907 class check_array_bounds_dom_walker : public dom_walker
4908 {
4909 public:
4910 check_array_bounds_dom_walker (vrp_prop *prop)
4911 : dom_walker (CDI_DOMINATORS,
4912 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
4913 flags, so that we can merge in information on
4914 non-executable edges from vrp_folder . */
4915 REACHABLE_BLOCKS_PRESERVING_FLAGS),
4916 m_prop (prop) {}
4917 ~check_array_bounds_dom_walker () {}
4918
4919 edge before_dom_children (basic_block) FINAL OVERRIDE;
4920
4921 private:
4922 vrp_prop *m_prop;
4923 };
4924
4925 /* Implementation of dom_walker::before_dom_children.
4926
4927 Walk over all statements of BB and call check_array_bounds on them,
4928 and determine if there's a unique successor edge. */
4929
4930 edge
4931 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
4932 {
4933 gimple_stmt_iterator si;
4934 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
4935 {
4936 gimple *stmt = gsi_stmt (si);
4937 struct walk_stmt_info wi;
4938 if (!gimple_has_location (stmt)
4939 || is_gimple_debug (stmt))
4940 continue;
4941
4942 memset (&wi, 0, sizeof (wi));
4943
4944 wi.info = m_prop;
4945
4946 walk_gimple_op (stmt, check_array_bounds, &wi);
4947 }
4948
4949 /* Determine if there's a unique successor edge, and if so, return
4950 that back to dom_walker, ensuring that we don't visit blocks that
4951 became unreachable during the VRP propagation
4952 (PR tree-optimization/83312). */
4953 return find_taken_edge (bb, NULL_TREE);
4954 }
4955
4956 /* Walk over all statements of all reachable BBs and call check_array_bounds
4957 on them. */
4958
4959 void
4960 vrp_prop::check_all_array_refs ()
4961 {
4962 check_array_bounds_dom_walker w (this);
4963 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
4964 }
4965
4966 /* Return true if all imm uses of VAR are either in STMT, or
4967 feed (optionally through a chain of single imm uses) GIMPLE_COND
4968 in basic block COND_BB. */
4969
4970 static bool
4971 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
4972 {
4973 use_operand_p use_p, use2_p;
4974 imm_use_iterator iter;
4975
4976 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
4977 if (USE_STMT (use_p) != stmt)
4978 {
4979 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
4980 if (is_gimple_debug (use_stmt))
4981 continue;
4982 while (is_gimple_assign (use_stmt)
4983 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
4984 && single_imm_use (gimple_assign_lhs (use_stmt),
4985 &use2_p, &use_stmt2))
4986 use_stmt = use_stmt2;
4987 if (gimple_code (use_stmt) != GIMPLE_COND
4988 || gimple_bb (use_stmt) != cond_bb)
4989 return false;
4990 }
4991 return true;
4992 }
4993
4994 /* Handle
4995 _4 = x_3 & 31;
4996 if (_4 != 0)
4997 goto <bb 6>;
4998 else
4999 goto <bb 7>;
5000 <bb 6>:
5001 __builtin_unreachable ();
5002 <bb 7>:
5003 x_5 = ASSERT_EXPR <x_3, ...>;
5004 If x_3 has no other immediate uses (checked by caller),
5005 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
5006 from the non-zero bitmask. */
5007
5008 void
5009 maybe_set_nonzero_bits (edge e, tree var)
5010 {
5011 basic_block cond_bb = e->src;
5012 gimple *stmt = last_stmt (cond_bb);
5013 tree cst;
5014
5015 if (stmt == NULL
5016 || gimple_code (stmt) != GIMPLE_COND
5017 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
5018 ? EQ_EXPR : NE_EXPR)
5019 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
5020 || !integer_zerop (gimple_cond_rhs (stmt)))
5021 return;
5022
5023 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
5024 if (!is_gimple_assign (stmt)
5025 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
5026 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
5027 return;
5028 if (gimple_assign_rhs1 (stmt) != var)
5029 {
5030 gimple *stmt2;
5031
5032 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
5033 return;
5034 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
5035 if (!gimple_assign_cast_p (stmt2)
5036 || gimple_assign_rhs1 (stmt2) != var
5037 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
5038 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
5039 != TYPE_PRECISION (TREE_TYPE (var))))
5040 return;
5041 }
5042 cst = gimple_assign_rhs2 (stmt);
5043 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
5044 wi::to_wide (cst)));
5045 }
5046
5047 /* Convert range assertion expressions into the implied copies and
5048 copy propagate away the copies. Doing the trivial copy propagation
5049 here avoids the need to run the full copy propagation pass after
5050 VRP.
5051
5052 FIXME, this will eventually lead to copy propagation removing the
5053 names that had useful range information attached to them. For
5054 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
5055 then N_i will have the range [3, +INF].
5056
5057 However, by converting the assertion into the implied copy
5058 operation N_i = N_j, we will then copy-propagate N_j into the uses
5059 of N_i and lose the range information. We may want to hold on to
5060 ASSERT_EXPRs a little while longer as the ranges could be used in
5061 things like jump threading.
5062
5063 The problem with keeping ASSERT_EXPRs around is that passes after
5064 VRP need to handle them appropriately.
5065
5066 Another approach would be to make the range information a first
5067 class property of the SSA_NAME so that it can be queried from
5068 any pass. This is made somewhat more complex by the need for
5069 multiple ranges to be associated with one SSA_NAME. */
5070
5071 static void
5072 remove_range_assertions (void)
5073 {
5074 basic_block bb;
5075 gimple_stmt_iterator si;
5076 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
5077 a basic block preceeded by GIMPLE_COND branching to it and
5078 __builtin_trap, -1 if not yet checked, 0 otherwise. */
5079 int is_unreachable;
5080
5081 /* Note that the BSI iterator bump happens at the bottom of the
5082 loop and no bump is necessary if we're removing the statement
5083 referenced by the current BSI. */
5084 FOR_EACH_BB_FN (bb, cfun)
5085 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
5086 {
5087 gimple *stmt = gsi_stmt (si);
5088
5089 if (is_gimple_assign (stmt)
5090 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
5091 {
5092 tree lhs = gimple_assign_lhs (stmt);
5093 tree rhs = gimple_assign_rhs1 (stmt);
5094 tree var;
5095
5096 var = ASSERT_EXPR_VAR (rhs);
5097
5098 if (TREE_CODE (var) == SSA_NAME
5099 && !POINTER_TYPE_P (TREE_TYPE (lhs))
5100 && SSA_NAME_RANGE_INFO (lhs))
5101 {
5102 if (is_unreachable == -1)
5103 {
5104 is_unreachable = 0;
5105 if (single_pred_p (bb)
5106 && assert_unreachable_fallthru_edge_p
5107 (single_pred_edge (bb)))
5108 is_unreachable = 1;
5109 }
5110 /* Handle
5111 if (x_7 >= 10 && x_7 < 20)
5112 __builtin_unreachable ();
5113 x_8 = ASSERT_EXPR <x_7, ...>;
5114 if the only uses of x_7 are in the ASSERT_EXPR and
5115 in the condition. In that case, we can copy the
5116 range info from x_8 computed in this pass also
5117 for x_7. */
5118 if (is_unreachable
5119 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
5120 single_pred (bb)))
5121 {
5122 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
5123 SSA_NAME_RANGE_INFO (lhs)->get_min (),
5124 SSA_NAME_RANGE_INFO (lhs)->get_max ());
5125 maybe_set_nonzero_bits (single_pred_edge (bb), var);
5126 }
5127 }
5128
5129 /* Propagate the RHS into every use of the LHS. For SSA names
5130 also propagate abnormals as it merely restores the original
5131 IL in this case (an replace_uses_by would assert). */
5132 if (TREE_CODE (var) == SSA_NAME)
5133 {
5134 imm_use_iterator iter;
5135 use_operand_p use_p;
5136 gimple *use_stmt;
5137 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
5138 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5139 SET_USE (use_p, var);
5140 }
5141 else
5142 replace_uses_by (lhs, var);
5143
5144 /* And finally, remove the copy, it is not needed. */
5145 gsi_remove (&si, true);
5146 release_defs (stmt);
5147 }
5148 else
5149 {
5150 if (!is_gimple_debug (gsi_stmt (si)))
5151 is_unreachable = 0;
5152 gsi_next (&si);
5153 }
5154 }
5155 }
5156
5157 /* Return true if STMT is interesting for VRP. */
5158
5159 bool
5160 stmt_interesting_for_vrp (gimple *stmt)
5161 {
5162 if (gimple_code (stmt) == GIMPLE_PHI)
5163 {
5164 tree res = gimple_phi_result (stmt);
5165 return (!virtual_operand_p (res)
5166 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
5167 || POINTER_TYPE_P (TREE_TYPE (res))));
5168 }
5169 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5170 {
5171 tree lhs = gimple_get_lhs (stmt);
5172
5173 /* In general, assignments with virtual operands are not useful
5174 for deriving ranges, with the obvious exception of calls to
5175 builtin functions. */
5176 if (lhs && TREE_CODE (lhs) == SSA_NAME
5177 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5178 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5179 && (is_gimple_call (stmt)
5180 || !gimple_vuse (stmt)))
5181 return true;
5182 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5183 switch (gimple_call_internal_fn (stmt))
5184 {
5185 case IFN_ADD_OVERFLOW:
5186 case IFN_SUB_OVERFLOW:
5187 case IFN_MUL_OVERFLOW:
5188 case IFN_ATOMIC_COMPARE_EXCHANGE:
5189 /* These internal calls return _Complex integer type,
5190 but are interesting to VRP nevertheless. */
5191 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5192 return true;
5193 break;
5194 default:
5195 break;
5196 }
5197 }
5198 else if (gimple_code (stmt) == GIMPLE_COND
5199 || gimple_code (stmt) == GIMPLE_SWITCH)
5200 return true;
5201
5202 return false;
5203 }
5204
5205 /* Initialization required by ssa_propagate engine. */
5206
5207 void
5208 vrp_prop::vrp_initialize ()
5209 {
5210 basic_block bb;
5211
5212 FOR_EACH_BB_FN (bb, cfun)
5213 {
5214 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5215 gsi_next (&si))
5216 {
5217 gphi *phi = si.phi ();
5218 if (!stmt_interesting_for_vrp (phi))
5219 {
5220 tree lhs = PHI_RESULT (phi);
5221 set_def_to_varying (lhs);
5222 prop_set_simulate_again (phi, false);
5223 }
5224 else
5225 prop_set_simulate_again (phi, true);
5226 }
5227
5228 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5229 gsi_next (&si))
5230 {
5231 gimple *stmt = gsi_stmt (si);
5232
5233 /* If the statement is a control insn, then we do not
5234 want to avoid simulating the statement once. Failure
5235 to do so means that those edges will never get added. */
5236 if (stmt_ends_bb_p (stmt))
5237 prop_set_simulate_again (stmt, true);
5238 else if (!stmt_interesting_for_vrp (stmt))
5239 {
5240 set_defs_to_varying (stmt);
5241 prop_set_simulate_again (stmt, false);
5242 }
5243 else
5244 prop_set_simulate_again (stmt, true);
5245 }
5246 }
5247 }
5248
5249 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5250 that includes the value VAL. The search is restricted to the range
5251 [START_IDX, n - 1] where n is the size of VEC.
5252
5253 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5254 returned.
5255
5256 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5257 it is placed in IDX and false is returned.
5258
5259 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5260 returned. */
5261
5262 bool
5263 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5264 {
5265 size_t n = gimple_switch_num_labels (stmt);
5266 size_t low, high;
5267
5268 /* Find case label for minimum of the value range or the next one.
5269 At each iteration we are searching in [low, high - 1]. */
5270
5271 for (low = start_idx, high = n; high != low; )
5272 {
5273 tree t;
5274 int cmp;
5275 /* Note that i != high, so we never ask for n. */
5276 size_t i = (high + low) / 2;
5277 t = gimple_switch_label (stmt, i);
5278
5279 /* Cache the result of comparing CASE_LOW and val. */
5280 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5281
5282 if (cmp == 0)
5283 {
5284 /* Ranges cannot be empty. */
5285 *idx = i;
5286 return true;
5287 }
5288 else if (cmp > 0)
5289 high = i;
5290 else
5291 {
5292 low = i + 1;
5293 if (CASE_HIGH (t) != NULL
5294 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5295 {
5296 *idx = i;
5297 return true;
5298 }
5299 }
5300 }
5301
5302 *idx = high;
5303 return false;
5304 }
5305
5306 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5307 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5308 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5309 then MAX_IDX < MIN_IDX.
5310 Returns true if the default label is not needed. */
5311
5312 bool
5313 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5314 size_t *max_idx)
5315 {
5316 size_t i, j;
5317 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5318 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5319
5320 if (i == j
5321 && min_take_default
5322 && max_take_default)
5323 {
5324 /* Only the default case label reached.
5325 Return an empty range. */
5326 *min_idx = 1;
5327 *max_idx = 0;
5328 return false;
5329 }
5330 else
5331 {
5332 bool take_default = min_take_default || max_take_default;
5333 tree low, high;
5334 size_t k;
5335
5336 if (max_take_default)
5337 j--;
5338
5339 /* If the case label range is continuous, we do not need
5340 the default case label. Verify that. */
5341 high = CASE_LOW (gimple_switch_label (stmt, i));
5342 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5343 high = CASE_HIGH (gimple_switch_label (stmt, i));
5344 for (k = i + 1; k <= j; ++k)
5345 {
5346 low = CASE_LOW (gimple_switch_label (stmt, k));
5347 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5348 {
5349 take_default = true;
5350 break;
5351 }
5352 high = low;
5353 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5354 high = CASE_HIGH (gimple_switch_label (stmt, k));
5355 }
5356
5357 *min_idx = i;
5358 *max_idx = j;
5359 return !take_default;
5360 }
5361 }
5362
5363 /* Evaluate statement STMT. If the statement produces a useful range,
5364 return SSA_PROP_INTERESTING and record the SSA name with the
5365 interesting range into *OUTPUT_P.
5366
5367 If STMT is a conditional branch and we can determine its truth
5368 value, the taken edge is recorded in *TAKEN_EDGE_P.
5369
5370 If STMT produces a varying value, return SSA_PROP_VARYING. */
5371
5372 enum ssa_prop_result
5373 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5374 {
5375 tree lhs = gimple_get_lhs (stmt);
5376 value_range vr;
5377 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5378
5379 if (*output_p)
5380 {
5381 if (update_value_range (*output_p, &vr))
5382 {
5383 if (dump_file && (dump_flags & TDF_DETAILS))
5384 {
5385 fprintf (dump_file, "Found new range for ");
5386 print_generic_expr (dump_file, *output_p);
5387 fprintf (dump_file, ": ");
5388 dump_value_range (dump_file, &vr);
5389 fprintf (dump_file, "\n");
5390 }
5391
5392 if (vr.varying_p ())
5393 return SSA_PROP_VARYING;
5394
5395 return SSA_PROP_INTERESTING;
5396 }
5397 return SSA_PROP_NOT_INTERESTING;
5398 }
5399
5400 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5401 switch (gimple_call_internal_fn (stmt))
5402 {
5403 case IFN_ADD_OVERFLOW:
5404 case IFN_SUB_OVERFLOW:
5405 case IFN_MUL_OVERFLOW:
5406 case IFN_ATOMIC_COMPARE_EXCHANGE:
5407 /* These internal calls return _Complex integer type,
5408 which VRP does not track, but the immediate uses
5409 thereof might be interesting. */
5410 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5411 {
5412 imm_use_iterator iter;
5413 use_operand_p use_p;
5414 enum ssa_prop_result res = SSA_PROP_VARYING;
5415
5416 set_def_to_varying (lhs);
5417
5418 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5419 {
5420 gimple *use_stmt = USE_STMT (use_p);
5421 if (!is_gimple_assign (use_stmt))
5422 continue;
5423 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5424 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5425 continue;
5426 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5427 tree use_lhs = gimple_assign_lhs (use_stmt);
5428 if (TREE_CODE (rhs1) != rhs_code
5429 || TREE_OPERAND (rhs1, 0) != lhs
5430 || TREE_CODE (use_lhs) != SSA_NAME
5431 || !stmt_interesting_for_vrp (use_stmt)
5432 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5433 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5434 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5435 continue;
5436
5437 /* If there is a change in the value range for any of the
5438 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5439 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5440 or IMAGPART_EXPR immediate uses, but none of them have
5441 a change in their value ranges, return
5442 SSA_PROP_NOT_INTERESTING. If there are no
5443 {REAL,IMAG}PART_EXPR uses at all,
5444 return SSA_PROP_VARYING. */
5445 value_range new_vr;
5446 extract_range_basic (&new_vr, use_stmt);
5447 const value_range *old_vr = get_value_range (use_lhs);
5448 if (!old_vr->equal_p (new_vr, /*ignore_equivs=*/false))
5449 res = SSA_PROP_INTERESTING;
5450 else
5451 res = SSA_PROP_NOT_INTERESTING;
5452 new_vr.equiv_clear ();
5453 if (res == SSA_PROP_INTERESTING)
5454 {
5455 *output_p = lhs;
5456 return res;
5457 }
5458 }
5459
5460 return res;
5461 }
5462 break;
5463 default:
5464 break;
5465 }
5466
5467 /* All other statements produce nothing of interest for VRP, so mark
5468 their outputs varying and prevent further simulation. */
5469 set_defs_to_varying (stmt);
5470
5471 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5472 }
5473
5474 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5475 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5476 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5477 possible such range. The resulting range is not canonicalized. */
5478
5479 static void
5480 union_ranges (enum value_range_kind *vr0type,
5481 tree *vr0min, tree *vr0max,
5482 enum value_range_kind vr1type,
5483 tree vr1min, tree vr1max)
5484 {
5485 int cmpmin = compare_values (*vr0min, vr1min);
5486 int cmpmax = compare_values (*vr0max, vr1max);
5487 bool mineq = cmpmin == 0;
5488 bool maxeq = cmpmax == 0;
5489
5490 /* [] is vr0, () is vr1 in the following classification comments. */
5491 if (mineq && maxeq)
5492 {
5493 /* [( )] */
5494 if (*vr0type == vr1type)
5495 /* Nothing to do for equal ranges. */
5496 ;
5497 else if ((*vr0type == VR_RANGE
5498 && vr1type == VR_ANTI_RANGE)
5499 || (*vr0type == VR_ANTI_RANGE
5500 && vr1type == VR_RANGE))
5501 {
5502 /* For anti-range with range union the result is varying. */
5503 goto give_up;
5504 }
5505 else
5506 gcc_unreachable ();
5507 }
5508 else if (operand_less_p (*vr0max, vr1min) == 1
5509 || operand_less_p (vr1max, *vr0min) == 1)
5510 {
5511 /* [ ] ( ) or ( ) [ ]
5512 If the ranges have an empty intersection, result of the union
5513 operation is the anti-range or if both are anti-ranges
5514 it covers all. */
5515 if (*vr0type == VR_ANTI_RANGE
5516 && vr1type == VR_ANTI_RANGE)
5517 goto give_up;
5518 else if (*vr0type == VR_ANTI_RANGE
5519 && vr1type == VR_RANGE)
5520 ;
5521 else if (*vr0type == VR_RANGE
5522 && vr1type == VR_ANTI_RANGE)
5523 {
5524 *vr0type = vr1type;
5525 *vr0min = vr1min;
5526 *vr0max = vr1max;
5527 }
5528 else if (*vr0type == VR_RANGE
5529 && vr1type == VR_RANGE)
5530 {
5531 /* The result is the convex hull of both ranges. */
5532 if (operand_less_p (*vr0max, vr1min) == 1)
5533 {
5534 /* If the result can be an anti-range, create one. */
5535 if (TREE_CODE (*vr0max) == INTEGER_CST
5536 && TREE_CODE (vr1min) == INTEGER_CST
5537 && vrp_val_is_min (*vr0min)
5538 && vrp_val_is_max (vr1max))
5539 {
5540 tree min = int_const_binop (PLUS_EXPR,
5541 *vr0max,
5542 build_int_cst (TREE_TYPE (*vr0max), 1));
5543 tree max = int_const_binop (MINUS_EXPR,
5544 vr1min,
5545 build_int_cst (TREE_TYPE (vr1min), 1));
5546 if (!operand_less_p (max, min))
5547 {
5548 *vr0type = VR_ANTI_RANGE;
5549 *vr0min = min;
5550 *vr0max = max;
5551 }
5552 else
5553 *vr0max = vr1max;
5554 }
5555 else
5556 *vr0max = vr1max;
5557 }
5558 else
5559 {
5560 /* If the result can be an anti-range, create one. */
5561 if (TREE_CODE (vr1max) == INTEGER_CST
5562 && TREE_CODE (*vr0min) == INTEGER_CST
5563 && vrp_val_is_min (vr1min)
5564 && vrp_val_is_max (*vr0max))
5565 {
5566 tree min = int_const_binop (PLUS_EXPR,
5567 vr1max,
5568 build_int_cst (TREE_TYPE (vr1max), 1));
5569 tree max = int_const_binop (MINUS_EXPR,
5570 *vr0min,
5571 build_int_cst (TREE_TYPE (*vr0min), 1));
5572 if (!operand_less_p (max, min))
5573 {
5574 *vr0type = VR_ANTI_RANGE;
5575 *vr0min = min;
5576 *vr0max = max;
5577 }
5578 else
5579 *vr0min = vr1min;
5580 }
5581 else
5582 *vr0min = vr1min;
5583 }
5584 }
5585 else
5586 gcc_unreachable ();
5587 }
5588 else if ((maxeq || cmpmax == 1)
5589 && (mineq || cmpmin == -1))
5590 {
5591 /* [ ( ) ] or [( ) ] or [ ( )] */
5592 if (*vr0type == VR_RANGE
5593 && vr1type == VR_RANGE)
5594 ;
5595 else if (*vr0type == VR_ANTI_RANGE
5596 && vr1type == VR_ANTI_RANGE)
5597 {
5598 *vr0type = vr1type;
5599 *vr0min = vr1min;
5600 *vr0max = vr1max;
5601 }
5602 else if (*vr0type == VR_ANTI_RANGE
5603 && vr1type == VR_RANGE)
5604 {
5605 /* Arbitrarily choose the right or left gap. */
5606 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5607 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5608 build_int_cst (TREE_TYPE (vr1min), 1));
5609 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5610 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5611 build_int_cst (TREE_TYPE (vr1max), 1));
5612 else
5613 goto give_up;
5614 }
5615 else if (*vr0type == VR_RANGE
5616 && vr1type == VR_ANTI_RANGE)
5617 /* The result covers everything. */
5618 goto give_up;
5619 else
5620 gcc_unreachable ();
5621 }
5622 else if ((maxeq || cmpmax == -1)
5623 && (mineq || cmpmin == 1))
5624 {
5625 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5626 if (*vr0type == VR_RANGE
5627 && vr1type == VR_RANGE)
5628 {
5629 *vr0type = vr1type;
5630 *vr0min = vr1min;
5631 *vr0max = vr1max;
5632 }
5633 else if (*vr0type == VR_ANTI_RANGE
5634 && vr1type == VR_ANTI_RANGE)
5635 ;
5636 else if (*vr0type == VR_RANGE
5637 && vr1type == VR_ANTI_RANGE)
5638 {
5639 *vr0type = VR_ANTI_RANGE;
5640 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5641 {
5642 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5643 build_int_cst (TREE_TYPE (*vr0min), 1));
5644 *vr0min = vr1min;
5645 }
5646 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5647 {
5648 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5649 build_int_cst (TREE_TYPE (*vr0max), 1));
5650 *vr0max = vr1max;
5651 }
5652 else
5653 goto give_up;
5654 }
5655 else if (*vr0type == VR_ANTI_RANGE
5656 && vr1type == VR_RANGE)
5657 /* The result covers everything. */
5658 goto give_up;
5659 else
5660 gcc_unreachable ();
5661 }
5662 else if (cmpmin == -1
5663 && cmpmax == -1
5664 && (operand_less_p (vr1min, *vr0max) == 1
5665 || operand_equal_p (vr1min, *vr0max, 0)))
5666 {
5667 /* [ ( ] ) or [ ]( ) */
5668 if (*vr0type == VR_RANGE
5669 && vr1type == VR_RANGE)
5670 *vr0max = vr1max;
5671 else if (*vr0type == VR_ANTI_RANGE
5672 && vr1type == VR_ANTI_RANGE)
5673 *vr0min = vr1min;
5674 else if (*vr0type == VR_ANTI_RANGE
5675 && vr1type == VR_RANGE)
5676 {
5677 if (TREE_CODE (vr1min) == INTEGER_CST)
5678 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5679 build_int_cst (TREE_TYPE (vr1min), 1));
5680 else
5681 goto give_up;
5682 }
5683 else if (*vr0type == VR_RANGE
5684 && vr1type == VR_ANTI_RANGE)
5685 {
5686 if (TREE_CODE (*vr0max) == INTEGER_CST)
5687 {
5688 *vr0type = vr1type;
5689 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5690 build_int_cst (TREE_TYPE (*vr0max), 1));
5691 *vr0max = vr1max;
5692 }
5693 else
5694 goto give_up;
5695 }
5696 else
5697 gcc_unreachable ();
5698 }
5699 else if (cmpmin == 1
5700 && cmpmax == 1
5701 && (operand_less_p (*vr0min, vr1max) == 1
5702 || operand_equal_p (*vr0min, vr1max, 0)))
5703 {
5704 /* ( [ ) ] or ( )[ ] */
5705 if (*vr0type == VR_RANGE
5706 && vr1type == VR_RANGE)
5707 *vr0min = vr1min;
5708 else if (*vr0type == VR_ANTI_RANGE
5709 && vr1type == VR_ANTI_RANGE)
5710 *vr0max = vr1max;
5711 else if (*vr0type == VR_ANTI_RANGE
5712 && vr1type == VR_RANGE)
5713 {
5714 if (TREE_CODE (vr1max) == INTEGER_CST)
5715 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5716 build_int_cst (TREE_TYPE (vr1max), 1));
5717 else
5718 goto give_up;
5719 }
5720 else if (*vr0type == VR_RANGE
5721 && vr1type == VR_ANTI_RANGE)
5722 {
5723 if (TREE_CODE (*vr0min) == INTEGER_CST)
5724 {
5725 *vr0type = vr1type;
5726 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5727 build_int_cst (TREE_TYPE (*vr0min), 1));
5728 *vr0min = vr1min;
5729 }
5730 else
5731 goto give_up;
5732 }
5733 else
5734 gcc_unreachable ();
5735 }
5736 else
5737 goto give_up;
5738
5739 return;
5740
5741 give_up:
5742 *vr0type = VR_VARYING;
5743 *vr0min = NULL_TREE;
5744 *vr0max = NULL_TREE;
5745 }
5746
5747 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5748 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5749 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5750 possible such range. The resulting range is not canonicalized. */
5751
5752 static void
5753 intersect_ranges (enum value_range_kind *vr0type,
5754 tree *vr0min, tree *vr0max,
5755 enum value_range_kind vr1type,
5756 tree vr1min, tree vr1max)
5757 {
5758 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5759 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5760
5761 /* [] is vr0, () is vr1 in the following classification comments. */
5762 if (mineq && maxeq)
5763 {
5764 /* [( )] */
5765 if (*vr0type == vr1type)
5766 /* Nothing to do for equal ranges. */
5767 ;
5768 else if ((*vr0type == VR_RANGE
5769 && vr1type == VR_ANTI_RANGE)
5770 || (*vr0type == VR_ANTI_RANGE
5771 && vr1type == VR_RANGE))
5772 {
5773 /* For anti-range with range intersection the result is empty. */
5774 *vr0type = VR_UNDEFINED;
5775 *vr0min = NULL_TREE;
5776 *vr0max = NULL_TREE;
5777 }
5778 else
5779 gcc_unreachable ();
5780 }
5781 else if (operand_less_p (*vr0max, vr1min) == 1
5782 || operand_less_p (vr1max, *vr0min) == 1)
5783 {
5784 /* [ ] ( ) or ( ) [ ]
5785 If the ranges have an empty intersection, the result of the
5786 intersect operation is the range for intersecting an
5787 anti-range with a range or empty when intersecting two ranges. */
5788 if (*vr0type == VR_RANGE
5789 && vr1type == VR_ANTI_RANGE)
5790 ;
5791 else if (*vr0type == VR_ANTI_RANGE
5792 && vr1type == VR_RANGE)
5793 {
5794 *vr0type = vr1type;
5795 *vr0min = vr1min;
5796 *vr0max = vr1max;
5797 }
5798 else if (*vr0type == VR_RANGE
5799 && vr1type == VR_RANGE)
5800 {
5801 *vr0type = VR_UNDEFINED;
5802 *vr0min = NULL_TREE;
5803 *vr0max = NULL_TREE;
5804 }
5805 else if (*vr0type == VR_ANTI_RANGE
5806 && vr1type == VR_ANTI_RANGE)
5807 {
5808 /* If the anti-ranges are adjacent to each other merge them. */
5809 if (TREE_CODE (*vr0max) == INTEGER_CST
5810 && TREE_CODE (vr1min) == INTEGER_CST
5811 && operand_less_p (*vr0max, vr1min) == 1
5812 && integer_onep (int_const_binop (MINUS_EXPR,
5813 vr1min, *vr0max)))
5814 *vr0max = vr1max;
5815 else if (TREE_CODE (vr1max) == INTEGER_CST
5816 && TREE_CODE (*vr0min) == INTEGER_CST
5817 && operand_less_p (vr1max, *vr0min) == 1
5818 && integer_onep (int_const_binop (MINUS_EXPR,
5819 *vr0min, vr1max)))
5820 *vr0min = vr1min;
5821 /* Else arbitrarily take VR0. */
5822 }
5823 }
5824 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5825 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5826 {
5827 /* [ ( ) ] or [( ) ] or [ ( )] */
5828 if (*vr0type == VR_RANGE
5829 && vr1type == VR_RANGE)
5830 {
5831 /* If both are ranges the result is the inner one. */
5832 *vr0type = vr1type;
5833 *vr0min = vr1min;
5834 *vr0max = vr1max;
5835 }
5836 else if (*vr0type == VR_RANGE
5837 && vr1type == VR_ANTI_RANGE)
5838 {
5839 /* Choose the right gap if the left one is empty. */
5840 if (mineq)
5841 {
5842 if (TREE_CODE (vr1max) != INTEGER_CST)
5843 *vr0min = vr1max;
5844 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
5845 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
5846 *vr0min
5847 = int_const_binop (MINUS_EXPR, vr1max,
5848 build_int_cst (TREE_TYPE (vr1max), -1));
5849 else
5850 *vr0min
5851 = int_const_binop (PLUS_EXPR, vr1max,
5852 build_int_cst (TREE_TYPE (vr1max), 1));
5853 }
5854 /* Choose the left gap if the right one is empty. */
5855 else if (maxeq)
5856 {
5857 if (TREE_CODE (vr1min) != INTEGER_CST)
5858 *vr0max = vr1min;
5859 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
5860 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
5861 *vr0max
5862 = int_const_binop (PLUS_EXPR, vr1min,
5863 build_int_cst (TREE_TYPE (vr1min), -1));
5864 else
5865 *vr0max
5866 = int_const_binop (MINUS_EXPR, vr1min,
5867 build_int_cst (TREE_TYPE (vr1min), 1));
5868 }
5869 /* Choose the anti-range if the range is effectively varying. */
5870 else if (vrp_val_is_min (*vr0min)
5871 && vrp_val_is_max (*vr0max))
5872 {
5873 *vr0type = vr1type;
5874 *vr0min = vr1min;
5875 *vr0max = vr1max;
5876 }
5877 /* Else choose the range. */
5878 }
5879 else if (*vr0type == VR_ANTI_RANGE
5880 && vr1type == VR_ANTI_RANGE)
5881 /* If both are anti-ranges the result is the outer one. */
5882 ;
5883 else if (*vr0type == VR_ANTI_RANGE
5884 && vr1type == VR_RANGE)
5885 {
5886 /* The intersection is empty. */
5887 *vr0type = VR_UNDEFINED;
5888 *vr0min = NULL_TREE;
5889 *vr0max = NULL_TREE;
5890 }
5891 else
5892 gcc_unreachable ();
5893 }
5894 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5895 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5896 {
5897 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5898 if (*vr0type == VR_RANGE
5899 && vr1type == VR_RANGE)
5900 /* Choose the inner range. */
5901 ;
5902 else if (*vr0type == VR_ANTI_RANGE
5903 && vr1type == VR_RANGE)
5904 {
5905 /* Choose the right gap if the left is empty. */
5906 if (mineq)
5907 {
5908 *vr0type = VR_RANGE;
5909 if (TREE_CODE (*vr0max) != INTEGER_CST)
5910 *vr0min = *vr0max;
5911 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
5912 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
5913 *vr0min
5914 = int_const_binop (MINUS_EXPR, *vr0max,
5915 build_int_cst (TREE_TYPE (*vr0max), -1));
5916 else
5917 *vr0min
5918 = int_const_binop (PLUS_EXPR, *vr0max,
5919 build_int_cst (TREE_TYPE (*vr0max), 1));
5920 *vr0max = vr1max;
5921 }
5922 /* Choose the left gap if the right is empty. */
5923 else if (maxeq)
5924 {
5925 *vr0type = VR_RANGE;
5926 if (TREE_CODE (*vr0min) != INTEGER_CST)
5927 *vr0max = *vr0min;
5928 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
5929 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
5930 *vr0max
5931 = int_const_binop (PLUS_EXPR, *vr0min,
5932 build_int_cst (TREE_TYPE (*vr0min), -1));
5933 else
5934 *vr0max
5935 = int_const_binop (MINUS_EXPR, *vr0min,
5936 build_int_cst (TREE_TYPE (*vr0min), 1));
5937 *vr0min = vr1min;
5938 }
5939 /* Choose the anti-range if the range is effectively varying. */
5940 else if (vrp_val_is_min (vr1min)
5941 && vrp_val_is_max (vr1max))
5942 ;
5943 /* Choose the anti-range if it is ~[0,0], that range is special
5944 enough to special case when vr1's range is relatively wide.
5945 At least for types bigger than int - this covers pointers
5946 and arguments to functions like ctz. */
5947 else if (*vr0min == *vr0max
5948 && integer_zerop (*vr0min)
5949 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
5950 >= TYPE_PRECISION (integer_type_node))
5951 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
5952 && TREE_CODE (vr1max) == INTEGER_CST
5953 && TREE_CODE (vr1min) == INTEGER_CST
5954 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
5955 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
5956 ;
5957 /* Else choose the range. */
5958 else
5959 {
5960 *vr0type = vr1type;
5961 *vr0min = vr1min;
5962 *vr0max = vr1max;
5963 }
5964 }
5965 else if (*vr0type == VR_ANTI_RANGE
5966 && vr1type == VR_ANTI_RANGE)
5967 {
5968 /* If both are anti-ranges the result is the outer one. */
5969 *vr0type = vr1type;
5970 *vr0min = vr1min;
5971 *vr0max = vr1max;
5972 }
5973 else if (vr1type == VR_ANTI_RANGE
5974 && *vr0type == VR_RANGE)
5975 {
5976 /* The intersection is empty. */
5977 *vr0type = VR_UNDEFINED;
5978 *vr0min = NULL_TREE;
5979 *vr0max = NULL_TREE;
5980 }
5981 else
5982 gcc_unreachable ();
5983 }
5984 else if ((operand_less_p (vr1min, *vr0max) == 1
5985 || operand_equal_p (vr1min, *vr0max, 0))
5986 && operand_less_p (*vr0min, vr1min) == 1)
5987 {
5988 /* [ ( ] ) or [ ]( ) */
5989 if (*vr0type == VR_ANTI_RANGE
5990 && vr1type == VR_ANTI_RANGE)
5991 *vr0max = vr1max;
5992 else if (*vr0type == VR_RANGE
5993 && vr1type == VR_RANGE)
5994 *vr0min = vr1min;
5995 else if (*vr0type == VR_RANGE
5996 && vr1type == VR_ANTI_RANGE)
5997 {
5998 if (TREE_CODE (vr1min) == INTEGER_CST)
5999 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
6000 build_int_cst (TREE_TYPE (vr1min), 1));
6001 else
6002 *vr0max = vr1min;
6003 }
6004 else if (*vr0type == VR_ANTI_RANGE
6005 && vr1type == VR_RANGE)
6006 {
6007 *vr0type = VR_RANGE;
6008 if (TREE_CODE (*vr0max) == INTEGER_CST)
6009 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
6010 build_int_cst (TREE_TYPE (*vr0max), 1));
6011 else
6012 *vr0min = *vr0max;
6013 *vr0max = vr1max;
6014 }
6015 else
6016 gcc_unreachable ();
6017 }
6018 else if ((operand_less_p (*vr0min, vr1max) == 1
6019 || operand_equal_p (*vr0min, vr1max, 0))
6020 && operand_less_p (vr1min, *vr0min) == 1)
6021 {
6022 /* ( [ ) ] or ( )[ ] */
6023 if (*vr0type == VR_ANTI_RANGE
6024 && vr1type == VR_ANTI_RANGE)
6025 *vr0min = vr1min;
6026 else if (*vr0type == VR_RANGE
6027 && vr1type == VR_RANGE)
6028 *vr0max = vr1max;
6029 else if (*vr0type == VR_RANGE
6030 && vr1type == VR_ANTI_RANGE)
6031 {
6032 if (TREE_CODE (vr1max) == INTEGER_CST)
6033 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
6034 build_int_cst (TREE_TYPE (vr1max), 1));
6035 else
6036 *vr0min = vr1max;
6037 }
6038 else if (*vr0type == VR_ANTI_RANGE
6039 && vr1type == VR_RANGE)
6040 {
6041 *vr0type = VR_RANGE;
6042 if (TREE_CODE (*vr0min) == INTEGER_CST)
6043 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
6044 build_int_cst (TREE_TYPE (*vr0min), 1));
6045 else
6046 *vr0max = *vr0min;
6047 *vr0min = vr1min;
6048 }
6049 else
6050 gcc_unreachable ();
6051 }
6052
6053 /* If we know the intersection is empty, there's no need to
6054 conservatively add anything else to the set. */
6055 if (*vr0type == VR_UNDEFINED)
6056 return;
6057
6058 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
6059 result for the intersection. That's always a conservative
6060 correct estimate unless VR1 is a constant singleton range
6061 in which case we choose that. */
6062 if (vr1type == VR_RANGE
6063 && is_gimple_min_invariant (vr1min)
6064 && vrp_operand_equal_p (vr1min, vr1max))
6065 {
6066 *vr0type = vr1type;
6067 *vr0min = vr1min;
6068 *vr0max = vr1max;
6069 }
6070 }
6071
6072
6073 /* Helper for the intersection operation for value ranges. Given two
6074 value ranges VR0 and VR1, return the intersection of the two
6075 ranges. This may not be the smallest possible such range. */
6076
6077 value_range_base
6078 value_range_base::intersect_helper (const value_range_base *vr0,
6079 const value_range_base *vr1)
6080 {
6081 /* If either range is VR_VARYING the other one wins. */
6082 if (vr1->varying_p ())
6083 return *vr0;
6084 if (vr0->varying_p ())
6085 return *vr1;
6086
6087 /* When either range is VR_UNDEFINED the resulting range is
6088 VR_UNDEFINED, too. */
6089 if (vr0->undefined_p ())
6090 return *vr0;
6091 if (vr1->undefined_p ())
6092 return *vr1;
6093
6094 value_range_kind vr0type = vr0->kind ();
6095 tree vr0min = vr0->min ();
6096 tree vr0max = vr0->max ();
6097 intersect_ranges (&vr0type, &vr0min, &vr0max,
6098 vr1->kind (), vr1->min (), vr1->max ());
6099 /* Make sure to canonicalize the result though as the inversion of a
6100 VR_RANGE can still be a VR_RANGE. Work on a temporary so we can
6101 fall back to vr0 when this turns things to varying. */
6102 value_range_base tem;
6103 tem.set (vr0type, vr0min, vr0max);
6104 /* If that failed, use the saved original VR0. */
6105 if (tem.varying_p ())
6106 return *vr0;
6107
6108 return tem;
6109 }
6110
6111 void
6112 value_range_base::intersect (const value_range_base *other)
6113 {
6114 if (dump_file && (dump_flags & TDF_DETAILS))
6115 {
6116 fprintf (dump_file, "Intersecting\n ");
6117 dump_value_range (dump_file, this);
6118 fprintf (dump_file, "\nand\n ");
6119 dump_value_range (dump_file, other);
6120 fprintf (dump_file, "\n");
6121 }
6122
6123 *this = intersect_helper (this, other);
6124
6125 if (dump_file && (dump_flags & TDF_DETAILS))
6126 {
6127 fprintf (dump_file, "to\n ");
6128 dump_value_range (dump_file, this);
6129 fprintf (dump_file, "\n");
6130 }
6131 }
6132
6133 void
6134 value_range::intersect (const value_range *other)
6135 {
6136 if (dump_file && (dump_flags & TDF_DETAILS))
6137 {
6138 fprintf (dump_file, "Intersecting\n ");
6139 dump_value_range (dump_file, this);
6140 fprintf (dump_file, "\nand\n ");
6141 dump_value_range (dump_file, other);
6142 fprintf (dump_file, "\n");
6143 }
6144
6145 /* If THIS is varying we want to pick up equivalences from OTHER.
6146 Just special-case this here rather than trying to fixup after the
6147 fact. */
6148 if (this->varying_p ())
6149 this->deep_copy (other);
6150 else
6151 {
6152 value_range_base tem = intersect_helper (this, other);
6153 this->update (tem.kind (), tem.min (), tem.max ());
6154
6155 /* If the result is VR_UNDEFINED there is no need to mess with
6156 equivalencies. */
6157 if (!undefined_p ())
6158 {
6159 /* The resulting set of equivalences for range intersection
6160 is the union of the two sets. */
6161 if (m_equiv && other->m_equiv && m_equiv != other->m_equiv)
6162 bitmap_ior_into (m_equiv, other->m_equiv);
6163 else if (other->m_equiv && !m_equiv)
6164 {
6165 /* All equivalence bitmaps are allocated from the same
6166 obstack. So we can use the obstack associated with
6167 VR to allocate this->m_equiv. */
6168 m_equiv = BITMAP_ALLOC (other->m_equiv->obstack);
6169 bitmap_copy (m_equiv, other->m_equiv);
6170 }
6171 }
6172 }
6173
6174 if (dump_file && (dump_flags & TDF_DETAILS))
6175 {
6176 fprintf (dump_file, "to\n ");
6177 dump_value_range (dump_file, this);
6178 fprintf (dump_file, "\n");
6179 }
6180 }
6181
6182 /* Helper for meet operation for value ranges. Given two value ranges VR0 and
6183 VR1, return a range that contains both VR0 and VR1. This may not be the
6184 smallest possible such range. */
6185
6186 value_range_base
6187 value_range_base::union_helper (const value_range_base *vr0,
6188 const value_range_base *vr1)
6189 {
6190 /* VR0 has the resulting range if VR1 is undefined or VR0 is varying. */
6191 if (vr1->undefined_p ()
6192 || vr0->varying_p ())
6193 return *vr0;
6194
6195 /* VR1 has the resulting range if VR0 is undefined or VR1 is varying. */
6196 if (vr0->undefined_p ()
6197 || vr1->varying_p ())
6198 return *vr1;
6199
6200 value_range_kind vr0type = vr0->kind ();
6201 tree vr0min = vr0->min ();
6202 tree vr0max = vr0->max ();
6203 union_ranges (&vr0type, &vr0min, &vr0max,
6204 vr1->kind (), vr1->min (), vr1->max ());
6205
6206 /* Work on a temporary so we can still use vr0 when union returns varying. */
6207 value_range_base tem;
6208 tem.set (vr0type, vr0min, vr0max);
6209
6210 /* Failed to find an efficient meet. Before giving up and setting
6211 the result to VARYING, see if we can at least derive a useful
6212 anti-range. */
6213 if (tem.varying_p ()
6214 && range_includes_zero_p (vr0) == 0
6215 && range_includes_zero_p (vr1) == 0)
6216 {
6217 tem.set_nonzero (vr0->type ());
6218 return tem;
6219 }
6220
6221 return tem;
6222 }
6223
6224
6225 /* Meet operation for value ranges. Given two value ranges VR0 and
6226 VR1, store in VR0 a range that contains both VR0 and VR1. This
6227 may not be the smallest possible such range. */
6228
6229 void
6230 value_range_base::union_ (const value_range_base *other)
6231 {
6232 if (dump_file && (dump_flags & TDF_DETAILS))
6233 {
6234 fprintf (dump_file, "Meeting\n ");
6235 dump_value_range (dump_file, this);
6236 fprintf (dump_file, "\nand\n ");
6237 dump_value_range (dump_file, other);
6238 fprintf (dump_file, "\n");
6239 }
6240
6241 *this = union_helper (this, other);
6242
6243 if (dump_file && (dump_flags & TDF_DETAILS))
6244 {
6245 fprintf (dump_file, "to\n ");
6246 dump_value_range (dump_file, this);
6247 fprintf (dump_file, "\n");
6248 }
6249 }
6250
6251 void
6252 value_range::union_ (const value_range *other)
6253 {
6254 if (dump_file && (dump_flags & TDF_DETAILS))
6255 {
6256 fprintf (dump_file, "Meeting\n ");
6257 dump_value_range (dump_file, this);
6258 fprintf (dump_file, "\nand\n ");
6259 dump_value_range (dump_file, other);
6260 fprintf (dump_file, "\n");
6261 }
6262
6263 /* If THIS is undefined we want to pick up equivalences from OTHER.
6264 Just special-case this here rather than trying to fixup after the fact. */
6265 if (this->undefined_p ())
6266 this->deep_copy (other);
6267 else
6268 {
6269 value_range_base tem = union_helper (this, other);
6270 this->update (tem.kind (), tem.min (), tem.max ());
6271
6272 /* The resulting set of equivalences is always the intersection of
6273 the two sets. */
6274 if (this->m_equiv && other->m_equiv && this->m_equiv != other->m_equiv)
6275 bitmap_and_into (this->m_equiv, other->m_equiv);
6276 else if (this->m_equiv && !other->m_equiv)
6277 bitmap_clear (this->m_equiv);
6278 }
6279
6280 if (dump_file && (dump_flags & TDF_DETAILS))
6281 {
6282 fprintf (dump_file, "to\n ");
6283 dump_value_range (dump_file, this);
6284 fprintf (dump_file, "\n");
6285 }
6286 }
6287
6288 /* Normalize symbolics into constants. */
6289
6290 value_range_base
6291 value_range_base::normalize_symbolics () const
6292 {
6293 if (varying_p () || undefined_p ())
6294 return *this;
6295 tree ttype = type ();
6296 bool min_symbolic = !is_gimple_min_invariant (min ());
6297 bool max_symbolic = !is_gimple_min_invariant (max ());
6298 if (!min_symbolic && !max_symbolic)
6299 return *this;
6300
6301 // [SYM, SYM] -> VARYING
6302 if (min_symbolic && max_symbolic)
6303 {
6304 value_range_base var;
6305 var.set_varying ();
6306 return var;
6307 }
6308 if (kind () == VR_RANGE)
6309 {
6310 // [SYM, NUM] -> [-MIN, NUM]
6311 if (min_symbolic)
6312 return value_range_base (VR_RANGE, vrp_val_min (ttype), max ());
6313 // [NUM, SYM] -> [NUM, +MAX]
6314 return value_range_base (VR_RANGE, min (), vrp_val_max (ttype));
6315 }
6316 gcc_assert (kind () == VR_ANTI_RANGE);
6317 // ~[SYM, NUM] -> [NUM + 1, +MAX]
6318 if (min_symbolic)
6319 {
6320 if (!vrp_val_is_max (max ()))
6321 {
6322 tree n = wide_int_to_tree (ttype, wi::to_wide (max ()) + 1);
6323 return value_range_base (VR_RANGE, n, vrp_val_max (ttype));
6324 }
6325 value_range_base var;
6326 var.set_varying ();
6327 return var;
6328 }
6329 // ~[NUM, SYM] -> [-MIN, NUM - 1]
6330 if (!vrp_val_is_min (min ()))
6331 {
6332 tree n = wide_int_to_tree (ttype, wi::to_wide (min ()) - 1);
6333 return value_range_base (VR_RANGE, vrp_val_min (ttype), n);
6334 }
6335 value_range_base var;
6336 var.set_varying ();
6337 return var;
6338 }
6339
6340 /* Visit all arguments for PHI node PHI that flow through executable
6341 edges. If a valid value range can be derived from all the incoming
6342 value ranges, set a new range for the LHS of PHI. */
6343
6344 enum ssa_prop_result
6345 vrp_prop::visit_phi (gphi *phi)
6346 {
6347 tree lhs = PHI_RESULT (phi);
6348 value_range vr_result;
6349 extract_range_from_phi_node (phi, &vr_result);
6350 if (update_value_range (lhs, &vr_result))
6351 {
6352 if (dump_file && (dump_flags & TDF_DETAILS))
6353 {
6354 fprintf (dump_file, "Found new range for ");
6355 print_generic_expr (dump_file, lhs);
6356 fprintf (dump_file, ": ");
6357 dump_value_range (dump_file, &vr_result);
6358 fprintf (dump_file, "\n");
6359 }
6360
6361 if (vr_result.varying_p ())
6362 return SSA_PROP_VARYING;
6363
6364 return SSA_PROP_INTERESTING;
6365 }
6366
6367 /* Nothing changed, don't add outgoing edges. */
6368 return SSA_PROP_NOT_INTERESTING;
6369 }
6370
6371 class vrp_folder : public substitute_and_fold_engine
6372 {
6373 public:
6374 tree get_value (tree) FINAL OVERRIDE;
6375 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6376 bool fold_predicate_in (gimple_stmt_iterator *);
6377
6378 class vr_values *vr_values;
6379
6380 /* Delegators. */
6381 tree vrp_evaluate_conditional (tree_code code, tree op0,
6382 tree op1, gimple *stmt)
6383 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6384 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6385 { return vr_values->simplify_stmt_using_ranges (gsi); }
6386 tree op_with_constant_singleton_value_range (tree op)
6387 { return vr_values->op_with_constant_singleton_value_range (op); }
6388 };
6389
6390 /* If the statement pointed by SI has a predicate whose value can be
6391 computed using the value range information computed by VRP, compute
6392 its value and return true. Otherwise, return false. */
6393
6394 bool
6395 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6396 {
6397 bool assignment_p = false;
6398 tree val;
6399 gimple *stmt = gsi_stmt (*si);
6400
6401 if (is_gimple_assign (stmt)
6402 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6403 {
6404 assignment_p = true;
6405 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6406 gimple_assign_rhs1 (stmt),
6407 gimple_assign_rhs2 (stmt),
6408 stmt);
6409 }
6410 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6411 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6412 gimple_cond_lhs (cond_stmt),
6413 gimple_cond_rhs (cond_stmt),
6414 stmt);
6415 else
6416 return false;
6417
6418 if (val)
6419 {
6420 if (assignment_p)
6421 val = fold_convert (gimple_expr_type (stmt), val);
6422
6423 if (dump_file)
6424 {
6425 fprintf (dump_file, "Folding predicate ");
6426 print_gimple_expr (dump_file, stmt, 0);
6427 fprintf (dump_file, " to ");
6428 print_generic_expr (dump_file, val);
6429 fprintf (dump_file, "\n");
6430 }
6431
6432 if (is_gimple_assign (stmt))
6433 gimple_assign_set_rhs_from_tree (si, val);
6434 else
6435 {
6436 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6437 gcond *cond_stmt = as_a <gcond *> (stmt);
6438 if (integer_zerop (val))
6439 gimple_cond_make_false (cond_stmt);
6440 else if (integer_onep (val))
6441 gimple_cond_make_true (cond_stmt);
6442 else
6443 gcc_unreachable ();
6444 }
6445
6446 return true;
6447 }
6448
6449 return false;
6450 }
6451
6452 /* Callback for substitute_and_fold folding the stmt at *SI. */
6453
6454 bool
6455 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6456 {
6457 if (fold_predicate_in (si))
6458 return true;
6459
6460 return simplify_stmt_using_ranges (si);
6461 }
6462
6463 /* If OP has a value range with a single constant value return that,
6464 otherwise return NULL_TREE. This returns OP itself if OP is a
6465 constant.
6466
6467 Implemented as a pure wrapper right now, but this will change. */
6468
6469 tree
6470 vrp_folder::get_value (tree op)
6471 {
6472 return op_with_constant_singleton_value_range (op);
6473 }
6474
6475 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6476 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6477 BB. If no such ASSERT_EXPR is found, return OP. */
6478
6479 static tree
6480 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6481 {
6482 imm_use_iterator imm_iter;
6483 gimple *use_stmt;
6484 use_operand_p use_p;
6485
6486 if (TREE_CODE (op) == SSA_NAME)
6487 {
6488 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6489 {
6490 use_stmt = USE_STMT (use_p);
6491 if (use_stmt != stmt
6492 && gimple_assign_single_p (use_stmt)
6493 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6494 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6495 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6496 return gimple_assign_lhs (use_stmt);
6497 }
6498 }
6499 return op;
6500 }
6501
6502 /* A hack. */
6503 static class vr_values *x_vr_values;
6504
6505 /* A trivial wrapper so that we can present the generic jump threading
6506 code with a simple API for simplifying statements. STMT is the
6507 statement we want to simplify, WITHIN_STMT provides the location
6508 for any overflow warnings. */
6509
6510 static tree
6511 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6512 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6513 basic_block bb)
6514 {
6515 /* First see if the conditional is in the hash table. */
6516 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6517 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6518 return cached_lhs;
6519
6520 vr_values *vr_values = x_vr_values;
6521 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6522 {
6523 tree op0 = gimple_cond_lhs (cond_stmt);
6524 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6525
6526 tree op1 = gimple_cond_rhs (cond_stmt);
6527 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6528
6529 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6530 op0, op1, within_stmt);
6531 }
6532
6533 /* We simplify a switch statement by trying to determine which case label
6534 will be taken. If we are successful then we return the corresponding
6535 CASE_LABEL_EXPR. */
6536 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6537 {
6538 tree op = gimple_switch_index (switch_stmt);
6539 if (TREE_CODE (op) != SSA_NAME)
6540 return NULL_TREE;
6541
6542 op = lhs_of_dominating_assert (op, bb, stmt);
6543
6544 const value_range *vr = vr_values->get_value_range (op);
6545 if (vr->undefined_p ()
6546 || vr->varying_p ()
6547 || vr->symbolic_p ())
6548 return NULL_TREE;
6549
6550 if (vr->kind () == VR_RANGE)
6551 {
6552 size_t i, j;
6553 /* Get the range of labels that contain a part of the operand's
6554 value range. */
6555 find_case_label_range (switch_stmt, vr->min (), vr->max (), &i, &j);
6556
6557 /* Is there only one such label? */
6558 if (i == j)
6559 {
6560 tree label = gimple_switch_label (switch_stmt, i);
6561
6562 /* The i'th label will be taken only if the value range of the
6563 operand is entirely within the bounds of this label. */
6564 if (CASE_HIGH (label) != NULL_TREE
6565 ? (tree_int_cst_compare (CASE_LOW (label), vr->min ()) <= 0
6566 && tree_int_cst_compare (CASE_HIGH (label),
6567 vr->max ()) >= 0)
6568 : (tree_int_cst_equal (CASE_LOW (label), vr->min ())
6569 && tree_int_cst_equal (vr->min (), vr->max ())))
6570 return label;
6571 }
6572
6573 /* If there are no such labels then the default label will be
6574 taken. */
6575 if (i > j)
6576 return gimple_switch_label (switch_stmt, 0);
6577 }
6578
6579 if (vr->kind () == VR_ANTI_RANGE)
6580 {
6581 unsigned n = gimple_switch_num_labels (switch_stmt);
6582 tree min_label = gimple_switch_label (switch_stmt, 1);
6583 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6584
6585 /* The default label will be taken only if the anti-range of the
6586 operand is entirely outside the bounds of all the (non-default)
6587 case labels. */
6588 if (tree_int_cst_compare (vr->min (), CASE_LOW (min_label)) <= 0
6589 && (CASE_HIGH (max_label) != NULL_TREE
6590 ? tree_int_cst_compare (vr->max (),
6591 CASE_HIGH (max_label)) >= 0
6592 : tree_int_cst_compare (vr->max (),
6593 CASE_LOW (max_label)) >= 0))
6594 return gimple_switch_label (switch_stmt, 0);
6595 }
6596
6597 return NULL_TREE;
6598 }
6599
6600 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6601 {
6602 tree lhs = gimple_assign_lhs (assign_stmt);
6603 if (TREE_CODE (lhs) == SSA_NAME
6604 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6605 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6606 && stmt_interesting_for_vrp (stmt))
6607 {
6608 edge dummy_e;
6609 tree dummy_tree;
6610 value_range new_vr;
6611 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6612 &dummy_tree, &new_vr);
6613 tree singleton;
6614 if (new_vr.singleton_p (&singleton))
6615 return singleton;
6616 }
6617 }
6618
6619 return NULL_TREE;
6620 }
6621
6622 class vrp_dom_walker : public dom_walker
6623 {
6624 public:
6625 vrp_dom_walker (cdi_direction direction,
6626 class const_and_copies *const_and_copies,
6627 class avail_exprs_stack *avail_exprs_stack)
6628 : dom_walker (direction, REACHABLE_BLOCKS),
6629 m_const_and_copies (const_and_copies),
6630 m_avail_exprs_stack (avail_exprs_stack),
6631 m_dummy_cond (NULL) {}
6632
6633 virtual edge before_dom_children (basic_block);
6634 virtual void after_dom_children (basic_block);
6635
6636 class vr_values *vr_values;
6637
6638 private:
6639 class const_and_copies *m_const_and_copies;
6640 class avail_exprs_stack *m_avail_exprs_stack;
6641
6642 gcond *m_dummy_cond;
6643
6644 };
6645
6646 /* Called before processing dominator children of BB. We want to look
6647 at ASSERT_EXPRs and record information from them in the appropriate
6648 tables.
6649
6650 We could look at other statements here. It's not seen as likely
6651 to significantly increase the jump threads we discover. */
6652
6653 edge
6654 vrp_dom_walker::before_dom_children (basic_block bb)
6655 {
6656 gimple_stmt_iterator gsi;
6657
6658 m_avail_exprs_stack->push_marker ();
6659 m_const_and_copies->push_marker ();
6660 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6661 {
6662 gimple *stmt = gsi_stmt (gsi);
6663 if (gimple_assign_single_p (stmt)
6664 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6665 {
6666 tree rhs1 = gimple_assign_rhs1 (stmt);
6667 tree cond = TREE_OPERAND (rhs1, 1);
6668 tree inverted = invert_truthvalue (cond);
6669 vec<cond_equivalence> p;
6670 p.create (3);
6671 record_conditions (&p, cond, inverted);
6672 for (unsigned int i = 0; i < p.length (); i++)
6673 m_avail_exprs_stack->record_cond (&p[i]);
6674
6675 tree lhs = gimple_assign_lhs (stmt);
6676 m_const_and_copies->record_const_or_copy (lhs,
6677 TREE_OPERAND (rhs1, 0));
6678 p.release ();
6679 continue;
6680 }
6681 break;
6682 }
6683 return NULL;
6684 }
6685
6686 /* Called after processing dominator children of BB. This is where we
6687 actually call into the threader. */
6688 void
6689 vrp_dom_walker::after_dom_children (basic_block bb)
6690 {
6691 if (!m_dummy_cond)
6692 m_dummy_cond = gimple_build_cond (NE_EXPR,
6693 integer_zero_node, integer_zero_node,
6694 NULL, NULL);
6695
6696 x_vr_values = vr_values;
6697 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6698 m_avail_exprs_stack, NULL,
6699 simplify_stmt_for_jump_threading);
6700 x_vr_values = NULL;
6701
6702 m_avail_exprs_stack->pop_to_marker ();
6703 m_const_and_copies->pop_to_marker ();
6704 }
6705
6706 /* Blocks which have more than one predecessor and more than
6707 one successor present jump threading opportunities, i.e.,
6708 when the block is reached from a specific predecessor, we
6709 may be able to determine which of the outgoing edges will
6710 be traversed. When this optimization applies, we are able
6711 to avoid conditionals at runtime and we may expose secondary
6712 optimization opportunities.
6713
6714 This routine is effectively a driver for the generic jump
6715 threading code. It basically just presents the generic code
6716 with edges that may be suitable for jump threading.
6717
6718 Unlike DOM, we do not iterate VRP if jump threading was successful.
6719 While iterating may expose new opportunities for VRP, it is expected
6720 those opportunities would be very limited and the compile time cost
6721 to expose those opportunities would be significant.
6722
6723 As jump threading opportunities are discovered, they are registered
6724 for later realization. */
6725
6726 static void
6727 identify_jump_threads (class vr_values *vr_values)
6728 {
6729 /* Ugh. When substituting values earlier in this pass we can
6730 wipe the dominance information. So rebuild the dominator
6731 information as we need it within the jump threading code. */
6732 calculate_dominance_info (CDI_DOMINATORS);
6733
6734 /* We do not allow VRP information to be used for jump threading
6735 across a back edge in the CFG. Otherwise it becomes too
6736 difficult to avoid eliminating loop exit tests. Of course
6737 EDGE_DFS_BACK is not accurate at this time so we have to
6738 recompute it. */
6739 mark_dfs_back_edges ();
6740
6741 /* Allocate our unwinder stack to unwind any temporary equivalences
6742 that might be recorded. */
6743 const_and_copies *equiv_stack = new const_and_copies ();
6744
6745 hash_table<expr_elt_hasher> *avail_exprs
6746 = new hash_table<expr_elt_hasher> (1024);
6747 avail_exprs_stack *avail_exprs_stack
6748 = new class avail_exprs_stack (avail_exprs);
6749
6750 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6751 walker.vr_values = vr_values;
6752 walker.walk (cfun->cfg->x_entry_block_ptr);
6753
6754 /* We do not actually update the CFG or SSA graphs at this point as
6755 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6756 handle ASSERT_EXPRs gracefully. */
6757 delete equiv_stack;
6758 delete avail_exprs;
6759 delete avail_exprs_stack;
6760 }
6761
6762 /* Traverse all the blocks folding conditionals with known ranges. */
6763
6764 void
6765 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6766 {
6767 size_t i;
6768
6769 /* We have completed propagating through the lattice. */
6770 vr_values.set_lattice_propagation_complete ();
6771
6772 if (dump_file)
6773 {
6774 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6775 vr_values.dump_all_value_ranges (dump_file);
6776 fprintf (dump_file, "\n");
6777 }
6778
6779 /* Set value range to non pointer SSA_NAMEs. */
6780 for (i = 0; i < num_ssa_names; i++)
6781 {
6782 tree name = ssa_name (i);
6783 if (!name)
6784 continue;
6785
6786 const value_range *vr = get_value_range (name);
6787 if (!name || !vr->constant_p ())
6788 continue;
6789
6790 if (POINTER_TYPE_P (TREE_TYPE (name))
6791 && range_includes_zero_p (vr) == 0)
6792 set_ptr_nonnull (name);
6793 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6794 set_range_info (name, *vr);
6795 }
6796
6797 /* If we're checking array refs, we want to merge information on
6798 the executability of each edge between vrp_folder and the
6799 check_array_bounds_dom_walker: each can clear the
6800 EDGE_EXECUTABLE flag on edges, in different ways.
6801
6802 Hence, if we're going to call check_all_array_refs, set
6803 the flag on every edge now, rather than in
6804 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6805 it from some edges. */
6806 if (warn_array_bounds && warn_array_bounds_p)
6807 set_all_edges_as_executable (cfun);
6808
6809 class vrp_folder vrp_folder;
6810 vrp_folder.vr_values = &vr_values;
6811 vrp_folder.substitute_and_fold ();
6812
6813 if (warn_array_bounds && warn_array_bounds_p)
6814 check_all_array_refs ();
6815 }
6816
6817 /* Main entry point to VRP (Value Range Propagation). This pass is
6818 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6819 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6820 Programming Language Design and Implementation, pp. 67-78, 1995.
6821 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6822
6823 This is essentially an SSA-CCP pass modified to deal with ranges
6824 instead of constants.
6825
6826 While propagating ranges, we may find that two or more SSA name
6827 have equivalent, though distinct ranges. For instance,
6828
6829 1 x_9 = p_3->a;
6830 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6831 3 if (p_4 == q_2)
6832 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6833 5 endif
6834 6 if (q_2)
6835
6836 In the code above, pointer p_5 has range [q_2, q_2], but from the
6837 code we can also determine that p_5 cannot be NULL and, if q_2 had
6838 a non-varying range, p_5's range should also be compatible with it.
6839
6840 These equivalences are created by two expressions: ASSERT_EXPR and
6841 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6842 result of another assertion, then we can use the fact that p_5 and
6843 p_4 are equivalent when evaluating p_5's range.
6844
6845 Together with value ranges, we also propagate these equivalences
6846 between names so that we can take advantage of information from
6847 multiple ranges when doing final replacement. Note that this
6848 equivalency relation is transitive but not symmetric.
6849
6850 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6851 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6852 in contexts where that assertion does not hold (e.g., in line 6).
6853
6854 TODO, the main difference between this pass and Patterson's is that
6855 we do not propagate edge probabilities. We only compute whether
6856 edges can be taken or not. That is, instead of having a spectrum
6857 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6858 DON'T KNOW. In the future, it may be worthwhile to propagate
6859 probabilities to aid branch prediction. */
6860
6861 static unsigned int
6862 execute_vrp (bool warn_array_bounds_p)
6863 {
6864
6865 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6866 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6867 scev_initialize ();
6868
6869 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6870 Inserting assertions may split edges which will invalidate
6871 EDGE_DFS_BACK. */
6872 insert_range_assertions ();
6873
6874 threadedge_initialize_values ();
6875
6876 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6877 mark_dfs_back_edges ();
6878
6879 class vrp_prop vrp_prop;
6880 vrp_prop.vrp_initialize ();
6881 vrp_prop.ssa_propagate ();
6882 vrp_prop.vrp_finalize (warn_array_bounds_p);
6883
6884 /* We must identify jump threading opportunities before we release
6885 the datastructures built by VRP. */
6886 identify_jump_threads (&vrp_prop.vr_values);
6887
6888 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6889 was set by a type conversion can often be rewritten to use the
6890 RHS of the type conversion.
6891
6892 However, doing so inhibits jump threading through the comparison.
6893 So that transformation is not performed until after jump threading
6894 is complete. */
6895 basic_block bb;
6896 FOR_EACH_BB_FN (bb, cfun)
6897 {
6898 gimple *last = last_stmt (bb);
6899 if (last && gimple_code (last) == GIMPLE_COND)
6900 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6901 }
6902
6903 free_numbers_of_iterations_estimates (cfun);
6904
6905 /* ASSERT_EXPRs must be removed before finalizing jump threads
6906 as finalizing jump threads calls the CFG cleanup code which
6907 does not properly handle ASSERT_EXPRs. */
6908 remove_range_assertions ();
6909
6910 /* If we exposed any new variables, go ahead and put them into
6911 SSA form now, before we handle jump threading. This simplifies
6912 interactions between rewriting of _DECL nodes into SSA form
6913 and rewriting SSA_NAME nodes into SSA form after block
6914 duplication and CFG manipulation. */
6915 update_ssa (TODO_update_ssa);
6916
6917 /* We identified all the jump threading opportunities earlier, but could
6918 not transform the CFG at that time. This routine transforms the
6919 CFG and arranges for the dominator tree to be rebuilt if necessary.
6920
6921 Note the SSA graph update will occur during the normal TODO
6922 processing by the pass manager. */
6923 thread_through_all_blocks (false);
6924
6925 vrp_prop.vr_values.cleanup_edges_and_switches ();
6926 threadedge_finalize_values ();
6927
6928 scev_finalize ();
6929 loop_optimizer_finalize ();
6930 return 0;
6931 }
6932
6933 namespace {
6934
6935 const pass_data pass_data_vrp =
6936 {
6937 GIMPLE_PASS, /* type */
6938 "vrp", /* name */
6939 OPTGROUP_NONE, /* optinfo_flags */
6940 TV_TREE_VRP, /* tv_id */
6941 PROP_ssa, /* properties_required */
6942 0, /* properties_provided */
6943 0, /* properties_destroyed */
6944 0, /* todo_flags_start */
6945 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
6946 };
6947
6948 class pass_vrp : public gimple_opt_pass
6949 {
6950 public:
6951 pass_vrp (gcc::context *ctxt)
6952 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
6953 {}
6954
6955 /* opt_pass methods: */
6956 opt_pass * clone () { return new pass_vrp (m_ctxt); }
6957 void set_pass_param (unsigned int n, bool param)
6958 {
6959 gcc_assert (n == 0);
6960 warn_array_bounds_p = param;
6961 }
6962 virtual bool gate (function *) { return flag_tree_vrp != 0; }
6963 virtual unsigned int execute (function *)
6964 { return execute_vrp (warn_array_bounds_p); }
6965
6966 private:
6967 bool warn_array_bounds_p;
6968 }; // class pass_vrp
6969
6970 } // anon namespace
6971
6972 gimple_opt_pass *
6973 make_pass_vrp (gcc::context *ctxt)
6974 {
6975 return new pass_vrp (ctxt);
6976 }
6977
6978
6979 /* Worker for determine_value_range. */
6980
6981 static void
6982 determine_value_range_1 (value_range_base *vr, tree expr)
6983 {
6984 if (BINARY_CLASS_P (expr))
6985 {
6986 value_range_base vr0, vr1;
6987 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6988 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
6989 extract_range_from_binary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6990 &vr0, &vr1);
6991 }
6992 else if (UNARY_CLASS_P (expr))
6993 {
6994 value_range_base vr0;
6995 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6996 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6997 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
6998 }
6999 else if (TREE_CODE (expr) == INTEGER_CST)
7000 vr->set (expr);
7001 else
7002 {
7003 value_range_kind kind;
7004 wide_int min, max;
7005 /* For SSA names try to extract range info computed by VRP. Otherwise
7006 fall back to varying. */
7007 if (TREE_CODE (expr) == SSA_NAME
7008 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
7009 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
7010 vr->set (kind, wide_int_to_tree (TREE_TYPE (expr), min),
7011 wide_int_to_tree (TREE_TYPE (expr), max));
7012 else
7013 vr->set_varying ();
7014 }
7015 }
7016
7017 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
7018 the determined range type. */
7019
7020 value_range_kind
7021 determine_value_range (tree expr, wide_int *min, wide_int *max)
7022 {
7023 value_range_base vr;
7024 determine_value_range_1 (&vr, expr);
7025 if (vr.constant_p ())
7026 {
7027 *min = wi::to_wide (vr.min ());
7028 *max = wi::to_wide (vr.max ());
7029 return vr.kind ();
7030 }
7031
7032 return VR_VARYING;
7033 }