1 //===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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):
17 // [F, F) = {} = Empty set
20 // [T, T) = {F, T} = Full set
22 //===----------------------------------------------------------------------===//
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"
32 ConstantRange::ConstantRange(uint32_t BitWidth, bool Full) {
34 Lower = Upper = APInt::getMaxValue(BitWidth);
36 Lower = Upper = APInt::getMinValue(BitWidth);
39 ConstantRange::ConstantRange(APInt V)
40 : Lower(std::move(V)), Upper(Lower + 1) {}
42 ConstantRange::ConstantRange(APInt L, APInt U)
43 : Lower(std::move(L)), Upper(std::move(U)) {
44 assert(Lower.getBitWidth() == Upper.getBitWidth() &&
45 "ConstantRange with unequal bit widths");
46 assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
47 "Lower == Upper, but they aren't min or max value!");
50 ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
51 const ConstantRange &CR) {
55 uint32_t W = CR.getBitWidth();
58 llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
59 case CmpInst::ICMP_EQ:
61 case CmpInst::ICMP_NE:
62 if (CR.isSingleElement())
63 return ConstantRange(CR.getUpper(), CR.getLower());
64 return ConstantRange(W);
65 case CmpInst::ICMP_ULT: {
66 APInt UMax(CR.getUnsignedMax());
67 if (UMax.isMinValue())
68 return ConstantRange(W, /* empty */ false);
69 return ConstantRange(APInt::getMinValue(W), UMax);
71 case CmpInst::ICMP_SLT: {
72 APInt SMax(CR.getSignedMax());
73 if (SMax.isMinSignedValue())
74 return ConstantRange(W, /* empty */ false);
75 return ConstantRange(APInt::getSignedMinValue(W), SMax);
77 case CmpInst::ICMP_ULE: {
78 APInt UMax(CR.getUnsignedMax());
79 if (UMax.isMaxValue())
80 return ConstantRange(W);
81 return ConstantRange(APInt::getMinValue(W), UMax + 1);
83 case CmpInst::ICMP_SLE: {
84 APInt SMax(CR.getSignedMax());
85 if (SMax.isMaxSignedValue())
86 return ConstantRange(W);
87 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
89 case CmpInst::ICMP_UGT: {
90 APInt UMin(CR.getUnsignedMin());
91 if (UMin.isMaxValue())
92 return ConstantRange(W, /* empty */ false);
93 return ConstantRange(UMin + 1, APInt::getNullValue(W));
95 case CmpInst::ICMP_SGT: {
96 APInt SMin(CR.getSignedMin());
97 if (SMin.isMaxSignedValue())
98 return ConstantRange(W, /* empty */ false);
99 return ConstantRange(SMin + 1, APInt::getSignedMinValue(W));
101 case CmpInst::ICMP_UGE: {
102 APInt UMin(CR.getUnsignedMin());
103 if (UMin.isMinValue())
104 return ConstantRange(W);
105 return ConstantRange(UMin, APInt::getNullValue(W));
107 case CmpInst::ICMP_SGE: {
108 APInt SMin(CR.getSignedMin());
109 if (SMin.isMinSignedValue())
110 return ConstantRange(W);
111 return ConstantRange(SMin, APInt::getSignedMinValue(W));
116 ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
117 const ConstantRange &CR) {
118 // Follows from De-Morgan's laws:
120 // ~(~A union ~B) == A intersect B.
122 return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
126 ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
128 // Computes the exact range that is equal to both the constant ranges returned
129 // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
130 // when RHS is a singleton such as an APInt and so the assert is valid.
131 // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
132 // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
134 assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
135 return makeAllowedICmpRegion(Pred, C);
138 bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
140 bool Success = false;
142 if (isFullSet() || isEmptySet()) {
143 Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
144 RHS = APInt(getBitWidth(), 0);
146 } else if (auto *OnlyElt = getSingleElement()) {
147 Pred = CmpInst::ICMP_EQ;
150 } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
151 Pred = CmpInst::ICMP_NE;
152 RHS = *OnlyMissingElt;
154 } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
156 getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
159 } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
161 getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
166 assert((!Success || ConstantRange::makeExactICmpRegion(Pred, RHS) == *this) &&
173 ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
174 const ConstantRange &Other,
175 unsigned NoWrapKind) {
176 typedef OverflowingBinaryOperator OBO;
178 // Computes the intersection of CR0 and CR1. It is different from
179 // intersectWith in that the ConstantRange returned will only contain elements
180 // in both CR0 and CR1 (i.e. SubsetIntersect(X, Y) is a *subset*, proper or
181 // not, of both X and Y).
182 auto SubsetIntersect =
183 [](const ConstantRange &CR0, const ConstantRange &CR1) {
184 return CR0.inverse().unionWith(CR1.inverse()).inverse();
187 assert(BinOp >= Instruction::BinaryOpsBegin &&
188 BinOp < Instruction::BinaryOpsEnd && "Binary operators only!");
190 assert((NoWrapKind == OBO::NoSignedWrap ||
191 NoWrapKind == OBO::NoUnsignedWrap ||
192 NoWrapKind == (OBO::NoUnsignedWrap | OBO::NoSignedWrap)) &&
193 "NoWrapKind invalid!");
195 unsigned BitWidth = Other.getBitWidth();
196 if (BinOp != Instruction::Add)
197 // Conservative answer: empty set
198 return ConstantRange(BitWidth, false);
200 if (auto *C = Other.getSingleElement())
202 // Full set: nothing signed / unsigned wraps when added to 0.
203 return ConstantRange(BitWidth);
205 ConstantRange Result(BitWidth);
207 if (NoWrapKind & OBO::NoUnsignedWrap)
209 SubsetIntersect(Result, ConstantRange(APInt::getNullValue(BitWidth),
210 -Other.getUnsignedMax()));
212 if (NoWrapKind & OBO::NoSignedWrap) {
213 APInt SignedMin = Other.getSignedMin();
214 APInt SignedMax = Other.getSignedMax();
216 if (SignedMax.isStrictlyPositive())
217 Result = SubsetIntersect(
219 ConstantRange(APInt::getSignedMinValue(BitWidth),
220 APInt::getSignedMinValue(BitWidth) - SignedMax));
222 if (SignedMin.isNegative())
223 Result = SubsetIntersect(
224 Result, ConstantRange(APInt::getSignedMinValue(BitWidth) - SignedMin,
225 APInt::getSignedMinValue(BitWidth)));
231 bool ConstantRange::isFullSet() const {
232 return Lower == Upper && Lower.isMaxValue();
235 bool ConstantRange::isEmptySet() const {
236 return Lower == Upper && Lower.isMinValue();
239 bool ConstantRange::isWrappedSet() const {
240 return Lower.ugt(Upper);
243 bool ConstantRange::isSignWrappedSet() const {
244 return contains(APInt::getSignedMaxValue(getBitWidth())) &&
245 contains(APInt::getSignedMinValue(getBitWidth()));
248 APInt ConstantRange::getSetSize() const {
250 APInt Size(getBitWidth()+1, 0);
251 Size.setBit(getBitWidth());
255 // This is also correct for wrapped sets.
256 return (Upper - Lower).zext(getBitWidth()+1);
260 ConstantRange::isSizeStrictlySmallerThanOf(const ConstantRange &Other) const {
261 assert(getBitWidth() == Other.getBitWidth());
264 if (Other.isFullSet())
266 return (Upper - Lower).ult(Other.Upper - Other.Lower);
269 APInt ConstantRange::getUnsignedMax() const {
270 if (isFullSet() || isWrappedSet())
271 return APInt::getMaxValue(getBitWidth());
272 return getUpper() - 1;
275 APInt ConstantRange::getUnsignedMin() const {
276 if (isFullSet() || (isWrappedSet() && getUpper() != 0))
277 return APInt::getMinValue(getBitWidth());
281 APInt ConstantRange::getSignedMax() const {
282 APInt SignedMax(APInt::getSignedMaxValue(getBitWidth()));
283 if (!isWrappedSet()) {
284 APInt UpperMinusOne = getUpper() - 1;
285 if (getLower().sle(UpperMinusOne))
286 return UpperMinusOne;
287 return APInt::getSignedMaxValue(getBitWidth());
289 if (getLower().isNegative() == getUpper().isNegative())
290 return APInt::getSignedMaxValue(getBitWidth());
291 return getUpper() - 1;
294 APInt ConstantRange::getSignedMin() const {
295 if (!isWrappedSet()) {
296 if (getLower().sle(getUpper() - 1))
298 return APInt::getSignedMinValue(getBitWidth());
300 if ((getUpper() - 1).slt(getLower())) {
301 if (!getUpper().isMinSignedValue())
302 return APInt::getSignedMinValue(getBitWidth());
307 bool ConstantRange::contains(const APInt &V) const {
312 return Lower.ule(V) && V.ult(Upper);
313 return Lower.ule(V) || V.ult(Upper);
316 bool ConstantRange::contains(const ConstantRange &Other) const {
317 if (isFullSet() || Other.isEmptySet()) return true;
318 if (isEmptySet() || Other.isFullSet()) return false;
320 if (!isWrappedSet()) {
321 if (Other.isWrappedSet())
324 return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
327 if (!Other.isWrappedSet())
328 return Other.getUpper().ule(Upper) ||
329 Lower.ule(Other.getLower());
331 return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
334 ConstantRange ConstantRange::subtract(const APInt &Val) const {
335 assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
336 // If the set is empty or full, don't modify the endpoints.
339 return ConstantRange(Lower - Val, Upper - Val);
342 ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
343 return intersectWith(CR.inverse());
346 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR) const {
347 assert(getBitWidth() == CR.getBitWidth() &&
348 "ConstantRange types don't agree!");
350 // Handle common cases.
351 if ( isEmptySet() || CR.isFullSet()) return *this;
352 if (CR.isEmptySet() || isFullSet()) return CR;
354 if (!isWrappedSet() && CR.isWrappedSet())
355 return CR.intersectWith(*this);
357 if (!isWrappedSet() && !CR.isWrappedSet()) {
358 if (Lower.ult(CR.Lower)) {
359 if (Upper.ule(CR.Lower))
360 return ConstantRange(getBitWidth(), false);
362 if (Upper.ult(CR.Upper))
363 return ConstantRange(CR.Lower, Upper);
367 if (Upper.ult(CR.Upper))
370 if (Lower.ult(CR.Upper))
371 return ConstantRange(Lower, CR.Upper);
373 return ConstantRange(getBitWidth(), false);
376 if (isWrappedSet() && !CR.isWrappedSet()) {
377 if (CR.Lower.ult(Upper)) {
378 if (CR.Upper.ult(Upper))
381 if (CR.Upper.ule(Lower))
382 return ConstantRange(CR.Lower, Upper);
384 if (isSizeStrictlySmallerThanOf(CR))
388 if (CR.Lower.ult(Lower)) {
389 if (CR.Upper.ule(Lower))
390 return ConstantRange(getBitWidth(), false);
392 return ConstantRange(Lower, CR.Upper);
397 if (CR.Upper.ult(Upper)) {
398 if (CR.Lower.ult(Upper)) {
399 if (isSizeStrictlySmallerThanOf(CR))
404 if (CR.Lower.ult(Lower))
405 return ConstantRange(Lower, CR.Upper);
409 if (CR.Upper.ule(Lower)) {
410 if (CR.Lower.ult(Lower))
413 return ConstantRange(CR.Lower, Upper);
415 if (isSizeStrictlySmallerThanOf(CR))
420 ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const {
421 assert(getBitWidth() == CR.getBitWidth() &&
422 "ConstantRange types don't agree!");
424 if ( isFullSet() || CR.isEmptySet()) return *this;
425 if (CR.isFullSet() || isEmptySet()) return CR;
427 if (!isWrappedSet() && CR.isWrappedSet()) return CR.unionWith(*this);
429 if (!isWrappedSet() && !CR.isWrappedSet()) {
430 if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower)) {
431 // If the two ranges are disjoint, find the smaller gap and bridge it.
432 APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
434 return ConstantRange(Lower, CR.Upper);
435 return ConstantRange(CR.Lower, Upper);
438 APInt L = Lower, U = Upper;
441 if ((CR.Upper - 1).ugt(U - 1))
444 if (L == 0 && U == 0)
445 return ConstantRange(getBitWidth());
447 return ConstantRange(L, U);
450 if (!CR.isWrappedSet()) {
451 // ------U L----- and ------U L----- : this
453 if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
456 // ------U L----- : this
458 if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
459 return ConstantRange(getBitWidth());
461 // ----U L---- : this
464 if (Upper.ule(CR.Lower) && CR.Upper.ule(Lower)) {
465 APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
467 return ConstantRange(Lower, CR.Upper);
468 return ConstantRange(CR.Lower, Upper);
471 // ----U L----- : this
473 if (Upper.ult(CR.Lower) && Lower.ult(CR.Upper))
474 return ConstantRange(CR.Lower, Upper);
476 // ------U L---- : this
478 assert(CR.Lower.ult(Upper) && CR.Upper.ult(Lower) &&
479 "ConstantRange::unionWith missed a case with one range wrapped");
480 return ConstantRange(Lower, CR.Upper);
483 // ------U L---- and ------U L---- : this
484 // -U L----------- and ------------U L : CR
485 if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
486 return ConstantRange(getBitWidth());
488 APInt L = Lower, U = Upper;
494 return ConstantRange(L, U);
497 ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
498 uint32_t ResultBitWidth) const {
501 llvm_unreachable("unsupported cast type");
502 case Instruction::Trunc:
503 return truncate(ResultBitWidth);
504 case Instruction::SExt:
505 return signExtend(ResultBitWidth);
506 case Instruction::ZExt:
507 return zeroExtend(ResultBitWidth);
508 case Instruction::BitCast:
510 case Instruction::FPToUI:
511 case Instruction::FPToSI:
512 if (getBitWidth() == ResultBitWidth)
515 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
516 case Instruction::UIToFP: {
517 // TODO: use input range if available
518 auto BW = getBitWidth();
519 APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
520 APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
521 return ConstantRange(Min, Max);
523 case Instruction::SIToFP: {
524 // TODO: use input range if available
525 auto BW = getBitWidth();
526 APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
527 APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
528 return ConstantRange(SMin, SMax);
530 case Instruction::FPTrunc:
531 case Instruction::FPExt:
532 case Instruction::IntToPtr:
533 case Instruction::PtrToInt:
534 case Instruction::AddrSpaceCast:
535 // Conservatively return full set.
536 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
540 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
541 if (isEmptySet()) return ConstantRange(DstTySize, /*isFullSet=*/false);
543 unsigned SrcTySize = getBitWidth();
544 assert(SrcTySize < DstTySize && "Not a value extension");
545 if (isFullSet() || isWrappedSet()) {
546 // Change into [0, 1 << src bit width)
547 APInt LowerExt(DstTySize, 0);
548 if (!Upper) // special case: [X, 0) -- not really wrapping around
549 LowerExt = Lower.zext(DstTySize);
550 return ConstantRange(LowerExt, APInt::getOneBitSet(DstTySize, SrcTySize));
553 return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
556 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
557 if (isEmptySet()) return ConstantRange(DstTySize, /*isFullSet=*/false);
559 unsigned SrcTySize = getBitWidth();
560 assert(SrcTySize < DstTySize && "Not a value extension");
562 // special case: [X, INT_MIN) -- not really wrapping around
563 if (Upper.isMinSignedValue())
564 return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
566 if (isFullSet() || isSignWrappedSet()) {
567 return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
568 APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
571 return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
574 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
575 assert(getBitWidth() > DstTySize && "Not a value truncation");
577 return ConstantRange(DstTySize, /*isFullSet=*/false);
579 return ConstantRange(DstTySize, /*isFullSet=*/true);
581 APInt MaxValue = APInt::getMaxValue(DstTySize).zext(getBitWidth());
582 APInt MaxBitValue(getBitWidth(), 0);
583 MaxBitValue.setBit(DstTySize);
585 APInt LowerDiv(Lower), UpperDiv(Upper);
586 ConstantRange Union(DstTySize, /*isFullSet=*/false);
588 // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
589 // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
590 // then we do the union with [MaxValue, Upper)
591 if (isWrappedSet()) {
592 // If Upper is greater than Max Value, it covers the whole truncated range.
593 if (Upper.uge(MaxValue))
594 return ConstantRange(DstTySize, /*isFullSet=*/true);
596 Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
597 UpperDiv = APInt::getMaxValue(getBitWidth());
599 // Union covers the MaxValue case, so return if the remaining range is just
601 if (LowerDiv == UpperDiv)
605 // Chop off the most significant bits that are past the destination bitwidth.
606 if (LowerDiv.uge(MaxValue)) {
607 APInt Div(getBitWidth(), 0);
608 APInt::udivrem(LowerDiv, MaxBitValue, Div, LowerDiv);
609 UpperDiv = UpperDiv - MaxBitValue * Div;
612 if (UpperDiv.ule(MaxValue))
613 return ConstantRange(LowerDiv.trunc(DstTySize),
614 UpperDiv.trunc(DstTySize)).unionWith(Union);
616 // The truncated value wraps around. Check if we can do better than fullset.
617 APInt UpperModulo = UpperDiv - MaxBitValue;
618 if (UpperModulo.ult(LowerDiv))
619 return ConstantRange(LowerDiv.trunc(DstTySize),
620 UpperModulo.trunc(DstTySize)).unionWith(Union);
622 return ConstantRange(DstTySize, /*isFullSet=*/true);
625 ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
626 unsigned SrcTySize = getBitWidth();
627 if (SrcTySize > DstTySize)
628 return truncate(DstTySize);
629 if (SrcTySize < DstTySize)
630 return zeroExtend(DstTySize);
634 ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
635 unsigned SrcTySize = getBitWidth();
636 if (SrcTySize > DstTySize)
637 return truncate(DstTySize);
638 if (SrcTySize < DstTySize)
639 return signExtend(DstTySize);
643 ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
644 const ConstantRange &Other) const {
645 assert(BinOp >= Instruction::BinaryOpsBegin &&
646 BinOp < Instruction::BinaryOpsEnd && "Binary operators only!");
649 case Instruction::Add:
651 case Instruction::Sub:
653 case Instruction::Mul:
654 return multiply(Other);
655 case Instruction::UDiv:
657 case Instruction::Shl:
659 case Instruction::LShr:
661 case Instruction::And:
662 return binaryAnd(Other);
663 case Instruction::Or:
664 return binaryOr(Other);
665 // Note: floating point operations applied to abstract ranges are just
666 // ideal integer operations with a lossy representation
667 case Instruction::FAdd:
669 case Instruction::FSub:
671 case Instruction::FMul:
672 return multiply(Other);
674 // Conservatively return full set.
675 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
680 ConstantRange::add(const ConstantRange &Other) const {
681 if (isEmptySet() || Other.isEmptySet())
682 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
683 if (isFullSet() || Other.isFullSet())
684 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
686 APInt NewLower = getLower() + Other.getLower();
687 APInt NewUpper = getUpper() + Other.getUpper() - 1;
688 if (NewLower == NewUpper)
689 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
691 ConstantRange X = ConstantRange(NewLower, NewUpper);
692 if (X.isSizeStrictlySmallerThanOf(*this) ||
693 X.isSizeStrictlySmallerThanOf(Other))
694 // We've wrapped, therefore, full set.
695 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
699 ConstantRange ConstantRange::addWithNoSignedWrap(const APInt &Other) const {
700 // Calculate the subset of this range such that "X + Other" is
701 // guaranteed not to wrap (overflow) for all X in this subset.
702 // makeGuaranteedNoWrapRegion will produce an exact NSW range since we are
703 // passing a single element range.
704 auto NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(BinaryOperator::Add,
705 ConstantRange(Other),
706 OverflowingBinaryOperator::NoSignedWrap);
707 auto NSWConstrainedRange = intersectWith(NSWRange);
709 return NSWConstrainedRange.add(ConstantRange(Other));
713 ConstantRange::sub(const ConstantRange &Other) const {
714 if (isEmptySet() || Other.isEmptySet())
715 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
716 if (isFullSet() || Other.isFullSet())
717 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
719 APInt NewLower = getLower() - Other.getUpper() + 1;
720 APInt NewUpper = getUpper() - Other.getLower();
721 if (NewLower == NewUpper)
722 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
724 ConstantRange X = ConstantRange(NewLower, NewUpper);
725 if (X.isSizeStrictlySmallerThanOf(*this) ||
726 X.isSizeStrictlySmallerThanOf(Other))
727 // We've wrapped, therefore, full set.
728 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
733 ConstantRange::multiply(const ConstantRange &Other) const {
734 // TODO: If either operand is a single element and the multiply is known to
735 // be non-wrapping, round the result min and max value to the appropriate
736 // multiple of that element. If wrapping is possible, at least adjust the
737 // range according to the greatest power-of-two factor of the single element.
739 if (isEmptySet() || Other.isEmptySet())
740 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
742 // Multiplication is signedness-independent. However different ranges can be
743 // obtained depending on how the input ranges are treated. These different
744 // ranges are all conservatively correct, but one might be better than the
745 // other. We calculate two ranges; one treating the inputs as unsigned
746 // and the other signed, then return the smallest of these ranges.
748 // Unsigned range first.
749 APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
750 APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
751 APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
752 APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
754 ConstantRange Result_zext = ConstantRange(this_min * Other_min,
755 this_max * Other_max + 1);
756 ConstantRange UR = Result_zext.truncate(getBitWidth());
758 // If the unsigned range doesn't wrap, and isn't negative then it's a range
759 // from one positive number to another which is as good as we can generate.
760 // In this case, skip the extra work of generating signed ranges which aren't
761 // going to be better than this range.
762 if (!UR.isWrappedSet() && UR.getLower().isNonNegative())
765 // Now the signed range. Because we could be dealing with negative numbers
766 // here, the lower bound is the smallest of the cartesian product of the
767 // lower and upper ranges; for example:
768 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
769 // Similarly for the upper bound, swapping min for max.
771 this_min = getSignedMin().sext(getBitWidth() * 2);
772 this_max = getSignedMax().sext(getBitWidth() * 2);
773 Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
774 Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
776 auto L = {this_min * Other_min, this_min * Other_max,
777 this_max * Other_min, this_max * Other_max};
778 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
779 ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
780 ConstantRange SR = Result_sext.truncate(getBitWidth());
782 return UR.isSizeStrictlySmallerThanOf(SR) ? UR : SR;
786 ConstantRange::smax(const ConstantRange &Other) const {
787 // X smax Y is: range(smax(X_smin, Y_smin),
788 // smax(X_smax, Y_smax))
789 if (isEmptySet() || Other.isEmptySet())
790 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
791 APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
792 APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
794 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
795 return ConstantRange(NewL, NewU);
799 ConstantRange::umax(const ConstantRange &Other) const {
800 // X umax Y is: range(umax(X_umin, Y_umin),
801 // umax(X_umax, Y_umax))
802 if (isEmptySet() || Other.isEmptySet())
803 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
804 APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
805 APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
807 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
808 return ConstantRange(NewL, NewU);
812 ConstantRange::smin(const ConstantRange &Other) const {
813 // X smin Y is: range(smin(X_smin, Y_smin),
814 // smin(X_smax, Y_smax))
815 if (isEmptySet() || Other.isEmptySet())
816 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
817 APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
818 APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
820 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
821 return ConstantRange(NewL, NewU);
825 ConstantRange::umin(const ConstantRange &Other) const {
826 // X umin Y is: range(umin(X_umin, Y_umin),
827 // umin(X_umax, Y_umax))
828 if (isEmptySet() || Other.isEmptySet())
829 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
830 APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
831 APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
833 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
834 return ConstantRange(NewL, NewU);
838 ConstantRange::udiv(const ConstantRange &RHS) const {
839 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax() == 0)
840 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
842 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
844 APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
846 APInt RHS_umin = RHS.getUnsignedMin();
848 // We want the lowest value in RHS excluding zero. Usually that would be 1
849 // except for a range in the form of [X, 1) in which case it would be X.
850 if (RHS.getUpper() == 1)
851 RHS_umin = RHS.getLower();
853 RHS_umin = APInt(getBitWidth(), 1);
856 APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
858 // If the LHS is Full and the RHS is a wrapped interval containing 1 then
861 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
863 return ConstantRange(Lower, Upper);
867 ConstantRange::binaryAnd(const ConstantRange &Other) const {
868 if (isEmptySet() || Other.isEmptySet())
869 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
871 // TODO: replace this with something less conservative
873 APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
874 if (umin.isAllOnesValue())
875 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
876 return ConstantRange(APInt::getNullValue(getBitWidth()), umin + 1);
880 ConstantRange::binaryOr(const ConstantRange &Other) const {
881 if (isEmptySet() || Other.isEmptySet())
882 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
884 // TODO: replace this with something less conservative
886 APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
887 if (umax.isMinValue())
888 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
889 return ConstantRange(umax, APInt::getNullValue(getBitWidth()));
893 ConstantRange::shl(const ConstantRange &Other) const {
894 if (isEmptySet() || Other.isEmptySet())
895 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
897 APInt min = getUnsignedMin().shl(Other.getUnsignedMin());
898 APInt max = getUnsignedMax().shl(Other.getUnsignedMax());
900 // there's no overflow!
901 APInt Zeros(getBitWidth(), getUnsignedMax().countLeadingZeros());
902 if (Zeros.ugt(Other.getUnsignedMax()))
903 return ConstantRange(min, max + 1);
905 // FIXME: implement the other tricky cases
906 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
910 ConstantRange::lshr(const ConstantRange &Other) const {
911 if (isEmptySet() || Other.isEmptySet())
912 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
914 APInt max = getUnsignedMax().lshr(Other.getUnsignedMin());
915 APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
917 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
919 return ConstantRange(min, max + 1);
922 ConstantRange ConstantRange::inverse() const {
924 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
926 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
927 return ConstantRange(Upper, Lower);
930 void ConstantRange::print(raw_ostream &OS) const {
933 else if (isEmptySet())
936 OS << "[" << Lower << "," << Upper << ")";
939 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
940 LLVM_DUMP_METHOD void ConstantRange::dump() const {
945 ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
946 const unsigned NumRanges = Ranges.getNumOperands() / 2;
947 assert(NumRanges >= 1 && "Must have at least one range!");
948 assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
950 auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
951 auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
953 ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
955 for (unsigned i = 1; i < NumRanges; ++i) {
956 auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
957 auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
959 // Note: unionWith will potentially create a range that contains values not
960 // contained in any of the original N ranges.
961 CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));