1 //===- ConstantRange.cpp - ConstantRange implementation -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Represent a range of possible values that may occur when the program is run
10 // for an integral value.  This keeps track of a lower and upper bound for the
11 // constant, which MAY wrap around the end of the numeric range.  To do this, it
12 // keeps track of a [lower, upper) bound, which specifies an interval just like
13 // STL iterators.  When used with boolean values, the following are important
14 // ranges (other integral ranges use min/max values for special range values):
15 //
16 //  [F, F) = {}     = Empty set
17 //  [T, F) = {T}
18 //  [F, T) = {F}
19 //  [T, T) = {F, T} = Full set
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/IR/ConstantRange.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/InstrTypes.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/KnownBits.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 #include <cassert>
38 #include <cstdint>
39 
40 using namespace llvm;
41 
42 ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)
43     : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
44       Upper(Lower) {}
45 
46 ConstantRange::ConstantRange(APInt V)
47     : Lower(std::move(V)), Upper(Lower + 1) {}
48 
49 ConstantRange::ConstantRange(APInt L, APInt U)
50     : Lower(std::move(L)), Upper(std::move(U)) {
51   assert(Lower.getBitWidth() == Upper.getBitWidth() &&
52          "ConstantRange with unequal bit widths");
53   assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
54          "Lower == Upper, but they aren't min or max value!");
55 }
56 
57 ConstantRange ConstantRange::fromKnownBits(const KnownBits &Known,
58                                            bool IsSigned) {
59   assert(!Known.hasConflict() && "Expected valid KnownBits");
60 
61   if (Known.isUnknown())
62     return getFull(Known.getBitWidth());
63 
64   // For unsigned ranges, or signed ranges with known sign bit, create a simple
65   // range between the smallest and largest possible value.
66   if (!IsSigned || Known.isNegative() || Known.isNonNegative())
67     return ConstantRange(Known.One, ~Known.Zero + 1);
68 
69   // If we don't know the sign bit, pick the lower bound as a negative number
70   // and the upper bound as a non-negative one.
71   APInt Lower = Known.One, Upper = ~Known.Zero;
72   Lower.setSignBit();
73   Upper.clearSignBit();
74   return ConstantRange(Lower, Upper + 1);
75 }
76 
77 ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
78                                                    const ConstantRange &CR) {
79   if (CR.isEmptySet())
80     return CR;
81 
82   uint32_t W = CR.getBitWidth();
83   switch (Pred) {
84   default:
85     llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
86   case CmpInst::ICMP_EQ:
87     return CR;
88   case CmpInst::ICMP_NE:
89     if (CR.isSingleElement())
90       return ConstantRange(CR.getUpper(), CR.getLower());
91     return getFull(W);
92   case CmpInst::ICMP_ULT: {
93     APInt UMax(CR.getUnsignedMax());
94     if (UMax.isMinValue())
95       return getEmpty(W);
96     return ConstantRange(APInt::getMinValue(W), std::move(UMax));
97   }
98   case CmpInst::ICMP_SLT: {
99     APInt SMax(CR.getSignedMax());
100     if (SMax.isMinSignedValue())
101       return getEmpty(W);
102     return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));
103   }
104   case CmpInst::ICMP_ULE:
105     return getNonEmpty(APInt::getMinValue(W), CR.getUnsignedMax() + 1);
106   case CmpInst::ICMP_SLE:
107     return getNonEmpty(APInt::getSignedMinValue(W), CR.getSignedMax() + 1);
108   case CmpInst::ICMP_UGT: {
109     APInt UMin(CR.getUnsignedMin());
110     if (UMin.isMaxValue())
111       return getEmpty(W);
112     return ConstantRange(std::move(UMin) + 1, APInt::getNullValue(W));
113   }
114   case CmpInst::ICMP_SGT: {
115     APInt SMin(CR.getSignedMin());
116     if (SMin.isMaxSignedValue())
117       return getEmpty(W);
118     return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));
119   }
120   case CmpInst::ICMP_UGE:
121     return getNonEmpty(CR.getUnsignedMin(), APInt::getNullValue(W));
122   case CmpInst::ICMP_SGE:
123     return getNonEmpty(CR.getSignedMin(), APInt::getSignedMinValue(W));
124   }
125 }
126 
127 ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
128                                                       const ConstantRange &CR) {
129   // Follows from De-Morgan's laws:
130   //
131   // ~(~A union ~B) == A intersect B.
132   //
133   return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
134       .inverse();
135 }
136 
137 ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
138                                                  const APInt &C) {
139   // Computes the exact range that is equal to both the constant ranges returned
140   // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
141   // when RHS is a singleton such as an APInt and so the assert is valid.
142   // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
143   // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
144   //
145   assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
146   return makeAllowedICmpRegion(Pred, C);
147 }
148 
149 bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
150                                       APInt &RHS) const {
151   bool Success = false;
152 
153   if (isFullSet() || isEmptySet()) {
154     Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
155     RHS = APInt(getBitWidth(), 0);
156     Success = true;
157   } else if (auto *OnlyElt = getSingleElement()) {
158     Pred = CmpInst::ICMP_EQ;
159     RHS = *OnlyElt;
160     Success = true;
161   } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
162     Pred = CmpInst::ICMP_NE;
163     RHS = *OnlyMissingElt;
164     Success = true;
165   } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
166     Pred =
167         getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
168     RHS = getUpper();
169     Success = true;
170   } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
171     Pred =
172         getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
173     RHS = getLower();
174     Success = true;
175   }
176 
177   assert((!Success || ConstantRange::makeExactICmpRegion(Pred, RHS) == *this) &&
178          "Bad result!");
179 
180   return Success;
181 }
182 
183 /// Exact mul nuw region for single element RHS.
184 static ConstantRange makeExactMulNUWRegion(const APInt &V) {
185   unsigned BitWidth = V.getBitWidth();
186   if (V == 0)
187     return ConstantRange::getFull(V.getBitWidth());
188 
189   return ConstantRange::getNonEmpty(
190       APIntOps::RoundingUDiv(APInt::getMinValue(BitWidth), V,
191                              APInt::Rounding::UP),
192       APIntOps::RoundingUDiv(APInt::getMaxValue(BitWidth), V,
193                              APInt::Rounding::DOWN) + 1);
194 }
195 
196 /// Exact mul nsw region for single element RHS.
197 static ConstantRange makeExactMulNSWRegion(const APInt &V) {
198   // Handle special case for 0, -1 and 1. See the last for reason why we
199   // specialize -1 and 1.
200   unsigned BitWidth = V.getBitWidth();
201   if (V == 0 || V.isOneValue())
202     return ConstantRange::getFull(BitWidth);
203 
204   APInt MinValue = APInt::getSignedMinValue(BitWidth);
205   APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
206   // e.g. Returning [-127, 127], represented as [-127, -128).
207   if (V.isAllOnesValue())
208     return ConstantRange(-MaxValue, MinValue);
209 
210   APInt Lower, Upper;
211   if (V.isNegative()) {
212     Lower = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::UP);
213     Upper = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::DOWN);
214   } else {
215     Lower = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::UP);
216     Upper = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::DOWN);
217   }
218   // ConstantRange ctor take a half inclusive interval [Lower, Upper + 1).
219   // Upper + 1 is guaranteed not to overflow, because |divisor| > 1. 0, -1,
220   // and 1 are already handled as special cases.
221   return ConstantRange(Lower, Upper + 1);
222 }
223 
224 ConstantRange
225 ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
226                                           const ConstantRange &Other,
227                                           unsigned NoWrapKind) {
228   using OBO = OverflowingBinaryOperator;
229 
230   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
231 
232   assert((NoWrapKind == OBO::NoSignedWrap ||
233           NoWrapKind == OBO::NoUnsignedWrap) &&
234          "NoWrapKind invalid!");
235 
236   bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;
237   unsigned BitWidth = Other.getBitWidth();
238 
239   switch (BinOp) {
240   default:
241     llvm_unreachable("Unsupported binary op");
242 
243   case Instruction::Add: {
244     if (Unsigned)
245       return getNonEmpty(APInt::getNullValue(BitWidth),
246                          -Other.getUnsignedMax());
247 
248     APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
249     APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
250     return getNonEmpty(
251         SMin.isNegative() ? SignedMinVal - SMin : SignedMinVal,
252         SMax.isStrictlyPositive() ? SignedMinVal - SMax : SignedMinVal);
253   }
254 
255   case Instruction::Sub: {
256     if (Unsigned)
257       return getNonEmpty(Other.getUnsignedMax(), APInt::getMinValue(BitWidth));
258 
259     APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
260     APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
261     return getNonEmpty(
262         SMax.isStrictlyPositive() ? SignedMinVal + SMax : SignedMinVal,
263         SMin.isNegative() ? SignedMinVal + SMin : SignedMinVal);
264   }
265 
266   case Instruction::Mul:
267     if (Unsigned)
268       return makeExactMulNUWRegion(Other.getUnsignedMax());
269 
270     return makeExactMulNSWRegion(Other.getSignedMin())
271         .intersectWith(makeExactMulNSWRegion(Other.getSignedMax()));
272   }
273 }
274 
275 ConstantRange ConstantRange::makeExactNoWrapRegion(Instruction::BinaryOps BinOp,
276                                                    const APInt &Other,
277                                                    unsigned NoWrapKind) {
278   // makeGuaranteedNoWrapRegion() is exact for single-element ranges, as
279   // "for all" and "for any" coincide in this case.
280   return makeGuaranteedNoWrapRegion(BinOp, ConstantRange(Other), NoWrapKind);
281 }
282 
283 bool ConstantRange::isFullSet() const {
284   return Lower == Upper && Lower.isMaxValue();
285 }
286 
287 bool ConstantRange::isEmptySet() const {
288   return Lower == Upper && Lower.isMinValue();
289 }
290 
291 bool ConstantRange::isWrappedSet() const {
292   return Lower.ugt(Upper) && !Upper.isNullValue();
293 }
294 
295 bool ConstantRange::isUpperWrapped() const {
296   return Lower.ugt(Upper);
297 }
298 
299 bool ConstantRange::isSignWrappedSet() const {
300   return Lower.sgt(Upper) && !Upper.isMinSignedValue();
301 }
302 
303 bool ConstantRange::isUpperSignWrapped() const {
304   return Lower.sgt(Upper);
305 }
306 
307 bool
308 ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
309   assert(getBitWidth() == Other.getBitWidth());
310   if (isFullSet())
311     return false;
312   if (Other.isFullSet())
313     return true;
314   return (Upper - Lower).ult(Other.Upper - Other.Lower);
315 }
316 
317 bool
318 ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
319   assert(MaxSize && "MaxSize can't be 0.");
320   // If this a full set, we need special handling to avoid needing an extra bit
321   // to represent the size.
322   if (isFullSet())
323     return APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
324 
325   return (Upper - Lower).ugt(MaxSize);
326 }
327 
328 bool ConstantRange::isAllNegative() const {
329   // Empty set is all negative, full set is not.
330   if (isEmptySet())
331     return true;
332   if (isFullSet())
333     return false;
334 
335   return !isUpperSignWrapped() && !Upper.isStrictlyPositive();
336 }
337 
338 bool ConstantRange::isAllNonNegative() const {
339   // Empty and full set are automatically treated correctly.
340   return !isSignWrappedSet() && Lower.isNonNegative();
341 }
342 
343 APInt ConstantRange::getUnsignedMax() const {
344   if (isFullSet() || isUpperWrapped())
345     return APInt::getMaxValue(getBitWidth());
346   return getUpper() - 1;
347 }
348 
349 APInt ConstantRange::getUnsignedMin() const {
350   if (isFullSet() || isWrappedSet())
351     return APInt::getMinValue(getBitWidth());
352   return getLower();
353 }
354 
355 APInt ConstantRange::getSignedMax() const {
356   if (isFullSet() || isUpperSignWrapped())
357     return APInt::getSignedMaxValue(getBitWidth());
358   return getUpper() - 1;
359 }
360 
361 APInt ConstantRange::getSignedMin() const {
362   if (isFullSet() || isSignWrappedSet())
363     return APInt::getSignedMinValue(getBitWidth());
364   return getLower();
365 }
366 
367 bool ConstantRange::contains(const APInt &V) const {
368   if (Lower == Upper)
369     return isFullSet();
370 
371   if (!isUpperWrapped())
372     return Lower.ule(V) && V.ult(Upper);
373   return Lower.ule(V) || V.ult(Upper);
374 }
375 
376 bool ConstantRange::contains(const ConstantRange &Other) const {
377   if (isFullSet() || Other.isEmptySet()) return true;
378   if (isEmptySet() || Other.isFullSet()) return false;
379 
380   if (!isUpperWrapped()) {
381     if (Other.isUpperWrapped())
382       return false;
383 
384     return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
385   }
386 
387   if (!Other.isUpperWrapped())
388     return Other.getUpper().ule(Upper) ||
389            Lower.ule(Other.getLower());
390 
391   return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
392 }
393 
394 ConstantRange ConstantRange::subtract(const APInt &Val) const {
395   assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
396   // If the set is empty or full, don't modify the endpoints.
397   if (Lower == Upper)
398     return *this;
399   return ConstantRange(Lower - Val, Upper - Val);
400 }
401 
402 ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
403   return intersectWith(CR.inverse());
404 }
405 
406 static ConstantRange getPreferredRange(
407     const ConstantRange &CR1, const ConstantRange &CR2,
408     ConstantRange::PreferredRangeType Type) {
409   if (Type == ConstantRange::Unsigned) {
410     if (!CR1.isWrappedSet() && CR2.isWrappedSet())
411       return CR1;
412     if (CR1.isWrappedSet() && !CR2.isWrappedSet())
413       return CR2;
414   } else if (Type == ConstantRange::Signed) {
415     if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet())
416       return CR1;
417     if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet())
418       return CR2;
419   }
420 
421   if (CR1.isSizeStrictlySmallerThan(CR2))
422     return CR1;
423   return CR2;
424 }
425 
426 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,
427                                            PreferredRangeType Type) const {
428   assert(getBitWidth() == CR.getBitWidth() &&
429          "ConstantRange types don't agree!");
430 
431   // Handle common cases.
432   if (   isEmptySet() || CR.isFullSet()) return *this;
433   if (CR.isEmptySet() ||    isFullSet()) return CR;
434 
435   if (!isUpperWrapped() && CR.isUpperWrapped())
436     return CR.intersectWith(*this, Type);
437 
438   if (!isUpperWrapped() && !CR.isUpperWrapped()) {
439     if (Lower.ult(CR.Lower)) {
440       // L---U       : this
441       //       L---U : CR
442       if (Upper.ule(CR.Lower))
443         return getEmpty();
444 
445       // L---U       : this
446       //   L---U     : CR
447       if (Upper.ult(CR.Upper))
448         return ConstantRange(CR.Lower, Upper);
449 
450       // L-------U   : this
451       //   L---U     : CR
452       return CR;
453     }
454     //   L---U     : this
455     // L-------U   : CR
456     if (Upper.ult(CR.Upper))
457       return *this;
458 
459     //   L-----U   : this
460     // L-----U     : CR
461     if (Lower.ult(CR.Upper))
462       return ConstantRange(Lower, CR.Upper);
463 
464     //       L---U : this
465     // L---U       : CR
466     return getEmpty();
467   }
468 
469   if (isUpperWrapped() && !CR.isUpperWrapped()) {
470     if (CR.Lower.ult(Upper)) {
471       // ------U   L--- : this
472       //  L--U          : CR
473       if (CR.Upper.ult(Upper))
474         return CR;
475 
476       // ------U   L--- : this
477       //  L------U      : CR
478       if (CR.Upper.ule(Lower))
479         return ConstantRange(CR.Lower, Upper);
480 
481       // ------U   L--- : this
482       //  L----------U  : CR
483       return getPreferredRange(*this, CR, Type);
484     }
485     if (CR.Lower.ult(Lower)) {
486       // --U      L---- : this
487       //     L--U       : CR
488       if (CR.Upper.ule(Lower))
489         return getEmpty();
490 
491       // --U      L---- : this
492       //     L------U   : CR
493       return ConstantRange(Lower, CR.Upper);
494     }
495 
496     // --U  L------ : this
497     //        L--U  : CR
498     return CR;
499   }
500 
501   if (CR.Upper.ult(Upper)) {
502     // ------U L-- : this
503     // --U L------ : CR
504     if (CR.Lower.ult(Upper))
505       return getPreferredRange(*this, CR, Type);
506 
507     // ----U   L-- : this
508     // --U   L---- : CR
509     if (CR.Lower.ult(Lower))
510       return ConstantRange(Lower, CR.Upper);
511 
512     // ----U L---- : this
513     // --U     L-- : CR
514     return CR;
515   }
516   if (CR.Upper.ule(Lower)) {
517     // --U     L-- : this
518     // ----U L---- : CR
519     if (CR.Lower.ult(Lower))
520       return *this;
521 
522     // --U   L---- : this
523     // ----U   L-- : CR
524     return ConstantRange(CR.Lower, Upper);
525   }
526 
527   // --U L------ : this
528   // ------U L-- : CR
529   return getPreferredRange(*this, CR, Type);
530 }
531 
532 ConstantRange ConstantRange::unionWith(const ConstantRange &CR,
533                                        PreferredRangeType Type) const {
534   assert(getBitWidth() == CR.getBitWidth() &&
535          "ConstantRange types don't agree!");
536 
537   if (   isFullSet() || CR.isEmptySet()) return *this;
538   if (CR.isFullSet() ||    isEmptySet()) return CR;
539 
540   if (!isUpperWrapped() && CR.isUpperWrapped())
541     return CR.unionWith(*this, Type);
542 
543   if (!isUpperWrapped() && !CR.isUpperWrapped()) {
544     //        L---U  and  L---U        : this
545     //  L---U                   L---U  : CR
546     // result in one of
547     //  L---------U
548     // -----U L-----
549     if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower))
550       return getPreferredRange(
551           ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
552 
553     APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
554     APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
555 
556     if (L.isNullValue() && U.isNullValue())
557       return getFull();
558 
559     return ConstantRange(std::move(L), std::move(U));
560   }
561 
562   if (!CR.isUpperWrapped()) {
563     // ------U   L-----  and  ------U   L----- : this
564     //   L--U                            L--U  : CR
565     if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
566       return *this;
567 
568     // ------U   L----- : this
569     //    L---------U   : CR
570     if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
571       return getFull();
572 
573     // ----U       L---- : this
574     //       L---U       : CR
575     // results in one of
576     // ----------U L----
577     // ----U L----------
578     if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower))
579       return getPreferredRange(
580           ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
581 
582     // ----U     L----- : this
583     //        L----U    : CR
584     if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper))
585       return ConstantRange(CR.Lower, Upper);
586 
587     // ------U    L---- : this
588     //    L-----U       : CR
589     assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) &&
590            "ConstantRange::unionWith missed a case with one range wrapped");
591     return ConstantRange(Lower, CR.Upper);
592   }
593 
594   // ------U    L----  and  ------U    L---- : this
595   // -U  L-----------  and  ------------U  L : CR
596   if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
597     return getFull();
598 
599   APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
600   APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
601 
602   return ConstantRange(std::move(L), std::move(U));
603 }
604 
605 ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
606                                     uint32_t ResultBitWidth) const {
607   switch (CastOp) {
608   default:
609     llvm_unreachable("unsupported cast type");
610   case Instruction::Trunc:
611     return truncate(ResultBitWidth);
612   case Instruction::SExt:
613     return signExtend(ResultBitWidth);
614   case Instruction::ZExt:
615     return zeroExtend(ResultBitWidth);
616   case Instruction::BitCast:
617     return *this;
618   case Instruction::FPToUI:
619   case Instruction::FPToSI:
620     if (getBitWidth() == ResultBitWidth)
621       return *this;
622     else
623       return getFull();
624   case Instruction::UIToFP: {
625     // TODO: use input range if available
626     auto BW = getBitWidth();
627     APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
628     APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
629     return ConstantRange(std::move(Min), std::move(Max));
630   }
631   case Instruction::SIToFP: {
632     // TODO: use input range if available
633     auto BW = getBitWidth();
634     APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
635     APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
636     return ConstantRange(std::move(SMin), std::move(SMax));
637   }
638   case Instruction::FPTrunc:
639   case Instruction::FPExt:
640   case Instruction::IntToPtr:
641   case Instruction::PtrToInt:
642   case Instruction::AddrSpaceCast:
643     // Conservatively return getFull set.
644     return getFull();
645   };
646 }
647 
648 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
649   if (isEmptySet()) return getEmpty(DstTySize);
650 
651   unsigned SrcTySize = getBitWidth();
652   assert(SrcTySize < DstTySize && "Not a value extension");
653   if (isFullSet() || isUpperWrapped()) {
654     // Change into [0, 1 << src bit width)
655     APInt LowerExt(DstTySize, 0);
656     if (!Upper) // special case: [X, 0) -- not really wrapping around
657       LowerExt = Lower.zext(DstTySize);
658     return ConstantRange(std::move(LowerExt),
659                          APInt::getOneBitSet(DstTySize, SrcTySize));
660   }
661 
662   return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
663 }
664 
665 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
666   if (isEmptySet()) return getEmpty(DstTySize);
667 
668   unsigned SrcTySize = getBitWidth();
669   assert(SrcTySize < DstTySize && "Not a value extension");
670 
671   // special case: [X, INT_MIN) -- not really wrapping around
672   if (Upper.isMinSignedValue())
673     return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
674 
675   if (isFullSet() || isSignWrappedSet()) {
676     return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
677                          APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
678   }
679 
680   return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
681 }
682 
683 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
684   assert(getBitWidth() > DstTySize && "Not a value truncation");
685   if (isEmptySet())
686     return getEmpty(DstTySize);
687   if (isFullSet())
688     return getFull(DstTySize);
689 
690   APInt LowerDiv(Lower), UpperDiv(Upper);
691   ConstantRange Union(DstTySize, /*isFullSet=*/false);
692 
693   // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
694   // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
695   // then we do the union with [MaxValue, Upper)
696   if (isUpperWrapped()) {
697     // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
698     // truncated range.
699     if (Upper.getActiveBits() > DstTySize ||
700         Upper.countTrailingOnes() == DstTySize)
701       return getFull(DstTySize);
702 
703     Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
704     UpperDiv.setAllBits();
705 
706     // Union covers the MaxValue case, so return if the remaining range is just
707     // MaxValue(DstTy).
708     if (LowerDiv == UpperDiv)
709       return Union;
710   }
711 
712   // Chop off the most significant bits that are past the destination bitwidth.
713   if (LowerDiv.getActiveBits() > DstTySize) {
714     // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
715     APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
716     LowerDiv -= Adjust;
717     UpperDiv -= Adjust;
718   }
719 
720   unsigned UpperDivWidth = UpperDiv.getActiveBits();
721   if (UpperDivWidth <= DstTySize)
722     return ConstantRange(LowerDiv.trunc(DstTySize),
723                          UpperDiv.trunc(DstTySize)).unionWith(Union);
724 
725   // The truncated value wraps around. Check if we can do better than fullset.
726   if (UpperDivWidth == DstTySize + 1) {
727     // Clear the MSB so that UpperDiv wraps around.
728     UpperDiv.clearBit(DstTySize);
729     if (UpperDiv.ult(LowerDiv))
730       return ConstantRange(LowerDiv.trunc(DstTySize),
731                            UpperDiv.trunc(DstTySize)).unionWith(Union);
732   }
733 
734   return getFull(DstTySize);
735 }
736 
737 ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
738   unsigned SrcTySize = getBitWidth();
739   if (SrcTySize > DstTySize)
740     return truncate(DstTySize);
741   if (SrcTySize < DstTySize)
742     return zeroExtend(DstTySize);
743   return *this;
744 }
745 
746 ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
747   unsigned SrcTySize = getBitWidth();
748   if (SrcTySize > DstTySize)
749     return truncate(DstTySize);
750   if (SrcTySize < DstTySize)
751     return signExtend(DstTySize);
752   return *this;
753 }
754 
755 ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
756                                       const ConstantRange &Other) const {
757   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
758 
759   switch (BinOp) {
760   case Instruction::Add:
761     return add(Other);
762   case Instruction::Sub:
763     return sub(Other);
764   case Instruction::Mul:
765     return multiply(Other);
766   case Instruction::UDiv:
767     return udiv(Other);
768   case Instruction::URem:
769     return urem(Other);
770   case Instruction::SRem:
771     return srem(Other);
772   case Instruction::Shl:
773     return shl(Other);
774   case Instruction::LShr:
775     return lshr(Other);
776   case Instruction::AShr:
777     return ashr(Other);
778   case Instruction::And:
779     return binaryAnd(Other);
780   case Instruction::Or:
781     return binaryOr(Other);
782   // Note: floating point operations applied to abstract ranges are just
783   // ideal integer operations with a lossy representation
784   case Instruction::FAdd:
785     return add(Other);
786   case Instruction::FSub:
787     return sub(Other);
788   case Instruction::FMul:
789     return multiply(Other);
790   default:
791     // Conservatively return getFull set.
792     return getFull();
793   }
794 }
795 
796 ConstantRange
797 ConstantRange::add(const ConstantRange &Other) const {
798   if (isEmptySet() || Other.isEmptySet())
799     return getEmpty();
800   if (isFullSet() || Other.isFullSet())
801     return getFull();
802 
803   APInt NewLower = getLower() + Other.getLower();
804   APInt NewUpper = getUpper() + Other.getUpper() - 1;
805   if (NewLower == NewUpper)
806     return getFull();
807 
808   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
809   if (X.isSizeStrictlySmallerThan(*this) ||
810       X.isSizeStrictlySmallerThan(Other))
811     // We've wrapped, therefore, full set.
812     return getFull();
813   return X;
814 }
815 
816 ConstantRange ConstantRange::addWithNoSignedWrap(const APInt &Other) const {
817   // Calculate the subset of this range such that "X + Other" is
818   // guaranteed not to wrap (overflow) for all X in this subset.
819   auto NSWRange = ConstantRange::makeExactNoWrapRegion(
820       BinaryOperator::Add, Other, OverflowingBinaryOperator::NoSignedWrap);
821   auto NSWConstrainedRange = intersectWith(NSWRange);
822 
823   return NSWConstrainedRange.add(ConstantRange(Other));
824 }
825 
826 ConstantRange
827 ConstantRange::sub(const ConstantRange &Other) const {
828   if (isEmptySet() || Other.isEmptySet())
829     return getEmpty();
830   if (isFullSet() || Other.isFullSet())
831     return getFull();
832 
833   APInt NewLower = getLower() - Other.getUpper() + 1;
834   APInt NewUpper = getUpper() - Other.getLower();
835   if (NewLower == NewUpper)
836     return getFull();
837 
838   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
839   if (X.isSizeStrictlySmallerThan(*this) ||
840       X.isSizeStrictlySmallerThan(Other))
841     // We've wrapped, therefore, full set.
842     return getFull();
843   return X;
844 }
845 
846 ConstantRange
847 ConstantRange::multiply(const ConstantRange &Other) const {
848   // TODO: If either operand is a single element and the multiply is known to
849   // be non-wrapping, round the result min and max value to the appropriate
850   // multiple of that element. If wrapping is possible, at least adjust the
851   // range according to the greatest power-of-two factor of the single element.
852 
853   if (isEmptySet() || Other.isEmptySet())
854     return getEmpty();
855 
856   // Multiplication is signedness-independent. However different ranges can be
857   // obtained depending on how the input ranges are treated. These different
858   // ranges are all conservatively correct, but one might be better than the
859   // other. We calculate two ranges; one treating the inputs as unsigned
860   // and the other signed, then return the smallest of these ranges.
861 
862   // Unsigned range first.
863   APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
864   APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
865   APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
866   APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
867 
868   ConstantRange Result_zext = ConstantRange(this_min * Other_min,
869                                             this_max * Other_max + 1);
870   ConstantRange UR = Result_zext.truncate(getBitWidth());
871 
872   // If the unsigned range doesn't wrap, and isn't negative then it's a range
873   // from one positive number to another which is as good as we can generate.
874   // In this case, skip the extra work of generating signed ranges which aren't
875   // going to be better than this range.
876   if (!UR.isUpperWrapped() &&
877       (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
878     return UR;
879 
880   // Now the signed range. Because we could be dealing with negative numbers
881   // here, the lower bound is the smallest of the cartesian product of the
882   // lower and upper ranges; for example:
883   //   [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
884   // Similarly for the upper bound, swapping min for max.
885 
886   this_min = getSignedMin().sext(getBitWidth() * 2);
887   this_max = getSignedMax().sext(getBitWidth() * 2);
888   Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
889   Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
890 
891   auto L = {this_min * Other_min, this_min * Other_max,
892             this_max * Other_min, this_max * Other_max};
893   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
894   ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
895   ConstantRange SR = Result_sext.truncate(getBitWidth());
896 
897   return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
898 }
899 
900 ConstantRange
901 ConstantRange::smax(const ConstantRange &Other) const {
902   // X smax Y is: range(smax(X_smin, Y_smin),
903   //                    smax(X_smax, Y_smax))
904   if (isEmptySet() || Other.isEmptySet())
905     return getEmpty();
906   APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
907   APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
908   return getNonEmpty(std::move(NewL), std::move(NewU));
909 }
910 
911 ConstantRange
912 ConstantRange::umax(const ConstantRange &Other) const {
913   // X umax Y is: range(umax(X_umin, Y_umin),
914   //                    umax(X_umax, Y_umax))
915   if (isEmptySet() || Other.isEmptySet())
916     return getEmpty();
917   APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
918   APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
919   return getNonEmpty(std::move(NewL), std::move(NewU));
920 }
921 
922 ConstantRange
923 ConstantRange::smin(const ConstantRange &Other) const {
924   // X smin Y is: range(smin(X_smin, Y_smin),
925   //                    smin(X_smax, Y_smax))
926   if (isEmptySet() || Other.isEmptySet())
927     return getEmpty();
928   APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
929   APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
930   return getNonEmpty(std::move(NewL), std::move(NewU));
931 }
932 
933 ConstantRange
934 ConstantRange::umin(const ConstantRange &Other) const {
935   // X umin Y is: range(umin(X_umin, Y_umin),
936   //                    umin(X_umax, Y_umax))
937   if (isEmptySet() || Other.isEmptySet())
938     return getEmpty();
939   APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
940   APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
941   return getNonEmpty(std::move(NewL), std::move(NewU));
942 }
943 
944 ConstantRange
945 ConstantRange::udiv(const ConstantRange &RHS) const {
946   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
947     return getEmpty();
948 
949   APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
950 
951   APInt RHS_umin = RHS.getUnsignedMin();
952   if (RHS_umin.isNullValue()) {
953     // We want the lowest value in RHS excluding zero. Usually that would be 1
954     // except for a range in the form of [X, 1) in which case it would be X.
955     if (RHS.getUpper() == 1)
956       RHS_umin = RHS.getLower();
957     else
958       RHS_umin = 1;
959   }
960 
961   APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
962   return getNonEmpty(std::move(Lower), std::move(Upper));
963 }
964 
965 ConstantRange ConstantRange::urem(const ConstantRange &RHS) const {
966   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
967     return getEmpty();
968 
969   // L % R for L < R is L.
970   if (getUnsignedMax().ult(RHS.getUnsignedMin()))
971     return *this;
972 
973   // L % R is <= L and < R.
974   APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1;
975   return getNonEmpty(APInt::getNullValue(getBitWidth()), std::move(Upper));
976 }
977 
978 ConstantRange ConstantRange::srem(const ConstantRange &RHS) const {
979   if (isEmptySet() || RHS.isEmptySet())
980     return getEmpty();
981 
982   ConstantRange AbsRHS = RHS.abs();
983   APInt MinAbsRHS = AbsRHS.getUnsignedMin();
984   APInt MaxAbsRHS = AbsRHS.getUnsignedMax();
985 
986   // Modulus by zero is UB.
987   if (MaxAbsRHS.isNullValue())
988     return getEmpty();
989 
990   if (MinAbsRHS.isNullValue())
991     ++MinAbsRHS;
992 
993   APInt MinLHS = getSignedMin(), MaxLHS = getSignedMax();
994 
995   if (MinLHS.isNonNegative()) {
996     // L % R for L < R is L.
997     if (MaxLHS.ult(MinAbsRHS))
998       return *this;
999 
1000     // L % R is <= L and < R.
1001     APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
1002     return ConstantRange(APInt::getNullValue(getBitWidth()), std::move(Upper));
1003   }
1004 
1005   // Same basic logic as above, but the result is negative.
1006   if (MaxLHS.isNegative()) {
1007     if (MinLHS.ugt(-MinAbsRHS))
1008       return *this;
1009 
1010     APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
1011     return ConstantRange(std::move(Lower), APInt(getBitWidth(), 1));
1012   }
1013 
1014   // LHS range crosses zero.
1015   APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
1016   APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
1017   return ConstantRange(std::move(Lower), std::move(Upper));
1018 }
1019 
1020 ConstantRange
1021 ConstantRange::binaryAnd(const ConstantRange &Other) const {
1022   if (isEmptySet() || Other.isEmptySet())
1023     return getEmpty();
1024 
1025   // TODO: replace this with something less conservative
1026 
1027   APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
1028   return getNonEmpty(APInt::getNullValue(getBitWidth()), std::move(umin) + 1);
1029 }
1030 
1031 ConstantRange
1032 ConstantRange::binaryOr(const ConstantRange &Other) const {
1033   if (isEmptySet() || Other.isEmptySet())
1034     return getEmpty();
1035 
1036   // TODO: replace this with something less conservative
1037 
1038   APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
1039   return getNonEmpty(std::move(umax), APInt::getNullValue(getBitWidth()));
1040 }
1041 
1042 ConstantRange
1043 ConstantRange::shl(const ConstantRange &Other) const {
1044   if (isEmptySet() || Other.isEmptySet())
1045     return getEmpty();
1046 
1047   APInt max = getUnsignedMax();
1048   APInt Other_umax = Other.getUnsignedMax();
1049 
1050   // If we are shifting by maximum amount of
1051   // zero return return the original range.
1052   if (Other_umax.isNullValue())
1053     return *this;
1054   // there's overflow!
1055   if (Other_umax.ugt(max.countLeadingZeros()))
1056     return getFull();
1057 
1058   // FIXME: implement the other tricky cases
1059 
1060   APInt min = getUnsignedMin();
1061   min <<= Other.getUnsignedMin();
1062   max <<= Other_umax;
1063 
1064   return ConstantRange(std::move(min), std::move(max) + 1);
1065 }
1066 
1067 ConstantRange
1068 ConstantRange::lshr(const ConstantRange &Other) const {
1069   if (isEmptySet() || Other.isEmptySet())
1070     return getEmpty();
1071 
1072   APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
1073   APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
1074   return getNonEmpty(std::move(min), std::move(max));
1075 }
1076 
1077 ConstantRange
1078 ConstantRange::ashr(const ConstantRange &Other) const {
1079   if (isEmptySet() || Other.isEmptySet())
1080     return getEmpty();
1081 
1082   // May straddle zero, so handle both positive and negative cases.
1083   // 'PosMax' is the upper bound of the result of the ashr
1084   // operation, when Upper of the LHS of ashr is a non-negative.
1085   // number. Since ashr of a non-negative number will result in a
1086   // smaller number, the Upper value of LHS is shifted right with
1087   // the minimum value of 'Other' instead of the maximum value.
1088   APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;
1089 
1090   // 'PosMin' is the lower bound of the result of the ashr
1091   // operation, when Lower of the LHS is a non-negative number.
1092   // Since ashr of a non-negative number will result in a smaller
1093   // number, the Lower value of LHS is shifted right with the
1094   // maximum value of 'Other'.
1095   APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());
1096 
1097   // 'NegMax' is the upper bound of the result of the ashr
1098   // operation, when Upper of the LHS of ashr is a negative number.
1099   // Since 'ashr' of a negative number will result in a bigger
1100   // number, the Upper value of LHS is shifted right with the
1101   // maximum value of 'Other'.
1102   APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;
1103 
1104   // 'NegMin' is the lower bound of the result of the ashr
1105   // operation, when Lower of the LHS of ashr is a negative number.
1106   // Since 'ashr' of a negative number will result in a bigger
1107   // number, the Lower value of LHS is shifted right with the
1108   // minimum value of 'Other'.
1109   APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());
1110 
1111   APInt max, min;
1112   if (getSignedMin().isNonNegative()) {
1113     // Upper and Lower of LHS are non-negative.
1114     min = PosMin;
1115     max = PosMax;
1116   } else if (getSignedMax().isNegative()) {
1117     // Upper and Lower of LHS are negative.
1118     min = NegMin;
1119     max = NegMax;
1120   } else {
1121     // Upper is non-negative and Lower is negative.
1122     min = NegMin;
1123     max = PosMax;
1124   }
1125   return getNonEmpty(std::move(min), std::move(max));
1126 }
1127 
1128 ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const {
1129   if (isEmptySet() || Other.isEmptySet())
1130     return getEmpty();
1131 
1132   APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin());
1133   APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1;
1134   return getNonEmpty(std::move(NewL), std::move(NewU));
1135 }
1136 
1137 ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const {
1138   if (isEmptySet() || Other.isEmptySet())
1139     return getEmpty();
1140 
1141   APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin());
1142   APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1;
1143   return getNonEmpty(std::move(NewL), std::move(NewU));
1144 }
1145 
1146 ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const {
1147   if (isEmptySet() || Other.isEmptySet())
1148     return getEmpty();
1149 
1150   APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax());
1151   APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1;
1152   return getNonEmpty(std::move(NewL), std::move(NewU));
1153 }
1154 
1155 ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const {
1156   if (isEmptySet() || Other.isEmptySet())
1157     return getEmpty();
1158 
1159   APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax());
1160   APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1;
1161   return getNonEmpty(std::move(NewL), std::move(NewU));
1162 }
1163 
1164 ConstantRange ConstantRange::inverse() const {
1165   if (isFullSet())
1166     return getEmpty();
1167   if (isEmptySet())
1168     return getFull();
1169   return ConstantRange(Upper, Lower);
1170 }
1171 
1172 ConstantRange ConstantRange::abs() const {
1173   if (isEmptySet())
1174     return getEmpty();
1175 
1176   if (isSignWrappedSet()) {
1177     APInt Lo;
1178     // Check whether the range crosses zero.
1179     if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive())
1180       Lo = APInt::getNullValue(getBitWidth());
1181     else
1182       Lo = APIntOps::umin(Lower, -Upper + 1);
1183 
1184     // SignedMin is included in the result range.
1185     return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()) + 1);
1186   }
1187 
1188   APInt SMin = getSignedMin(), SMax = getSignedMax();
1189 
1190   // All non-negative.
1191   if (SMin.isNonNegative())
1192     return *this;
1193 
1194   // All negative.
1195   if (SMax.isNegative())
1196     return ConstantRange(-SMax, -SMin + 1);
1197 
1198   // Range crosses zero.
1199   return ConstantRange(APInt::getNullValue(getBitWidth()),
1200                        APIntOps::umax(-SMin, SMax) + 1);
1201 }
1202 
1203 ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow(
1204     const ConstantRange &Other) const {
1205   if (isEmptySet() || Other.isEmptySet())
1206     return OverflowResult::MayOverflow;
1207 
1208   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1209   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1210 
1211   // a u+ b overflows iff a u> ~b.
1212   if (Min.ugt(~OtherMin))
1213     return OverflowResult::AlwaysOverflows;
1214   if (Max.ugt(~OtherMax))
1215     return OverflowResult::MayOverflow;
1216   return OverflowResult::NeverOverflows;
1217 }
1218 
1219 ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow(
1220     const ConstantRange &Other) const {
1221   if (isEmptySet() || Other.isEmptySet())
1222     return OverflowResult::MayOverflow;
1223 
1224   APInt Min = getSignedMin(), Max = getSignedMax();
1225   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
1226 
1227   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1228   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
1229 
1230   // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
1231   // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
1232   if (Min.isNonNegative() && OtherMin.isNonNegative() &&
1233       Min.sgt(SignedMax - OtherMin))
1234     return OverflowResult::AlwaysOverflows;
1235   if (Max.isNegative() && OtherMax.isNegative() &&
1236       Max.slt(SignedMin - OtherMax))
1237     return OverflowResult::AlwaysOverflows;
1238 
1239   if (Max.isNonNegative() && OtherMax.isNonNegative() &&
1240       Max.sgt(SignedMax - OtherMax))
1241     return OverflowResult::MayOverflow;
1242   if (Min.isNegative() && OtherMin.isNegative() &&
1243       Min.slt(SignedMin - OtherMin))
1244     return OverflowResult::MayOverflow;
1245 
1246   return OverflowResult::NeverOverflows;
1247 }
1248 
1249 ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow(
1250     const ConstantRange &Other) const {
1251   if (isEmptySet() || Other.isEmptySet())
1252     return OverflowResult::MayOverflow;
1253 
1254   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1255   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1256 
1257   // a u- b overflows iff a u< b.
1258   if (Max.ult(OtherMin))
1259     return OverflowResult::AlwaysOverflows;
1260   if (Min.ult(OtherMax))
1261     return OverflowResult::MayOverflow;
1262   return OverflowResult::NeverOverflows;
1263 }
1264 
1265 ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow(
1266     const ConstantRange &Other) const {
1267   if (isEmptySet() || Other.isEmptySet())
1268     return OverflowResult::MayOverflow;
1269 
1270   APInt Min = getSignedMin(), Max = getSignedMax();
1271   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
1272 
1273   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1274   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
1275 
1276   // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
1277   // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
1278   if (Min.isNonNegative() && OtherMax.isNegative() &&
1279       Min.sgt(SignedMax + OtherMax))
1280     return OverflowResult::AlwaysOverflows;
1281   if (Max.isNegative() && OtherMin.isNonNegative() &&
1282       Max.slt(SignedMin + OtherMin))
1283     return OverflowResult::AlwaysOverflows;
1284 
1285   if (Max.isNonNegative() && OtherMin.isNegative() &&
1286       Max.sgt(SignedMax + OtherMin))
1287     return OverflowResult::MayOverflow;
1288   if (Min.isNegative() && OtherMax.isNonNegative() &&
1289       Min.slt(SignedMin + OtherMax))
1290     return OverflowResult::MayOverflow;
1291 
1292   return OverflowResult::NeverOverflows;
1293 }
1294 
1295 ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow(
1296     const ConstantRange &Other) const {
1297   if (isEmptySet() || Other.isEmptySet())
1298     return OverflowResult::MayOverflow;
1299 
1300   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1301   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1302   bool Overflow;
1303 
1304   (void) Min.umul_ov(OtherMin, Overflow);
1305   if (Overflow)
1306     return OverflowResult::AlwaysOverflows;
1307 
1308   (void) Max.umul_ov(OtherMax, Overflow);
1309   if (Overflow)
1310     return OverflowResult::MayOverflow;
1311 
1312   return OverflowResult::NeverOverflows;
1313 }
1314 
1315 void ConstantRange::print(raw_ostream &OS) const {
1316   if (isFullSet())
1317     OS << "full-set";
1318   else if (isEmptySet())
1319     OS << "empty-set";
1320   else
1321     OS << "[" << Lower << "," << Upper << ")";
1322 }
1323 
1324 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1325 LLVM_DUMP_METHOD void ConstantRange::dump() const {
1326   print(dbgs());
1327 }
1328 #endif
1329 
1330 ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
1331   const unsigned NumRanges = Ranges.getNumOperands() / 2;
1332   assert(NumRanges >= 1 && "Must have at least one range!");
1333   assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
1334 
1335   auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
1336   auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
1337 
1338   ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
1339 
1340   for (unsigned i = 1; i < NumRanges; ++i) {
1341     auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
1342     auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
1343 
1344     // Note: unionWith will potentially create a range that contains values not
1345     // contained in any of the original N ranges.
1346     CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
1347   }
1348 
1349   return CR;
1350 }
1351