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