1 //===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Represent a range of possible values that may occur when the program is run
11 // for an integral value.  This keeps track of a lower and upper bound for the
12 // constant, which MAY wrap around the end of the numeric range.  To do this, it
13 // keeps track of a [lower, upper) bound, which specifies an interval just like
14 // STL iterators.  When used with boolean values, the following are important
15 // ranges (other integral ranges use min/max values for special range values):
16 //
17 //  [F, F) = {}     = Empty set
18 //  [T, F) = {T}
19 //  [F, T) = {F}
20 //  [T, T) = {F, T} = Full set
21 //
22 //===----------------------------------------------------------------------===//
23 
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/InstrTypes.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm;
31 
32 ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)
33     : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
34       Upper(Lower) {}
35 
36 ConstantRange::ConstantRange(APInt V)
37     : Lower(std::move(V)), Upper(Lower + 1) {}
38 
39 ConstantRange::ConstantRange(APInt L, APInt U)
40     : Lower(std::move(L)), Upper(std::move(U)) {
41   assert(Lower.getBitWidth() == Upper.getBitWidth() &&
42          "ConstantRange with unequal bit widths");
43   assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
44          "Lower == Upper, but they aren't min or max value!");
45 }
46 
47 ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
48                                                    const ConstantRange &CR) {
49   if (CR.isEmptySet())
50     return CR;
51 
52   uint32_t W = CR.getBitWidth();
53   switch (Pred) {
54   default:
55     llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
56   case CmpInst::ICMP_EQ:
57     return CR;
58   case CmpInst::ICMP_NE:
59     if (CR.isSingleElement())
60       return ConstantRange(CR.getUpper(), CR.getLower());
61     return ConstantRange(W);
62   case CmpInst::ICMP_ULT: {
63     APInt UMax(CR.getUnsignedMax());
64     if (UMax.isMinValue())
65       return ConstantRange(W, /* empty */ false);
66     return ConstantRange(APInt::getMinValue(W), std::move(UMax));
67   }
68   case CmpInst::ICMP_SLT: {
69     APInt SMax(CR.getSignedMax());
70     if (SMax.isMinSignedValue())
71       return ConstantRange(W, /* empty */ false);
72     return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));
73   }
74   case CmpInst::ICMP_ULE: {
75     APInt UMax(CR.getUnsignedMax());
76     if (UMax.isMaxValue())
77       return ConstantRange(W);
78     return ConstantRange(APInt::getMinValue(W), std::move(UMax) + 1);
79   }
80   case CmpInst::ICMP_SLE: {
81     APInt SMax(CR.getSignedMax());
82     if (SMax.isMaxSignedValue())
83       return ConstantRange(W);
84     return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax) + 1);
85   }
86   case CmpInst::ICMP_UGT: {
87     APInt UMin(CR.getUnsignedMin());
88     if (UMin.isMaxValue())
89       return ConstantRange(W, /* empty */ false);
90     return ConstantRange(std::move(UMin) + 1, APInt::getNullValue(W));
91   }
92   case CmpInst::ICMP_SGT: {
93     APInt SMin(CR.getSignedMin());
94     if (SMin.isMaxSignedValue())
95       return ConstantRange(W, /* empty */ false);
96     return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));
97   }
98   case CmpInst::ICMP_UGE: {
99     APInt UMin(CR.getUnsignedMin());
100     if (UMin.isMinValue())
101       return ConstantRange(W);
102     return ConstantRange(std::move(UMin), APInt::getNullValue(W));
103   }
104   case CmpInst::ICMP_SGE: {
105     APInt SMin(CR.getSignedMin());
106     if (SMin.isMinSignedValue())
107       return ConstantRange(W);
108     return ConstantRange(std::move(SMin), APInt::getSignedMinValue(W));
109   }
110   }
111 }
112 
113 ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
114                                                       const ConstantRange &CR) {
115   // Follows from De-Morgan's laws:
116   //
117   // ~(~A union ~B) == A intersect B.
118   //
119   return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
120       .inverse();
121 }
122 
123 ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
124                                                  const APInt &C) {
125   // Computes the exact range that is equal to both the constant ranges returned
126   // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
127   // when RHS is a singleton such as an APInt and so the assert is valid.
128   // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
129   // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
130   //
131   assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
132   return makeAllowedICmpRegion(Pred, C);
133 }
134 
135 bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
136                                       APInt &RHS) const {
137   bool Success = false;
138 
139   if (isFullSet() || isEmptySet()) {
140     Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
141     RHS = APInt(getBitWidth(), 0);
142     Success = true;
143   } else if (auto *OnlyElt = getSingleElement()) {
144     Pred = CmpInst::ICMP_EQ;
145     RHS = *OnlyElt;
146     Success = true;
147   } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
148     Pred = CmpInst::ICMP_NE;
149     RHS = *OnlyMissingElt;
150     Success = true;
151   } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
152     Pred =
153         getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
154     RHS = getUpper();
155     Success = true;
156   } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
157     Pred =
158         getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
159     RHS = getLower();
160     Success = true;
161   }
162 
163   assert((!Success || ConstantRange::makeExactICmpRegion(Pred, RHS) == *this) &&
164          "Bad result!");
165 
166   return Success;
167 }
168 
169 ConstantRange
170 ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
171                                           const ConstantRange &Other,
172                                           unsigned NoWrapKind) {
173   typedef OverflowingBinaryOperator OBO;
174 
175   // Computes the intersection of CR0 and CR1.  It is different from
176   // intersectWith in that the ConstantRange returned will only contain elements
177   // in both CR0 and CR1 (i.e. SubsetIntersect(X, Y) is a *subset*, proper or
178   // not, of both X and Y).
179   auto SubsetIntersect =
180       [](const ConstantRange &CR0, const ConstantRange &CR1) {
181     return CR0.inverse().unionWith(CR1.inverse()).inverse();
182   };
183 
184   assert(BinOp >= Instruction::BinaryOpsBegin &&
185          BinOp < Instruction::BinaryOpsEnd && "Binary operators only!");
186 
187   assert((NoWrapKind == OBO::NoSignedWrap ||
188           NoWrapKind == OBO::NoUnsignedWrap ||
189           NoWrapKind == (OBO::NoUnsignedWrap | OBO::NoSignedWrap)) &&
190          "NoWrapKind invalid!");
191 
192   unsigned BitWidth = Other.getBitWidth();
193   if (BinOp != Instruction::Add)
194     // Conservative answer: empty set
195     return ConstantRange(BitWidth, false);
196 
197   if (auto *C = Other.getSingleElement())
198     if (C->isNullValue())
199       // Full set: nothing signed / unsigned wraps when added to 0.
200       return ConstantRange(BitWidth);
201 
202   ConstantRange Result(BitWidth);
203 
204   if (NoWrapKind & OBO::NoUnsignedWrap)
205     Result =
206         SubsetIntersect(Result, ConstantRange(APInt::getNullValue(BitWidth),
207                                               -Other.getUnsignedMax()));
208 
209   if (NoWrapKind & OBO::NoSignedWrap) {
210     const APInt &SignedMin = Other.getSignedMin();
211     const APInt &SignedMax = Other.getSignedMax();
212 
213     if (SignedMax.isStrictlyPositive())
214       Result = SubsetIntersect(
215           Result,
216           ConstantRange(APInt::getSignedMinValue(BitWidth),
217                         APInt::getSignedMinValue(BitWidth) - SignedMax));
218 
219     if (SignedMin.isNegative())
220       Result = SubsetIntersect(
221           Result, ConstantRange(APInt::getSignedMinValue(BitWidth) - SignedMin,
222                                 APInt::getSignedMinValue(BitWidth)));
223   }
224 
225   return Result;
226 }
227 
228 bool ConstantRange::isFullSet() const {
229   return Lower == Upper && Lower.isMaxValue();
230 }
231 
232 bool ConstantRange::isEmptySet() const {
233   return Lower == Upper && Lower.isMinValue();
234 }
235 
236 bool ConstantRange::isWrappedSet() const {
237   return Lower.ugt(Upper);
238 }
239 
240 bool ConstantRange::isSignWrappedSet() const {
241   return contains(APInt::getSignedMaxValue(getBitWidth())) &&
242          contains(APInt::getSignedMinValue(getBitWidth()));
243 }
244 
245 APInt ConstantRange::getSetSize() const {
246   if (isFullSet())
247     return APInt::getOneBitSet(getBitWidth()+1, getBitWidth());
248 
249   // This is also correct for wrapped sets.
250   return (Upper - Lower).zext(getBitWidth()+1);
251 }
252 
253 bool
254 ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
255   assert(getBitWidth() == Other.getBitWidth());
256   if (isFullSet())
257     return false;
258   if (Other.isFullSet())
259     return true;
260   return (Upper - Lower).ult(Other.Upper - Other.Lower);
261 }
262 
263 bool
264 ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
265   assert(MaxSize && "MaxSize can't be 0.");
266   // If this a full set, we need special handling to avoid needing an extra bit
267   // to represent the size.
268   if (isFullSet())
269     return APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
270 
271   return (Upper - Lower).ugt(MaxSize);
272 }
273 
274 APInt ConstantRange::getUnsignedMax() const {
275   if (isFullSet() || isWrappedSet())
276     return APInt::getMaxValue(getBitWidth());
277   return getUpper() - 1;
278 }
279 
280 APInt ConstantRange::getUnsignedMin() const {
281   if (isFullSet() || (isWrappedSet() && !getUpper().isNullValue()))
282     return APInt::getMinValue(getBitWidth());
283   return getLower();
284 }
285 
286 APInt ConstantRange::getSignedMax() const {
287   if (!isWrappedSet()) {
288     APInt UpperMinusOne = getUpper() - 1;
289     if (getLower().sle(UpperMinusOne))
290       return UpperMinusOne;
291     return APInt::getSignedMaxValue(getBitWidth());
292   }
293   if (getLower().isNegative() == getUpper().isNegative())
294     return APInt::getSignedMaxValue(getBitWidth());
295   return getUpper() - 1;
296 }
297 
298 APInt ConstantRange::getSignedMin() const {
299   if (!isWrappedSet()) {
300     if (getLower().sle(getUpper() - 1))
301       return getLower();
302     return APInt::getSignedMinValue(getBitWidth());
303   }
304   if ((getUpper() - 1).slt(getLower())) {
305     if (!getUpper().isMinSignedValue())
306       return APInt::getSignedMinValue(getBitWidth());
307   }
308   return getLower();
309 }
310 
311 bool ConstantRange::contains(const APInt &V) const {
312   if (Lower == Upper)
313     return isFullSet();
314 
315   if (!isWrappedSet())
316     return Lower.ule(V) && V.ult(Upper);
317   return Lower.ule(V) || V.ult(Upper);
318 }
319 
320 bool ConstantRange::contains(const ConstantRange &Other) const {
321   if (isFullSet() || Other.isEmptySet()) return true;
322   if (isEmptySet() || Other.isFullSet()) return false;
323 
324   if (!isWrappedSet()) {
325     if (Other.isWrappedSet())
326       return false;
327 
328     return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
329   }
330 
331   if (!Other.isWrappedSet())
332     return Other.getUpper().ule(Upper) ||
333            Lower.ule(Other.getLower());
334 
335   return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
336 }
337 
338 ConstantRange ConstantRange::subtract(const APInt &Val) const {
339   assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
340   // If the set is empty or full, don't modify the endpoints.
341   if (Lower == Upper)
342     return *this;
343   return ConstantRange(Lower - Val, Upper - Val);
344 }
345 
346 ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
347   return intersectWith(CR.inverse());
348 }
349 
350 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR) const {
351   assert(getBitWidth() == CR.getBitWidth() &&
352          "ConstantRange types don't agree!");
353 
354   // Handle common cases.
355   if (   isEmptySet() || CR.isFullSet()) return *this;
356   if (CR.isEmptySet() ||    isFullSet()) return CR;
357 
358   if (!isWrappedSet() && CR.isWrappedSet())
359     return CR.intersectWith(*this);
360 
361   if (!isWrappedSet() && !CR.isWrappedSet()) {
362     if (Lower.ult(CR.Lower)) {
363       if (Upper.ule(CR.Lower))
364         return ConstantRange(getBitWidth(), false);
365 
366       if (Upper.ult(CR.Upper))
367         return ConstantRange(CR.Lower, Upper);
368 
369       return CR;
370     }
371     if (Upper.ult(CR.Upper))
372       return *this;
373 
374     if (Lower.ult(CR.Upper))
375       return ConstantRange(Lower, CR.Upper);
376 
377     return ConstantRange(getBitWidth(), false);
378   }
379 
380   if (isWrappedSet() && !CR.isWrappedSet()) {
381     if (CR.Lower.ult(Upper)) {
382       if (CR.Upper.ult(Upper))
383         return CR;
384 
385       if (CR.Upper.ule(Lower))
386         return ConstantRange(CR.Lower, Upper);
387 
388       if (isSizeStrictlySmallerThan(CR))
389         return *this;
390       return CR;
391     }
392     if (CR.Lower.ult(Lower)) {
393       if (CR.Upper.ule(Lower))
394         return ConstantRange(getBitWidth(), false);
395 
396       return ConstantRange(Lower, CR.Upper);
397     }
398     return CR;
399   }
400 
401   if (CR.Upper.ult(Upper)) {
402     if (CR.Lower.ult(Upper)) {
403       if (isSizeStrictlySmallerThan(CR))
404         return *this;
405       return CR;
406     }
407 
408     if (CR.Lower.ult(Lower))
409       return ConstantRange(Lower, CR.Upper);
410 
411     return CR;
412   }
413   if (CR.Upper.ule(Lower)) {
414     if (CR.Lower.ult(Lower))
415       return *this;
416 
417     return ConstantRange(CR.Lower, Upper);
418   }
419   if (isSizeStrictlySmallerThan(CR))
420     return *this;
421   return CR;
422 }
423 
424 ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const {
425   assert(getBitWidth() == CR.getBitWidth() &&
426          "ConstantRange types don't agree!");
427 
428   if (   isFullSet() || CR.isEmptySet()) return *this;
429   if (CR.isFullSet() ||    isEmptySet()) return CR;
430 
431   if (!isWrappedSet() && CR.isWrappedSet()) return CR.unionWith(*this);
432 
433   if (!isWrappedSet() && !CR.isWrappedSet()) {
434     if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower)) {
435       // If the two ranges are disjoint, find the smaller gap and bridge it.
436       APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
437       if (d1.ult(d2))
438         return ConstantRange(Lower, CR.Upper);
439       return ConstantRange(CR.Lower, Upper);
440     }
441 
442     APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
443     APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
444 
445     if (L.isNullValue() && U.isNullValue())
446       return ConstantRange(getBitWidth());
447 
448     return ConstantRange(std::move(L), std::move(U));
449   }
450 
451   if (!CR.isWrappedSet()) {
452     // ------U   L-----  and  ------U   L----- : this
453     //   L--U                            L--U  : CR
454     if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
455       return *this;
456 
457     // ------U   L----- : this
458     //    L---------U   : CR
459     if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
460       return ConstantRange(getBitWidth());
461 
462     // ----U       L---- : this
463     //       L---U       : CR
464     //    <d1>  <d2>
465     if (Upper.ule(CR.Lower) && CR.Upper.ule(Lower)) {
466       APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
467       if (d1.ult(d2))
468         return ConstantRange(Lower, CR.Upper);
469       return ConstantRange(CR.Lower, Upper);
470     }
471 
472     // ----U     L----- : this
473     //        L----U    : CR
474     if (Upper.ult(CR.Lower) && Lower.ult(CR.Upper))
475       return ConstantRange(CR.Lower, Upper);
476 
477     // ------U    L---- : this
478     //    L-----U       : CR
479     assert(CR.Lower.ult(Upper) && CR.Upper.ult(Lower) &&
480            "ConstantRange::unionWith missed a case with one range wrapped");
481     return ConstantRange(Lower, CR.Upper);
482   }
483 
484   // ------U    L----  and  ------U    L---- : this
485   // -U  L-----------  and  ------------U  L : CR
486   if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
487     return ConstantRange(getBitWidth());
488 
489   APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
490   APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
491 
492   return ConstantRange(std::move(L), std::move(U));
493 }
494 
495 ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
496                                     uint32_t ResultBitWidth) const {
497   switch (CastOp) {
498   default:
499     llvm_unreachable("unsupported cast type");
500   case Instruction::Trunc:
501     return truncate(ResultBitWidth);
502   case Instruction::SExt:
503     return signExtend(ResultBitWidth);
504   case Instruction::ZExt:
505     return zeroExtend(ResultBitWidth);
506   case Instruction::BitCast:
507     return *this;
508   case Instruction::FPToUI:
509   case Instruction::FPToSI:
510     if (getBitWidth() == ResultBitWidth)
511       return *this;
512     else
513       return ConstantRange(getBitWidth(), /*isFullSet=*/true);
514   case Instruction::UIToFP: {
515     // TODO: use input range if available
516     auto BW = getBitWidth();
517     APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
518     APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
519     return ConstantRange(std::move(Min), std::move(Max));
520   }
521   case Instruction::SIToFP: {
522     // TODO: use input range if available
523     auto BW = getBitWidth();
524     APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
525     APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
526     return ConstantRange(std::move(SMin), std::move(SMax));
527   }
528   case Instruction::FPTrunc:
529   case Instruction::FPExt:
530   case Instruction::IntToPtr:
531   case Instruction::PtrToInt:
532   case Instruction::AddrSpaceCast:
533     // Conservatively return full set.
534     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
535   };
536 }
537 
538 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
539   if (isEmptySet()) return ConstantRange(DstTySize, /*isFullSet=*/false);
540 
541   unsigned SrcTySize = getBitWidth();
542   assert(SrcTySize < DstTySize && "Not a value extension");
543   if (isFullSet() || isWrappedSet()) {
544     // Change into [0, 1 << src bit width)
545     APInt LowerExt(DstTySize, 0);
546     if (!Upper) // special case: [X, 0) -- not really wrapping around
547       LowerExt = Lower.zext(DstTySize);
548     return ConstantRange(std::move(LowerExt),
549                          APInt::getOneBitSet(DstTySize, SrcTySize));
550   }
551 
552   return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
553 }
554 
555 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
556   if (isEmptySet()) return ConstantRange(DstTySize, /*isFullSet=*/false);
557 
558   unsigned SrcTySize = getBitWidth();
559   assert(SrcTySize < DstTySize && "Not a value extension");
560 
561   // special case: [X, INT_MIN) -- not really wrapping around
562   if (Upper.isMinSignedValue())
563     return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
564 
565   if (isFullSet() || isSignWrappedSet()) {
566     return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
567                          APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
568   }
569 
570   return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
571 }
572 
573 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
574   assert(getBitWidth() > DstTySize && "Not a value truncation");
575   if (isEmptySet())
576     return ConstantRange(DstTySize, /*isFullSet=*/false);
577   if (isFullSet())
578     return ConstantRange(DstTySize, /*isFullSet=*/true);
579 
580   APInt MaxValue = APInt::getLowBitsSet(getBitWidth(), DstTySize);
581   APInt MaxBitValue = APInt::getOneBitSet(getBitWidth(), DstTySize);
582 
583   APInt LowerDiv(Lower), UpperDiv(Upper);
584   ConstantRange Union(DstTySize, /*isFullSet=*/false);
585 
586   // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
587   // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
588   // then we do the union with [MaxValue, Upper)
589   if (isWrappedSet()) {
590     // If Upper is greater than Max Value, it covers the whole truncated range.
591     if (Upper.uge(MaxValue))
592       return ConstantRange(DstTySize, /*isFullSet=*/true);
593 
594     Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
595     UpperDiv.setAllBits();
596 
597     // Union covers the MaxValue case, so return if the remaining range is just
598     // MaxValue.
599     if (LowerDiv == UpperDiv)
600       return Union;
601   }
602 
603   // Chop off the most significant bits that are past the destination bitwidth.
604   if (LowerDiv.uge(MaxValue)) {
605     APInt Div(getBitWidth(), 0);
606     APInt::udivrem(LowerDiv, MaxBitValue, Div, LowerDiv);
607     UpperDiv -= MaxBitValue * Div;
608   }
609 
610   if (UpperDiv.ule(MaxValue))
611     return ConstantRange(LowerDiv.trunc(DstTySize),
612                          UpperDiv.trunc(DstTySize)).unionWith(Union);
613 
614   // The truncated value wraps around. Check if we can do better than fullset.
615   UpperDiv -= MaxBitValue;
616   if (UpperDiv.ult(LowerDiv))
617     return ConstantRange(LowerDiv.trunc(DstTySize),
618                          UpperDiv.trunc(DstTySize)).unionWith(Union);
619 
620   return ConstantRange(DstTySize, /*isFullSet=*/true);
621 }
622 
623 ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
624   unsigned SrcTySize = getBitWidth();
625   if (SrcTySize > DstTySize)
626     return truncate(DstTySize);
627   if (SrcTySize < DstTySize)
628     return zeroExtend(DstTySize);
629   return *this;
630 }
631 
632 ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
633   unsigned SrcTySize = getBitWidth();
634   if (SrcTySize > DstTySize)
635     return truncate(DstTySize);
636   if (SrcTySize < DstTySize)
637     return signExtend(DstTySize);
638   return *this;
639 }
640 
641 ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
642                                       const ConstantRange &Other) const {
643   assert(BinOp >= Instruction::BinaryOpsBegin &&
644          BinOp < Instruction::BinaryOpsEnd && "Binary operators only!");
645 
646   switch (BinOp) {
647   case Instruction::Add:
648     return add(Other);
649   case Instruction::Sub:
650     return sub(Other);
651   case Instruction::Mul:
652     return multiply(Other);
653   case Instruction::UDiv:
654     return udiv(Other);
655   case Instruction::Shl:
656     return shl(Other);
657   case Instruction::LShr:
658     return lshr(Other);
659   case Instruction::And:
660     return binaryAnd(Other);
661   case Instruction::Or:
662     return binaryOr(Other);
663   // Note: floating point operations applied to abstract ranges are just
664   // ideal integer operations with a lossy representation
665   case Instruction::FAdd:
666     return add(Other);
667   case Instruction::FSub:
668     return sub(Other);
669   case Instruction::FMul:
670     return multiply(Other);
671   default:
672     // Conservatively return full set.
673     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
674   }
675 }
676 
677 ConstantRange
678 ConstantRange::add(const ConstantRange &Other) const {
679   if (isEmptySet() || Other.isEmptySet())
680     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
681   if (isFullSet() || Other.isFullSet())
682     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
683 
684   APInt NewLower = getLower() + Other.getLower();
685   APInt NewUpper = getUpper() + Other.getUpper() - 1;
686   if (NewLower == NewUpper)
687     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
688 
689   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
690   if (X.isSizeStrictlySmallerThan(*this) ||
691       X.isSizeStrictlySmallerThan(Other))
692     // We've wrapped, therefore, full set.
693     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
694   return X;
695 }
696 
697 ConstantRange ConstantRange::addWithNoSignedWrap(const APInt &Other) const {
698   // Calculate the subset of this range such that "X + Other" is
699   // guaranteed not to wrap (overflow) for all X in this subset.
700   // makeGuaranteedNoWrapRegion will produce an exact NSW range since we are
701   // passing a single element range.
702   auto NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(BinaryOperator::Add,
703                                       ConstantRange(Other),
704                                       OverflowingBinaryOperator::NoSignedWrap);
705   auto NSWConstrainedRange = intersectWith(NSWRange);
706 
707   return NSWConstrainedRange.add(ConstantRange(Other));
708 }
709 
710 ConstantRange
711 ConstantRange::sub(const ConstantRange &Other) const {
712   if (isEmptySet() || Other.isEmptySet())
713     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
714   if (isFullSet() || Other.isFullSet())
715     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
716 
717   APInt NewLower = getLower() - Other.getUpper() + 1;
718   APInt NewUpper = getUpper() - Other.getLower();
719   if (NewLower == NewUpper)
720     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
721 
722   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
723   if (X.isSizeStrictlySmallerThan(*this) ||
724       X.isSizeStrictlySmallerThan(Other))
725     // We've wrapped, therefore, full set.
726     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
727   return X;
728 }
729 
730 ConstantRange
731 ConstantRange::multiply(const ConstantRange &Other) const {
732   // TODO: If either operand is a single element and the multiply is known to
733   // be non-wrapping, round the result min and max value to the appropriate
734   // multiple of that element. If wrapping is possible, at least adjust the
735   // range according to the greatest power-of-two factor of the single element.
736 
737   if (isEmptySet() || Other.isEmptySet())
738     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
739 
740   // Multiplication is signedness-independent. However different ranges can be
741   // obtained depending on how the input ranges are treated. These different
742   // ranges are all conservatively correct, but one might be better than the
743   // other. We calculate two ranges; one treating the inputs as unsigned
744   // and the other signed, then return the smallest of these ranges.
745 
746   // Unsigned range first.
747   APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
748   APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
749   APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
750   APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
751 
752   ConstantRange Result_zext = ConstantRange(this_min * Other_min,
753                                             this_max * Other_max + 1);
754   ConstantRange UR = Result_zext.truncate(getBitWidth());
755 
756   // If the unsigned range doesn't wrap, and isn't negative then it's a range
757   // from one positive number to another which is as good as we can generate.
758   // In this case, skip the extra work of generating signed ranges which aren't
759   // going to be better than this range.
760   if (!UR.isWrappedSet() &&
761       (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
762     return UR;
763 
764   // Now the signed range. Because we could be dealing with negative numbers
765   // here, the lower bound is the smallest of the cartesian product of the
766   // lower and upper ranges; for example:
767   //   [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
768   // Similarly for the upper bound, swapping min for max.
769 
770   this_min = getSignedMin().sext(getBitWidth() * 2);
771   this_max = getSignedMax().sext(getBitWidth() * 2);
772   Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
773   Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
774 
775   auto L = {this_min * Other_min, this_min * Other_max,
776             this_max * Other_min, this_max * Other_max};
777   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
778   ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
779   ConstantRange SR = Result_sext.truncate(getBitWidth());
780 
781   return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
782 }
783 
784 ConstantRange
785 ConstantRange::smax(const ConstantRange &Other) const {
786   // X smax Y is: range(smax(X_smin, Y_smin),
787   //                    smax(X_smax, Y_smax))
788   if (isEmptySet() || Other.isEmptySet())
789     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
790   APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
791   APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
792   if (NewU == NewL)
793     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
794   return ConstantRange(std::move(NewL), std::move(NewU));
795 }
796 
797 ConstantRange
798 ConstantRange::umax(const ConstantRange &Other) const {
799   // X umax Y is: range(umax(X_umin, Y_umin),
800   //                    umax(X_umax, Y_umax))
801   if (isEmptySet() || Other.isEmptySet())
802     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
803   APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
804   APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
805   if (NewU == NewL)
806     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
807   return ConstantRange(std::move(NewL), std::move(NewU));
808 }
809 
810 ConstantRange
811 ConstantRange::smin(const ConstantRange &Other) const {
812   // X smin Y is: range(smin(X_smin, Y_smin),
813   //                    smin(X_smax, Y_smax))
814   if (isEmptySet() || Other.isEmptySet())
815     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
816   APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
817   APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
818   if (NewU == NewL)
819     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
820   return ConstantRange(std::move(NewL), std::move(NewU));
821 }
822 
823 ConstantRange
824 ConstantRange::umin(const ConstantRange &Other) const {
825   // X umin Y is: range(umin(X_umin, Y_umin),
826   //                    umin(X_umax, Y_umax))
827   if (isEmptySet() || Other.isEmptySet())
828     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
829   APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
830   APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
831   if (NewU == NewL)
832     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
833   return ConstantRange(std::move(NewL), std::move(NewU));
834 }
835 
836 ConstantRange
837 ConstantRange::udiv(const ConstantRange &RHS) const {
838   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
839     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
840   if (RHS.isFullSet())
841     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
842 
843   APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
844 
845   APInt RHS_umin = RHS.getUnsignedMin();
846   if (RHS_umin.isNullValue()) {
847     // We want the lowest value in RHS excluding zero. Usually that would be 1
848     // except for a range in the form of [X, 1) in which case it would be X.
849     if (RHS.getUpper() == 1)
850       RHS_umin = RHS.getLower();
851     else
852       RHS_umin = 1;
853   }
854 
855   APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
856 
857   // If the LHS is Full and the RHS is a wrapped interval containing 1 then
858   // this could occur.
859   if (Lower == Upper)
860     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
861 
862   return ConstantRange(std::move(Lower), std::move(Upper));
863 }
864 
865 ConstantRange
866 ConstantRange::binaryAnd(const ConstantRange &Other) const {
867   if (isEmptySet() || Other.isEmptySet())
868     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
869 
870   // TODO: replace this with something less conservative
871 
872   APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
873   if (umin.isAllOnesValue())
874     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
875   return ConstantRange(APInt::getNullValue(getBitWidth()), std::move(umin) + 1);
876 }
877 
878 ConstantRange
879 ConstantRange::binaryOr(const ConstantRange &Other) const {
880   if (isEmptySet() || Other.isEmptySet())
881     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
882 
883   // TODO: replace this with something less conservative
884 
885   APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
886   if (umax.isNullValue())
887     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
888   return ConstantRange(std::move(umax), APInt::getNullValue(getBitWidth()));
889 }
890 
891 ConstantRange
892 ConstantRange::shl(const ConstantRange &Other) const {
893   if (isEmptySet() || Other.isEmptySet())
894     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
895 
896   APInt max = getUnsignedMax();
897   APInt Other_umax = Other.getUnsignedMax();
898 
899   // there's overflow!
900   if (Other_umax.uge(max.countLeadingZeros()))
901     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
902 
903   // FIXME: implement the other tricky cases
904 
905   APInt min = getUnsignedMin();
906   min <<= Other.getUnsignedMin();
907   max <<= Other_umax;
908 
909   return ConstantRange(std::move(min), std::move(max) + 1);
910 }
911 
912 ConstantRange
913 ConstantRange::lshr(const ConstantRange &Other) const {
914   if (isEmptySet() || Other.isEmptySet())
915     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
916 
917   APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
918   APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
919   if (min == max)
920     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
921 
922   return ConstantRange(std::move(min), std::move(max));
923 }
924 
925 ConstantRange ConstantRange::inverse() const {
926   if (isFullSet())
927     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
928   if (isEmptySet())
929     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
930   return ConstantRange(Upper, Lower);
931 }
932 
933 void ConstantRange::print(raw_ostream &OS) const {
934   if (isFullSet())
935     OS << "full-set";
936   else if (isEmptySet())
937     OS << "empty-set";
938   else
939     OS << "[" << Lower << "," << Upper << ")";
940 }
941 
942 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
943 LLVM_DUMP_METHOD void ConstantRange::dump() const {
944   print(dbgs());
945 }
946 #endif
947 
948 ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
949   const unsigned NumRanges = Ranges.getNumOperands() / 2;
950   assert(NumRanges >= 1 && "Must have at least one range!");
951   assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
952 
953   auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
954   auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
955 
956   ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
957 
958   for (unsigned i = 1; i < NumRanges; ++i) {
959     auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
960     auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
961 
962     // Note: unionWith will potentially create a range that contains values not
963     // contained in any of the original N ranges.
964     CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
965   }
966 
967   return CR;
968 }
969