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