Path: blob/main/contrib/llvm-project/llvm/lib/IR/ConstantRange.cpp
35234 views
//===- ConstantRange.cpp - ConstantRange implementation -------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// Represent a range of possible values that may occur when the program is run9// for an integral value. This keeps track of a lower and upper bound for the10// constant, which MAY wrap around the end of the numeric range. To do this, it11// keeps track of a [lower, upper) bound, which specifies an interval just like12// STL iterators. When used with boolean values, the following are important13// ranges (other integral ranges use min/max values for special range values):14//15// [F, F) = {} = Empty set16// [T, F) = {T}17// [F, T) = {F}18// [T, T) = {F, T} = Full set19//20//===----------------------------------------------------------------------===//2122#include "llvm/ADT/APInt.h"23#include "llvm/Config/llvm-config.h"24#include "llvm/IR/ConstantRange.h"25#include "llvm/IR/Constants.h"26#include "llvm/IR/InstrTypes.h"27#include "llvm/IR/Instruction.h"28#include "llvm/IR/Intrinsics.h"29#include "llvm/IR/Metadata.h"30#include "llvm/IR/Operator.h"31#include "llvm/Support/Compiler.h"32#include "llvm/Support/Debug.h"33#include "llvm/Support/ErrorHandling.h"34#include "llvm/Support/KnownBits.h"35#include "llvm/Support/raw_ostream.h"36#include <algorithm>37#include <cassert>38#include <cstdint>39#include <optional>4041using namespace llvm;4243ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)44: Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),45Upper(Lower) {}4647ConstantRange::ConstantRange(APInt V)48: Lower(std::move(V)), Upper(Lower + 1) {}4950ConstantRange::ConstantRange(APInt L, APInt U)51: Lower(std::move(L)), Upper(std::move(U)) {52assert(Lower.getBitWidth() == Upper.getBitWidth() &&53"ConstantRange with unequal bit widths");54assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&55"Lower == Upper, but they aren't min or max value!");56}5758ConstantRange ConstantRange::fromKnownBits(const KnownBits &Known,59bool IsSigned) {60if (Known.hasConflict())61return getEmpty(Known.getBitWidth());62if (Known.isUnknown())63return getFull(Known.getBitWidth());6465// For unsigned ranges, or signed ranges with known sign bit, create a simple66// range between the smallest and largest possible value.67if (!IsSigned || Known.isNegative() || Known.isNonNegative())68return ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1);6970// If we don't know the sign bit, pick the lower bound as a negative number71// and the upper bound as a non-negative one.72APInt Lower = Known.getMinValue(), Upper = Known.getMaxValue();73Lower.setSignBit();74Upper.clearSignBit();75return ConstantRange(Lower, Upper + 1);76}7778KnownBits ConstantRange::toKnownBits() const {79// TODO: We could return conflicting known bits here, but consumers are80// likely not prepared for that.81if (isEmptySet())82return KnownBits(getBitWidth());8384// We can only retain the top bits that are the same between min and max.85APInt Min = getUnsignedMin();86APInt Max = getUnsignedMax();87KnownBits Known = KnownBits::makeConstant(Min);88if (std::optional<unsigned> DifferentBit =89APIntOps::GetMostSignificantDifferentBit(Min, Max)) {90Known.Zero.clearLowBits(*DifferentBit + 1);91Known.One.clearLowBits(*DifferentBit + 1);92}93return Known;94}9596ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,97const ConstantRange &CR) {98if (CR.isEmptySet())99return CR;100101uint32_t W = CR.getBitWidth();102switch (Pred) {103default:104llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");105case CmpInst::ICMP_EQ:106return CR;107case CmpInst::ICMP_NE:108if (CR.isSingleElement())109return ConstantRange(CR.getUpper(), CR.getLower());110return getFull(W);111case CmpInst::ICMP_ULT: {112APInt UMax(CR.getUnsignedMax());113if (UMax.isMinValue())114return getEmpty(W);115return ConstantRange(APInt::getMinValue(W), std::move(UMax));116}117case CmpInst::ICMP_SLT: {118APInt SMax(CR.getSignedMax());119if (SMax.isMinSignedValue())120return getEmpty(W);121return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));122}123case CmpInst::ICMP_ULE:124return getNonEmpty(APInt::getMinValue(W), CR.getUnsignedMax() + 1);125case CmpInst::ICMP_SLE:126return getNonEmpty(APInt::getSignedMinValue(W), CR.getSignedMax() + 1);127case CmpInst::ICMP_UGT: {128APInt UMin(CR.getUnsignedMin());129if (UMin.isMaxValue())130return getEmpty(W);131return ConstantRange(std::move(UMin) + 1, APInt::getZero(W));132}133case CmpInst::ICMP_SGT: {134APInt SMin(CR.getSignedMin());135if (SMin.isMaxSignedValue())136return getEmpty(W);137return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));138}139case CmpInst::ICMP_UGE:140return getNonEmpty(CR.getUnsignedMin(), APInt::getZero(W));141case CmpInst::ICMP_SGE:142return getNonEmpty(CR.getSignedMin(), APInt::getSignedMinValue(W));143}144}145146ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,147const ConstantRange &CR) {148// Follows from De-Morgan's laws:149//150// ~(~A union ~B) == A intersect B.151//152return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)153.inverse();154}155156ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,157const APInt &C) {158// Computes the exact range that is equal to both the constant ranges returned159// by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true160// when RHS is a singleton such as an APInt and so the assert is valid.161// However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion162// returns [0,4) but makeSatisfyICmpRegion returns [0,2).163//164assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));165return makeAllowedICmpRegion(Pred, C);166}167168bool ConstantRange::areInsensitiveToSignednessOfICmpPredicate(169const ConstantRange &CR1, const ConstantRange &CR2) {170if (CR1.isEmptySet() || CR2.isEmptySet())171return true;172173return (CR1.isAllNonNegative() && CR2.isAllNonNegative()) ||174(CR1.isAllNegative() && CR2.isAllNegative());175}176177bool ConstantRange::areInsensitiveToSignednessOfInvertedICmpPredicate(178const ConstantRange &CR1, const ConstantRange &CR2) {179if (CR1.isEmptySet() || CR2.isEmptySet())180return true;181182return (CR1.isAllNonNegative() && CR2.isAllNegative()) ||183(CR1.isAllNegative() && CR2.isAllNonNegative());184}185186CmpInst::Predicate ConstantRange::getEquivalentPredWithFlippedSignedness(187CmpInst::Predicate Pred, const ConstantRange &CR1,188const ConstantRange &CR2) {189assert(CmpInst::isIntPredicate(Pred) && CmpInst::isRelational(Pred) &&190"Only for relational integer predicates!");191192CmpInst::Predicate FlippedSignednessPred =193CmpInst::getFlippedSignednessPredicate(Pred);194195if (areInsensitiveToSignednessOfICmpPredicate(CR1, CR2))196return FlippedSignednessPred;197198if (areInsensitiveToSignednessOfInvertedICmpPredicate(CR1, CR2))199return CmpInst::getInversePredicate(FlippedSignednessPred);200201return CmpInst::Predicate::BAD_ICMP_PREDICATE;202}203204void ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,205APInt &RHS, APInt &Offset) const {206Offset = APInt(getBitWidth(), 0);207if (isFullSet() || isEmptySet()) {208Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;209RHS = APInt(getBitWidth(), 0);210} else if (auto *OnlyElt = getSingleElement()) {211Pred = CmpInst::ICMP_EQ;212RHS = *OnlyElt;213} else if (auto *OnlyMissingElt = getSingleMissingElement()) {214Pred = CmpInst::ICMP_NE;215RHS = *OnlyMissingElt;216} else if (getLower().isMinSignedValue() || getLower().isMinValue()) {217Pred =218getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;219RHS = getUpper();220} else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {221Pred =222getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;223RHS = getLower();224} else {225Pred = CmpInst::ICMP_ULT;226RHS = getUpper() - getLower();227Offset = -getLower();228}229230assert(ConstantRange::makeExactICmpRegion(Pred, RHS) == add(Offset) &&231"Bad result!");232}233234bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,235APInt &RHS) const {236APInt Offset;237getEquivalentICmp(Pred, RHS, Offset);238return Offset.isZero();239}240241bool ConstantRange::icmp(CmpInst::Predicate Pred,242const ConstantRange &Other) const {243if (isEmptySet() || Other.isEmptySet())244return true;245246switch (Pred) {247case CmpInst::ICMP_EQ:248if (const APInt *L = getSingleElement())249if (const APInt *R = Other.getSingleElement())250return *L == *R;251return false;252case CmpInst::ICMP_NE:253return inverse().contains(Other);254case CmpInst::ICMP_ULT:255return getUnsignedMax().ult(Other.getUnsignedMin());256case CmpInst::ICMP_ULE:257return getUnsignedMax().ule(Other.getUnsignedMin());258case CmpInst::ICMP_UGT:259return getUnsignedMin().ugt(Other.getUnsignedMax());260case CmpInst::ICMP_UGE:261return getUnsignedMin().uge(Other.getUnsignedMax());262case CmpInst::ICMP_SLT:263return getSignedMax().slt(Other.getSignedMin());264case CmpInst::ICMP_SLE:265return getSignedMax().sle(Other.getSignedMin());266case CmpInst::ICMP_SGT:267return getSignedMin().sgt(Other.getSignedMax());268case CmpInst::ICMP_SGE:269return getSignedMin().sge(Other.getSignedMax());270default:271llvm_unreachable("Invalid ICmp predicate");272}273}274275/// Exact mul nuw region for single element RHS.276static ConstantRange makeExactMulNUWRegion(const APInt &V) {277unsigned BitWidth = V.getBitWidth();278if (V == 0)279return ConstantRange::getFull(V.getBitWidth());280281return ConstantRange::getNonEmpty(282APIntOps::RoundingUDiv(APInt::getMinValue(BitWidth), V,283APInt::Rounding::UP),284APIntOps::RoundingUDiv(APInt::getMaxValue(BitWidth), V,285APInt::Rounding::DOWN) + 1);286}287288/// Exact mul nsw region for single element RHS.289static ConstantRange makeExactMulNSWRegion(const APInt &V) {290// Handle 0 and -1 separately to avoid division by zero or overflow.291unsigned BitWidth = V.getBitWidth();292if (V == 0)293return ConstantRange::getFull(BitWidth);294295APInt MinValue = APInt::getSignedMinValue(BitWidth);296APInt MaxValue = APInt::getSignedMaxValue(BitWidth);297// e.g. Returning [-127, 127], represented as [-127, -128).298if (V.isAllOnes())299return ConstantRange(-MaxValue, MinValue);300301APInt Lower, Upper;302if (V.isNegative()) {303Lower = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::UP);304Upper = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::DOWN);305} else {306Lower = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::UP);307Upper = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::DOWN);308}309return ConstantRange::getNonEmpty(Lower, Upper + 1);310}311312ConstantRange313ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,314const ConstantRange &Other,315unsigned NoWrapKind) {316using OBO = OverflowingBinaryOperator;317318assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");319320assert((NoWrapKind == OBO::NoSignedWrap ||321NoWrapKind == OBO::NoUnsignedWrap) &&322"NoWrapKind invalid!");323324bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;325unsigned BitWidth = Other.getBitWidth();326327switch (BinOp) {328default:329llvm_unreachable("Unsupported binary op");330331case Instruction::Add: {332if (Unsigned)333return getNonEmpty(APInt::getZero(BitWidth), -Other.getUnsignedMax());334335APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);336APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();337return getNonEmpty(338SMin.isNegative() ? SignedMinVal - SMin : SignedMinVal,339SMax.isStrictlyPositive() ? SignedMinVal - SMax : SignedMinVal);340}341342case Instruction::Sub: {343if (Unsigned)344return getNonEmpty(Other.getUnsignedMax(), APInt::getMinValue(BitWidth));345346APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);347APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();348return getNonEmpty(349SMax.isStrictlyPositive() ? SignedMinVal + SMax : SignedMinVal,350SMin.isNegative() ? SignedMinVal + SMin : SignedMinVal);351}352353case Instruction::Mul:354if (Unsigned)355return makeExactMulNUWRegion(Other.getUnsignedMax());356357// Avoid one makeExactMulNSWRegion() call for the common case of constants.358if (const APInt *C = Other.getSingleElement())359return makeExactMulNSWRegion(*C);360361return makeExactMulNSWRegion(Other.getSignedMin())362.intersectWith(makeExactMulNSWRegion(Other.getSignedMax()));363364case Instruction::Shl: {365// For given range of shift amounts, if we ignore all illegal shift amounts366// (that always produce poison), what shift amount range is left?367ConstantRange ShAmt = Other.intersectWith(368ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, (BitWidth - 1) + 1)));369if (ShAmt.isEmptySet()) {370// If the entire range of shift amounts is already poison-producing,371// then we can freely add more poison-producing flags ontop of that.372return getFull(BitWidth);373}374// There are some legal shift amounts, we can compute conservatively-correct375// range of no-wrap inputs. Note that by now we have clamped the ShAmtUMax376// to be at most bitwidth-1, which results in most conservative range.377APInt ShAmtUMax = ShAmt.getUnsignedMax();378if (Unsigned)379return getNonEmpty(APInt::getZero(BitWidth),380APInt::getMaxValue(BitWidth).lshr(ShAmtUMax) + 1);381return getNonEmpty(APInt::getSignedMinValue(BitWidth).ashr(ShAmtUMax),382APInt::getSignedMaxValue(BitWidth).ashr(ShAmtUMax) + 1);383}384}385}386387ConstantRange ConstantRange::makeExactNoWrapRegion(Instruction::BinaryOps BinOp,388const APInt &Other,389unsigned NoWrapKind) {390// makeGuaranteedNoWrapRegion() is exact for single-element ranges, as391// "for all" and "for any" coincide in this case.392return makeGuaranteedNoWrapRegion(BinOp, ConstantRange(Other), NoWrapKind);393}394395ConstantRange ConstantRange::makeMaskNotEqualRange(const APInt &Mask,396const APInt &C) {397unsigned BitWidth = Mask.getBitWidth();398399if ((Mask & C) != C)400return getFull(BitWidth);401402if (Mask.isZero())403return getEmpty(BitWidth);404405// If (Val & Mask) != C, constrained to the non-equality being406// satisfiable, then the value must be larger than the lowest set bit of407// Mask, offset by constant C.408return ConstantRange::getNonEmpty(409APInt::getOneBitSet(BitWidth, Mask.countr_zero()) + C, C);410}411412bool ConstantRange::isFullSet() const {413return Lower == Upper && Lower.isMaxValue();414}415416bool ConstantRange::isEmptySet() const {417return Lower == Upper && Lower.isMinValue();418}419420bool ConstantRange::isWrappedSet() const {421return Lower.ugt(Upper) && !Upper.isZero();422}423424bool ConstantRange::isUpperWrapped() const {425return Lower.ugt(Upper);426}427428bool ConstantRange::isSignWrappedSet() const {429return Lower.sgt(Upper) && !Upper.isMinSignedValue();430}431432bool ConstantRange::isUpperSignWrapped() const {433return Lower.sgt(Upper);434}435436bool437ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {438assert(getBitWidth() == Other.getBitWidth());439if (isFullSet())440return false;441if (Other.isFullSet())442return true;443return (Upper - Lower).ult(Other.Upper - Other.Lower);444}445446bool447ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {448// If this a full set, we need special handling to avoid needing an extra bit449// to represent the size.450if (isFullSet())451return MaxSize == 0 || APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);452453return (Upper - Lower).ugt(MaxSize);454}455456bool ConstantRange::isAllNegative() const {457// Empty set is all negative, full set is not.458if (isEmptySet())459return true;460if (isFullSet())461return false;462463return !isUpperSignWrapped() && !Upper.isStrictlyPositive();464}465466bool ConstantRange::isAllNonNegative() const {467// Empty and full set are automatically treated correctly.468return !isSignWrappedSet() && Lower.isNonNegative();469}470471bool ConstantRange::isAllPositive() const {472// Empty set is all positive, full set is not.473if (isEmptySet())474return true;475if (isFullSet())476return false;477478return !isSignWrappedSet() && Lower.isStrictlyPositive();479}480481APInt ConstantRange::getUnsignedMax() const {482if (isFullSet() || isUpperWrapped())483return APInt::getMaxValue(getBitWidth());484return getUpper() - 1;485}486487APInt ConstantRange::getUnsignedMin() const {488if (isFullSet() || isWrappedSet())489return APInt::getMinValue(getBitWidth());490return getLower();491}492493APInt ConstantRange::getSignedMax() const {494if (isFullSet() || isUpperSignWrapped())495return APInt::getSignedMaxValue(getBitWidth());496return getUpper() - 1;497}498499APInt ConstantRange::getSignedMin() const {500if (isFullSet() || isSignWrappedSet())501return APInt::getSignedMinValue(getBitWidth());502return getLower();503}504505bool ConstantRange::contains(const APInt &V) const {506if (Lower == Upper)507return isFullSet();508509if (!isUpperWrapped())510return Lower.ule(V) && V.ult(Upper);511return Lower.ule(V) || V.ult(Upper);512}513514bool ConstantRange::contains(const ConstantRange &Other) const {515if (isFullSet() || Other.isEmptySet()) return true;516if (isEmptySet() || Other.isFullSet()) return false;517518if (!isUpperWrapped()) {519if (Other.isUpperWrapped())520return false;521522return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);523}524525if (!Other.isUpperWrapped())526return Other.getUpper().ule(Upper) ||527Lower.ule(Other.getLower());528529return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());530}531532unsigned ConstantRange::getActiveBits() const {533if (isEmptySet())534return 0;535536return getUnsignedMax().getActiveBits();537}538539unsigned ConstantRange::getMinSignedBits() const {540if (isEmptySet())541return 0;542543return std::max(getSignedMin().getSignificantBits(),544getSignedMax().getSignificantBits());545}546547ConstantRange ConstantRange::subtract(const APInt &Val) const {548assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");549// If the set is empty or full, don't modify the endpoints.550if (Lower == Upper)551return *this;552return ConstantRange(Lower - Val, Upper - Val);553}554555ConstantRange ConstantRange::difference(const ConstantRange &CR) const {556return intersectWith(CR.inverse());557}558559static ConstantRange getPreferredRange(560const ConstantRange &CR1, const ConstantRange &CR2,561ConstantRange::PreferredRangeType Type) {562if (Type == ConstantRange::Unsigned) {563if (!CR1.isWrappedSet() && CR2.isWrappedSet())564return CR1;565if (CR1.isWrappedSet() && !CR2.isWrappedSet())566return CR2;567} else if (Type == ConstantRange::Signed) {568if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet())569return CR1;570if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet())571return CR2;572}573574if (CR1.isSizeStrictlySmallerThan(CR2))575return CR1;576return CR2;577}578579ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,580PreferredRangeType Type) const {581assert(getBitWidth() == CR.getBitWidth() &&582"ConstantRange types don't agree!");583584// Handle common cases.585if ( isEmptySet() || CR.isFullSet()) return *this;586if (CR.isEmptySet() || isFullSet()) return CR;587588if (!isUpperWrapped() && CR.isUpperWrapped())589return CR.intersectWith(*this, Type);590591if (!isUpperWrapped() && !CR.isUpperWrapped()) {592if (Lower.ult(CR.Lower)) {593// L---U : this594// L---U : CR595if (Upper.ule(CR.Lower))596return getEmpty();597598// L---U : this599// L---U : CR600if (Upper.ult(CR.Upper))601return ConstantRange(CR.Lower, Upper);602603// L-------U : this604// L---U : CR605return CR;606}607// L---U : this608// L-------U : CR609if (Upper.ult(CR.Upper))610return *this;611612// L-----U : this613// L-----U : CR614if (Lower.ult(CR.Upper))615return ConstantRange(Lower, CR.Upper);616617// L---U : this618// L---U : CR619return getEmpty();620}621622if (isUpperWrapped() && !CR.isUpperWrapped()) {623if (CR.Lower.ult(Upper)) {624// ------U L--- : this625// L--U : CR626if (CR.Upper.ult(Upper))627return CR;628629// ------U L--- : this630// L------U : CR631if (CR.Upper.ule(Lower))632return ConstantRange(CR.Lower, Upper);633634// ------U L--- : this635// L----------U : CR636return getPreferredRange(*this, CR, Type);637}638if (CR.Lower.ult(Lower)) {639// --U L---- : this640// L--U : CR641if (CR.Upper.ule(Lower))642return getEmpty();643644// --U L---- : this645// L------U : CR646return ConstantRange(Lower, CR.Upper);647}648649// --U L------ : this650// L--U : CR651return CR;652}653654if (CR.Upper.ult(Upper)) {655// ------U L-- : this656// --U L------ : CR657if (CR.Lower.ult(Upper))658return getPreferredRange(*this, CR, Type);659660// ----U L-- : this661// --U L---- : CR662if (CR.Lower.ult(Lower))663return ConstantRange(Lower, CR.Upper);664665// ----U L---- : this666// --U L-- : CR667return CR;668}669if (CR.Upper.ule(Lower)) {670// --U L-- : this671// ----U L---- : CR672if (CR.Lower.ult(Lower))673return *this;674675// --U L---- : this676// ----U L-- : CR677return ConstantRange(CR.Lower, Upper);678}679680// --U L------ : this681// ------U L-- : CR682return getPreferredRange(*this, CR, Type);683}684685ConstantRange ConstantRange::unionWith(const ConstantRange &CR,686PreferredRangeType Type) const {687assert(getBitWidth() == CR.getBitWidth() &&688"ConstantRange types don't agree!");689690if ( isFullSet() || CR.isEmptySet()) return *this;691if (CR.isFullSet() || isEmptySet()) return CR;692693if (!isUpperWrapped() && CR.isUpperWrapped())694return CR.unionWith(*this, Type);695696if (!isUpperWrapped() && !CR.isUpperWrapped()) {697// L---U and L---U : this698// L---U L---U : CR699// result in one of700// L---------U701// -----U L-----702if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower))703return getPreferredRange(704ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);705706APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;707APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;708709if (L.isZero() && U.isZero())710return getFull();711712return ConstantRange(std::move(L), std::move(U));713}714715if (!CR.isUpperWrapped()) {716// ------U L----- and ------U L----- : this717// L--U L--U : CR718if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))719return *this;720721// ------U L----- : this722// L---------U : CR723if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))724return getFull();725726// ----U L---- : this727// L---U : CR728// results in one of729// ----------U L----730// ----U L----------731if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower))732return getPreferredRange(733ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);734735// ----U L----- : this736// L----U : CR737if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper))738return ConstantRange(CR.Lower, Upper);739740// ------U L---- : this741// L-----U : CR742assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) &&743"ConstantRange::unionWith missed a case with one range wrapped");744return ConstantRange(Lower, CR.Upper);745}746747// ------U L---- and ------U L---- : this748// -U L----------- and ------------U L : CR749if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))750return getFull();751752APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;753APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;754755return ConstantRange(std::move(L), std::move(U));756}757758std::optional<ConstantRange>759ConstantRange::exactIntersectWith(const ConstantRange &CR) const {760// TODO: This can be implemented more efficiently.761ConstantRange Result = intersectWith(CR);762if (Result == inverse().unionWith(CR.inverse()).inverse())763return Result;764return std::nullopt;765}766767std::optional<ConstantRange>768ConstantRange::exactUnionWith(const ConstantRange &CR) const {769// TODO: This can be implemented more efficiently.770ConstantRange Result = unionWith(CR);771if (Result == inverse().intersectWith(CR.inverse()).inverse())772return Result;773return std::nullopt;774}775776ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,777uint32_t ResultBitWidth) const {778switch (CastOp) {779default:780llvm_unreachable("unsupported cast type");781case Instruction::Trunc:782return truncate(ResultBitWidth);783case Instruction::SExt:784return signExtend(ResultBitWidth);785case Instruction::ZExt:786return zeroExtend(ResultBitWidth);787case Instruction::BitCast:788return *this;789case Instruction::FPToUI:790case Instruction::FPToSI:791if (getBitWidth() == ResultBitWidth)792return *this;793else794return getFull(ResultBitWidth);795case Instruction::UIToFP: {796// TODO: use input range if available797auto BW = getBitWidth();798APInt Min = APInt::getMinValue(BW);799APInt Max = APInt::getMaxValue(BW);800if (ResultBitWidth > BW) {801Min = Min.zext(ResultBitWidth);802Max = Max.zext(ResultBitWidth);803}804return getNonEmpty(std::move(Min), std::move(Max) + 1);805}806case Instruction::SIToFP: {807// TODO: use input range if available808auto BW = getBitWidth();809APInt SMin = APInt::getSignedMinValue(BW);810APInt SMax = APInt::getSignedMaxValue(BW);811if (ResultBitWidth > BW) {812SMin = SMin.sext(ResultBitWidth);813SMax = SMax.sext(ResultBitWidth);814}815return getNonEmpty(std::move(SMin), std::move(SMax) + 1);816}817case Instruction::FPTrunc:818case Instruction::FPExt:819case Instruction::IntToPtr:820case Instruction::PtrToInt:821case Instruction::AddrSpaceCast:822// Conservatively return getFull set.823return getFull(ResultBitWidth);824};825}826827ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {828if (isEmptySet()) return getEmpty(DstTySize);829830unsigned SrcTySize = getBitWidth();831assert(SrcTySize < DstTySize && "Not a value extension");832if (isFullSet() || isUpperWrapped()) {833// Change into [0, 1 << src bit width)834APInt LowerExt(DstTySize, 0);835if (!Upper) // special case: [X, 0) -- not really wrapping around836LowerExt = Lower.zext(DstTySize);837return ConstantRange(std::move(LowerExt),838APInt::getOneBitSet(DstTySize, SrcTySize));839}840841return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));842}843844ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {845if (isEmptySet()) return getEmpty(DstTySize);846847unsigned SrcTySize = getBitWidth();848assert(SrcTySize < DstTySize && "Not a value extension");849850// special case: [X, INT_MIN) -- not really wrapping around851if (Upper.isMinSignedValue())852return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));853854if (isFullSet() || isSignWrappedSet()) {855return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),856APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);857}858859return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));860}861862ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {863assert(getBitWidth() > DstTySize && "Not a value truncation");864if (isEmptySet())865return getEmpty(DstTySize);866if (isFullSet())867return getFull(DstTySize);868869APInt LowerDiv(Lower), UpperDiv(Upper);870ConstantRange Union(DstTySize, /*isFullSet=*/false);871872// Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]873// We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and874// then we do the union with [MaxValue, Upper)875if (isUpperWrapped()) {876// If Upper is greater than or equal to MaxValue(DstTy), it covers the whole877// truncated range.878if (Upper.getActiveBits() > DstTySize || Upper.countr_one() == DstTySize)879return getFull(DstTySize);880881Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));882UpperDiv.setAllBits();883884// Union covers the MaxValue case, so return if the remaining range is just885// MaxValue(DstTy).886if (LowerDiv == UpperDiv)887return Union;888}889890// Chop off the most significant bits that are past the destination bitwidth.891if (LowerDiv.getActiveBits() > DstTySize) {892// Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.893APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);894LowerDiv -= Adjust;895UpperDiv -= Adjust;896}897898unsigned UpperDivWidth = UpperDiv.getActiveBits();899if (UpperDivWidth <= DstTySize)900return ConstantRange(LowerDiv.trunc(DstTySize),901UpperDiv.trunc(DstTySize)).unionWith(Union);902903// The truncated value wraps around. Check if we can do better than fullset.904if (UpperDivWidth == DstTySize + 1) {905// Clear the MSB so that UpperDiv wraps around.906UpperDiv.clearBit(DstTySize);907if (UpperDiv.ult(LowerDiv))908return ConstantRange(LowerDiv.trunc(DstTySize),909UpperDiv.trunc(DstTySize)).unionWith(Union);910}911912return getFull(DstTySize);913}914915ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {916unsigned SrcTySize = getBitWidth();917if (SrcTySize > DstTySize)918return truncate(DstTySize);919if (SrcTySize < DstTySize)920return zeroExtend(DstTySize);921return *this;922}923924ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {925unsigned SrcTySize = getBitWidth();926if (SrcTySize > DstTySize)927return truncate(DstTySize);928if (SrcTySize < DstTySize)929return signExtend(DstTySize);930return *this;931}932933ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,934const ConstantRange &Other) const {935assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");936937switch (BinOp) {938case Instruction::Add:939return add(Other);940case Instruction::Sub:941return sub(Other);942case Instruction::Mul:943return multiply(Other);944case Instruction::UDiv:945return udiv(Other);946case Instruction::SDiv:947return sdiv(Other);948case Instruction::URem:949return urem(Other);950case Instruction::SRem:951return srem(Other);952case Instruction::Shl:953return shl(Other);954case Instruction::LShr:955return lshr(Other);956case Instruction::AShr:957return ashr(Other);958case Instruction::And:959return binaryAnd(Other);960case Instruction::Or:961return binaryOr(Other);962case Instruction::Xor:963return binaryXor(Other);964// Note: floating point operations applied to abstract ranges are just965// ideal integer operations with a lossy representation966case Instruction::FAdd:967return add(Other);968case Instruction::FSub:969return sub(Other);970case Instruction::FMul:971return multiply(Other);972default:973// Conservatively return getFull set.974return getFull();975}976}977978ConstantRange ConstantRange::overflowingBinaryOp(Instruction::BinaryOps BinOp,979const ConstantRange &Other,980unsigned NoWrapKind) const {981assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");982983switch (BinOp) {984case Instruction::Add:985return addWithNoWrap(Other, NoWrapKind);986case Instruction::Sub:987return subWithNoWrap(Other, NoWrapKind);988case Instruction::Mul:989return multiplyWithNoWrap(Other, NoWrapKind);990default:991// Don't know about this Overflowing Binary Operation.992// Conservatively fallback to plain binop handling.993return binaryOp(BinOp, Other);994}995}996997bool ConstantRange::isIntrinsicSupported(Intrinsic::ID IntrinsicID) {998switch (IntrinsicID) {999case Intrinsic::uadd_sat:1000case Intrinsic::usub_sat:1001case Intrinsic::sadd_sat:1002case Intrinsic::ssub_sat:1003case Intrinsic::umin:1004case Intrinsic::umax:1005case Intrinsic::smin:1006case Intrinsic::smax:1007case Intrinsic::abs:1008case Intrinsic::ctlz:1009case Intrinsic::cttz:1010case Intrinsic::ctpop:1011return true;1012default:1013return false;1014}1015}10161017ConstantRange ConstantRange::intrinsic(Intrinsic::ID IntrinsicID,1018ArrayRef<ConstantRange> Ops) {1019switch (IntrinsicID) {1020case Intrinsic::uadd_sat:1021return Ops[0].uadd_sat(Ops[1]);1022case Intrinsic::usub_sat:1023return Ops[0].usub_sat(Ops[1]);1024case Intrinsic::sadd_sat:1025return Ops[0].sadd_sat(Ops[1]);1026case Intrinsic::ssub_sat:1027return Ops[0].ssub_sat(Ops[1]);1028case Intrinsic::umin:1029return Ops[0].umin(Ops[1]);1030case Intrinsic::umax:1031return Ops[0].umax(Ops[1]);1032case Intrinsic::smin:1033return Ops[0].smin(Ops[1]);1034case Intrinsic::smax:1035return Ops[0].smax(Ops[1]);1036case Intrinsic::abs: {1037const APInt *IntMinIsPoison = Ops[1].getSingleElement();1038assert(IntMinIsPoison && "Must be known (immarg)");1039assert(IntMinIsPoison->getBitWidth() == 1 && "Must be boolean");1040return Ops[0].abs(IntMinIsPoison->getBoolValue());1041}1042case Intrinsic::ctlz: {1043const APInt *ZeroIsPoison = Ops[1].getSingleElement();1044assert(ZeroIsPoison && "Must be known (immarg)");1045assert(ZeroIsPoison->getBitWidth() == 1 && "Must be boolean");1046return Ops[0].ctlz(ZeroIsPoison->getBoolValue());1047}1048case Intrinsic::cttz: {1049const APInt *ZeroIsPoison = Ops[1].getSingleElement();1050assert(ZeroIsPoison && "Must be known (immarg)");1051assert(ZeroIsPoison->getBitWidth() == 1 && "Must be boolean");1052return Ops[0].cttz(ZeroIsPoison->getBoolValue());1053}1054case Intrinsic::ctpop:1055return Ops[0].ctpop();1056default:1057assert(!isIntrinsicSupported(IntrinsicID) && "Shouldn't be supported");1058llvm_unreachable("Unsupported intrinsic");1059}1060}10611062ConstantRange1063ConstantRange::add(const ConstantRange &Other) const {1064if (isEmptySet() || Other.isEmptySet())1065return getEmpty();1066if (isFullSet() || Other.isFullSet())1067return getFull();10681069APInt NewLower = getLower() + Other.getLower();1070APInt NewUpper = getUpper() + Other.getUpper() - 1;1071if (NewLower == NewUpper)1072return getFull();10731074ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));1075if (X.isSizeStrictlySmallerThan(*this) ||1076X.isSizeStrictlySmallerThan(Other))1077// We've wrapped, therefore, full set.1078return getFull();1079return X;1080}10811082ConstantRange ConstantRange::addWithNoWrap(const ConstantRange &Other,1083unsigned NoWrapKind,1084PreferredRangeType RangeType) const {1085// Calculate the range for "X + Y" which is guaranteed not to wrap(overflow).1086// (X is from this, and Y is from Other)1087if (isEmptySet() || Other.isEmptySet())1088return getEmpty();1089if (isFullSet() && Other.isFullSet())1090return getFull();10911092using OBO = OverflowingBinaryOperator;1093ConstantRange Result = add(Other);10941095// If an overflow happens for every value pair in these two constant ranges,1096// we must return Empty set. In this case, we get that for free, because we1097// get lucky that intersection of add() with uadd_sat()/sadd_sat() results1098// in an empty set.10991100if (NoWrapKind & OBO::NoSignedWrap)1101Result = Result.intersectWith(sadd_sat(Other), RangeType);11021103if (NoWrapKind & OBO::NoUnsignedWrap)1104Result = Result.intersectWith(uadd_sat(Other), RangeType);11051106return Result;1107}11081109ConstantRange1110ConstantRange::sub(const ConstantRange &Other) const {1111if (isEmptySet() || Other.isEmptySet())1112return getEmpty();1113if (isFullSet() || Other.isFullSet())1114return getFull();11151116APInt NewLower = getLower() - Other.getUpper() + 1;1117APInt NewUpper = getUpper() - Other.getLower();1118if (NewLower == NewUpper)1119return getFull();11201121ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));1122if (X.isSizeStrictlySmallerThan(*this) ||1123X.isSizeStrictlySmallerThan(Other))1124// We've wrapped, therefore, full set.1125return getFull();1126return X;1127}11281129ConstantRange ConstantRange::subWithNoWrap(const ConstantRange &Other,1130unsigned NoWrapKind,1131PreferredRangeType RangeType) const {1132// Calculate the range for "X - Y" which is guaranteed not to wrap(overflow).1133// (X is from this, and Y is from Other)1134if (isEmptySet() || Other.isEmptySet())1135return getEmpty();1136if (isFullSet() && Other.isFullSet())1137return getFull();11381139using OBO = OverflowingBinaryOperator;1140ConstantRange Result = sub(Other);11411142// If an overflow happens for every value pair in these two constant ranges,1143// we must return Empty set. In signed case, we get that for free, because we1144// get lucky that intersection of sub() with ssub_sat() results in an1145// empty set. But for unsigned we must perform the overflow check manually.11461147if (NoWrapKind & OBO::NoSignedWrap)1148Result = Result.intersectWith(ssub_sat(Other), RangeType);11491150if (NoWrapKind & OBO::NoUnsignedWrap) {1151if (getUnsignedMax().ult(Other.getUnsignedMin()))1152return getEmpty(); // Always overflows.1153Result = Result.intersectWith(usub_sat(Other), RangeType);1154}11551156return Result;1157}11581159ConstantRange1160ConstantRange::multiply(const ConstantRange &Other) const {1161// TODO: If either operand is a single element and the multiply is known to1162// be non-wrapping, round the result min and max value to the appropriate1163// multiple of that element. If wrapping is possible, at least adjust the1164// range according to the greatest power-of-two factor of the single element.11651166if (isEmptySet() || Other.isEmptySet())1167return getEmpty();11681169if (const APInt *C = getSingleElement()) {1170if (C->isOne())1171return Other;1172if (C->isAllOnes())1173return ConstantRange(APInt::getZero(getBitWidth())).sub(Other);1174}11751176if (const APInt *C = Other.getSingleElement()) {1177if (C->isOne())1178return *this;1179if (C->isAllOnes())1180return ConstantRange(APInt::getZero(getBitWidth())).sub(*this);1181}11821183// Multiplication is signedness-independent. However different ranges can be1184// obtained depending on how the input ranges are treated. These different1185// ranges are all conservatively correct, but one might be better than the1186// other. We calculate two ranges; one treating the inputs as unsigned1187// and the other signed, then return the smallest of these ranges.11881189// Unsigned range first.1190APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);1191APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);1192APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);1193APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);11941195ConstantRange Result_zext = ConstantRange(this_min * Other_min,1196this_max * Other_max + 1);1197ConstantRange UR = Result_zext.truncate(getBitWidth());11981199// If the unsigned range doesn't wrap, and isn't negative then it's a range1200// from one positive number to another which is as good as we can generate.1201// In this case, skip the extra work of generating signed ranges which aren't1202// going to be better than this range.1203if (!UR.isUpperWrapped() &&1204(UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))1205return UR;12061207// Now the signed range. Because we could be dealing with negative numbers1208// here, the lower bound is the smallest of the cartesian product of the1209// lower and upper ranges; for example:1210// [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.1211// Similarly for the upper bound, swapping min for max.12121213this_min = getSignedMin().sext(getBitWidth() * 2);1214this_max = getSignedMax().sext(getBitWidth() * 2);1215Other_min = Other.getSignedMin().sext(getBitWidth() * 2);1216Other_max = Other.getSignedMax().sext(getBitWidth() * 2);12171218auto L = {this_min * Other_min, this_min * Other_max,1219this_max * Other_min, this_max * Other_max};1220auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };1221ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);1222ConstantRange SR = Result_sext.truncate(getBitWidth());12231224return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;1225}12261227ConstantRange1228ConstantRange::multiplyWithNoWrap(const ConstantRange &Other,1229unsigned NoWrapKind,1230PreferredRangeType RangeType) const {1231if (isEmptySet() || Other.isEmptySet())1232return getEmpty();1233if (isFullSet() && Other.isFullSet())1234return getFull();12351236ConstantRange Result = multiply(Other);12371238if (NoWrapKind & OverflowingBinaryOperator::NoSignedWrap)1239Result = Result.intersectWith(smul_sat(Other), RangeType);12401241if (NoWrapKind & OverflowingBinaryOperator::NoUnsignedWrap)1242Result = Result.intersectWith(umul_sat(Other), RangeType);12431244return Result;1245}12461247ConstantRange ConstantRange::smul_fast(const ConstantRange &Other) const {1248if (isEmptySet() || Other.isEmptySet())1249return getEmpty();12501251APInt Min = getSignedMin();1252APInt Max = getSignedMax();1253APInt OtherMin = Other.getSignedMin();1254APInt OtherMax = Other.getSignedMax();12551256bool O1, O2, O3, O4;1257auto Muls = {Min.smul_ov(OtherMin, O1), Min.smul_ov(OtherMax, O2),1258Max.smul_ov(OtherMin, O3), Max.smul_ov(OtherMax, O4)};1259if (O1 || O2 || O3 || O4)1260return getFull();12611262auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };1263return getNonEmpty(std::min(Muls, Compare), std::max(Muls, Compare) + 1);1264}12651266ConstantRange1267ConstantRange::smax(const ConstantRange &Other) const {1268// X smax Y is: range(smax(X_smin, Y_smin),1269// smax(X_smax, Y_smax))1270if (isEmptySet() || Other.isEmptySet())1271return getEmpty();1272APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());1273APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;1274ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));1275if (isSignWrappedSet() || Other.isSignWrappedSet())1276return Res.intersectWith(unionWith(Other, Signed), Signed);1277return Res;1278}12791280ConstantRange1281ConstantRange::umax(const ConstantRange &Other) const {1282// X umax Y is: range(umax(X_umin, Y_umin),1283// umax(X_umax, Y_umax))1284if (isEmptySet() || Other.isEmptySet())1285return getEmpty();1286APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());1287APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;1288ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));1289if (isWrappedSet() || Other.isWrappedSet())1290return Res.intersectWith(unionWith(Other, Unsigned), Unsigned);1291return Res;1292}12931294ConstantRange1295ConstantRange::smin(const ConstantRange &Other) const {1296// X smin Y is: range(smin(X_smin, Y_smin),1297// smin(X_smax, Y_smax))1298if (isEmptySet() || Other.isEmptySet())1299return getEmpty();1300APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());1301APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;1302ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));1303if (isSignWrappedSet() || Other.isSignWrappedSet())1304return Res.intersectWith(unionWith(Other, Signed), Signed);1305return Res;1306}13071308ConstantRange1309ConstantRange::umin(const ConstantRange &Other) const {1310// X umin Y is: range(umin(X_umin, Y_umin),1311// umin(X_umax, Y_umax))1312if (isEmptySet() || Other.isEmptySet())1313return getEmpty();1314APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());1315APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;1316ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));1317if (isWrappedSet() || Other.isWrappedSet())1318return Res.intersectWith(unionWith(Other, Unsigned), Unsigned);1319return Res;1320}13211322ConstantRange1323ConstantRange::udiv(const ConstantRange &RHS) const {1324if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())1325return getEmpty();13261327APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());13281329APInt RHS_umin = RHS.getUnsignedMin();1330if (RHS_umin.isZero()) {1331// We want the lowest value in RHS excluding zero. Usually that would be 11332// except for a range in the form of [X, 1) in which case it would be X.1333if (RHS.getUpper() == 1)1334RHS_umin = RHS.getLower();1335else1336RHS_umin = 1;1337}13381339APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;1340return getNonEmpty(std::move(Lower), std::move(Upper));1341}13421343ConstantRange ConstantRange::sdiv(const ConstantRange &RHS) const {1344// We split up the LHS and RHS into positive and negative components1345// and then also compute the positive and negative components of the result1346// separately by combining division results with the appropriate signs.1347APInt Zero = APInt::getZero(getBitWidth());1348APInt SignedMin = APInt::getSignedMinValue(getBitWidth());1349// There are no positive 1-bit values. The 1 would get interpreted as -1.1350ConstantRange PosFilter =1351getBitWidth() == 1 ? getEmpty()1352: ConstantRange(APInt(getBitWidth(), 1), SignedMin);1353ConstantRange NegFilter(SignedMin, Zero);1354ConstantRange PosL = intersectWith(PosFilter);1355ConstantRange NegL = intersectWith(NegFilter);1356ConstantRange PosR = RHS.intersectWith(PosFilter);1357ConstantRange NegR = RHS.intersectWith(NegFilter);13581359ConstantRange PosRes = getEmpty();1360if (!PosL.isEmptySet() && !PosR.isEmptySet())1361// pos / pos = pos.1362PosRes = ConstantRange(PosL.Lower.sdiv(PosR.Upper - 1),1363(PosL.Upper - 1).sdiv(PosR.Lower) + 1);13641365if (!NegL.isEmptySet() && !NegR.isEmptySet()) {1366// neg / neg = pos.1367//1368// We need to deal with one tricky case here: SignedMin / -1 is UB on the1369// IR level, so we'll want to exclude this case when calculating bounds.1370// (For APInts the operation is well-defined and yields SignedMin.) We1371// handle this by dropping either SignedMin from the LHS or -1 from the RHS.1372APInt Lo = (NegL.Upper - 1).sdiv(NegR.Lower);1373if (NegL.Lower.isMinSignedValue() && NegR.Upper.isZero()) {1374// Remove -1 from the LHS. Skip if it's the only element, as this would1375// leave us with an empty set.1376if (!NegR.Lower.isAllOnes()) {1377APInt AdjNegRUpper;1378if (RHS.Lower.isAllOnes())1379// Negative part of [-1, X] without -1 is [SignedMin, X].1380AdjNegRUpper = RHS.Upper;1381else1382// [X, -1] without -1 is [X, -2].1383AdjNegRUpper = NegR.Upper - 1;13841385PosRes = PosRes.unionWith(1386ConstantRange(Lo, NegL.Lower.sdiv(AdjNegRUpper - 1) + 1));1387}13881389// Remove SignedMin from the RHS. Skip if it's the only element, as this1390// would leave us with an empty set.1391if (NegL.Upper != SignedMin + 1) {1392APInt AdjNegLLower;1393if (Upper == SignedMin + 1)1394// Negative part of [X, SignedMin] without SignedMin is [X, -1].1395AdjNegLLower = Lower;1396else1397// [SignedMin, X] without SignedMin is [SignedMin + 1, X].1398AdjNegLLower = NegL.Lower + 1;13991400PosRes = PosRes.unionWith(1401ConstantRange(std::move(Lo),1402AdjNegLLower.sdiv(NegR.Upper - 1) + 1));1403}1404} else {1405PosRes = PosRes.unionWith(1406ConstantRange(std::move(Lo), NegL.Lower.sdiv(NegR.Upper - 1) + 1));1407}1408}14091410ConstantRange NegRes = getEmpty();1411if (!PosL.isEmptySet() && !NegR.isEmptySet())1412// pos / neg = neg.1413NegRes = ConstantRange((PosL.Upper - 1).sdiv(NegR.Upper - 1),1414PosL.Lower.sdiv(NegR.Lower) + 1);14151416if (!NegL.isEmptySet() && !PosR.isEmptySet())1417// neg / pos = neg.1418NegRes = NegRes.unionWith(1419ConstantRange(NegL.Lower.sdiv(PosR.Lower),1420(NegL.Upper - 1).sdiv(PosR.Upper - 1) + 1));14211422// Prefer a non-wrapping signed range here.1423ConstantRange Res = NegRes.unionWith(PosRes, PreferredRangeType::Signed);14241425// Preserve the zero that we dropped when splitting the LHS by sign.1426if (contains(Zero) && (!PosR.isEmptySet() || !NegR.isEmptySet()))1427Res = Res.unionWith(ConstantRange(Zero));1428return Res;1429}14301431ConstantRange ConstantRange::urem(const ConstantRange &RHS) const {1432if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())1433return getEmpty();14341435if (const APInt *RHSInt = RHS.getSingleElement()) {1436// UREM by null is UB.1437if (RHSInt->isZero())1438return getEmpty();1439// Use APInt's implementation of UREM for single element ranges.1440if (const APInt *LHSInt = getSingleElement())1441return {LHSInt->urem(*RHSInt)};1442}14431444// L % R for L < R is L.1445if (getUnsignedMax().ult(RHS.getUnsignedMin()))1446return *this;14471448// L % R is <= L and < R.1449APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1;1450return getNonEmpty(APInt::getZero(getBitWidth()), std::move(Upper));1451}14521453ConstantRange ConstantRange::srem(const ConstantRange &RHS) const {1454if (isEmptySet() || RHS.isEmptySet())1455return getEmpty();14561457if (const APInt *RHSInt = RHS.getSingleElement()) {1458// SREM by null is UB.1459if (RHSInt->isZero())1460return getEmpty();1461// Use APInt's implementation of SREM for single element ranges.1462if (const APInt *LHSInt = getSingleElement())1463return {LHSInt->srem(*RHSInt)};1464}14651466ConstantRange AbsRHS = RHS.abs();1467APInt MinAbsRHS = AbsRHS.getUnsignedMin();1468APInt MaxAbsRHS = AbsRHS.getUnsignedMax();14691470// Modulus by zero is UB.1471if (MaxAbsRHS.isZero())1472return getEmpty();14731474if (MinAbsRHS.isZero())1475++MinAbsRHS;14761477APInt MinLHS = getSignedMin(), MaxLHS = getSignedMax();14781479if (MinLHS.isNonNegative()) {1480// L % R for L < R is L.1481if (MaxLHS.ult(MinAbsRHS))1482return *this;14831484// L % R is <= L and < R.1485APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;1486return ConstantRange(APInt::getZero(getBitWidth()), std::move(Upper));1487}14881489// Same basic logic as above, but the result is negative.1490if (MaxLHS.isNegative()) {1491if (MinLHS.ugt(-MinAbsRHS))1492return *this;14931494APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);1495return ConstantRange(std::move(Lower), APInt(getBitWidth(), 1));1496}14971498// LHS range crosses zero.1499APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);1500APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;1501return ConstantRange(std::move(Lower), std::move(Upper));1502}15031504ConstantRange ConstantRange::binaryNot() const {1505return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);1506}15071508ConstantRange ConstantRange::binaryAnd(const ConstantRange &Other) const {1509if (isEmptySet() || Other.isEmptySet())1510return getEmpty();15111512ConstantRange KnownBitsRange =1513fromKnownBits(toKnownBits() & Other.toKnownBits(), false);1514ConstantRange UMinUMaxRange =1515getNonEmpty(APInt::getZero(getBitWidth()),1516APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax()) + 1);1517return KnownBitsRange.intersectWith(UMinUMaxRange);1518}15191520ConstantRange ConstantRange::binaryOr(const ConstantRange &Other) const {1521if (isEmptySet() || Other.isEmptySet())1522return getEmpty();15231524ConstantRange KnownBitsRange =1525fromKnownBits(toKnownBits() | Other.toKnownBits(), false);1526// Upper wrapped range.1527ConstantRange UMaxUMinRange =1528getNonEmpty(APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin()),1529APInt::getZero(getBitWidth()));1530return KnownBitsRange.intersectWith(UMaxUMinRange);1531}15321533ConstantRange ConstantRange::binaryXor(const ConstantRange &Other) const {1534if (isEmptySet() || Other.isEmptySet())1535return getEmpty();15361537// Use APInt's implementation of XOR for single element ranges.1538if (isSingleElement() && Other.isSingleElement())1539return {*getSingleElement() ^ *Other.getSingleElement()};15401541// Special-case binary complement, since we can give a precise answer.1542if (Other.isSingleElement() && Other.getSingleElement()->isAllOnes())1543return binaryNot();1544if (isSingleElement() && getSingleElement()->isAllOnes())1545return Other.binaryNot();15461547KnownBits LHSKnown = toKnownBits();1548KnownBits RHSKnown = Other.toKnownBits();1549KnownBits Known = LHSKnown ^ RHSKnown;1550ConstantRange CR = fromKnownBits(Known, /*IsSigned*/ false);1551// Typically the following code doesn't improve the result if BW = 1.1552if (getBitWidth() == 1)1553return CR;15541555// If LHS is known to be the subset of RHS, treat LHS ^ RHS as RHS -nuw/nsw1556// LHS. If RHS is known to be the subset of LHS, treat LHS ^ RHS as LHS1557// -nuw/nsw RHS.1558if ((~LHSKnown.Zero).isSubsetOf(RHSKnown.One))1559CR = CR.intersectWith(Other.sub(*this), PreferredRangeType::Unsigned);1560else if ((~RHSKnown.Zero).isSubsetOf(LHSKnown.One))1561CR = CR.intersectWith(this->sub(Other), PreferredRangeType::Unsigned);1562return CR;1563}15641565ConstantRange1566ConstantRange::shl(const ConstantRange &Other) const {1567if (isEmptySet() || Other.isEmptySet())1568return getEmpty();15691570APInt Min = getUnsignedMin();1571APInt Max = getUnsignedMax();1572if (const APInt *RHS = Other.getSingleElement()) {1573unsigned BW = getBitWidth();1574if (RHS->uge(BW))1575return getEmpty();15761577unsigned EqualLeadingBits = (Min ^ Max).countl_zero();1578if (RHS->ule(EqualLeadingBits))1579return getNonEmpty(Min << *RHS, (Max << *RHS) + 1);15801581return getNonEmpty(APInt::getZero(BW),1582APInt::getBitsSetFrom(BW, RHS->getZExtValue()) + 1);1583}15841585APInt OtherMax = Other.getUnsignedMax();1586if (isAllNegative() && OtherMax.ule(Min.countl_one())) {1587// For negative numbers, if the shift does not overflow in a signed sense,1588// a larger shift will make the number smaller.1589Max <<= Other.getUnsignedMin();1590Min <<= OtherMax;1591return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1);1592}15931594// There's overflow!1595if (OtherMax.ugt(Max.countl_zero()))1596return getFull();15971598// FIXME: implement the other tricky cases15991600Min <<= Other.getUnsignedMin();1601Max <<= OtherMax;16021603return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1);1604}16051606ConstantRange1607ConstantRange::lshr(const ConstantRange &Other) const {1608if (isEmptySet() || Other.isEmptySet())1609return getEmpty();16101611APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;1612APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());1613return getNonEmpty(std::move(min), std::move(max));1614}16151616ConstantRange1617ConstantRange::ashr(const ConstantRange &Other) const {1618if (isEmptySet() || Other.isEmptySet())1619return getEmpty();16201621// May straddle zero, so handle both positive and negative cases.1622// 'PosMax' is the upper bound of the result of the ashr1623// operation, when Upper of the LHS of ashr is a non-negative.1624// number. Since ashr of a non-negative number will result in a1625// smaller number, the Upper value of LHS is shifted right with1626// the minimum value of 'Other' instead of the maximum value.1627APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;16281629// 'PosMin' is the lower bound of the result of the ashr1630// operation, when Lower of the LHS is a non-negative number.1631// Since ashr of a non-negative number will result in a smaller1632// number, the Lower value of LHS is shifted right with the1633// maximum value of 'Other'.1634APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());16351636// 'NegMax' is the upper bound of the result of the ashr1637// operation, when Upper of the LHS of ashr is a negative number.1638// Since 'ashr' of a negative number will result in a bigger1639// number, the Upper value of LHS is shifted right with the1640// maximum value of 'Other'.1641APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;16421643// 'NegMin' is the lower bound of the result of the ashr1644// operation, when Lower of the LHS of ashr is a negative number.1645// Since 'ashr' of a negative number will result in a bigger1646// number, the Lower value of LHS is shifted right with the1647// minimum value of 'Other'.1648APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());16491650APInt max, min;1651if (getSignedMin().isNonNegative()) {1652// Upper and Lower of LHS are non-negative.1653min = PosMin;1654max = PosMax;1655} else if (getSignedMax().isNegative()) {1656// Upper and Lower of LHS are negative.1657min = NegMin;1658max = NegMax;1659} else {1660// Upper is non-negative and Lower is negative.1661min = NegMin;1662max = PosMax;1663}1664return getNonEmpty(std::move(min), std::move(max));1665}16661667ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const {1668if (isEmptySet() || Other.isEmptySet())1669return getEmpty();16701671APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin());1672APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1;1673return getNonEmpty(std::move(NewL), std::move(NewU));1674}16751676ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const {1677if (isEmptySet() || Other.isEmptySet())1678return getEmpty();16791680APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin());1681APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1;1682return getNonEmpty(std::move(NewL), std::move(NewU));1683}16841685ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const {1686if (isEmptySet() || Other.isEmptySet())1687return getEmpty();16881689APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax());1690APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1;1691return getNonEmpty(std::move(NewL), std::move(NewU));1692}16931694ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const {1695if (isEmptySet() || Other.isEmptySet())1696return getEmpty();16971698APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax());1699APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1;1700return getNonEmpty(std::move(NewL), std::move(NewU));1701}17021703ConstantRange ConstantRange::umul_sat(const ConstantRange &Other) const {1704if (isEmptySet() || Other.isEmptySet())1705return getEmpty();17061707APInt NewL = getUnsignedMin().umul_sat(Other.getUnsignedMin());1708APInt NewU = getUnsignedMax().umul_sat(Other.getUnsignedMax()) + 1;1709return getNonEmpty(std::move(NewL), std::move(NewU));1710}17111712ConstantRange ConstantRange::smul_sat(const ConstantRange &Other) const {1713if (isEmptySet() || Other.isEmptySet())1714return getEmpty();17151716// Because we could be dealing with negative numbers here, the lower bound is1717// the smallest of the cartesian product of the lower and upper ranges;1718// for example:1719// [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.1720// Similarly for the upper bound, swapping min for max.17211722APInt Min = getSignedMin();1723APInt Max = getSignedMax();1724APInt OtherMin = Other.getSignedMin();1725APInt OtherMax = Other.getSignedMax();17261727auto L = {Min.smul_sat(OtherMin), Min.smul_sat(OtherMax),1728Max.smul_sat(OtherMin), Max.smul_sat(OtherMax)};1729auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };1730return getNonEmpty(std::min(L, Compare), std::max(L, Compare) + 1);1731}17321733ConstantRange ConstantRange::ushl_sat(const ConstantRange &Other) const {1734if (isEmptySet() || Other.isEmptySet())1735return getEmpty();17361737APInt NewL = getUnsignedMin().ushl_sat(Other.getUnsignedMin());1738APInt NewU = getUnsignedMax().ushl_sat(Other.getUnsignedMax()) + 1;1739return getNonEmpty(std::move(NewL), std::move(NewU));1740}17411742ConstantRange ConstantRange::sshl_sat(const ConstantRange &Other) const {1743if (isEmptySet() || Other.isEmptySet())1744return getEmpty();17451746APInt Min = getSignedMin(), Max = getSignedMax();1747APInt ShAmtMin = Other.getUnsignedMin(), ShAmtMax = Other.getUnsignedMax();1748APInt NewL = Min.sshl_sat(Min.isNonNegative() ? ShAmtMin : ShAmtMax);1749APInt NewU = Max.sshl_sat(Max.isNegative() ? ShAmtMin : ShAmtMax) + 1;1750return getNonEmpty(std::move(NewL), std::move(NewU));1751}17521753ConstantRange ConstantRange::inverse() const {1754if (isFullSet())1755return getEmpty();1756if (isEmptySet())1757return getFull();1758return ConstantRange(Upper, Lower);1759}17601761ConstantRange ConstantRange::abs(bool IntMinIsPoison) const {1762if (isEmptySet())1763return getEmpty();17641765if (isSignWrappedSet()) {1766APInt Lo;1767// Check whether the range crosses zero.1768if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive())1769Lo = APInt::getZero(getBitWidth());1770else1771Lo = APIntOps::umin(Lower, -Upper + 1);17721773// If SignedMin is not poison, then it is included in the result range.1774if (IntMinIsPoison)1775return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()));1776else1777return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()) + 1);1778}17791780APInt SMin = getSignedMin(), SMax = getSignedMax();17811782// Skip SignedMin if it is poison.1783if (IntMinIsPoison && SMin.isMinSignedValue()) {1784// The range may become empty if it *only* contains SignedMin.1785if (SMax.isMinSignedValue())1786return getEmpty();1787++SMin;1788}17891790// All non-negative.1791if (SMin.isNonNegative())1792return ConstantRange(SMin, SMax + 1);17931794// All negative.1795if (SMax.isNegative())1796return ConstantRange(-SMax, -SMin + 1);17971798// Range crosses zero.1799return ConstantRange::getNonEmpty(APInt::getZero(getBitWidth()),1800APIntOps::umax(-SMin, SMax) + 1);1801}18021803ConstantRange ConstantRange::ctlz(bool ZeroIsPoison) const {1804if (isEmptySet())1805return getEmpty();18061807APInt Zero = APInt::getZero(getBitWidth());1808if (ZeroIsPoison && contains(Zero)) {1809// ZeroIsPoison is set, and zero is contained. We discern three cases, in1810// which a zero can appear:1811// 1) Lower is zero, handling cases of kind [0, 1), [0, 2), etc.1812// 2) Upper is zero, wrapped set, handling cases of kind [3, 0], etc.1813// 3) Zero contained in a wrapped set, e.g., [3, 2), [3, 1), etc.18141815if (getLower().isZero()) {1816if ((getUpper() - 1).isZero()) {1817// We have in input interval of kind [0, 1). In this case we cannot1818// really help but return empty-set.1819return getEmpty();1820}18211822// Compute the resulting range by excluding zero from Lower.1823return ConstantRange(1824APInt(getBitWidth(), (getUpper() - 1).countl_zero()),1825APInt(getBitWidth(), (getLower() + 1).countl_zero() + 1));1826} else if ((getUpper() - 1).isZero()) {1827// Compute the resulting range by excluding zero from Upper.1828return ConstantRange(Zero,1829APInt(getBitWidth(), getLower().countl_zero() + 1));1830} else {1831return ConstantRange(Zero, APInt(getBitWidth(), getBitWidth()));1832}1833}18341835// Zero is either safe or not in the range. The output range is composed by1836// the result of countLeadingZero of the two extremes.1837return getNonEmpty(APInt(getBitWidth(), getUnsignedMax().countl_zero()),1838APInt(getBitWidth(), getUnsignedMin().countl_zero() + 1));1839}18401841static ConstantRange getUnsignedCountTrailingZerosRange(const APInt &Lower,1842const APInt &Upper) {1843assert(!ConstantRange(Lower, Upper).isWrappedSet() &&1844"Unexpected wrapped set.");1845assert(Lower != Upper && "Unexpected empty set.");1846unsigned BitWidth = Lower.getBitWidth();1847if (Lower + 1 == Upper)1848return ConstantRange(APInt(BitWidth, Lower.countr_zero()));1849if (Lower.isZero())1850return ConstantRange(APInt::getZero(BitWidth),1851APInt(BitWidth, BitWidth + 1));18521853// Calculate longest common prefix.1854unsigned LCPLength = (Lower ^ (Upper - 1)).countl_zero();1855// If Lower is {LCP, 000...}, the maximum is Lower.countr_zero().1856// Otherwise, the maximum is BitWidth - LCPLength - 1 ({LCP, 100...}).1857return ConstantRange(1858APInt::getZero(BitWidth),1859APInt(BitWidth,1860std::max(BitWidth - LCPLength - 1, Lower.countr_zero()) + 1));1861}18621863ConstantRange ConstantRange::cttz(bool ZeroIsPoison) const {1864if (isEmptySet())1865return getEmpty();18661867unsigned BitWidth = getBitWidth();1868APInt Zero = APInt::getZero(BitWidth);1869if (ZeroIsPoison && contains(Zero)) {1870// ZeroIsPoison is set, and zero is contained. We discern three cases, in1871// which a zero can appear:1872// 1) Lower is zero, handling cases of kind [0, 1), [0, 2), etc.1873// 2) Upper is zero, wrapped set, handling cases of kind [3, 0], etc.1874// 3) Zero contained in a wrapped set, e.g., [3, 2), [3, 1), etc.18751876if (Lower.isZero()) {1877if (Upper == 1) {1878// We have in input interval of kind [0, 1). In this case we cannot1879// really help but return empty-set.1880return getEmpty();1881}18821883// Compute the resulting range by excluding zero from Lower.1884return getUnsignedCountTrailingZerosRange(APInt(BitWidth, 1), Upper);1885} else if (Upper == 1) {1886// Compute the resulting range by excluding zero from Upper.1887return getUnsignedCountTrailingZerosRange(Lower, Zero);1888} else {1889ConstantRange CR1 = getUnsignedCountTrailingZerosRange(Lower, Zero);1890ConstantRange CR2 =1891getUnsignedCountTrailingZerosRange(APInt(BitWidth, 1), Upper);1892return CR1.unionWith(CR2);1893}1894}18951896if (isFullSet())1897return getNonEmpty(Zero, APInt(BitWidth, BitWidth + 1));1898if (!isWrappedSet())1899return getUnsignedCountTrailingZerosRange(Lower, Upper);1900// The range is wrapped. We decompose it into two ranges, [0, Upper) and1901// [Lower, 0).1902// Handle [Lower, 0)1903ConstantRange CR1 = getUnsignedCountTrailingZerosRange(Lower, Zero);1904// Handle [0, Upper)1905ConstantRange CR2 = getUnsignedCountTrailingZerosRange(Zero, Upper);1906return CR1.unionWith(CR2);1907}19081909static ConstantRange getUnsignedPopCountRange(const APInt &Lower,1910const APInt &Upper) {1911assert(!ConstantRange(Lower, Upper).isWrappedSet() &&1912"Unexpected wrapped set.");1913assert(Lower != Upper && "Unexpected empty set.");1914unsigned BitWidth = Lower.getBitWidth();1915if (Lower + 1 == Upper)1916return ConstantRange(APInt(BitWidth, Lower.popcount()));19171918APInt Max = Upper - 1;1919// Calculate longest common prefix.1920unsigned LCPLength = (Lower ^ Max).countl_zero();1921unsigned LCPPopCount = Lower.getHiBits(LCPLength).popcount();1922// If Lower is {LCP, 000...}, the minimum is the popcount of LCP.1923// Otherwise, the minimum is the popcount of LCP + 1.1924unsigned MinBits =1925LCPPopCount + (Lower.countr_zero() < BitWidth - LCPLength ? 1 : 0);1926// If Max is {LCP, 111...}, the maximum is the popcount of LCP + (BitWidth -1927// length of LCP).1928// Otherwise, the minimum is the popcount of LCP + (BitWidth -1929// length of LCP - 1).1930unsigned MaxBits = LCPPopCount + (BitWidth - LCPLength) -1931(Max.countr_one() < BitWidth - LCPLength ? 1 : 0);1932return ConstantRange(APInt(BitWidth, MinBits), APInt(BitWidth, MaxBits + 1));1933}19341935ConstantRange ConstantRange::ctpop() const {1936if (isEmptySet())1937return getEmpty();19381939unsigned BitWidth = getBitWidth();1940APInt Zero = APInt::getZero(BitWidth);1941if (isFullSet())1942return getNonEmpty(Zero, APInt(BitWidth, BitWidth + 1));1943if (!isWrappedSet())1944return getUnsignedPopCountRange(Lower, Upper);1945// The range is wrapped. We decompose it into two ranges, [0, Upper) and1946// [Lower, 0).1947// Handle [Lower, 0) == [Lower, Max]1948ConstantRange CR1 = ConstantRange(APInt(BitWidth, Lower.countl_one()),1949APInt(BitWidth, BitWidth + 1));1950// Handle [0, Upper)1951ConstantRange CR2 = getUnsignedPopCountRange(Zero, Upper);1952return CR1.unionWith(CR2);1953}19541955ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow(1956const ConstantRange &Other) const {1957if (isEmptySet() || Other.isEmptySet())1958return OverflowResult::MayOverflow;19591960APInt Min = getUnsignedMin(), Max = getUnsignedMax();1961APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();19621963// a u+ b overflows high iff a u> ~b.1964if (Min.ugt(~OtherMin))1965return OverflowResult::AlwaysOverflowsHigh;1966if (Max.ugt(~OtherMax))1967return OverflowResult::MayOverflow;1968return OverflowResult::NeverOverflows;1969}19701971ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow(1972const ConstantRange &Other) const {1973if (isEmptySet() || Other.isEmptySet())1974return OverflowResult::MayOverflow;19751976APInt Min = getSignedMin(), Max = getSignedMax();1977APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();19781979APInt SignedMin = APInt::getSignedMinValue(getBitWidth());1980APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());19811982// a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.1983// a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.1984if (Min.isNonNegative() && OtherMin.isNonNegative() &&1985Min.sgt(SignedMax - OtherMin))1986return OverflowResult::AlwaysOverflowsHigh;1987if (Max.isNegative() && OtherMax.isNegative() &&1988Max.slt(SignedMin - OtherMax))1989return OverflowResult::AlwaysOverflowsLow;19901991if (Max.isNonNegative() && OtherMax.isNonNegative() &&1992Max.sgt(SignedMax - OtherMax))1993return OverflowResult::MayOverflow;1994if (Min.isNegative() && OtherMin.isNegative() &&1995Min.slt(SignedMin - OtherMin))1996return OverflowResult::MayOverflow;19971998return OverflowResult::NeverOverflows;1999}20002001ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow(2002const ConstantRange &Other) const {2003if (isEmptySet() || Other.isEmptySet())2004return OverflowResult::MayOverflow;20052006APInt Min = getUnsignedMin(), Max = getUnsignedMax();2007APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();20082009// a u- b overflows low iff a u< b.2010if (Max.ult(OtherMin))2011return OverflowResult::AlwaysOverflowsLow;2012if (Min.ult(OtherMax))2013return OverflowResult::MayOverflow;2014return OverflowResult::NeverOverflows;2015}20162017ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow(2018const ConstantRange &Other) const {2019if (isEmptySet() || Other.isEmptySet())2020return OverflowResult::MayOverflow;20212022APInt Min = getSignedMin(), Max = getSignedMax();2023APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();20242025APInt SignedMin = APInt::getSignedMinValue(getBitWidth());2026APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());20272028// a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.2029// a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.2030if (Min.isNonNegative() && OtherMax.isNegative() &&2031Min.sgt(SignedMax + OtherMax))2032return OverflowResult::AlwaysOverflowsHigh;2033if (Max.isNegative() && OtherMin.isNonNegative() &&2034Max.slt(SignedMin + OtherMin))2035return OverflowResult::AlwaysOverflowsLow;20362037if (Max.isNonNegative() && OtherMin.isNegative() &&2038Max.sgt(SignedMax + OtherMin))2039return OverflowResult::MayOverflow;2040if (Min.isNegative() && OtherMax.isNonNegative() &&2041Min.slt(SignedMin + OtherMax))2042return OverflowResult::MayOverflow;20432044return OverflowResult::NeverOverflows;2045}20462047ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow(2048const ConstantRange &Other) const {2049if (isEmptySet() || Other.isEmptySet())2050return OverflowResult::MayOverflow;20512052APInt Min = getUnsignedMin(), Max = getUnsignedMax();2053APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();2054bool Overflow;20552056(void) Min.umul_ov(OtherMin, Overflow);2057if (Overflow)2058return OverflowResult::AlwaysOverflowsHigh;20592060(void) Max.umul_ov(OtherMax, Overflow);2061if (Overflow)2062return OverflowResult::MayOverflow;20632064return OverflowResult::NeverOverflows;2065}20662067void ConstantRange::print(raw_ostream &OS) const {2068if (isFullSet())2069OS << "full-set";2070else if (isEmptySet())2071OS << "empty-set";2072else2073OS << "[" << Lower << "," << Upper << ")";2074}20752076#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)2077LLVM_DUMP_METHOD void ConstantRange::dump() const {2078print(dbgs());2079}2080#endif20812082ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {2083const unsigned NumRanges = Ranges.getNumOperands() / 2;2084assert(NumRanges >= 1 && "Must have at least one range!");2085assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");20862087auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));2088auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));20892090ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());20912092for (unsigned i = 1; i < NumRanges; ++i) {2093auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));2094auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));20952096// Note: unionWith will potentially create a range that contains values not2097// contained in any of the original N ranges.2098CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));2099}21002101return CR;2102}210321042105