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