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/Intrinsics.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/KnownBits.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <cstdint>
40 
41 using namespace llvm;
42 
43 ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)
44     : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
45       Upper(Lower) {}
46 
47 ConstantRange::ConstantRange(APInt V)
48     : Lower(std::move(V)), Upper(Lower + 1) {}
49 
50 ConstantRange::ConstantRange(APInt L, APInt U)
51     : Lower(std::move(L)), Upper(std::move(U)) {
52   assert(Lower.getBitWidth() == Upper.getBitWidth() &&
53          "ConstantRange with unequal bit widths");
54   assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
55          "Lower == Upper, but they aren't min or max value!");
56 }
57 
58 ConstantRange ConstantRange::fromKnownBits(const KnownBits &Known,
59                                            bool IsSigned) {
60   assert(!Known.hasConflict() && "Expected valid KnownBits");
61 
62   if (Known.isUnknown())
63     return getFull(Known.getBitWidth());
64 
65   // For unsigned ranges, or signed ranges with known sign bit, create a simple
66   // range between the smallest and largest possible value.
67   if (!IsSigned || Known.isNegative() || Known.isNonNegative())
68     return ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1);
69 
70   // If we don't know the sign bit, pick the lower bound as a negative number
71   // and the upper bound as a non-negative one.
72   APInt Lower = Known.getMinValue(), Upper = Known.getMaxValue();
73   Lower.setSignBit();
74   Upper.clearSignBit();
75   return ConstantRange(Lower, Upper + 1);
76 }
77 
78 KnownBits ConstantRange::toKnownBits() const {
79   // TODO: We could return conflicting known bits here, but consumers are
80   // likely not prepared for that.
81   if (isEmptySet())
82     return KnownBits(getBitWidth());
83 
84   // We can only retain the top bits that are the same between min and max.
85   APInt Min = getUnsignedMin();
86   APInt Max = getUnsignedMax();
87   KnownBits Known = KnownBits::makeConstant(Min);
88   if (Optional<unsigned> DifferentBit =
89           APIntOps::GetMostSignificantDifferentBit(Min, Max)) {
90     Known.Zero.clearLowBits(*DifferentBit + 1);
91     Known.One.clearLowBits(*DifferentBit + 1);
92   }
93   return Known;
94 }
95 
96 ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
97                                                    const ConstantRange &CR) {
98   if (CR.isEmptySet())
99     return CR;
100 
101   uint32_t W = CR.getBitWidth();
102   switch (Pred) {
103   default:
104     llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
105   case CmpInst::ICMP_EQ:
106     return CR;
107   case CmpInst::ICMP_NE:
108     if (CR.isSingleElement())
109       return ConstantRange(CR.getUpper(), CR.getLower());
110     return getFull(W);
111   case CmpInst::ICMP_ULT: {
112     APInt UMax(CR.getUnsignedMax());
113     if (UMax.isMinValue())
114       return getEmpty(W);
115     return ConstantRange(APInt::getMinValue(W), std::move(UMax));
116   }
117   case CmpInst::ICMP_SLT: {
118     APInt SMax(CR.getSignedMax());
119     if (SMax.isMinSignedValue())
120       return getEmpty(W);
121     return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));
122   }
123   case CmpInst::ICMP_ULE:
124     return getNonEmpty(APInt::getMinValue(W), CR.getUnsignedMax() + 1);
125   case CmpInst::ICMP_SLE:
126     return getNonEmpty(APInt::getSignedMinValue(W), CR.getSignedMax() + 1);
127   case CmpInst::ICMP_UGT: {
128     APInt UMin(CR.getUnsignedMin());
129     if (UMin.isMaxValue())
130       return getEmpty(W);
131     return ConstantRange(std::move(UMin) + 1, APInt::getZero(W));
132   }
133   case CmpInst::ICMP_SGT: {
134     APInt SMin(CR.getSignedMin());
135     if (SMin.isMaxSignedValue())
136       return getEmpty(W);
137     return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));
138   }
139   case CmpInst::ICMP_UGE:
140     return getNonEmpty(CR.getUnsignedMin(), APInt::getZero(W));
141   case CmpInst::ICMP_SGE:
142     return getNonEmpty(CR.getSignedMin(), APInt::getSignedMinValue(W));
143   }
144 }
145 
146 ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
147                                                       const ConstantRange &CR) {
148   // Follows from De-Morgan's laws:
149   //
150   // ~(~A union ~B) == A intersect B.
151   //
152   return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
153       .inverse();
154 }
155 
156 ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
157                                                  const APInt &C) {
158   // Computes the exact range that is equal to both the constant ranges returned
159   // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
160   // when RHS is a singleton such as an APInt and so the assert is valid.
161   // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
162   // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
163   //
164   assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
165   return makeAllowedICmpRegion(Pred, C);
166 }
167 
168 bool ConstantRange::areInsensitiveToSignednessOfICmpPredicate(
169     const ConstantRange &CR1, const ConstantRange &CR2) {
170   if (CR1.isEmptySet() || CR2.isEmptySet())
171     return true;
172 
173   return (CR1.isAllNonNegative() && CR2.isAllNonNegative()) ||
174          (CR1.isAllNegative() && CR2.isAllNegative());
175 }
176 
177 bool ConstantRange::areInsensitiveToSignednessOfInvertedICmpPredicate(
178     const ConstantRange &CR1, const ConstantRange &CR2) {
179   if (CR1.isEmptySet() || CR2.isEmptySet())
180     return true;
181 
182   return (CR1.isAllNonNegative() && CR2.isAllNegative()) ||
183          (CR1.isAllNegative() && CR2.isAllNonNegative());
184 }
185 
186 CmpInst::Predicate ConstantRange::getEquivalentPredWithFlippedSignedness(
187     CmpInst::Predicate Pred, const ConstantRange &CR1,
188     const ConstantRange &CR2) {
189   assert(CmpInst::isIntPredicate(Pred) && CmpInst::isRelational(Pred) &&
190          "Only for relational integer predicates!");
191 
192   CmpInst::Predicate FlippedSignednessPred =
193       CmpInst::getFlippedSignednessPredicate(Pred);
194 
195   if (areInsensitiveToSignednessOfICmpPredicate(CR1, CR2))
196     return FlippedSignednessPred;
197 
198   if (areInsensitiveToSignednessOfInvertedICmpPredicate(CR1, CR2))
199     return CmpInst::getInversePredicate(FlippedSignednessPred);
200 
201   return CmpInst::Predicate::BAD_ICMP_PREDICATE;
202 }
203 
204 void ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
205                                       APInt &RHS, APInt &Offset) const {
206   Offset = APInt(getBitWidth(), 0);
207   if (isFullSet() || isEmptySet()) {
208     Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
209     RHS = APInt(getBitWidth(), 0);
210   } else if (auto *OnlyElt = getSingleElement()) {
211     Pred = CmpInst::ICMP_EQ;
212     RHS = *OnlyElt;
213   } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
214     Pred = CmpInst::ICMP_NE;
215     RHS = *OnlyMissingElt;
216   } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
217     Pred =
218         getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
219     RHS = getUpper();
220   } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
221     Pred =
222         getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
223     RHS = getLower();
224   } else {
225     Pred = CmpInst::ICMP_ULT;
226     RHS = getUpper() - getLower();
227     Offset = -getLower();
228   }
229 
230   assert(ConstantRange::makeExactICmpRegion(Pred, RHS) == add(Offset) &&
231          "Bad result!");
232 }
233 
234 bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
235                                       APInt &RHS) const {
236   APInt Offset;
237   getEquivalentICmp(Pred, RHS, Offset);
238   return Offset.isZero();
239 }
240 
241 bool ConstantRange::icmp(CmpInst::Predicate Pred,
242                          const ConstantRange &Other) const {
243   return makeSatisfyingICmpRegion(Pred, Other).contains(*this);
244 }
245 
246 /// Exact mul nuw region for single element RHS.
247 static ConstantRange makeExactMulNUWRegion(const APInt &V) {
248   unsigned BitWidth = V.getBitWidth();
249   if (V == 0)
250     return ConstantRange::getFull(V.getBitWidth());
251 
252   return ConstantRange::getNonEmpty(
253       APIntOps::RoundingUDiv(APInt::getMinValue(BitWidth), V,
254                              APInt::Rounding::UP),
255       APIntOps::RoundingUDiv(APInt::getMaxValue(BitWidth), V,
256                              APInt::Rounding::DOWN) + 1);
257 }
258 
259 /// Exact mul nsw region for single element RHS.
260 static ConstantRange makeExactMulNSWRegion(const APInt &V) {
261   // Handle special case for 0, -1 and 1. See the last for reason why we
262   // specialize -1 and 1.
263   unsigned BitWidth = V.getBitWidth();
264   if (V == 0 || V.isOne())
265     return ConstantRange::getFull(BitWidth);
266 
267   APInt MinValue = APInt::getSignedMinValue(BitWidth);
268   APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
269   // e.g. Returning [-127, 127], represented as [-127, -128).
270   if (V.isAllOnes())
271     return ConstantRange(-MaxValue, MinValue);
272 
273   APInt Lower, Upper;
274   if (V.isNegative()) {
275     Lower = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::UP);
276     Upper = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::DOWN);
277   } else {
278     Lower = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::UP);
279     Upper = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::DOWN);
280   }
281   // ConstantRange ctor take a half inclusive interval [Lower, Upper + 1).
282   // Upper + 1 is guaranteed not to overflow, because |divisor| > 1. 0, -1,
283   // and 1 are already handled as special cases.
284   return ConstantRange(Lower, Upper + 1);
285 }
286 
287 ConstantRange
288 ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
289                                           const ConstantRange &Other,
290                                           unsigned NoWrapKind) {
291   using OBO = OverflowingBinaryOperator;
292 
293   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
294 
295   assert((NoWrapKind == OBO::NoSignedWrap ||
296           NoWrapKind == OBO::NoUnsignedWrap) &&
297          "NoWrapKind invalid!");
298 
299   bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;
300   unsigned BitWidth = Other.getBitWidth();
301 
302   switch (BinOp) {
303   default:
304     llvm_unreachable("Unsupported binary op");
305 
306   case Instruction::Add: {
307     if (Unsigned)
308       return getNonEmpty(APInt::getZero(BitWidth), -Other.getUnsignedMax());
309 
310     APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
311     APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
312     return getNonEmpty(
313         SMin.isNegative() ? SignedMinVal - SMin : SignedMinVal,
314         SMax.isStrictlyPositive() ? SignedMinVal - SMax : SignedMinVal);
315   }
316 
317   case Instruction::Sub: {
318     if (Unsigned)
319       return getNonEmpty(Other.getUnsignedMax(), APInt::getMinValue(BitWidth));
320 
321     APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
322     APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
323     return getNonEmpty(
324         SMax.isStrictlyPositive() ? SignedMinVal + SMax : SignedMinVal,
325         SMin.isNegative() ? SignedMinVal + SMin : SignedMinVal);
326   }
327 
328   case Instruction::Mul:
329     if (Unsigned)
330       return makeExactMulNUWRegion(Other.getUnsignedMax());
331 
332     return makeExactMulNSWRegion(Other.getSignedMin())
333         .intersectWith(makeExactMulNSWRegion(Other.getSignedMax()));
334 
335   case Instruction::Shl: {
336     // For given range of shift amounts, if we ignore all illegal shift amounts
337     // (that always produce poison), what shift amount range is left?
338     ConstantRange ShAmt = Other.intersectWith(
339         ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, (BitWidth - 1) + 1)));
340     if (ShAmt.isEmptySet()) {
341       // If the entire range of shift amounts is already poison-producing,
342       // then we can freely add more poison-producing flags ontop of that.
343       return getFull(BitWidth);
344     }
345     // There are some legal shift amounts, we can compute conservatively-correct
346     // range of no-wrap inputs. Note that by now we have clamped the ShAmtUMax
347     // to be at most bitwidth-1, which results in most conservative range.
348     APInt ShAmtUMax = ShAmt.getUnsignedMax();
349     if (Unsigned)
350       return getNonEmpty(APInt::getZero(BitWidth),
351                          APInt::getMaxValue(BitWidth).lshr(ShAmtUMax) + 1);
352     return getNonEmpty(APInt::getSignedMinValue(BitWidth).ashr(ShAmtUMax),
353                        APInt::getSignedMaxValue(BitWidth).ashr(ShAmtUMax) + 1);
354   }
355   }
356 }
357 
358 ConstantRange ConstantRange::makeExactNoWrapRegion(Instruction::BinaryOps BinOp,
359                                                    const APInt &Other,
360                                                    unsigned NoWrapKind) {
361   // makeGuaranteedNoWrapRegion() is exact for single-element ranges, as
362   // "for all" and "for any" coincide in this case.
363   return makeGuaranteedNoWrapRegion(BinOp, ConstantRange(Other), NoWrapKind);
364 }
365 
366 bool ConstantRange::isFullSet() const {
367   return Lower == Upper && Lower.isMaxValue();
368 }
369 
370 bool ConstantRange::isEmptySet() const {
371   return Lower == Upper && Lower.isMinValue();
372 }
373 
374 bool ConstantRange::isWrappedSet() const {
375   return Lower.ugt(Upper) && !Upper.isZero();
376 }
377 
378 bool ConstantRange::isUpperWrapped() const {
379   return Lower.ugt(Upper);
380 }
381 
382 bool ConstantRange::isSignWrappedSet() const {
383   return Lower.sgt(Upper) && !Upper.isMinSignedValue();
384 }
385 
386 bool ConstantRange::isUpperSignWrapped() const {
387   return Lower.sgt(Upper);
388 }
389 
390 bool
391 ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
392   assert(getBitWidth() == Other.getBitWidth());
393   if (isFullSet())
394     return false;
395   if (Other.isFullSet())
396     return true;
397   return (Upper - Lower).ult(Other.Upper - Other.Lower);
398 }
399 
400 bool
401 ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
402   // If this a full set, we need special handling to avoid needing an extra bit
403   // to represent the size.
404   if (isFullSet())
405     return MaxSize == 0 || APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
406 
407   return (Upper - Lower).ugt(MaxSize);
408 }
409 
410 bool ConstantRange::isAllNegative() const {
411   // Empty set is all negative, full set is not.
412   if (isEmptySet())
413     return true;
414   if (isFullSet())
415     return false;
416 
417   return !isUpperSignWrapped() && !Upper.isStrictlyPositive();
418 }
419 
420 bool ConstantRange::isAllNonNegative() const {
421   // Empty and full set are automatically treated correctly.
422   return !isSignWrappedSet() && Lower.isNonNegative();
423 }
424 
425 APInt ConstantRange::getUnsignedMax() const {
426   if (isFullSet() || isUpperWrapped())
427     return APInt::getMaxValue(getBitWidth());
428   return getUpper() - 1;
429 }
430 
431 APInt ConstantRange::getUnsignedMin() const {
432   if (isFullSet() || isWrappedSet())
433     return APInt::getMinValue(getBitWidth());
434   return getLower();
435 }
436 
437 APInt ConstantRange::getSignedMax() const {
438   if (isFullSet() || isUpperSignWrapped())
439     return APInt::getSignedMaxValue(getBitWidth());
440   return getUpper() - 1;
441 }
442 
443 APInt ConstantRange::getSignedMin() const {
444   if (isFullSet() || isSignWrappedSet())
445     return APInt::getSignedMinValue(getBitWidth());
446   return getLower();
447 }
448 
449 bool ConstantRange::contains(const APInt &V) const {
450   if (Lower == Upper)
451     return isFullSet();
452 
453   if (!isUpperWrapped())
454     return Lower.ule(V) && V.ult(Upper);
455   return Lower.ule(V) || V.ult(Upper);
456 }
457 
458 bool ConstantRange::contains(const ConstantRange &Other) const {
459   if (isFullSet() || Other.isEmptySet()) return true;
460   if (isEmptySet() || Other.isFullSet()) return false;
461 
462   if (!isUpperWrapped()) {
463     if (Other.isUpperWrapped())
464       return false;
465 
466     return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
467   }
468 
469   if (!Other.isUpperWrapped())
470     return Other.getUpper().ule(Upper) ||
471            Lower.ule(Other.getLower());
472 
473   return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
474 }
475 
476 unsigned ConstantRange::getActiveBits() const {
477   if (isEmptySet())
478     return 0;
479 
480   return getUnsignedMax().getActiveBits();
481 }
482 
483 unsigned ConstantRange::getMinSignedBits() const {
484   if (isEmptySet())
485     return 0;
486 
487   return std::max(getSignedMin().getMinSignedBits(),
488                   getSignedMax().getMinSignedBits());
489 }
490 
491 ConstantRange ConstantRange::subtract(const APInt &Val) const {
492   assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
493   // If the set is empty or full, don't modify the endpoints.
494   if (Lower == Upper)
495     return *this;
496   return ConstantRange(Lower - Val, Upper - Val);
497 }
498 
499 ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
500   return intersectWith(CR.inverse());
501 }
502 
503 static ConstantRange getPreferredRange(
504     const ConstantRange &CR1, const ConstantRange &CR2,
505     ConstantRange::PreferredRangeType Type) {
506   if (Type == ConstantRange::Unsigned) {
507     if (!CR1.isWrappedSet() && CR2.isWrappedSet())
508       return CR1;
509     if (CR1.isWrappedSet() && !CR2.isWrappedSet())
510       return CR2;
511   } else if (Type == ConstantRange::Signed) {
512     if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet())
513       return CR1;
514     if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet())
515       return CR2;
516   }
517 
518   if (CR1.isSizeStrictlySmallerThan(CR2))
519     return CR1;
520   return CR2;
521 }
522 
523 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,
524                                            PreferredRangeType Type) const {
525   assert(getBitWidth() == CR.getBitWidth() &&
526          "ConstantRange types don't agree!");
527 
528   // Handle common cases.
529   if (   isEmptySet() || CR.isFullSet()) return *this;
530   if (CR.isEmptySet() ||    isFullSet()) return CR;
531 
532   if (!isUpperWrapped() && CR.isUpperWrapped())
533     return CR.intersectWith(*this, Type);
534 
535   if (!isUpperWrapped() && !CR.isUpperWrapped()) {
536     if (Lower.ult(CR.Lower)) {
537       // L---U       : this
538       //       L---U : CR
539       if (Upper.ule(CR.Lower))
540         return getEmpty();
541 
542       // L---U       : this
543       //   L---U     : CR
544       if (Upper.ult(CR.Upper))
545         return ConstantRange(CR.Lower, Upper);
546 
547       // L-------U   : this
548       //   L---U     : CR
549       return CR;
550     }
551     //   L---U     : this
552     // L-------U   : CR
553     if (Upper.ult(CR.Upper))
554       return *this;
555 
556     //   L-----U   : this
557     // L-----U     : CR
558     if (Lower.ult(CR.Upper))
559       return ConstantRange(Lower, CR.Upper);
560 
561     //       L---U : this
562     // L---U       : CR
563     return getEmpty();
564   }
565 
566   if (isUpperWrapped() && !CR.isUpperWrapped()) {
567     if (CR.Lower.ult(Upper)) {
568       // ------U   L--- : this
569       //  L--U          : CR
570       if (CR.Upper.ult(Upper))
571         return CR;
572 
573       // ------U   L--- : this
574       //  L------U      : CR
575       if (CR.Upper.ule(Lower))
576         return ConstantRange(CR.Lower, Upper);
577 
578       // ------U   L--- : this
579       //  L----------U  : CR
580       return getPreferredRange(*this, CR, Type);
581     }
582     if (CR.Lower.ult(Lower)) {
583       // --U      L---- : this
584       //     L--U       : CR
585       if (CR.Upper.ule(Lower))
586         return getEmpty();
587 
588       // --U      L---- : this
589       //     L------U   : CR
590       return ConstantRange(Lower, CR.Upper);
591     }
592 
593     // --U  L------ : this
594     //        L--U  : CR
595     return CR;
596   }
597 
598   if (CR.Upper.ult(Upper)) {
599     // ------U L-- : this
600     // --U L------ : CR
601     if (CR.Lower.ult(Upper))
602       return getPreferredRange(*this, CR, Type);
603 
604     // ----U   L-- : this
605     // --U   L---- : CR
606     if (CR.Lower.ult(Lower))
607       return ConstantRange(Lower, CR.Upper);
608 
609     // ----U L---- : this
610     // --U     L-- : CR
611     return CR;
612   }
613   if (CR.Upper.ule(Lower)) {
614     // --U     L-- : this
615     // ----U L---- : CR
616     if (CR.Lower.ult(Lower))
617       return *this;
618 
619     // --U   L---- : this
620     // ----U   L-- : CR
621     return ConstantRange(CR.Lower, Upper);
622   }
623 
624   // --U L------ : this
625   // ------U L-- : CR
626   return getPreferredRange(*this, CR, Type);
627 }
628 
629 ConstantRange ConstantRange::unionWith(const ConstantRange &CR,
630                                        PreferredRangeType Type) const {
631   assert(getBitWidth() == CR.getBitWidth() &&
632          "ConstantRange types don't agree!");
633 
634   if (   isFullSet() || CR.isEmptySet()) return *this;
635   if (CR.isFullSet() ||    isEmptySet()) return CR;
636 
637   if (!isUpperWrapped() && CR.isUpperWrapped())
638     return CR.unionWith(*this, Type);
639 
640   if (!isUpperWrapped() && !CR.isUpperWrapped()) {
641     //        L---U  and  L---U        : this
642     //  L---U                   L---U  : CR
643     // result in one of
644     //  L---------U
645     // -----U L-----
646     if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower))
647       return getPreferredRange(
648           ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
649 
650     APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
651     APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
652 
653     if (L.isZero() && U.isZero())
654       return getFull();
655 
656     return ConstantRange(std::move(L), std::move(U));
657   }
658 
659   if (!CR.isUpperWrapped()) {
660     // ------U   L-----  and  ------U   L----- : this
661     //   L--U                            L--U  : CR
662     if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
663       return *this;
664 
665     // ------U   L----- : this
666     //    L---------U   : CR
667     if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
668       return getFull();
669 
670     // ----U       L---- : this
671     //       L---U       : CR
672     // results in one of
673     // ----------U L----
674     // ----U L----------
675     if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower))
676       return getPreferredRange(
677           ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
678 
679     // ----U     L----- : this
680     //        L----U    : CR
681     if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper))
682       return ConstantRange(CR.Lower, Upper);
683 
684     // ------U    L---- : this
685     //    L-----U       : CR
686     assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) &&
687            "ConstantRange::unionWith missed a case with one range wrapped");
688     return ConstantRange(Lower, CR.Upper);
689   }
690 
691   // ------U    L----  and  ------U    L---- : this
692   // -U  L-----------  and  ------------U  L : CR
693   if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
694     return getFull();
695 
696   APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
697   APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
698 
699   return ConstantRange(std::move(L), std::move(U));
700 }
701 
702 Optional<ConstantRange>
703 ConstantRange::exactIntersectWith(const ConstantRange &CR) const {
704   // TODO: This can be implemented more efficiently.
705   ConstantRange Result = intersectWith(CR);
706   if (Result == inverse().unionWith(CR.inverse()).inverse())
707     return Result;
708   return None;
709 }
710 
711 Optional<ConstantRange>
712 ConstantRange::exactUnionWith(const ConstantRange &CR) const {
713   // TODO: This can be implemented more efficiently.
714   ConstantRange Result = unionWith(CR);
715   if (Result == inverse().intersectWith(CR.inverse()).inverse())
716     return Result;
717   return None;
718 }
719 
720 ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
721                                     uint32_t ResultBitWidth) const {
722   switch (CastOp) {
723   default:
724     llvm_unreachable("unsupported cast type");
725   case Instruction::Trunc:
726     return truncate(ResultBitWidth);
727   case Instruction::SExt:
728     return signExtend(ResultBitWidth);
729   case Instruction::ZExt:
730     return zeroExtend(ResultBitWidth);
731   case Instruction::BitCast:
732     return *this;
733   case Instruction::FPToUI:
734   case Instruction::FPToSI:
735     if (getBitWidth() == ResultBitWidth)
736       return *this;
737     else
738       return getFull(ResultBitWidth);
739   case Instruction::UIToFP: {
740     // TODO: use input range if available
741     auto BW = getBitWidth();
742     APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
743     APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
744     return ConstantRange(std::move(Min), std::move(Max));
745   }
746   case Instruction::SIToFP: {
747     // TODO: use input range if available
748     auto BW = getBitWidth();
749     APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
750     APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
751     return ConstantRange(std::move(SMin), std::move(SMax));
752   }
753   case Instruction::FPTrunc:
754   case Instruction::FPExt:
755   case Instruction::IntToPtr:
756   case Instruction::PtrToInt:
757   case Instruction::AddrSpaceCast:
758     // Conservatively return getFull set.
759     return getFull(ResultBitWidth);
760   };
761 }
762 
763 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
764   if (isEmptySet()) return getEmpty(DstTySize);
765 
766   unsigned SrcTySize = getBitWidth();
767   assert(SrcTySize < DstTySize && "Not a value extension");
768   if (isFullSet() || isUpperWrapped()) {
769     // Change into [0, 1 << src bit width)
770     APInt LowerExt(DstTySize, 0);
771     if (!Upper) // special case: [X, 0) -- not really wrapping around
772       LowerExt = Lower.zext(DstTySize);
773     return ConstantRange(std::move(LowerExt),
774                          APInt::getOneBitSet(DstTySize, SrcTySize));
775   }
776 
777   return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
778 }
779 
780 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
781   if (isEmptySet()) return getEmpty(DstTySize);
782 
783   unsigned SrcTySize = getBitWidth();
784   assert(SrcTySize < DstTySize && "Not a value extension");
785 
786   // special case: [X, INT_MIN) -- not really wrapping around
787   if (Upper.isMinSignedValue())
788     return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
789 
790   if (isFullSet() || isSignWrappedSet()) {
791     return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
792                          APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
793   }
794 
795   return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
796 }
797 
798 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
799   assert(getBitWidth() > DstTySize && "Not a value truncation");
800   if (isEmptySet())
801     return getEmpty(DstTySize);
802   if (isFullSet())
803     return getFull(DstTySize);
804 
805   APInt LowerDiv(Lower), UpperDiv(Upper);
806   ConstantRange Union(DstTySize, /*isFullSet=*/false);
807 
808   // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
809   // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
810   // then we do the union with [MaxValue, Upper)
811   if (isUpperWrapped()) {
812     // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
813     // truncated range.
814     if (Upper.getActiveBits() > DstTySize ||
815         Upper.countTrailingOnes() == DstTySize)
816       return getFull(DstTySize);
817 
818     Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
819     UpperDiv.setAllBits();
820 
821     // Union covers the MaxValue case, so return if the remaining range is just
822     // MaxValue(DstTy).
823     if (LowerDiv == UpperDiv)
824       return Union;
825   }
826 
827   // Chop off the most significant bits that are past the destination bitwidth.
828   if (LowerDiv.getActiveBits() > DstTySize) {
829     // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
830     APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
831     LowerDiv -= Adjust;
832     UpperDiv -= Adjust;
833   }
834 
835   unsigned UpperDivWidth = UpperDiv.getActiveBits();
836   if (UpperDivWidth <= DstTySize)
837     return ConstantRange(LowerDiv.trunc(DstTySize),
838                          UpperDiv.trunc(DstTySize)).unionWith(Union);
839 
840   // The truncated value wraps around. Check if we can do better than fullset.
841   if (UpperDivWidth == DstTySize + 1) {
842     // Clear the MSB so that UpperDiv wraps around.
843     UpperDiv.clearBit(DstTySize);
844     if (UpperDiv.ult(LowerDiv))
845       return ConstantRange(LowerDiv.trunc(DstTySize),
846                            UpperDiv.trunc(DstTySize)).unionWith(Union);
847   }
848 
849   return getFull(DstTySize);
850 }
851 
852 ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
853   unsigned SrcTySize = getBitWidth();
854   if (SrcTySize > DstTySize)
855     return truncate(DstTySize);
856   if (SrcTySize < DstTySize)
857     return zeroExtend(DstTySize);
858   return *this;
859 }
860 
861 ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
862   unsigned SrcTySize = getBitWidth();
863   if (SrcTySize > DstTySize)
864     return truncate(DstTySize);
865   if (SrcTySize < DstTySize)
866     return signExtend(DstTySize);
867   return *this;
868 }
869 
870 ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
871                                       const ConstantRange &Other) const {
872   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
873 
874   switch (BinOp) {
875   case Instruction::Add:
876     return add(Other);
877   case Instruction::Sub:
878     return sub(Other);
879   case Instruction::Mul:
880     return multiply(Other);
881   case Instruction::UDiv:
882     return udiv(Other);
883   case Instruction::SDiv:
884     return sdiv(Other);
885   case Instruction::URem:
886     return urem(Other);
887   case Instruction::SRem:
888     return srem(Other);
889   case Instruction::Shl:
890     return shl(Other);
891   case Instruction::LShr:
892     return lshr(Other);
893   case Instruction::AShr:
894     return ashr(Other);
895   case Instruction::And:
896     return binaryAnd(Other);
897   case Instruction::Or:
898     return binaryOr(Other);
899   case Instruction::Xor:
900     return binaryXor(Other);
901   // Note: floating point operations applied to abstract ranges are just
902   // ideal integer operations with a lossy representation
903   case Instruction::FAdd:
904     return add(Other);
905   case Instruction::FSub:
906     return sub(Other);
907   case Instruction::FMul:
908     return multiply(Other);
909   default:
910     // Conservatively return getFull set.
911     return getFull();
912   }
913 }
914 
915 ConstantRange ConstantRange::overflowingBinaryOp(Instruction::BinaryOps BinOp,
916                                                  const ConstantRange &Other,
917                                                  unsigned NoWrapKind) const {
918   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
919 
920   switch (BinOp) {
921   case Instruction::Add:
922     return addWithNoWrap(Other, NoWrapKind);
923   case Instruction::Sub:
924     return subWithNoWrap(Other, NoWrapKind);
925   default:
926     // Don't know about this Overflowing Binary Operation.
927     // Conservatively fallback to plain binop handling.
928     return binaryOp(BinOp, Other);
929   }
930 }
931 
932 bool ConstantRange::isIntrinsicSupported(Intrinsic::ID IntrinsicID) {
933   switch (IntrinsicID) {
934   case Intrinsic::uadd_sat:
935   case Intrinsic::usub_sat:
936   case Intrinsic::sadd_sat:
937   case Intrinsic::ssub_sat:
938   case Intrinsic::umin:
939   case Intrinsic::umax:
940   case Intrinsic::smin:
941   case Intrinsic::smax:
942   case Intrinsic::abs:
943     return true;
944   default:
945     return false;
946   }
947 }
948 
949 ConstantRange ConstantRange::intrinsic(Intrinsic::ID IntrinsicID,
950                                        ArrayRef<ConstantRange> Ops) {
951   switch (IntrinsicID) {
952   case Intrinsic::uadd_sat:
953     return Ops[0].uadd_sat(Ops[1]);
954   case Intrinsic::usub_sat:
955     return Ops[0].usub_sat(Ops[1]);
956   case Intrinsic::sadd_sat:
957     return Ops[0].sadd_sat(Ops[1]);
958   case Intrinsic::ssub_sat:
959     return Ops[0].ssub_sat(Ops[1]);
960   case Intrinsic::umin:
961     return Ops[0].umin(Ops[1]);
962   case Intrinsic::umax:
963     return Ops[0].umax(Ops[1]);
964   case Intrinsic::smin:
965     return Ops[0].smin(Ops[1]);
966   case Intrinsic::smax:
967     return Ops[0].smax(Ops[1]);
968   case Intrinsic::abs: {
969     const APInt *IntMinIsPoison = Ops[1].getSingleElement();
970     assert(IntMinIsPoison && "Must be known (immarg)");
971     assert(IntMinIsPoison->getBitWidth() == 1 && "Must be boolean");
972     return Ops[0].abs(IntMinIsPoison->getBoolValue());
973   }
974   default:
975     assert(!isIntrinsicSupported(IntrinsicID) && "Shouldn't be supported");
976     llvm_unreachable("Unsupported intrinsic");
977   }
978 }
979 
980 ConstantRange
981 ConstantRange::add(const ConstantRange &Other) const {
982   if (isEmptySet() || Other.isEmptySet())
983     return getEmpty();
984   if (isFullSet() || Other.isFullSet())
985     return getFull();
986 
987   APInt NewLower = getLower() + Other.getLower();
988   APInt NewUpper = getUpper() + Other.getUpper() - 1;
989   if (NewLower == NewUpper)
990     return getFull();
991 
992   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
993   if (X.isSizeStrictlySmallerThan(*this) ||
994       X.isSizeStrictlySmallerThan(Other))
995     // We've wrapped, therefore, full set.
996     return getFull();
997   return X;
998 }
999 
1000 ConstantRange ConstantRange::addWithNoWrap(const ConstantRange &Other,
1001                                            unsigned NoWrapKind,
1002                                            PreferredRangeType RangeType) const {
1003   // Calculate the range for "X + Y" which is guaranteed not to wrap(overflow).
1004   // (X is from this, and Y is from Other)
1005   if (isEmptySet() || Other.isEmptySet())
1006     return getEmpty();
1007   if (isFullSet() && Other.isFullSet())
1008     return getFull();
1009 
1010   using OBO = OverflowingBinaryOperator;
1011   ConstantRange Result = add(Other);
1012 
1013   // If an overflow happens for every value pair in these two constant ranges,
1014   // we must return Empty set. In this case, we get that for free, because we
1015   // get lucky that intersection of add() with uadd_sat()/sadd_sat() results
1016   // in an empty set.
1017 
1018   if (NoWrapKind & OBO::NoSignedWrap)
1019     Result = Result.intersectWith(sadd_sat(Other), RangeType);
1020 
1021   if (NoWrapKind & OBO::NoUnsignedWrap)
1022     Result = Result.intersectWith(uadd_sat(Other), RangeType);
1023 
1024   return Result;
1025 }
1026 
1027 ConstantRange
1028 ConstantRange::sub(const ConstantRange &Other) const {
1029   if (isEmptySet() || Other.isEmptySet())
1030     return getEmpty();
1031   if (isFullSet() || Other.isFullSet())
1032     return getFull();
1033 
1034   APInt NewLower = getLower() - Other.getUpper() + 1;
1035   APInt NewUpper = getUpper() - Other.getLower();
1036   if (NewLower == NewUpper)
1037     return getFull();
1038 
1039   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
1040   if (X.isSizeStrictlySmallerThan(*this) ||
1041       X.isSizeStrictlySmallerThan(Other))
1042     // We've wrapped, therefore, full set.
1043     return getFull();
1044   return X;
1045 }
1046 
1047 ConstantRange ConstantRange::subWithNoWrap(const ConstantRange &Other,
1048                                            unsigned NoWrapKind,
1049                                            PreferredRangeType RangeType) const {
1050   // Calculate the range for "X - Y" which is guaranteed not to wrap(overflow).
1051   // (X is from this, and Y is from Other)
1052   if (isEmptySet() || Other.isEmptySet())
1053     return getEmpty();
1054   if (isFullSet() && Other.isFullSet())
1055     return getFull();
1056 
1057   using OBO = OverflowingBinaryOperator;
1058   ConstantRange Result = sub(Other);
1059 
1060   // If an overflow happens for every value pair in these two constant ranges,
1061   // we must return Empty set. In signed case, we get that for free, because we
1062   // get lucky that intersection of sub() with ssub_sat() results in an
1063   // empty set. But for unsigned we must perform the overflow check manually.
1064 
1065   if (NoWrapKind & OBO::NoSignedWrap)
1066     Result = Result.intersectWith(ssub_sat(Other), RangeType);
1067 
1068   if (NoWrapKind & OBO::NoUnsignedWrap) {
1069     if (getUnsignedMax().ult(Other.getUnsignedMin()))
1070       return getEmpty(); // Always overflows.
1071     Result = Result.intersectWith(usub_sat(Other), RangeType);
1072   }
1073 
1074   return Result;
1075 }
1076 
1077 ConstantRange
1078 ConstantRange::multiply(const ConstantRange &Other) const {
1079   // TODO: If either operand is a single element and the multiply is known to
1080   // be non-wrapping, round the result min and max value to the appropriate
1081   // multiple of that element. If wrapping is possible, at least adjust the
1082   // range according to the greatest power-of-two factor of the single element.
1083 
1084   if (isEmptySet() || Other.isEmptySet())
1085     return getEmpty();
1086 
1087   // Multiplication is signedness-independent. However different ranges can be
1088   // obtained depending on how the input ranges are treated. These different
1089   // ranges are all conservatively correct, but one might be better than the
1090   // other. We calculate two ranges; one treating the inputs as unsigned
1091   // and the other signed, then return the smallest of these ranges.
1092 
1093   // Unsigned range first.
1094   APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
1095   APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
1096   APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
1097   APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
1098 
1099   ConstantRange Result_zext = ConstantRange(this_min * Other_min,
1100                                             this_max * Other_max + 1);
1101   ConstantRange UR = Result_zext.truncate(getBitWidth());
1102 
1103   // If the unsigned range doesn't wrap, and isn't negative then it's a range
1104   // from one positive number to another which is as good as we can generate.
1105   // In this case, skip the extra work of generating signed ranges which aren't
1106   // going to be better than this range.
1107   if (!UR.isUpperWrapped() &&
1108       (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
1109     return UR;
1110 
1111   // Now the signed range. Because we could be dealing with negative numbers
1112   // here, the lower bound is the smallest of the cartesian product of the
1113   // lower and upper ranges; for example:
1114   //   [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
1115   // Similarly for the upper bound, swapping min for max.
1116 
1117   this_min = getSignedMin().sext(getBitWidth() * 2);
1118   this_max = getSignedMax().sext(getBitWidth() * 2);
1119   Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
1120   Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
1121 
1122   auto L = {this_min * Other_min, this_min * Other_max,
1123             this_max * Other_min, this_max * Other_max};
1124   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1125   ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
1126   ConstantRange SR = Result_sext.truncate(getBitWidth());
1127 
1128   return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
1129 }
1130 
1131 ConstantRange ConstantRange::smul_fast(const ConstantRange &Other) const {
1132   if (isEmptySet() || Other.isEmptySet())
1133     return getEmpty();
1134 
1135   APInt Min = getSignedMin();
1136   APInt Max = getSignedMax();
1137   APInt OtherMin = Other.getSignedMin();
1138   APInt OtherMax = Other.getSignedMax();
1139 
1140   bool O1, O2, O3, O4;
1141   auto Muls = {Min.smul_ov(OtherMin, O1), Min.smul_ov(OtherMax, O2),
1142                Max.smul_ov(OtherMin, O3), Max.smul_ov(OtherMax, O4)};
1143   if (O1 || O2 || O3 || O4)
1144     return getFull();
1145 
1146   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1147   return getNonEmpty(std::min(Muls, Compare), std::max(Muls, Compare) + 1);
1148 }
1149 
1150 ConstantRange
1151 ConstantRange::smax(const ConstantRange &Other) const {
1152   // X smax Y is: range(smax(X_smin, Y_smin),
1153   //                    smax(X_smax, Y_smax))
1154   if (isEmptySet() || Other.isEmptySet())
1155     return getEmpty();
1156   APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
1157   APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
1158   ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1159   if (isSignWrappedSet() || Other.isSignWrappedSet())
1160     return Res.intersectWith(unionWith(Other, Signed), Signed);
1161   return Res;
1162 }
1163 
1164 ConstantRange
1165 ConstantRange::umax(const ConstantRange &Other) const {
1166   // X umax Y is: range(umax(X_umin, Y_umin),
1167   //                    umax(X_umax, Y_umax))
1168   if (isEmptySet() || Other.isEmptySet())
1169     return getEmpty();
1170   APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
1171   APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
1172   ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1173   if (isWrappedSet() || Other.isWrappedSet())
1174     return Res.intersectWith(unionWith(Other, Unsigned), Unsigned);
1175   return Res;
1176 }
1177 
1178 ConstantRange
1179 ConstantRange::smin(const ConstantRange &Other) const {
1180   // X smin Y is: range(smin(X_smin, Y_smin),
1181   //                    smin(X_smax, Y_smax))
1182   if (isEmptySet() || Other.isEmptySet())
1183     return getEmpty();
1184   APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
1185   APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
1186   ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1187   if (isSignWrappedSet() || Other.isSignWrappedSet())
1188     return Res.intersectWith(unionWith(Other, Signed), Signed);
1189   return Res;
1190 }
1191 
1192 ConstantRange
1193 ConstantRange::umin(const ConstantRange &Other) const {
1194   // X umin Y is: range(umin(X_umin, Y_umin),
1195   //                    umin(X_umax, Y_umax))
1196   if (isEmptySet() || Other.isEmptySet())
1197     return getEmpty();
1198   APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
1199   APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
1200   ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1201   if (isWrappedSet() || Other.isWrappedSet())
1202     return Res.intersectWith(unionWith(Other, Unsigned), Unsigned);
1203   return Res;
1204 }
1205 
1206 ConstantRange
1207 ConstantRange::udiv(const ConstantRange &RHS) const {
1208   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
1209     return getEmpty();
1210 
1211   APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
1212 
1213   APInt RHS_umin = RHS.getUnsignedMin();
1214   if (RHS_umin.isZero()) {
1215     // We want the lowest value in RHS excluding zero. Usually that would be 1
1216     // except for a range in the form of [X, 1) in which case it would be X.
1217     if (RHS.getUpper() == 1)
1218       RHS_umin = RHS.getLower();
1219     else
1220       RHS_umin = 1;
1221   }
1222 
1223   APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
1224   return getNonEmpty(std::move(Lower), std::move(Upper));
1225 }
1226 
1227 ConstantRange ConstantRange::sdiv(const ConstantRange &RHS) const {
1228   // We split up the LHS and RHS into positive and negative components
1229   // and then also compute the positive and negative components of the result
1230   // separately by combining division results with the appropriate signs.
1231   APInt Zero = APInt::getZero(getBitWidth());
1232   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1233   ConstantRange PosFilter(APInt(getBitWidth(), 1), SignedMin);
1234   ConstantRange NegFilter(SignedMin, Zero);
1235   ConstantRange PosL = intersectWith(PosFilter);
1236   ConstantRange NegL = intersectWith(NegFilter);
1237   ConstantRange PosR = RHS.intersectWith(PosFilter);
1238   ConstantRange NegR = RHS.intersectWith(NegFilter);
1239 
1240   ConstantRange PosRes = getEmpty();
1241   if (!PosL.isEmptySet() && !PosR.isEmptySet())
1242     // pos / pos = pos.
1243     PosRes = ConstantRange(PosL.Lower.sdiv(PosR.Upper - 1),
1244                            (PosL.Upper - 1).sdiv(PosR.Lower) + 1);
1245 
1246   if (!NegL.isEmptySet() && !NegR.isEmptySet()) {
1247     // neg / neg = pos.
1248     //
1249     // We need to deal with one tricky case here: SignedMin / -1 is UB on the
1250     // IR level, so we'll want to exclude this case when calculating bounds.
1251     // (For APInts the operation is well-defined and yields SignedMin.) We
1252     // handle this by dropping either SignedMin from the LHS or -1 from the RHS.
1253     APInt Lo = (NegL.Upper - 1).sdiv(NegR.Lower);
1254     if (NegL.Lower.isMinSignedValue() && NegR.Upper.isZero()) {
1255       // Remove -1 from the LHS. Skip if it's the only element, as this would
1256       // leave us with an empty set.
1257       if (!NegR.Lower.isAllOnes()) {
1258         APInt AdjNegRUpper;
1259         if (RHS.Lower.isAllOnes())
1260           // Negative part of [-1, X] without -1 is [SignedMin, X].
1261           AdjNegRUpper = RHS.Upper;
1262         else
1263           // [X, -1] without -1 is [X, -2].
1264           AdjNegRUpper = NegR.Upper - 1;
1265 
1266         PosRes = PosRes.unionWith(
1267             ConstantRange(Lo, NegL.Lower.sdiv(AdjNegRUpper - 1) + 1));
1268       }
1269 
1270       // Remove SignedMin from the RHS. Skip if it's the only element, as this
1271       // would leave us with an empty set.
1272       if (NegL.Upper != SignedMin + 1) {
1273         APInt AdjNegLLower;
1274         if (Upper == SignedMin + 1)
1275           // Negative part of [X, SignedMin] without SignedMin is [X, -1].
1276           AdjNegLLower = Lower;
1277         else
1278           // [SignedMin, X] without SignedMin is [SignedMin + 1, X].
1279           AdjNegLLower = NegL.Lower + 1;
1280 
1281         PosRes = PosRes.unionWith(
1282             ConstantRange(std::move(Lo),
1283                           AdjNegLLower.sdiv(NegR.Upper - 1) + 1));
1284       }
1285     } else {
1286       PosRes = PosRes.unionWith(
1287           ConstantRange(std::move(Lo), NegL.Lower.sdiv(NegR.Upper - 1) + 1));
1288     }
1289   }
1290 
1291   ConstantRange NegRes = getEmpty();
1292   if (!PosL.isEmptySet() && !NegR.isEmptySet())
1293     // pos / neg = neg.
1294     NegRes = ConstantRange((PosL.Upper - 1).sdiv(NegR.Upper - 1),
1295                            PosL.Lower.sdiv(NegR.Lower) + 1);
1296 
1297   if (!NegL.isEmptySet() && !PosR.isEmptySet())
1298     // neg / pos = neg.
1299     NegRes = NegRes.unionWith(
1300         ConstantRange(NegL.Lower.sdiv(PosR.Lower),
1301                       (NegL.Upper - 1).sdiv(PosR.Upper - 1) + 1));
1302 
1303   // Prefer a non-wrapping signed range here.
1304   ConstantRange Res = NegRes.unionWith(PosRes, PreferredRangeType::Signed);
1305 
1306   // Preserve the zero that we dropped when splitting the LHS by sign.
1307   if (contains(Zero) && (!PosR.isEmptySet() || !NegR.isEmptySet()))
1308     Res = Res.unionWith(ConstantRange(Zero));
1309   return Res;
1310 }
1311 
1312 ConstantRange ConstantRange::urem(const ConstantRange &RHS) const {
1313   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
1314     return getEmpty();
1315 
1316   if (const APInt *RHSInt = RHS.getSingleElement()) {
1317     // UREM by null is UB.
1318     if (RHSInt->isZero())
1319       return getEmpty();
1320     // Use APInt's implementation of UREM for single element ranges.
1321     if (const APInt *LHSInt = getSingleElement())
1322       return {LHSInt->urem(*RHSInt)};
1323   }
1324 
1325   // L % R for L < R is L.
1326   if (getUnsignedMax().ult(RHS.getUnsignedMin()))
1327     return *this;
1328 
1329   // L % R is <= L and < R.
1330   APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1;
1331   return getNonEmpty(APInt::getZero(getBitWidth()), std::move(Upper));
1332 }
1333 
1334 ConstantRange ConstantRange::srem(const ConstantRange &RHS) const {
1335   if (isEmptySet() || RHS.isEmptySet())
1336     return getEmpty();
1337 
1338   if (const APInt *RHSInt = RHS.getSingleElement()) {
1339     // SREM by null is UB.
1340     if (RHSInt->isZero())
1341       return getEmpty();
1342     // Use APInt's implementation of SREM for single element ranges.
1343     if (const APInt *LHSInt = getSingleElement())
1344       return {LHSInt->srem(*RHSInt)};
1345   }
1346 
1347   ConstantRange AbsRHS = RHS.abs();
1348   APInt MinAbsRHS = AbsRHS.getUnsignedMin();
1349   APInt MaxAbsRHS = AbsRHS.getUnsignedMax();
1350 
1351   // Modulus by zero is UB.
1352   if (MaxAbsRHS.isZero())
1353     return getEmpty();
1354 
1355   if (MinAbsRHS.isZero())
1356     ++MinAbsRHS;
1357 
1358   APInt MinLHS = getSignedMin(), MaxLHS = getSignedMax();
1359 
1360   if (MinLHS.isNonNegative()) {
1361     // L % R for L < R is L.
1362     if (MaxLHS.ult(MinAbsRHS))
1363       return *this;
1364 
1365     // L % R is <= L and < R.
1366     APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
1367     return ConstantRange(APInt::getZero(getBitWidth()), std::move(Upper));
1368   }
1369 
1370   // Same basic logic as above, but the result is negative.
1371   if (MaxLHS.isNegative()) {
1372     if (MinLHS.ugt(-MinAbsRHS))
1373       return *this;
1374 
1375     APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
1376     return ConstantRange(std::move(Lower), APInt(getBitWidth(), 1));
1377   }
1378 
1379   // LHS range crosses zero.
1380   APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
1381   APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
1382   return ConstantRange(std::move(Lower), std::move(Upper));
1383 }
1384 
1385 ConstantRange ConstantRange::binaryNot() const {
1386   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
1387 }
1388 
1389 ConstantRange
1390 ConstantRange::binaryAnd(const ConstantRange &Other) const {
1391   if (isEmptySet() || Other.isEmptySet())
1392     return getEmpty();
1393 
1394   // Use APInt's implementation of AND for single element ranges.
1395   if (isSingleElement() && Other.isSingleElement())
1396     return {*getSingleElement() & *Other.getSingleElement()};
1397 
1398   // TODO: replace this with something less conservative
1399 
1400   APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
1401   return getNonEmpty(APInt::getZero(getBitWidth()), std::move(umin) + 1);
1402 }
1403 
1404 ConstantRange
1405 ConstantRange::binaryOr(const ConstantRange &Other) const {
1406   if (isEmptySet() || Other.isEmptySet())
1407     return getEmpty();
1408 
1409   // Use APInt's implementation of OR for single element ranges.
1410   if (isSingleElement() && Other.isSingleElement())
1411     return {*getSingleElement() | *Other.getSingleElement()};
1412 
1413   // TODO: replace this with something less conservative
1414 
1415   APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
1416   return getNonEmpty(std::move(umax), APInt::getZero(getBitWidth()));
1417 }
1418 
1419 ConstantRange ConstantRange::binaryXor(const ConstantRange &Other) const {
1420   if (isEmptySet() || Other.isEmptySet())
1421     return getEmpty();
1422 
1423   // Use APInt's implementation of XOR for single element ranges.
1424   if (isSingleElement() && Other.isSingleElement())
1425     return {*getSingleElement() ^ *Other.getSingleElement()};
1426 
1427   // Special-case binary complement, since we can give a precise answer.
1428   if (Other.isSingleElement() && Other.getSingleElement()->isAllOnes())
1429     return binaryNot();
1430   if (isSingleElement() && getSingleElement()->isAllOnes())
1431     return Other.binaryNot();
1432 
1433   // TODO: replace this with something less conservative
1434   return getFull();
1435 }
1436 
1437 ConstantRange
1438 ConstantRange::shl(const ConstantRange &Other) const {
1439   if (isEmptySet() || Other.isEmptySet())
1440     return getEmpty();
1441 
1442   APInt Min = getUnsignedMin();
1443   APInt Max = getUnsignedMax();
1444   if (const APInt *RHS = Other.getSingleElement()) {
1445     unsigned BW = getBitWidth();
1446     if (RHS->uge(BW))
1447       return getEmpty();
1448 
1449     unsigned EqualLeadingBits = (Min ^ Max).countLeadingZeros();
1450     if (RHS->ule(EqualLeadingBits))
1451       return getNonEmpty(Min << *RHS, (Max << *RHS) + 1);
1452 
1453     return getNonEmpty(APInt::getZero(BW),
1454                        APInt::getBitsSetFrom(BW, RHS->getZExtValue()) + 1);
1455   }
1456 
1457   APInt OtherMax = Other.getUnsignedMax();
1458 
1459   // There's overflow!
1460   if (OtherMax.ugt(Max.countLeadingZeros()))
1461     return getFull();
1462 
1463   // FIXME: implement the other tricky cases
1464 
1465   Min <<= Other.getUnsignedMin();
1466   Max <<= OtherMax;
1467 
1468   return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1);
1469 }
1470 
1471 ConstantRange
1472 ConstantRange::lshr(const ConstantRange &Other) const {
1473   if (isEmptySet() || Other.isEmptySet())
1474     return getEmpty();
1475 
1476   APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
1477   APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
1478   return getNonEmpty(std::move(min), std::move(max));
1479 }
1480 
1481 ConstantRange
1482 ConstantRange::ashr(const ConstantRange &Other) const {
1483   if (isEmptySet() || Other.isEmptySet())
1484     return getEmpty();
1485 
1486   // May straddle zero, so handle both positive and negative cases.
1487   // 'PosMax' is the upper bound of the result of the ashr
1488   // operation, when Upper of the LHS of ashr is a non-negative.
1489   // number. Since ashr of a non-negative number will result in a
1490   // smaller number, the Upper value of LHS is shifted right with
1491   // the minimum value of 'Other' instead of the maximum value.
1492   APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;
1493 
1494   // 'PosMin' is the lower bound of the result of the ashr
1495   // operation, when Lower of the LHS is a non-negative number.
1496   // Since ashr of a non-negative number will result in a smaller
1497   // number, the Lower value of LHS is shifted right with the
1498   // maximum value of 'Other'.
1499   APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());
1500 
1501   // 'NegMax' is the upper bound of the result of the ashr
1502   // operation, when Upper of the LHS of ashr is a negative number.
1503   // Since 'ashr' of a negative number will result in a bigger
1504   // number, the Upper value of LHS is shifted right with the
1505   // maximum value of 'Other'.
1506   APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;
1507 
1508   // 'NegMin' is the lower bound of the result of the ashr
1509   // operation, when Lower of the LHS of ashr is a negative number.
1510   // Since 'ashr' of a negative number will result in a bigger
1511   // number, the Lower value of LHS is shifted right with the
1512   // minimum value of 'Other'.
1513   APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());
1514 
1515   APInt max, min;
1516   if (getSignedMin().isNonNegative()) {
1517     // Upper and Lower of LHS are non-negative.
1518     min = PosMin;
1519     max = PosMax;
1520   } else if (getSignedMax().isNegative()) {
1521     // Upper and Lower of LHS are negative.
1522     min = NegMin;
1523     max = NegMax;
1524   } else {
1525     // Upper is non-negative and Lower is negative.
1526     min = NegMin;
1527     max = PosMax;
1528   }
1529   return getNonEmpty(std::move(min), std::move(max));
1530 }
1531 
1532 ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const {
1533   if (isEmptySet() || Other.isEmptySet())
1534     return getEmpty();
1535 
1536   APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin());
1537   APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1;
1538   return getNonEmpty(std::move(NewL), std::move(NewU));
1539 }
1540 
1541 ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const {
1542   if (isEmptySet() || Other.isEmptySet())
1543     return getEmpty();
1544 
1545   APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin());
1546   APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1;
1547   return getNonEmpty(std::move(NewL), std::move(NewU));
1548 }
1549 
1550 ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const {
1551   if (isEmptySet() || Other.isEmptySet())
1552     return getEmpty();
1553 
1554   APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax());
1555   APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1;
1556   return getNonEmpty(std::move(NewL), std::move(NewU));
1557 }
1558 
1559 ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const {
1560   if (isEmptySet() || Other.isEmptySet())
1561     return getEmpty();
1562 
1563   APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax());
1564   APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1;
1565   return getNonEmpty(std::move(NewL), std::move(NewU));
1566 }
1567 
1568 ConstantRange ConstantRange::umul_sat(const ConstantRange &Other) const {
1569   if (isEmptySet() || Other.isEmptySet())
1570     return getEmpty();
1571 
1572   APInt NewL = getUnsignedMin().umul_sat(Other.getUnsignedMin());
1573   APInt NewU = getUnsignedMax().umul_sat(Other.getUnsignedMax()) + 1;
1574   return getNonEmpty(std::move(NewL), std::move(NewU));
1575 }
1576 
1577 ConstantRange ConstantRange::smul_sat(const ConstantRange &Other) const {
1578   if (isEmptySet() || Other.isEmptySet())
1579     return getEmpty();
1580 
1581   // Because we could be dealing with negative numbers here, the lower bound is
1582   // the smallest of the cartesian product of the lower and upper ranges;
1583   // for example:
1584   //   [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
1585   // Similarly for the upper bound, swapping min for max.
1586 
1587   APInt Min = getSignedMin();
1588   APInt Max = getSignedMax();
1589   APInt OtherMin = Other.getSignedMin();
1590   APInt OtherMax = Other.getSignedMax();
1591 
1592   auto L = {Min.smul_sat(OtherMin), Min.smul_sat(OtherMax),
1593             Max.smul_sat(OtherMin), Max.smul_sat(OtherMax)};
1594   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1595   return getNonEmpty(std::min(L, Compare), std::max(L, Compare) + 1);
1596 }
1597 
1598 ConstantRange ConstantRange::ushl_sat(const ConstantRange &Other) const {
1599   if (isEmptySet() || Other.isEmptySet())
1600     return getEmpty();
1601 
1602   APInt NewL = getUnsignedMin().ushl_sat(Other.getUnsignedMin());
1603   APInt NewU = getUnsignedMax().ushl_sat(Other.getUnsignedMax()) + 1;
1604   return getNonEmpty(std::move(NewL), std::move(NewU));
1605 }
1606 
1607 ConstantRange ConstantRange::sshl_sat(const ConstantRange &Other) const {
1608   if (isEmptySet() || Other.isEmptySet())
1609     return getEmpty();
1610 
1611   APInt Min = getSignedMin(), Max = getSignedMax();
1612   APInt ShAmtMin = Other.getUnsignedMin(), ShAmtMax = Other.getUnsignedMax();
1613   APInt NewL = Min.sshl_sat(Min.isNonNegative() ? ShAmtMin : ShAmtMax);
1614   APInt NewU = Max.sshl_sat(Max.isNegative() ? ShAmtMin : ShAmtMax) + 1;
1615   return getNonEmpty(std::move(NewL), std::move(NewU));
1616 }
1617 
1618 ConstantRange ConstantRange::inverse() const {
1619   if (isFullSet())
1620     return getEmpty();
1621   if (isEmptySet())
1622     return getFull();
1623   return ConstantRange(Upper, Lower);
1624 }
1625 
1626 ConstantRange ConstantRange::abs(bool IntMinIsPoison) const {
1627   if (isEmptySet())
1628     return getEmpty();
1629 
1630   if (isSignWrappedSet()) {
1631     APInt Lo;
1632     // Check whether the range crosses zero.
1633     if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive())
1634       Lo = APInt::getZero(getBitWidth());
1635     else
1636       Lo = APIntOps::umin(Lower, -Upper + 1);
1637 
1638     // If SignedMin is not poison, then it is included in the result range.
1639     if (IntMinIsPoison)
1640       return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()));
1641     else
1642       return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()) + 1);
1643   }
1644 
1645   APInt SMin = getSignedMin(), SMax = getSignedMax();
1646 
1647   // Skip SignedMin if it is poison.
1648   if (IntMinIsPoison && SMin.isMinSignedValue()) {
1649     // The range may become empty if it *only* contains SignedMin.
1650     if (SMax.isMinSignedValue())
1651       return getEmpty();
1652     ++SMin;
1653   }
1654 
1655   // All non-negative.
1656   if (SMin.isNonNegative())
1657     return *this;
1658 
1659   // All negative.
1660   if (SMax.isNegative())
1661     return ConstantRange(-SMax, -SMin + 1);
1662 
1663   // Range crosses zero.
1664   return ConstantRange(APInt::getZero(getBitWidth()),
1665                        APIntOps::umax(-SMin, SMax) + 1);
1666 }
1667 
1668 ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow(
1669     const ConstantRange &Other) const {
1670   if (isEmptySet() || Other.isEmptySet())
1671     return OverflowResult::MayOverflow;
1672 
1673   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1674   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1675 
1676   // a u+ b overflows high iff a u> ~b.
1677   if (Min.ugt(~OtherMin))
1678     return OverflowResult::AlwaysOverflowsHigh;
1679   if (Max.ugt(~OtherMax))
1680     return OverflowResult::MayOverflow;
1681   return OverflowResult::NeverOverflows;
1682 }
1683 
1684 ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow(
1685     const ConstantRange &Other) const {
1686   if (isEmptySet() || Other.isEmptySet())
1687     return OverflowResult::MayOverflow;
1688 
1689   APInt Min = getSignedMin(), Max = getSignedMax();
1690   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
1691 
1692   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1693   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
1694 
1695   // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
1696   // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
1697   if (Min.isNonNegative() && OtherMin.isNonNegative() &&
1698       Min.sgt(SignedMax - OtherMin))
1699     return OverflowResult::AlwaysOverflowsHigh;
1700   if (Max.isNegative() && OtherMax.isNegative() &&
1701       Max.slt(SignedMin - OtherMax))
1702     return OverflowResult::AlwaysOverflowsLow;
1703 
1704   if (Max.isNonNegative() && OtherMax.isNonNegative() &&
1705       Max.sgt(SignedMax - OtherMax))
1706     return OverflowResult::MayOverflow;
1707   if (Min.isNegative() && OtherMin.isNegative() &&
1708       Min.slt(SignedMin - OtherMin))
1709     return OverflowResult::MayOverflow;
1710 
1711   return OverflowResult::NeverOverflows;
1712 }
1713 
1714 ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow(
1715     const ConstantRange &Other) const {
1716   if (isEmptySet() || Other.isEmptySet())
1717     return OverflowResult::MayOverflow;
1718 
1719   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1720   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1721 
1722   // a u- b overflows low iff a u< b.
1723   if (Max.ult(OtherMin))
1724     return OverflowResult::AlwaysOverflowsLow;
1725   if (Min.ult(OtherMax))
1726     return OverflowResult::MayOverflow;
1727   return OverflowResult::NeverOverflows;
1728 }
1729 
1730 ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow(
1731     const ConstantRange &Other) const {
1732   if (isEmptySet() || Other.isEmptySet())
1733     return OverflowResult::MayOverflow;
1734 
1735   APInt Min = getSignedMin(), Max = getSignedMax();
1736   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
1737 
1738   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1739   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
1740 
1741   // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
1742   // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
1743   if (Min.isNonNegative() && OtherMax.isNegative() &&
1744       Min.sgt(SignedMax + OtherMax))
1745     return OverflowResult::AlwaysOverflowsHigh;
1746   if (Max.isNegative() && OtherMin.isNonNegative() &&
1747       Max.slt(SignedMin + OtherMin))
1748     return OverflowResult::AlwaysOverflowsLow;
1749 
1750   if (Max.isNonNegative() && OtherMin.isNegative() &&
1751       Max.sgt(SignedMax + OtherMin))
1752     return OverflowResult::MayOverflow;
1753   if (Min.isNegative() && OtherMax.isNonNegative() &&
1754       Min.slt(SignedMin + OtherMax))
1755     return OverflowResult::MayOverflow;
1756 
1757   return OverflowResult::NeverOverflows;
1758 }
1759 
1760 ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow(
1761     const ConstantRange &Other) const {
1762   if (isEmptySet() || Other.isEmptySet())
1763     return OverflowResult::MayOverflow;
1764 
1765   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1766   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1767   bool Overflow;
1768 
1769   (void) Min.umul_ov(OtherMin, Overflow);
1770   if (Overflow)
1771     return OverflowResult::AlwaysOverflowsHigh;
1772 
1773   (void) Max.umul_ov(OtherMax, Overflow);
1774   if (Overflow)
1775     return OverflowResult::MayOverflow;
1776 
1777   return OverflowResult::NeverOverflows;
1778 }
1779 
1780 void ConstantRange::print(raw_ostream &OS) const {
1781   if (isFullSet())
1782     OS << "full-set";
1783   else if (isEmptySet())
1784     OS << "empty-set";
1785   else
1786     OS << "[" << Lower << "," << Upper << ")";
1787 }
1788 
1789 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1790 LLVM_DUMP_METHOD void ConstantRange::dump() const {
1791   print(dbgs());
1792 }
1793 #endif
1794 
1795 ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
1796   const unsigned NumRanges = Ranges.getNumOperands() / 2;
1797   assert(NumRanges >= 1 && "Must have at least one range!");
1798   assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
1799 
1800   auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
1801   auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
1802 
1803   ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
1804 
1805   for (unsigned i = 1; i < NumRanges; ++i) {
1806     auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
1807     auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
1808 
1809     // Note: unionWith will potentially create a range that contains values not
1810     // contained in any of the original N ranges.
1811     CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
1812   }
1813 
1814   return CR;
1815 }
1816