57#include "llvm/IR/IntrinsicsAArch64.h"
58#include "llvm/IR/IntrinsicsAMDGPU.h"
59#include "llvm/IR/IntrinsicsRISCV.h"
60#include "llvm/IR/IntrinsicsX86.h"
97 return DL.getPointerTypeSizeInBits(Ty);
109 CxtI = dyn_cast<Instruction>(V);
123 CxtI = dyn_cast<Instruction>(V1);
127 CxtI = dyn_cast<Instruction>(V2);
135 const APInt &DemandedElts,
137 if (isa<ScalableVectorType>(Shuf->
getType())) {
139 DemandedLHS = DemandedRHS = DemandedElts;
146 DemandedElts, DemandedLHS, DemandedRHS);
158 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
186 V, DemandedElts,
Depth,
242 "LHS and RHS should have the same type");
244 "LHS and RHS should be integers");
255 return !
I->user_empty() &&
all_of(
I->users(), [](
const User *U) {
256 return match(U, m_ICmp(m_Value(), m_Zero()));
261 return !
I->user_empty() &&
all_of(
I->users(), [](
const User *U) {
263 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
268 bool OrZero,
unsigned Depth,
271 return ::isKnownToBeAPowerOfTwo(
286 if (
auto *CI = dyn_cast<ConstantInt>(V))
287 return CI->getValue().isStrictlyPositive();
310 if (V1 == V2 || V1->
getType() != V2->getType())
312 auto *FVTy = dyn_cast<FixedVectorType>(V1->
getType());
315 return ::isKnownNonEqual(
316 V1, V2, DemandedElts, 0,
324 return Mask.isSubsetOf(Known.
Zero);
332 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
342 return ::ComputeNumSignBits(
351 return V->getType()->getScalarSizeInBits() - SignBits + 1;
356 const APInt &DemandedElts,
363 if (KnownOut.
isUnknown() && !NSW && !NUW)
371 bool NUW,
const APInt &DemandedElts,
388 bool isKnownNegativeOp0 = Known2.
isNegative();
391 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
403 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
405 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.
isNonZero());
409 bool SelfMultiply = Op0 == Op1;
429 unsigned NumRanges = Ranges.getNumOperands() / 2;
435 for (
unsigned i = 0; i < NumRanges; ++i) {
437 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
439 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
443 unsigned CommonPrefixBits =
447 Known.
One &= UnsignedMax & Mask;
448 Known.
Zero &= ~UnsignedMax & Mask;
463 while (!WorkSet.
empty()) {
465 if (!Visited.
insert(V).second)
470 return EphValues.count(U);
475 if (V ==
I || (isa<Instruction>(V) &&
477 !cast<Instruction>(V)->isTerminator())) {
479 if (
const User *U = dyn_cast<User>(V))
491 return CI->isAssumeLikeIntrinsic();
499 bool AllowEphemerals) {
517 if (!AllowEphemerals && Inv == CxtI)
553 if (Pred == ICmpInst::ICMP_UGT)
557 if (Pred == ICmpInst::ICMP_NE)
568 auto *VC = dyn_cast<ConstantDataVector>(
RHS);
572 for (
unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
575 Pred, VC->getElementAsAPInt(ElemIdx));
594 "Got assumption for the wrong function!");
597 if (!V->getType()->isPointerTy())
600 *
I,
I->bundle_op_info_begin()[Elem.Index])) {
602 (RK.AttrKind == Attribute::NonNull ||
603 (RK.AttrKind == Attribute::Dereferenceable &&
605 V->getType()->getPointerAddressSpace()))) &&
637 case ICmpInst::ICMP_EQ:
640 case ICmpInst::ICMP_SGE:
641 case ICmpInst::ICMP_SGT:
644 case ICmpInst::ICMP_SLT:
662 case ICmpInst::ICMP_EQ:
672 Known.
Zero |= ~*
C & *Mask;
678 Known.
One |= *
C & ~*Mask;
699 Known.
Zero |= RHSKnown.
Zero << ShAmt;
700 Known.
One |= RHSKnown.
One << ShAmt;
703 case ICmpInst::ICMP_NE: {
719 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
725 (*
C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
727 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
733 (*
C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
745 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
778 if (
auto *Cmp = dyn_cast<ICmpInst>(
Cond))
823 "Got assumption for the wrong function!");
826 if (!V->getType()->isPointerTy())
829 *
I,
I->bundle_op_info_begin()[Elem.Index])) {
833 if (RK.WasOn == V && RK.AttrKind == Attribute::Alignment &&
845 Value *Arg =
I->getArgOperand(0);
865 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
901 Known = KF(Known2, Known, ShAmtNonZero);
912 Value *
X =
nullptr, *
Y =
nullptr;
914 switch (
I->getOpcode()) {
915 case Instruction::And:
916 KnownOut = KnownLHS & KnownRHS;
926 KnownOut = KnownLHS.
blsi();
928 KnownOut = KnownRHS.
blsi();
931 case Instruction::Or:
932 KnownOut = KnownLHS | KnownRHS;
934 case Instruction::Xor:
935 KnownOut = KnownLHS ^ KnownRHS;
945 const KnownBits &XBits =
I->getOperand(0) ==
X ? KnownLHS : KnownRHS;
946 KnownOut = XBits.
blsmsk();
959 if (!KnownOut.
Zero[0] && !KnownOut.
One[0] &&
980 APInt DemandedEltsLHS, DemandedEltsRHS;
982 DemandedElts, DemandedEltsLHS,
985 const auto ComputeForSingleOpFunc =
987 return KnownBitsFunc(
992 if (DemandedEltsRHS.
isZero())
993 return ComputeForSingleOpFunc(
I->getOperand(0), DemandedEltsLHS);
994 if (DemandedEltsLHS.
isZero())
995 return ComputeForSingleOpFunc(
I->getOperand(1), DemandedEltsRHS);
997 return ComputeForSingleOpFunc(
I->getOperand(0), DemandedEltsLHS)
998 .intersectWith(ComputeForSingleOpFunc(
I->getOperand(1), DemandedEltsRHS));
1007 auto *FVTy = dyn_cast<FixedVectorType>(
I->getType());
1008 APInt DemandedElts =
1016 Attribute Attr =
F->getFnAttribute(Attribute::VScaleRange);
1024 return ConstantRange::getEmpty(
BitWidth);
1074 "Input should be a Select!");
1084 const Value *LHS2 =
nullptr, *RHS2 =
nullptr;
1096 return CLow->
sle(*CHigh);
1101 const APInt *&CHigh) {
1102 assert((
II->getIntrinsicID() == Intrinsic::smin ||
1103 II->getIntrinsicID() == Intrinsic::smax) &&
1104 "Must be smin/smax");
1107 auto *InnerII = dyn_cast<IntrinsicInst>(
II->getArgOperand(0));
1108 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1113 if (
II->getIntrinsicID() == Intrinsic::smin)
1115 return CLow->
sle(*CHigh);
1120 const APInt *CLow, *CHigh;
1127 const APInt &DemandedElts,
1133 switch (
I->getOpcode()) {
1135 case Instruction::Load:
1140 case Instruction::And:
1146 case Instruction::Or:
1152 case Instruction::Xor:
1158 case Instruction::Mul: {
1162 DemandedElts, Known, Known2,
Depth, Q);
1165 case Instruction::UDiv: {
1172 case Instruction::SDiv: {
1179 case Instruction::Select: {
1180 auto ComputeForArm = [&](
Value *Arm,
bool Invert) {
1188 ComputeForArm(
I->getOperand(1),
false)
1192 case Instruction::FPTrunc:
1193 case Instruction::FPExt:
1194 case Instruction::FPToUI:
1195 case Instruction::FPToSI:
1196 case Instruction::SIToFP:
1197 case Instruction::UIToFP:
1199 case Instruction::PtrToInt:
1200 case Instruction::IntToPtr:
1203 case Instruction::ZExt:
1204 case Instruction::Trunc: {
1205 Type *SrcTy =
I->getOperand(0)->getType();
1207 unsigned SrcBitWidth;
1215 assert(SrcBitWidth &&
"SrcBitWidth can't be zero");
1218 if (
auto *Inst = dyn_cast<PossiblyNonNegInst>(
I);
1219 Inst && Inst->hasNonNeg() && !Known.
isNegative())
1224 case Instruction::BitCast: {
1225 Type *SrcTy =
I->getOperand(0)->getType();
1229 !
I->getType()->isVectorTy()) {
1237 V->getType()->isFPOrFPVectorTy()) {
1238 Type *FPType = V->getType()->getScalarType();
1251 if (FPClasses &
fcInf)
1263 if (Result.SignBit) {
1264 if (*Result.SignBit)
1274 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1275 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1276 !
I->getType()->isIntOrIntVectorTy() ||
1277 isa<ScalableVectorType>(
I->getType()))
1282 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1299 unsigned SubScale =
BitWidth / SubBitWidth;
1301 for (
unsigned i = 0; i != NumElts; ++i) {
1302 if (DemandedElts[i])
1303 SubDemandedElts.
setBit(i * SubScale);
1307 for (
unsigned i = 0; i != SubScale; ++i) {
1311 Known.
insertBits(KnownSrc, ShiftElt * SubBitWidth);
1316 case Instruction::SExt: {
1318 unsigned SrcBitWidth =
I->getOperand(0)->getType()->getScalarSizeInBits();
1320 Known = Known.
trunc(SrcBitWidth);
1327 case Instruction::Shl: {
1331 bool ShAmtNonZero) {
1332 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1342 case Instruction::LShr: {
1343 bool Exact = Q.
IIQ.
isExact(cast<BinaryOperator>(
I));
1345 bool ShAmtNonZero) {
1356 case Instruction::AShr: {
1357 bool Exact = Q.
IIQ.
isExact(cast<BinaryOperator>(
I));
1359 bool ShAmtNonZero) {
1366 case Instruction::Sub: {
1370 DemandedElts, Known, Known2,
Depth, Q);
1373 case Instruction::Add: {
1377 DemandedElts, Known, Known2,
Depth, Q);
1380 case Instruction::SRem:
1386 case Instruction::URem:
1391 case Instruction::Alloca:
1394 case Instruction::GetElementPtr: {
1403 for (
unsigned i = 1, e =
I->getNumOperands(); i != e; ++i, ++GTI) {
1408 Value *Index =
I->getOperand(i);
1411 Constant *CIndex = dyn_cast<Constant>(Index);
1419 "Access to structure field must be known at compile time");
1424 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1427 AccConstIndices +=
Offset;
1438 unsigned IndexBitWidth = Index->getType()->getScalarSizeInBits();
1452 APInt ScalingFactor(IndexBitWidth, TypeSizeInBytes);
1453 IndexConst *= ScalingFactor;
1477 case Instruction::PHI: {
1480 Value *R =
nullptr, *L =
nullptr;
1493 case Instruction::LShr:
1494 case Instruction::AShr:
1495 case Instruction::Shl:
1496 case Instruction::UDiv:
1503 case Instruction::URem: {
1516 case Instruction::Shl:
1520 case Instruction::LShr:
1521 case Instruction::UDiv:
1522 case Instruction::URem:
1527 case Instruction::AShr:
1539 case Instruction::Add:
1540 case Instruction::Sub:
1541 case Instruction::And:
1542 case Instruction::Or:
1543 case Instruction::Mul: {
1550 unsigned OpNum =
P->getOperand(0) == R ? 0 : 1;
1551 Instruction *RInst =
P->getIncomingBlock(OpNum)->getTerminator();
1552 Instruction *LInst =
P->getIncomingBlock(1 - OpNum)->getTerminator();
1567 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1581 case Instruction::Add: {
1591 case Instruction::Sub: {
1602 case Instruction::Mul:
1619 if (
P->getNumIncomingValues() == 0)
1626 if (isa_and_nonnull<UndefValue>(
P->hasConstantValue()))
1631 for (
unsigned u = 0, e =
P->getNumIncomingValues(); u < e; ++u) {
1632 Value *IncValue =
P->getIncomingValue(u);
1634 if (IncValue ==
P)
continue;
1638 if (
auto *SI = dyn_cast<SelectInst>(IncValue)) {
1639 if (SI->getTrueValue() ==
P || SI->getFalseValue() ==
P)
1640 IncValue = SI->getTrueValue() ==
P ? SI->getFalseValue()
1641 : SI->getTrueValue();
1649 RecQ.
CxtI =
P->getIncomingBlock(u)->getTerminator();
1671 if ((TrueSucc ==
P->getParent()) != (FalseSucc ==
P->getParent())) {
1673 if (FalseSucc ==
P->getParent())
1687 Known2 = KnownUnion;
1701 case Instruction::Call:
1702 case Instruction::Invoke: {
1710 const auto *CB = cast<CallBase>(
I);
1712 if (std::optional<ConstantRange>
Range = CB->getRange())
1715 if (
const Value *RV = CB->getReturnedArgOperand()) {
1716 if (RV->getType() ==
I->getType()) {
1728 switch (
II->getIntrinsicID()) {
1731 case Intrinsic::abs: {
1733 bool IntMinIsPoison =
match(
II->getArgOperand(1),
m_One());
1734 Known = Known2.
abs(IntMinIsPoison);
1737 case Intrinsic::bitreverse:
1742 case Intrinsic::bswap:
1747 case Intrinsic::ctlz: {
1753 PossibleLZ = std::min(PossibleLZ,
BitWidth - 1);
1758 case Intrinsic::cttz: {
1764 PossibleTZ = std::min(PossibleTZ,
BitWidth - 1);
1769 case Intrinsic::ctpop: {
1780 case Intrinsic::fshr:
1781 case Intrinsic::fshl: {
1788 if (
II->getIntrinsicID() == Intrinsic::fshr)
1801 case Intrinsic::uadd_sat:
1806 case Intrinsic::usub_sat:
1811 case Intrinsic::sadd_sat:
1816 case Intrinsic::ssub_sat:
1822 case Intrinsic::vector_reverse:
1828 case Intrinsic::vector_reduce_and:
1829 case Intrinsic::vector_reduce_or:
1830 case Intrinsic::vector_reduce_umax:
1831 case Intrinsic::vector_reduce_umin:
1832 case Intrinsic::vector_reduce_smax:
1833 case Intrinsic::vector_reduce_smin:
1836 case Intrinsic::vector_reduce_xor: {
1841 auto *VecTy = cast<VectorType>(
I->getOperand(0)->getType());
1843 bool EvenCnt = VecTy->getElementCount().isKnownEven();
1847 if (VecTy->isScalableTy() || EvenCnt)
1851 case Intrinsic::umin:
1856 case Intrinsic::umax:
1861 case Intrinsic::smin:
1867 case Intrinsic::smax:
1873 case Intrinsic::ptrmask: {
1876 const Value *Mask =
I->getOperand(1);
1877 Known2 =
KnownBits(Mask->getType()->getScalarSizeInBits());
1883 case Intrinsic::x86_sse2_pmulh_w:
1884 case Intrinsic::x86_avx2_pmulh_w:
1885 case Intrinsic::x86_avx512_pmulh_w_512:
1890 case Intrinsic::x86_sse2_pmulhu_w:
1891 case Intrinsic::x86_avx2_pmulhu_w:
1892 case Intrinsic::x86_avx512_pmulhu_w_512:
1897 case Intrinsic::x86_sse42_crc32_64_64:
1900 case Intrinsic::x86_ssse3_phadd_d_128:
1901 case Intrinsic::x86_ssse3_phadd_w_128:
1902 case Intrinsic::x86_avx2_phadd_d:
1903 case Intrinsic::x86_avx2_phadd_w: {
1905 I, DemandedElts,
Depth, Q,
1911 case Intrinsic::x86_ssse3_phadd_sw_128:
1912 case Intrinsic::x86_avx2_phadd_sw: {
1917 case Intrinsic::x86_ssse3_phsub_d_128:
1918 case Intrinsic::x86_ssse3_phsub_w_128:
1919 case Intrinsic::x86_avx2_phsub_d:
1920 case Intrinsic::x86_avx2_phsub_w: {
1922 I, DemandedElts,
Depth, Q,
1928 case Intrinsic::x86_ssse3_phsub_sw_128:
1929 case Intrinsic::x86_avx2_phsub_sw: {
1934 case Intrinsic::riscv_vsetvli:
1935 case Intrinsic::riscv_vsetvlimax: {
1936 bool HasAVL =
II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
1939 cast<ConstantInt>(
II->getArgOperand(HasAVL))->getZExtValue());
1941 cast<ConstantInt>(
II->getArgOperand(1 + HasAVL))->getZExtValue());
1948 if (
auto *CI = dyn_cast<ConstantInt>(
II->getArgOperand(0)))
1949 MaxVL = std::min(MaxVL, CI->getZExtValue());
1951 unsigned KnownZeroFirstBit =
Log2_32(MaxVL) + 1;
1956 case Intrinsic::vscale: {
1957 if (!
II->getParent() || !
II->getFunction())
1967 case Instruction::ShuffleVector: {
1968 auto *Shuf = dyn_cast<ShuffleVectorInst>(
I);
1976 APInt DemandedLHS, DemandedRHS;
1983 if (!!DemandedLHS) {
1984 const Value *
LHS = Shuf->getOperand(0);
1990 if (!!DemandedRHS) {
1991 const Value *
RHS = Shuf->getOperand(1);
1997 case Instruction::InsertElement: {
1998 if (isa<ScalableVectorType>(
I->getType())) {
2002 const Value *Vec =
I->getOperand(0);
2003 const Value *Elt =
I->getOperand(1);
2004 auto *CIdx = dyn_cast<ConstantInt>(
I->getOperand(2));
2006 APInt DemandedVecElts = DemandedElts;
2007 bool NeedsElt =
true;
2009 if (CIdx && CIdx->getValue().ult(NumElts)) {
2010 DemandedVecElts.
clearBit(CIdx->getZExtValue());
2011 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2023 if (!DemandedVecElts.
isZero()) {
2029 case Instruction::ExtractElement: {
2032 const Value *Vec =
I->getOperand(0);
2034 auto *CIdx = dyn_cast<ConstantInt>(
Idx);
2035 if (isa<ScalableVectorType>(Vec->
getType())) {
2040 unsigned NumElts = cast<FixedVectorType>(Vec->
getType())->getNumElements();
2042 if (CIdx && CIdx->getValue().ult(NumElts))
2047 case Instruction::ExtractValue:
2052 switch (
II->getIntrinsicID()) {
2054 case Intrinsic::uadd_with_overflow:
2055 case Intrinsic::sadd_with_overflow:
2057 true,
II->getArgOperand(0),
II->getArgOperand(1),
false,
2058 false, DemandedElts, Known, Known2,
Depth, Q);
2060 case Intrinsic::usub_with_overflow:
2061 case Intrinsic::ssub_with_overflow:
2063 false,
II->getArgOperand(0),
II->getArgOperand(1),
false,
2064 false, DemandedElts, Known, Known2,
Depth, Q);
2066 case Intrinsic::umul_with_overflow:
2067 case Intrinsic::smul_with_overflow:
2069 false, DemandedElts, Known, Known2,
Depth, Q);
2075 case Instruction::Freeze:
2119 if (!DemandedElts) {
2125 assert(V &&
"No Value?");
2129 Type *Ty = V->getType();
2133 "Not integer or pointer type!");
2135 if (
auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2137 FVTy->getNumElements() == DemandedElts.
getBitWidth() &&
2138 "DemandedElt width should equal the fixed vector number of elements");
2141 "DemandedElt width should be 1 for scalars or scalable vectors");
2147 "V and Known should have same BitWidth");
2150 "V and Known should have same BitWidth");
2161 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
2168 assert(!isa<ScalableVectorType>(V->getType()));
2172 for (
unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2173 if (!DemandedElts[i])
2175 APInt Elt = CDV->getElementAsAPInt(i);
2184 if (
const auto *CV = dyn_cast<ConstantVector>(V)) {
2185 assert(!isa<ScalableVectorType>(V->getType()));
2189 for (
unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2190 if (!DemandedElts[i])
2193 if (isa<PoisonValue>(Element))
2195 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2200 const APInt &Elt = ElementCI->getValue();
2213 if (isa<UndefValue>(V))
2218 assert(!isa<ConstantData>(V) &&
"Unhandled constant data!");
2220 if (
const auto *
A = dyn_cast<Argument>(V))
2221 if (std::optional<ConstantRange>
Range =
A->getRange())
2230 if (
const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2231 if (!GA->isInterposable())
2236 if (
const Operator *
I = dyn_cast<Operator>(V))
2238 else if (
const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2239 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2240 Known = CR->toKnownBits();
2244 if (isa<PointerType>(V->getType())) {
2245 Align Alignment = V->getPointerAlignment(Q.
DL);
2261 Value *Start =
nullptr, *Step =
nullptr;
2267 if (U.get() == Start) {
2283 case Instruction::Mul:
2288 case Instruction::SDiv:
2294 case Instruction::UDiv:
2300 case Instruction::Shl:
2302 case Instruction::AShr:
2306 case Instruction::LShr:
2324 Pred = ICmpInst::getInversePredicate(Pred);
2326 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2329 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2340 if (isa<Constant>(V))
2344 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2379 auto *
I = dyn_cast<Instruction>(V);
2386 return F->hasFnAttribute(Attribute::VScaleRange);
2403 switch (
I->getOpcode()) {
2404 case Instruction::ZExt:
2406 case Instruction::Trunc:
2408 case Instruction::Shl:
2412 case Instruction::LShr:
2413 if (OrZero || Q.
IIQ.
isExact(cast<BinaryOperator>(
I)))
2416 case Instruction::UDiv:
2420 case Instruction::Mul:
2424 case Instruction::And:
2435 case Instruction::Add: {
2441 if (
match(
I->getOperand(0),
2445 if (
match(
I->getOperand(1),
2450 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2459 if ((~(LHSBits.
Zero & RHSBits.
Zero)).isPowerOf2())
2472 case Instruction::Select:
2475 case Instruction::PHI: {
2479 auto *PN = cast<PHINode>(
I);
2496 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2497 return isKnownToBeAPowerOfTwo(U.get(), OrZero, NewDepth, RecQ);
2500 case Instruction::Invoke:
2501 case Instruction::Call: {
2502 if (
auto *
II = dyn_cast<IntrinsicInst>(
I)) {
2503 switch (
II->getIntrinsicID()) {
2504 case Intrinsic::umax:
2505 case Intrinsic::smax:
2506 case Intrinsic::umin:
2507 case Intrinsic::smin:
2512 case Intrinsic::bitreverse:
2513 case Intrinsic::bswap:
2515 case Intrinsic::fshr:
2516 case Intrinsic::fshl:
2518 if (
II->getArgOperand(0) ==
II->getArgOperand(1))
2542 F =
I->getFunction();
2546 if (!
GEP->hasNoUnsignedWrap() &&
2547 !(
GEP->isInBounds() &&
2552 assert(
GEP->getType()->isPointerTy() &&
"We only support plain pointer GEP");
2563 GTI != GTE; ++GTI) {
2565 if (
StructType *STy = GTI.getStructTypeOrNull()) {
2566 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2570 if (ElementOffset > 0)
2576 if (GTI.getSequentialElementStride(Q.
DL).isZero())
2581 if (
ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2605 assert(!isa<Constant>(V) &&
"Called for constant?");
2610 unsigned NumUsesExplored = 0;
2611 for (
const auto *U : V->users()) {
2619 if (
const auto *CB = dyn_cast<CallBase>(U))
2620 if (
auto *CalledFunc = CB->getCalledFunction())
2621 for (
const Argument &Arg : CalledFunc->args())
2622 if (CB->getArgOperand(Arg.getArgNo()) == V &&
2623 Arg.hasNonNullAttr(
false) &&
2631 V->getType()->getPointerAddressSpace()) &&
2649 NonNullIfTrue =
true;
2651 NonNullIfTrue =
false;
2657 for (
const auto *CmpU : U->users()) {
2659 if (Visited.
insert(CmpU).second)
2662 while (!WorkList.
empty()) {
2671 for (
const auto *CurrU : Curr->users())
2672 if (Visited.
insert(CurrU).second)
2677 if (
const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
2678 assert(BI->isConditional() &&
"uses a comparison!");
2681 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
2685 }
else if (NonNullIfTrue &&
isGuard(Curr) &&
2686 DT->
dominates(cast<Instruction>(Curr), CtxI)) {
2700 const unsigned NumRanges = Ranges->getNumOperands() / 2;
2702 for (
unsigned i = 0; i < NumRanges; ++i) {
2704 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
2706 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
2718 Value *Start =
nullptr, *Step =
nullptr;
2719 const APInt *StartC, *StepC;
2725 case Instruction::Add:
2731 case Instruction::Mul:
2734 case Instruction::Shl:
2736 case Instruction::AShr:
2737 case Instruction::LShr:
2753 Value *
Y,
bool NSW,
bool NUW) {
2806 if (
auto *
C = dyn_cast<Constant>(
X))
2810 return ::isKnownNonEqual(
X,
Y, DemandedElts,
Depth, Q);
2815 Value *
Y,
bool NSW,
bool NUW) {
2844 auto ShiftOp = [&](
const APInt &Lhs,
const APInt &Rhs) {
2845 switch (
I->getOpcode()) {
2846 case Instruction::Shl:
2847 return Lhs.
shl(Rhs);
2848 case Instruction::LShr:
2849 return Lhs.
lshr(Rhs);
2850 case Instruction::AShr:
2851 return Lhs.
ashr(Rhs);
2857 auto InvShiftOp = [&](
const APInt &Lhs,
const APInt &Rhs) {
2858 switch (
I->getOpcode()) {
2859 case Instruction::Shl:
2860 return Lhs.
lshr(Rhs);
2861 case Instruction::LShr:
2862 case Instruction::AShr:
2863 return Lhs.
shl(Rhs);
2876 if (MaxShift.
uge(NumBits))
2879 if (!ShiftOp(KnownVal.
One, MaxShift).isZero())
2884 if (InvShiftOp(KnownVal.
Zero, NumBits - MaxShift)
2893 const APInt &DemandedElts,
2896 switch (
I->getOpcode()) {
2897 case Instruction::Alloca:
2899 return I->getType()->getPointerAddressSpace() == 0;
2900 case Instruction::GetElementPtr:
2901 if (
I->getType()->isPointerTy())
2904 case Instruction::BitCast: {
2932 Type *FromTy =
I->getOperand(0)->getType();
2937 case Instruction::IntToPtr:
2941 if (!isa<ScalableVectorType>(
I->getType()) &&
2946 case Instruction::PtrToInt:
2949 if (!isa<ScalableVectorType>(
I->getType()) &&
2954 case Instruction::Trunc:
2956 if (
auto *TI = dyn_cast<TruncInst>(
I))
2957 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
2961 case Instruction::Sub:
2964 case Instruction::Xor:
2969 case Instruction::Or:
2976 case Instruction::SExt:
2977 case Instruction::ZExt:
2981 case Instruction::Shl: {
2996 case Instruction::LShr:
2997 case Instruction::AShr: {
3012 case Instruction::UDiv:
3013 case Instruction::SDiv: {
3016 if (cast<PossiblyExactOperator>(
I)->isExact())
3028 if (
I->getOpcode() == Instruction::SDiv) {
3030 XKnown = XKnown.
abs(
false);
3031 YKnown = YKnown.
abs(
false);
3037 return XUgeY && *XUgeY;
3039 case Instruction::Add: {
3044 auto *BO = cast<OverflowingBinaryOperator>(
I);
3049 case Instruction::Mul: {
3055 case Instruction::Select: {
3062 auto SelectArmIsNonZero = [&](
bool IsTrueArm) {
3064 Op = IsTrueArm ?
I->getOperand(1) :
I->getOperand(2);
3077 Pred = ICmpInst::getInversePredicate(Pred);
3082 if (SelectArmIsNonZero(
true) &&
3083 SelectArmIsNonZero(
false))
3087 case Instruction::PHI: {
3088 auto *PN = cast<PHINode>(
I);
3098 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
3102 BasicBlock *TrueSucc, *FalseSucc;
3103 if (match(RecQ.CxtI,
3104 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3105 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3107 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3109 if (FalseSucc == PN->getParent())
3110 Pred = CmpInst::getInversePredicate(Pred);
3111 if (cmpExcludesZero(Pred, X))
3119 case Instruction::InsertElement: {
3120 if (isa<ScalableVectorType>(
I->getType()))
3123 const Value *Vec =
I->getOperand(0);
3124 const Value *Elt =
I->getOperand(1);
3125 auto *CIdx = dyn_cast<ConstantInt>(
I->getOperand(2));
3128 APInt DemandedVecElts = DemandedElts;
3129 bool SkipElt =
false;
3131 if (CIdx && CIdx->getValue().ult(NumElts)) {
3132 DemandedVecElts.
clearBit(CIdx->getZExtValue());
3133 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3139 (DemandedVecElts.
isZero() ||
3142 case Instruction::ExtractElement:
3143 if (
const auto *EEI = dyn_cast<ExtractElementInst>(
I)) {
3144 const Value *Vec = EEI->getVectorOperand();
3145 const Value *
Idx = EEI->getIndexOperand();
3146 auto *CIdx = dyn_cast<ConstantInt>(
Idx);
3147 if (
auto *VecTy = dyn_cast<FixedVectorType>(Vec->
getType())) {
3148 unsigned NumElts = VecTy->getNumElements();
3150 if (CIdx && CIdx->getValue().ult(NumElts))
3156 case Instruction::ShuffleVector: {
3157 auto *Shuf = dyn_cast<ShuffleVectorInst>(
I);
3160 APInt DemandedLHS, DemandedRHS;
3166 return (DemandedRHS.
isZero() ||
3171 case Instruction::Freeze:
3175 case Instruction::Load: {
3176 auto *LI = cast<LoadInst>(
I);
3179 if (
auto *PtrT = dyn_cast<PointerType>(
I->getType())) {
3192 case Instruction::ExtractValue: {
3198 case Instruction::Add:
3203 case Instruction::Sub:
3206 case Instruction::Mul:
3215 case Instruction::Call:
3216 case Instruction::Invoke: {
3217 const auto *Call = cast<CallBase>(
I);
3218 if (
I->getType()->isPointerTy()) {
3219 if (Call->isReturnNonNull())
3226 if (std::optional<ConstantRange>
Range = Call->getRange()) {
3231 if (
const Value *RV = Call->getReturnedArgOperand())
3236 if (
auto *
II = dyn_cast<IntrinsicInst>(
I)) {
3237 switch (
II->getIntrinsicID()) {
3238 case Intrinsic::sshl_sat:
3239 case Intrinsic::ushl_sat:
3240 case Intrinsic::abs:
3241 case Intrinsic::bitreverse:
3242 case Intrinsic::bswap:
3243 case Intrinsic::ctpop:
3247 case Intrinsic::ssub_sat:
3249 II->getArgOperand(0),
II->getArgOperand(1));
3250 case Intrinsic::sadd_sat:
3252 II->getArgOperand(0),
II->getArgOperand(1),
3255 case Intrinsic::vector_reverse:
3259 case Intrinsic::vector_reduce_or:
3260 case Intrinsic::vector_reduce_umax:
3261 case Intrinsic::vector_reduce_umin:
3262 case Intrinsic::vector_reduce_smax:
3263 case Intrinsic::vector_reduce_smin:
3265 case Intrinsic::umax:
3266 case Intrinsic::uadd_sat:
3274 case Intrinsic::smax: {
3277 auto IsNonZero = [&](
Value *
Op, std::optional<bool> &OpNonZero,
3279 if (!OpNonZero.has_value())
3280 OpNonZero = OpKnown.isNonZero() ||
3285 std::optional<bool> Op0NonZero, Op1NonZero;
3289 IsNonZero(
II->getArgOperand(1), Op1NonZero, Op1Known))
3294 IsNonZero(
II->getArgOperand(0), Op0NonZero, Op0Known))
3296 return IsNonZero(
II->getArgOperand(1), Op1NonZero, Op1Known) &&
3297 IsNonZero(
II->getArgOperand(0), Op0NonZero, Op0Known);
3299 case Intrinsic::smin: {
3315 case Intrinsic::umin:
3318 case Intrinsic::cttz:
3321 case Intrinsic::ctlz:
3324 case Intrinsic::fshr:
3325 case Intrinsic::fshl:
3327 if (
II->getArgOperand(0) ==
II->getArgOperand(1))
3330 case Intrinsic::vscale:
3332 case Intrinsic::experimental_get_vector_length:
3346 return Known.
One != 0;
3357 Type *Ty = V->getType();
3362 if (
auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3364 FVTy->getNumElements() == DemandedElts.
getBitWidth() &&
3365 "DemandedElt width should equal the fixed vector number of elements");
3368 "DemandedElt width should be 1 for scalars");
3372 if (
auto *
C = dyn_cast<Constant>(V)) {
3373 if (
C->isNullValue())
3375 if (isa<ConstantInt>(
C))
3381 if (
auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3382 for (
unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3383 if (!DemandedElts[i])
3385 Constant *Elt =
C->getAggregateElement(i);
3388 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3395 if (
auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3401 if (
const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3402 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3403 GV->getType()->getAddressSpace() == 0)
3408 if (!isa<ConstantExpr>(V))
3412 if (
const auto *
A = dyn_cast<Argument>(V))
3413 if (std::optional<ConstantRange>
Range =
A->getRange()) {
3428 if (
PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3431 if (
const Argument *
A = dyn_cast<Argument>(V)) {
3432 if (((
A->hasPassPointeeByValueCopyAttr() &&
3434 A->hasNonNullAttr()))
3439 if (
const auto *
I = dyn_cast<Operator>(V))
3443 if (!isa<Constant>(V) &&
3452 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3453 APInt DemandedElts =
3455 return ::isKnownNonZero(V, DemandedElts, Q,
Depth);
3464static std::optional<std::pair<Value*, Value*>>
3468 return std::nullopt;
3477 case Instruction::Or:
3478 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3479 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3482 case Instruction::Xor:
3483 case Instruction::Add: {
3491 case Instruction::Sub:
3497 case Instruction::Mul: {
3501 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3502 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3503 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3504 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3510 !cast<ConstantInt>(Op1->
getOperand(1))->isZero())
3514 case Instruction::Shl: {
3517 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3518 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3519 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3520 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3527 case Instruction::AShr:
3528 case Instruction::LShr: {
3529 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
3530 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
3531 if (!PEO1->isExact() || !PEO2->isExact())
3538 case Instruction::SExt:
3539 case Instruction::ZExt:
3543 case Instruction::PHI: {
3544 const PHINode *PN1 = cast<PHINode>(Op1);
3545 const PHINode *PN2 = cast<PHINode>(Op2);
3551 Value *Start1 =
nullptr, *Step1 =
nullptr;
3553 Value *Start2 =
nullptr, *Step2 =
nullptr;
3560 cast<Operator>(BO2));
3569 if (Values->first != PN1 || Values->second != PN2)
3572 return std::make_pair(Start1, Start2);
3575 return std::nullopt;
3590 case Instruction::Or:
3591 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
3594 case Instruction::Xor:
3595 case Instruction::Add:
3613 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
3616 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
3617 !
C->isZero() && !
C->isOne() &&
3628 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
3631 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
3645 bool UsedFullRecursion =
false;
3647 if (!VisitedBBs.
insert(IncomBB).second)
3651 const APInt *C1, *C2;
3656 if (UsedFullRecursion)
3660 RecQ.
CxtI = IncomBB->getTerminator();
3663 UsedFullRecursion =
true;
3671 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
3675 if (
const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
3677 const Value *Cond2 = SI2->getCondition();
3680 DemandedElts,
Depth + 1, Q) &&
3682 DemandedElts,
Depth + 1, Q);
3695 if (!
A->getType()->isPointerTy() || !
B->getType()->isPointerTy())
3698 auto *GEPA = dyn_cast<GEPOperator>(
A);
3699 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
3703 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
3704 if (!PN || PN->getNumIncomingValues() != 2)
3709 Value *Start =
nullptr;
3711 if (PN->getIncomingValue(0) == Step)
3712 Start = PN->getIncomingValue(1);
3713 else if (PN->getIncomingValue(1) == Step)
3714 Start = PN->getIncomingValue(0);
3725 APInt StartOffset(IndexWidth, 0);
3726 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.
DL, StartOffset);
3727 APInt StepOffset(IndexWidth, 0);
3733 APInt OffsetB(IndexWidth, 0);
3734 B =
B->stripAndAccumulateInBoundsConstantOffsets(Q.
DL, OffsetB);
3735 return Start ==
B &&
3746 if (V1->
getType() != V2->getType())
3756 auto *O1 = dyn_cast<Operator>(V1);
3757 auto *O2 = dyn_cast<Operator>(V2);
3758 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
3763 if (
const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
3764 const PHINode *PN2 = cast<PHINode>(V2);
3819 const APInt &DemandedElts,
3821 const auto *CV = dyn_cast<Constant>(V);
3822 if (!CV || !isa<FixedVectorType>(CV->getType()))
3825 unsigned MinSignBits = TyBits;
3826 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
3827 for (
unsigned i = 0; i != NumElts; ++i) {
3828 if (!DemandedElts[i])
3831 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
3835 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
3842 const APInt &DemandedElts,
3848 assert(Result > 0 &&
"At least one sign bit needs to be present!");
3860 const APInt &DemandedElts,
3862 Type *Ty = V->getType();
3866 if (
auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3868 FVTy->getNumElements() == DemandedElts.
getBitWidth() &&
3869 "DemandedElt width should equal the fixed vector number of elements");
3872 "DemandedElt width should be 1 for scalars");
3886 unsigned FirstAnswer = 1;
3894 if (
auto *U = dyn_cast<Operator>(V)) {
3897 case Instruction::SExt:
3898 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
3902 case Instruction::SDiv: {
3903 const APInt *Denominator;
3916 return std::min(TyBits, NumBits + Denominator->
logBase2());
3921 case Instruction::SRem: {
3924 const APInt *Denominator;
3945 unsigned ResBits = TyBits - Denominator->
ceilLogBase2();
3946 Tmp = std::max(Tmp, ResBits);
3952 case Instruction::AShr: {
3957 if (ShAmt->
uge(TyBits))
3960 Tmp += ShAmtLimited;
3961 if (Tmp > TyBits) Tmp = TyBits;
3965 case Instruction::Shl: {
3970 if (ShAmt->
uge(TyBits))
3975 ShAmt->
uge(TyBits -
X->getType()->getScalarSizeInBits())) {
3977 Tmp += TyBits -
X->getType()->getScalarSizeInBits();
3981 if (ShAmt->
uge(Tmp))
3988 case Instruction::And:
3989 case Instruction::Or:
3990 case Instruction::Xor:
3995 FirstAnswer = std::min(Tmp, Tmp2);
4002 case Instruction::Select: {
4006 const APInt *CLow, *CHigh;
4014 return std::min(Tmp, Tmp2);
4017 case Instruction::Add:
4021 if (Tmp == 1)
break;
4024 if (
const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4025 if (CRHS->isAllOnesValue()) {
4031 if ((Known.
Zero | 1).isAllOnes())
4043 return std::min(Tmp, Tmp2) - 1;
4045 case Instruction::Sub:
4051 if (
const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4052 if (CLHS->isNullValue()) {
4057 if ((Known.
Zero | 1).isAllOnes())
4074 return std::min(Tmp, Tmp2) - 1;
4076 case Instruction::Mul: {
4079 unsigned SignBitsOp0 =
4081 if (SignBitsOp0 == 1)
4083 unsigned SignBitsOp1 =
4085 if (SignBitsOp1 == 1)
4087 unsigned OutValidBits =
4088 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4089 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4092 case Instruction::PHI: {
4093 const PHINode *PN = cast<PHINode>(U);
4096 if (NumIncomingValues > 4)
break;
4098 if (NumIncomingValues == 0)
break;
4104 for (
unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4105 if (Tmp == 1)
return Tmp;
4108 DemandedElts,
Depth + 1, RecQ));
4113 case Instruction::Trunc: {
4118 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4119 if (Tmp > (OperandTyBits - TyBits))
4120 return Tmp - (OperandTyBits - TyBits);
4125 case Instruction::ExtractElement:
4132 case Instruction::ShuffleVector: {
4135 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4140 APInt DemandedLHS, DemandedRHS;
4145 Tmp = std::numeric_limits<unsigned>::max();
4146 if (!!DemandedLHS) {
4147 const Value *
LHS = Shuf->getOperand(0);
4154 if (!!DemandedRHS) {
4155 const Value *
RHS = Shuf->getOperand(1);
4157 Tmp = std::min(Tmp, Tmp2);
4163 assert(Tmp <= TyBits &&
"Failed to determine minimum sign bits");
4166 case Instruction::Call: {
4167 if (
const auto *
II = dyn_cast<IntrinsicInst>(U)) {
4168 switch (
II->getIntrinsicID()) {
4171 case Intrinsic::abs:
4179 case Intrinsic::smin:
4180 case Intrinsic::smax: {
4181 const APInt *CLow, *CHigh;
4196 if (
unsigned VecSignBits =
4214 if (
F->isIntrinsic())
4215 return F->getIntrinsicID();
4221 if (
F->hasLocalLinkage() || !TLI || !TLI->
getLibFunc(CB, Func) ||
4231 return Intrinsic::sin;
4235 return Intrinsic::cos;
4239 return Intrinsic::tan;
4243 return Intrinsic::asin;
4247 return Intrinsic::acos;
4251 return Intrinsic::atan;
4253 case LibFunc_atan2f:
4254 case LibFunc_atan2l:
4255 return Intrinsic::atan2;
4259 return Intrinsic::sinh;
4263 return Intrinsic::cosh;
4267 return Intrinsic::tanh;
4271 return Intrinsic::exp;
4275 return Intrinsic::exp2;
4277 case LibFunc_exp10f:
4278 case LibFunc_exp10l:
4279 return Intrinsic::exp10;
4283 return Intrinsic::log;
4285 case LibFunc_log10f:
4286 case LibFunc_log10l:
4287 return Intrinsic::log10;
4291 return Intrinsic::log2;
4295 return Intrinsic::fabs;
4299 return Intrinsic::minnum;
4303 return Intrinsic::maxnum;
4304 case LibFunc_copysign:
4305 case LibFunc_copysignf:
4306 case LibFunc_copysignl:
4307 return Intrinsic::copysign;
4309 case LibFunc_floorf:
4310 case LibFunc_floorl:
4311 return Intrinsic::floor;
4315 return Intrinsic::ceil;
4317 case LibFunc_truncf:
4318 case LibFunc_truncl:
4319 return Intrinsic::trunc;
4323 return Intrinsic::rint;
4324 case LibFunc_nearbyint:
4325 case LibFunc_nearbyintf:
4326 case LibFunc_nearbyintl:
4327 return Intrinsic::nearbyint;
4329 case LibFunc_roundf:
4330 case LibFunc_roundl:
4331 return Intrinsic::round;
4332 case LibFunc_roundeven:
4333 case LibFunc_roundevenf:
4334 case LibFunc_roundevenl:
4335 return Intrinsic::roundeven;
4339 return Intrinsic::pow;
4343 return Intrinsic::sqrt;
4391 switch (Mode.Input) {
4411 if (!Src.isKnownNeverPosZero() && !Src.isKnownNeverNegZero())
4415 if (Src.isKnownNeverSubnormal())
4445 bool &TrueIfSigned) {
4448 TrueIfSigned =
true;
4449 return RHS.isZero();
4451 TrueIfSigned =
true;
4452 return RHS.isAllOnes();
4454 TrueIfSigned =
false;
4455 return RHS.isAllOnes();
4457 TrueIfSigned =
false;
4458 return RHS.isZero();
4461 TrueIfSigned =
true;
4462 return RHS.isMaxSignedValue();
4465 TrueIfSigned =
true;
4466 return RHS.isMinSignedValue();
4469 TrueIfSigned =
false;
4470 return RHS.isMinSignedValue();
4473 TrueIfSigned =
false;
4474 return RHS.isMaxSignedValue();
4485 bool LookThroughSrc) {
4493std::pair<Value *, FPClassTest>
4495 const APFloat *ConstRHS,
bool LookThroughSrc) {
4497 auto [Src, ClassIfTrue, ClassIfFalse] =
4499 if (Src && ClassIfTrue == ~ClassIfFalse)
4500 return {Src, ClassIfTrue};
4511std::tuple<Value *, FPClassTest, FPClassTest>
4525 const bool IsNegativeRHS = (RHSClass &
fcNegative) == RHSClass;
4526 const bool IsPositiveRHS = (RHSClass &
fcPositive) == RHSClass;
4527 const bool IsNaN = (RHSClass & ~fcNan) ==
fcNone;
4547 const bool IsZero = (OrigClass &
fcZero) == OrigClass;
4594 const bool IsDenormalRHS = (OrigClass &
fcSubnormal) == OrigClass;
4596 const bool IsInf = (OrigClass &
fcInf) == OrigClass;
4614 if (IsNegativeRHS) {
4637 if (IsNegativeRHS) {
4638 Mask = ~fcNegInf & ~fcNan;
4642 Mask = ~fcPosInf & ~fcNan;
4651 if (IsNegativeRHS) {
4671 if (IsNegativeRHS) {
4691 if (IsNegativeRHS) {
4706 if (IsNegativeRHS) {
4734 return {Src, Class, ~fcNan};
4738 return {Src, ~fcNan, RHSClass |
fcNan};
4747 "should have been recognized as an exact class test");
4749 if (IsNegativeRHS) {
4759 return {Src, ~fcNan,
fcNan};
4768 return {Src,
fcNan, ~fcNan};
4787 return {Src, ClassesGE, ~ClassesGE | RHSClass};
4790 return {Src, ClassesGE |
fcNan, ~(ClassesGE |
fcNan) | RHSClass};
4793 return {Src, ClassesLE, ~ClassesLE | RHSClass};
4796 return {Src, ClassesLE |
fcNan, ~(ClassesLE |
fcNan) | RHSClass};
4800 }
else if (IsPositiveRHS) {
4816 return {Src, ClassesGE, ~ClassesGE | RHSClass};
4819 return {Src, ClassesGE |
fcNan, ~(ClassesGE |
fcNan) | RHSClass};
4822 return {Src, ClassesLE, ~ClassesLE | RHSClass};
4825 return {Src, ClassesLE |
fcNan, ~(ClassesLE |
fcNan) | RHSClass};
4834std::tuple<Value *, FPClassTest, FPClassTest>
4836 const APFloat &ConstRHS,
bool LookThroughSrc) {
4884std::tuple<Value *, FPClassTest, FPClassTest>
4886 Value *RHS,
bool LookThroughSrc) {
4896 unsigned Depth,
bool CondIsTrue,
4918 KnownFromContext.
knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
4919 }
else if (
match(
Cond, m_Intrinsic<Intrinsic::is_fpclass>(
4922 KnownFromContext.
knownNot(CondIsTrue ? ~Mask : Mask);
4928 if (TrueIfSigned == CondIsTrue)
4940 return KnownFromContext;
4950 Q.
CxtI, KnownFromContext);
4955 Q.
CxtI, KnownFromContext);
4960 return KnownFromContext;
4970 "Got assumption for the wrong function!");
4971 assert(
I->getIntrinsicID() == Intrinsic::assume &&
4972 "must be an assume intrinsic");
4978 true, Q.
CxtI, KnownFromContext);
4981 return KnownFromContext;
4991 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
4992 APInt DemandedElts =
4998 const APInt &DemandedElts,
5002 if ((InterestedClasses &
5008 KnownSrc,
Depth + 1, Q);
5023 assert(Known.
isUnknown() &&
"should not be called with known information");
5025 if (!DemandedElts) {
5033 if (
auto *CFP = dyn_cast<ConstantFP>(V)) {
5035 Known.
SignBit = CFP->isNegative();
5039 if (isa<ConstantAggregateZero>(V)) {
5045 if (isa<PoisonValue>(V)) {
5052 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5053 const Constant *CV = dyn_cast<Constant>(V);
5056 bool SignBitAllZero =
true;
5057 bool SignBitAllOne =
true;
5060 unsigned NumElts = VFVTy->getNumElements();
5061 for (
unsigned i = 0; i != NumElts; ++i) {
5062 if (!DemandedElts[i])
5070 if (isa<PoisonValue>(Elt))
5072 auto *CElt = dyn_cast<ConstantFP>(Elt);
5078 const APFloat &
C = CElt->getValueAPF();
5081 SignBitAllZero =
false;
5083 SignBitAllOne =
false;
5085 if (SignBitAllOne != SignBitAllZero)
5086 Known.
SignBit = SignBitAllOne;
5091 if (
const auto *CB = dyn_cast<CallBase>(V))
5092 KnownNotFromFlags |= CB->getRetNoFPClass();
5093 else if (
const auto *Arg = dyn_cast<Argument>(V))
5094 KnownNotFromFlags |= Arg->getNoFPClass();
5098 if (FPOp->hasNoNaNs())
5099 KnownNotFromFlags |=
fcNan;
5100 if (FPOp->hasNoInfs())
5101 KnownNotFromFlags |=
fcInf;
5105 KnownNotFromFlags |= ~AssumedClasses.KnownFPClasses;
5109 InterestedClasses &= ~KnownNotFromFlags;
5114 if (*AssumedClasses.SignBit)
5115 Known.signBitMustBeOne();
5117 Known.signBitMustBeZero();
5128 const unsigned Opc =
Op->getOpcode();
5130 case Instruction::FNeg: {
5132 Known,
Depth + 1, Q);
5136 case Instruction::Select: {
5144 Value *TestedValue =
nullptr;
5148 const Function *
F = cast<Instruction>(
Op)->getFunction();
5150 Value *CmpLHS, *CmpRHS;
5157 bool LookThroughFAbsFNeg = CmpLHS !=
LHS && CmpLHS !=
RHS;
5158 std::tie(TestedValue, MaskIfTrue, MaskIfFalse) =
5161 m_Intrinsic<Intrinsic::is_fpclass>(
5164 MaskIfTrue = TestedMask;
5165 MaskIfFalse = ~TestedMask;
5168 if (TestedValue ==
LHS) {
5170 FilterLHS = MaskIfTrue;
5171 }
else if (TestedValue ==
RHS) {
5173 FilterRHS = MaskIfFalse;
5182 Known2,
Depth + 1, Q);
5188 case Instruction::Call: {
5192 case Intrinsic::fabs: {
5197 InterestedClasses, Known,
Depth + 1, Q);
5203 case Intrinsic::copysign: {
5207 Known,
Depth + 1, Q);
5209 KnownSign,
Depth + 1, Q);
5213 case Intrinsic::fma:
5214 case Intrinsic::fmuladd: {
5218 if (
II->getArgOperand(0) !=
II->getArgOperand(1))
5227 KnownAddend,
Depth + 1, Q);
5233 case Intrinsic::sqrt:
5234 case Intrinsic::experimental_constrained_sqrt: {
5237 if (InterestedClasses &
fcNan)
5241 KnownSrc,
Depth + 1, Q);
5264 case Intrinsic::sin:
5265 case Intrinsic::cos: {
5269 KnownSrc,
Depth + 1, Q);
5275 case Intrinsic::maxnum:
5276 case Intrinsic::minnum:
5277 case Intrinsic::minimum:
5278 case Intrinsic::maximum: {
5281 KnownLHS,
Depth + 1, Q);
5283 KnownRHS,
Depth + 1, Q);
5286 Known = KnownLHS | KnownRHS;
5289 if (NeverNaN && (IID == Intrinsic::minnum || IID == Intrinsic::maxnum))
5292 if (IID == Intrinsic::maxnum) {
5300 }
else if (IID == Intrinsic::maximum) {
5306 }
else if (IID == Intrinsic::minnum) {
5336 II->getType()->getScalarType()->getFltSemantics());
5348 }
else if ((IID == Intrinsic::maximum || IID == Intrinsic::minimum) ||
5353 if ((IID == Intrinsic::maximum || IID == Intrinsic::maxnum) &&
5356 else if ((IID == Intrinsic::minimum || IID == Intrinsic::minnum) &&
5363 case Intrinsic::canonicalize: {
5366 KnownSrc,
Depth + 1, Q);
5390 II->getType()->getScalarType()->getFltSemantics();
5410 case Intrinsic::vector_reduce_fmax:
5411 case Intrinsic::vector_reduce_fmin:
5412 case Intrinsic::vector_reduce_fmaximum:
5413 case Intrinsic::vector_reduce_fminimum: {
5417 InterestedClasses,
Depth + 1, Q);
5424 case Intrinsic::vector_reverse:
5427 II->getFastMathFlags(), InterestedClasses,
Depth + 1, Q);
5429 case Intrinsic::trunc:
5430 case Intrinsic::floor:
5431 case Intrinsic::ceil:
5432 case Intrinsic::rint:
5433 case Intrinsic::nearbyint:
5434 case Intrinsic::round:
5435 case Intrinsic::roundeven: {
5443 KnownSrc,
Depth + 1, Q);
5452 if (IID == Intrinsic::trunc || !V->getType()->isMultiUnitFPType()) {
5467 case Intrinsic::exp:
5468 case Intrinsic::exp2:
5469 case Intrinsic::exp10: {
5476 KnownSrc,
Depth + 1, Q);
5484 case Intrinsic::fptrunc_round: {
5489 case Intrinsic::log:
5490 case Intrinsic::log10:
5491 case Intrinsic::log2:
5492 case Intrinsic::experimental_constrained_log:
5493 case Intrinsic::experimental_constrained_log10:
5494 case Intrinsic::experimental_constrained_log2: {
5510 KnownSrc,
Depth + 1, Q);
5524 case Intrinsic::powi: {
5528 const Value *Exp =
II->getArgOperand(1);
5529 Type *ExpTy = Exp->getType();
5533 ExponentKnownBits,
Depth + 1, Q);
5535 if (ExponentKnownBits.
Zero[0]) {
5550 KnownSrc,
Depth + 1, Q);
5555 case Intrinsic::ldexp: {
5558 KnownSrc,
Depth + 1, Q);
5574 if ((InterestedClasses & ExpInfoMask) ==
fcNone)
5580 II->getType()->getScalarType()->getFltSemantics();
5582 const Value *ExpArg =
II->getArgOperand(1);
5586 const int MantissaBits = Precision - 1;
5592 if (ConstVal && ConstVal->
isZero()) {
5615 case Intrinsic::arithmetic_fence: {
5617 Known,
Depth + 1, Q);
5620 case Intrinsic::experimental_constrained_sitofp:
5621 case Intrinsic::experimental_constrained_uitofp:
5631 if (IID == Intrinsic::experimental_constrained_uitofp)
5642 case Instruction::FAdd:
5643 case Instruction::FSub: {
5646 Op->getOpcode() == Instruction::FAdd &&
5648 bool WantNaN = (InterestedClasses &
fcNan) !=
fcNone;
5651 if (!WantNaN && !WantNegative && !WantNegZero)
5657 if (InterestedClasses &
fcNan)
5658 InterestedSrcs |=
fcInf;
5660 KnownRHS,
Depth + 1, Q);
5664 WantNegZero || Opc == Instruction::FSub) {
5669 KnownLHS,
Depth + 1, Q);
5677 const Function *
F = cast<Instruction>(
Op)->getFunction();
5679 if (
Op->getOpcode() == Instruction::FAdd) {
5707 case Instruction::FMul: {
5709 if (
Op->getOperand(0) ==
Op->getOperand(1))
5742 const Function *
F = cast<Instruction>(
Op)->getFunction();
5754 case Instruction::FDiv:
5755 case Instruction::FRem: {
5756 if (
Op->getOperand(0) ==
Op->getOperand(1)) {
5758 if (
Op->getOpcode() == Instruction::FDiv) {
5769 const bool WantNan = (InterestedClasses &
fcNan) !=
fcNone;
5771 const bool WantPositive =
5773 if (!WantNan && !WantNegative && !WantPositive)
5782 bool KnowSomethingUseful =
5785 if (KnowSomethingUseful || WantPositive) {
5791 InterestedClasses & InterestedLHS, KnownLHS,
5795 const Function *
F = cast<Instruction>(
Op)->getFunction();
5797 if (
Op->getOpcode() == Instruction::FDiv) {
5834 case Instruction::FPExt: {
5837 Known,
Depth + 1, Q);
5840 Op->getType()->getScalarType()->getFltSemantics();
5842 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
5858 case Instruction::FPTrunc: {
5863 case Instruction::SIToFP:
5864 case Instruction::UIToFP: {
5873 if (
Op->getOpcode() == Instruction::UIToFP)
5876 if (InterestedClasses &
fcInf) {
5880 int IntSize =
Op->getOperand(0)->getType()->getScalarSizeInBits();
5881 if (
Op->getOpcode() == Instruction::SIToFP)
5886 Type *FPTy =
Op->getType()->getScalarType();
5893 case Instruction::ExtractElement: {
5896 const Value *Vec =
Op->getOperand(0);
5898 auto *CIdx = dyn_cast<ConstantInt>(
Idx);
5900 if (
auto *VecTy = dyn_cast<FixedVectorType>(Vec->
getType())) {
5901 unsigned NumElts = VecTy->getNumElements();
5903 if (CIdx && CIdx->getValue().ult(NumElts))
5911 case Instruction::InsertElement: {
5912 if (isa<ScalableVectorType>(
Op->getType()))
5915 const Value *Vec =
Op->getOperand(0);
5916 const Value *Elt =
Op->getOperand(1);
5917 auto *CIdx = dyn_cast<ConstantInt>(
Op->getOperand(2));
5919 APInt DemandedVecElts = DemandedElts;
5920 bool NeedsElt =
true;
5922 if (CIdx && CIdx->getValue().ult(NumElts)) {
5923 DemandedVecElts.
clearBit(CIdx->getZExtValue());
5924 NeedsElt = DemandedElts[CIdx->getZExtValue()];
5938 if (!DemandedVecElts.
isZero()) {
5947 case Instruction::ShuffleVector: {
5950 APInt DemandedLHS, DemandedRHS;
5951 auto *Shuf = dyn_cast<ShuffleVectorInst>(
Op);
5955 if (!!DemandedLHS) {
5956 const Value *
LHS = Shuf->getOperand(0);
5967 if (!!DemandedRHS) {
5969 const Value *
RHS = Shuf->getOperand(1);
5977 case Instruction::ExtractValue: {
5981 if (isa<StructType>(Src->getType()) && Indices.
size() == 1 &&
5983 if (
const auto *
II = dyn_cast<IntrinsicInst>(Src)) {
5984 switch (
II->getIntrinsicID()) {
5985 case Intrinsic::frexp: {
5990 InterestedClasses, KnownSrc,
Depth + 1, Q);
5992 const Function *
F = cast<Instruction>(
Op)->getFunction();
6025 case Instruction::PHI: {
6028 if (
P->getNumIncomingValues() == 0)
6035 if (
Depth < PhiRecursionLimit) {
6037 if (isa_and_nonnull<UndefValue>(
P->hasConstantValue()))
6042 for (
const Use &U :
P->operands()) {
6043 Value *IncValue = U.get();
6048 Instruction *CxtI =
P->getIncomingBlock(U)->getTerminator();
6056 }
else if (
auto *IncPhi = dyn_cast<PHINode>(IncValue);
6057 IncPhi && IncPhi->getNumIncomingValues() == 2) {
6059 if (IncPhi->getIncomingValue(
Idx) ==
P) {
6060 IncValue = IncPhi->getIncomingValue(1 -
Idx);
6061 CxtI = IncPhi->getIncomingBlock(1 -
Idx)->getTerminator();
6089 case Instruction::BitCast: {
6092 !Src->getType()->isIntOrIntVectorTy())
6095 const Type *Ty =
Op->getType()->getScalarType();
6100 if (Bits.isNonNegative())
6102 else if (Bits.isNegative())
6121 InfKB.Zero.clearSignBit();
6123 assert(!InfResult.value());
6125 }
else if (Bits == InfKB) {
6133 ZeroKB.Zero.clearSignBit();
6135 assert(!ZeroResult.value());
6137 }
else if (Bits == ZeroKB) {
6150 const APInt &DemandedElts,
6157 return KnownClasses;
6172 if (V->getType()->isIntegerTy(8))
6179 if (isa<UndefValue>(V))
6183 if (
DL.getTypeStoreSize(V->getType()).isZero())
6198 if (
C->isNullValue())
6205 if (CFP->getType()->isHalfTy())
6207 else if (CFP->getType()->isFloatTy())
6209 else if (CFP->getType()->isDoubleTy())
6218 if (CI->getBitWidth() % 8 == 0) {
6219 assert(CI->getBitWidth() > 8 &&
"8 bits should be handled above!");
6220 if (!CI->getValue().isSplat(8))
6222 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6226 if (
auto *CE = dyn_cast<ConstantExpr>(
C)) {
6227 if (CE->getOpcode() == Instruction::IntToPtr) {
6228 if (
auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6229 unsigned BitWidth =
DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6242 if (
LHS == UndefInt8)
6244 if (
RHS == UndefInt8)
6250 Value *Val = UndefInt8;
6251 for (
unsigned I = 0, E = CA->getNumElements();
I != E; ++
I)
6257 if (isa<ConstantAggregate>(
C)) {
6258 Value *Val = UndefInt8;
6279 StructType *STy = dyn_cast<StructType>(IndexedType);
6293 while (PrevTo != OrigTo) {
6340 unsigned IdxSkip = Idxs.
size();
6353 std::optional<BasicBlock::iterator> InsertBefore) {
6356 if (idx_range.
empty())
6359 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6360 "Not looking at a struct or array?");
6362 "Invalid indices for type?");
6364 if (
Constant *
C = dyn_cast<Constant>(V)) {
6365 C =
C->getAggregateElement(idx_range[0]);
6366 if (!
C)
return nullptr;
6373 const unsigned *req_idx = idx_range.
begin();
6374 for (
const unsigned *i =
I->idx_begin(), *e =
I->idx_end();
6375 i != e; ++i, ++req_idx) {
6376 if (req_idx == idx_range.
end()) {
6406 ArrayRef(req_idx, idx_range.
end()), InsertBefore);
6415 unsigned size =
I->getNumIndices() + idx_range.
size();
6420 Idxs.
append(
I->idx_begin(),
I->idx_end());
6426 &&
"Number of indices added not correct?");
6436 unsigned CharSize) {
6438 if (
GEP->getNumOperands() != 3)
6443 ArrayType *AT = dyn_cast<ArrayType>(
GEP->getSourceElementType());
6449 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(
GEP->getOperand(1));
6450 if (!FirstIdx || !FirstIdx->
isZero())
6464 assert(V &&
"V should not be null.");
6465 assert((ElementSize % 8) == 0 &&
6466 "ElementSize expected to be a multiple of the size of a byte.");
6467 unsigned ElementSizeInBytes = ElementSize / 8;
6479 APInt Off(
DL.getIndexTypeSizeInBits(V->getType()), 0);
6481 if (GV != V->stripAndAccumulateConstantOffsets(
DL, Off,
6486 uint64_t StartIdx = Off.getLimitedValue();
6493 if ((StartIdx % ElementSizeInBytes) != 0)
6496 Offset += StartIdx / ElementSizeInBytes;
6502 uint64_t SizeInBytes =
DL.getTypeStoreSize(GVTy).getFixedValue();
6505 Slice.
Array =
nullptr;
6516 if (
auto *ArrayInit = dyn_cast<ConstantDataArray>(
Init)) {
6517 Type *InitElTy = ArrayInit->getElementType();
6522 ArrayTy = ArrayInit->getType();
6527 if (ElementSize != 8)
6538 Array = dyn_cast<ConstantDataArray>(
Init);
6539 ArrayTy = dyn_cast<ArrayType>(
Init->getType());
6546 Slice.
Array = Array;
6562 if (Slice.
Array ==
nullptr) {
6585 Str = Str.substr(Slice.
Offset);
6591 Str = Str.substr(0, Str.find(
'\0'));
6604 unsigned CharSize) {
6606 V = V->stripPointerCasts();
6610 if (
const PHINode *PN = dyn_cast<PHINode>(V)) {
6611 if (!PHIs.
insert(PN).second)
6616 for (
Value *IncValue : PN->incoming_values()) {
6618 if (Len == 0)
return 0;
6620 if (Len == ~0ULL)
continue;
6622 if (Len != LenSoFar && LenSoFar != ~0ULL)
6632 if (
const SelectInst *SI = dyn_cast<SelectInst>(V)) {
6634 if (Len1 == 0)
return 0;
6636 if (Len2 == 0)
return 0;
6637 if (Len1 == ~0ULL)
return Len2;
6638 if (Len2 == ~0ULL)
return Len1;
6639 if (Len1 != Len2)
return 0;
6648 if (Slice.
Array ==
nullptr)
6656 unsigned NullIndex = 0;
6657 for (
unsigned E = Slice.
Length; NullIndex < E; ++NullIndex) {
6662 return NullIndex + 1;
6668 if (!V->getType()->isPointerTy())
6675 return Len == ~0ULL ? 1 : Len;
6680 bool MustPreserveNullness) {
6682 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
6683 if (
const Value *RV = Call->getReturnedArgOperand())
6687 Call, MustPreserveNullness))
6688 return Call->getArgOperand(0);
6693 const CallBase *Call,
bool MustPreserveNullness) {
6694 switch (Call->getIntrinsicID()) {
6695 case Intrinsic::launder_invariant_group:
6696 case Intrinsic::strip_invariant_group:
6697 case Intrinsic::aarch64_irg:
6698 case Intrinsic::aarch64_tagp:
6708 case Intrinsic::amdgcn_make_buffer_rsrc:
6710 case Intrinsic::ptrmask:
6711 return !MustPreserveNullness;
6712 case Intrinsic::threadlocal_address:
6715 return !Call->getParent()->getParent()->isPresplitCoroutine();
6732 if (!PrevValue || LI->
getLoopFor(PrevValue->getParent()) != L)
6734 if (!PrevValue || LI->
getLoopFor(PrevValue->getParent()) != L)
6742 if (
auto *Load = dyn_cast<LoadInst>(PrevValue))
6743 if (!L->isLoopInvariant(Load->getPointerOperand()))
6749 for (
unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
6750 if (
auto *
GEP = dyn_cast<GEPOperator>(V)) {
6751 const Value *PtrOp =
GEP->getPointerOperand();
6757 Value *NewV = cast<Operator>(V)->getOperand(0);
6761 }
else if (
auto *GA = dyn_cast<GlobalAlias>(V)) {
6762 if (GA->isInterposable())
6764 V = GA->getAliasee();
6766 if (
auto *
PHI = dyn_cast<PHINode>(V)) {
6768 if (
PHI->getNumIncomingValues() == 1) {
6769 V =
PHI->getIncomingValue(0);
6772 }
else if (
auto *Call = dyn_cast<CallBase>(V)) {
6790 assert(V->getType()->isPointerTy() &&
"Unexpected operand type!");
6797 const LoopInfo *LI,
unsigned MaxLookup) {
6805 if (!Visited.
insert(
P).second)
6808 if (
auto *SI = dyn_cast<SelectInst>(
P)) {
6810 Worklist.
push_back(SI->getFalseValue());
6814 if (
auto *PN = dyn_cast<PHINode>(
P)) {
6834 }
while (!Worklist.
empty());
6838 const unsigned MaxVisited = 8;
6843 const Value *Object =
nullptr;
6853 if (!Visited.
insert(
P).second)
6856 if (Visited.
size() == MaxVisited)
6859 if (
auto *SI = dyn_cast<SelectInst>(
P)) {
6861 Worklist.
push_back(SI->getFalseValue());
6865 if (
auto *PN = dyn_cast<PHINode>(
P)) {
6872 else if (Object !=
P)
6874 }
while (!Worklist.
empty());
6883 if (
const Operator *U = dyn_cast<Operator>(V)) {
6886 if (U->getOpcode() == Instruction::PtrToInt)
6887 return U->getOperand(0);
6894 if (U->getOpcode() != Instruction::Add ||
6895 (!isa<ConstantInt>(U->getOperand(1)) &&
6897 !isa<PHINode>(U->getOperand(1))))
6899 V = U->getOperand(0);
6903 assert(V->getType()->isIntegerTy() &&
"Unexpected operand type!");
6920 for (
const Value *V : Objs) {
6921 if (!Visited.
insert(V).second)
6926 if (O->getType()->isPointerTy()) {
6939 }
while (!Working.
empty());
6948 auto AddWork = [&](
Value *V) {
6949 if (Visited.
insert(V).second)
6958 if (
AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
6959 if (Result && Result != AI)
6962 }
else if (
CastInst *CI = dyn_cast<CastInst>(V)) {
6963 AddWork(CI->getOperand(0));
6964 }
else if (
PHINode *PN = dyn_cast<PHINode>(V)) {
6965 for (
Value *IncValue : PN->incoming_values())
6967 }
else if (
auto *SI = dyn_cast<SelectInst>(V)) {
6968 AddWork(SI->getTrueValue());
6969 AddWork(SI->getFalseValue());
6971 if (OffsetZero && !
GEP->hasAllZeroIndices())
6973 AddWork(
GEP->getPointerOperand());
6974 }
else if (
CallBase *CB = dyn_cast<CallBase>(V)) {
6975 Value *Returned = CB->getReturnedArgOperand();
6983 }
while (!Worklist.
empty());
6989 const Value *V,
bool AllowLifetime,
bool AllowDroppable) {
6990 for (
const User *U : V->users()) {
6995 if (AllowLifetime &&
II->isLifetimeStartOrEnd())
6998 if (AllowDroppable &&
II->isDroppable())
7016 if (
auto *
II = dyn_cast<IntrinsicInst>(
I))
7018 auto *Shuffle = dyn_cast<ShuffleVectorInst>(
I);
7019 return (!Shuffle || Shuffle->isSelect()) &&
7020 !isa<CallBase, BitCastInst, ExtractElementInst>(
I);
7028 bool UseVariableInfo) {
7030 AC, DT, TLI, UseVariableInfo);
7036 bool UseVariableInfo) {
7040 auto hasEqualReturnAndLeadingOperandTypes =
7041 [](
const Instruction *Inst,
unsigned NumLeadingOperands) {
7045 for (
unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7051 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7053 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7060 case Instruction::UDiv:
7061 case Instruction::URem: {
7068 case Instruction::SDiv:
7069 case Instruction::SRem: {
7071 const APInt *Numerator, *Denominator;
7075 if (*Denominator == 0)
7087 case Instruction::Load: {
7088 if (!UseVariableInfo)
7091 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7101 case Instruction::Call: {
7102 auto *CI = dyn_cast<const CallInst>(Inst);
7105 const Function *Callee = CI->getCalledFunction();
7109 return Callee && Callee->isSpeculatable();
7111 case Instruction::VAArg:
7112 case Instruction::Alloca:
7113 case Instruction::Invoke:
7114 case Instruction::CallBr:
7115 case Instruction::PHI:
7116 case Instruction::Store:
7117 case Instruction::Ret:
7118 case Instruction::Br:
7119 case Instruction::IndirectBr:
7120 case Instruction::Switch:
7121 case Instruction::Unreachable:
7122 case Instruction::Fence:
7123 case Instruction::AtomicRMW:
7124 case Instruction::AtomicCmpXchg:
7125 case Instruction::LandingPad:
7126 case Instruction::Resume:
7127 case Instruction::CatchSwitch:
7128 case Instruction::CatchPad:
7129 case Instruction::CatchRet:
7130 case Instruction::CleanupPad:
7131 case Instruction::CleanupRet:
7137 if (
I.mayReadOrWriteMemory())
7250 if (
Add &&
Add->hasNoSignedWrap()) {
7290 bool LHSOrRHSKnownNonNegative =
7292 bool LHSOrRHSKnownNegative =
7294 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7297 if ((AddKnown.
isNonNegative() && LHSOrRHSKnownNonNegative) ||
7298 (AddKnown.
isNegative() && LHSOrRHSKnownNegative))
7373 if (
const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7374 assert(EVI->getNumIndices() == 1 &&
"Obvious from CI's type");
7376 if (EVI->getIndices()[0] == 0)
7379 assert(EVI->getIndices()[0] == 1 &&
"Obvious from CI's type");
7381 for (
const auto *U : EVI->users())
7382 if (
const auto *
B = dyn_cast<BranchInst>(U)) {
7383 assert(
B->isConditional() &&
"How else is it using an i1?");
7394 auto AllUsesGuardedByBranch = [&](
const BranchInst *BI) {
7400 for (
const auto *Result :
Results) {
7403 if (DT.
dominates(NoWrapEdge, Result->getParent()))
7406 for (
const auto &RU : Result->uses())
7414 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7419 auto *
C = dyn_cast<Constant>(ShiftAmount);
7425 if (
auto *FVTy = dyn_cast<FixedVectorType>(
C->getType())) {
7426 unsigned NumElts = FVTy->getNumElements();
7427 for (
unsigned i = 0; i < NumElts; ++i)
7428 ShiftAmounts.
push_back(
C->getAggregateElement(i));
7429 }
else if (isa<ScalableVectorType>(
C->getType()))
7435 auto *CI = dyn_cast_or_null<ConstantInt>(
C);
7436 return CI && CI->getValue().ult(
C->getType()->getIntegerBitWidth());
7449 return (
unsigned(Kind) &
unsigned(UndefPoisonKind::PoisonOnly)) != 0;
7453 return (
unsigned(Kind) &
unsigned(UndefPoisonKind::UndefOnly)) != 0;
7457 bool ConsiderFlagsAndMetadata) {
7460 Op->hasPoisonGeneratingAnnotations())
7463 unsigned Opcode =
Op->getOpcode();
7467 case Instruction::Shl:
7468 case Instruction::AShr:
7469 case Instruction::LShr:
7471 case Instruction::FPToSI:
7472 case Instruction::FPToUI:
7476 case Instruction::Call:
7477 if (
auto *
II = dyn_cast<IntrinsicInst>(
Op)) {
7478 switch (
II->getIntrinsicID()) {
7480 case Intrinsic::ctlz:
7481 case Intrinsic::cttz:
7482 case Intrinsic::abs:
7483 if (cast<ConstantInt>(
II->getArgOperand(1))->isNullValue())
7486 case Intrinsic::ctpop:
7487 case Intrinsic::bswap:
7488 case Intrinsic::bitreverse:
7489 case Intrinsic::fshl:
7490 case Intrinsic::fshr:
7491 case Intrinsic::smax:
7492 case Intrinsic::smin:
7493 case Intrinsic::umax:
7494 case Intrinsic::umin:
7495 case Intrinsic::ptrmask:
7496 case Intrinsic::fptoui_sat:
7497 case Intrinsic::fptosi_sat:
7498 case Intrinsic::sadd_with_overflow:
7499 case Intrinsic::ssub_with_overflow:
7500 case Intrinsic::smul_with_overflow:
7501 case Intrinsic::uadd_with_overflow:
7502 case Intrinsic::usub_with_overflow:
7503 case Intrinsic::umul_with_overflow:
7504 case Intrinsic::sadd_sat:
7505 case Intrinsic::uadd_sat:
7506 case Intrinsic::ssub_sat:
7507 case Intrinsic::usub_sat:
7509 case Intrinsic::sshl_sat:
7510 case Intrinsic::ushl_sat:
7513 case Intrinsic::fma:
7514 case Intrinsic::fmuladd:
7515 case Intrinsic::sqrt:
7516 case Intrinsic::powi:
7517 case Intrinsic::sin:
7518 case Intrinsic::cos:
7519 case Intrinsic::pow:
7520 case Intrinsic::log:
7521 case Intrinsic::log10:
7522 case Intrinsic::log2:
7523 case Intrinsic::exp:
7524 case Intrinsic::exp2:
7525 case Intrinsic::exp10:
7526 case Intrinsic::fabs:
7527 case Intrinsic::copysign:
7528 case Intrinsic::floor:
7529 case Intrinsic::ceil:
7530 case Intrinsic::trunc:
7531 case Intrinsic::rint:
7532 case Intrinsic::nearbyint:
7533 case Intrinsic::round:
7534 case Intrinsic::roundeven:
7535 case Intrinsic::fptrunc_round:
7536 case Intrinsic::canonicalize:
7537 case Intrinsic::arithmetic_fence:
7538 case Intrinsic::minnum:
7539 case Intrinsic::maxnum:
7540 case Intrinsic::minimum:
7541 case Intrinsic::maximum:
7542 case Intrinsic::is_fpclass:
7543 case Intrinsic::ldexp:
7544 case Intrinsic::frexp:
7546 case Intrinsic::lround:
7547 case Intrinsic::llround:
7548 case Intrinsic::lrint:
7549 case Intrinsic::llrint:
7556 case Instruction::CallBr:
7557 case Instruction::Invoke: {
7558 const auto *CB = cast<CallBase>(
Op);
7559 return !CB->hasRetAttr(Attribute::NoUndef);
7561 case Instruction::InsertElement:
7562 case Instruction::ExtractElement: {
7564 auto *VTy = cast<VectorType>(
Op->getOperand(0)->getType());
7565 unsigned IdxOp =
Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
7566 auto *
Idx = dyn_cast<ConstantInt>(
Op->getOperand(IdxOp));
7569 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
7572 case Instruction::ShuffleVector: {
7574 ? cast<ConstantExpr>(
Op)->getShuffleMask()
7575 : cast<ShuffleVectorInst>(
Op)->getShuffleMask();
7578 case Instruction::FNeg:
7579 case Instruction::PHI:
7580 case Instruction::Select:
7581 case Instruction::URem:
7582 case Instruction::SRem:
7583 case Instruction::ExtractValue:
7584 case Instruction::InsertValue:
7585 case Instruction::Freeze:
7586 case Instruction::ICmp:
7587 case Instruction::FCmp:
7588 case Instruction::FAdd:
7589 case Instruction::FSub:
7590 case Instruction::FMul:
7591 case Instruction::FDiv:
7592 case Instruction::FRem:
7594 case Instruction::GetElementPtr:
7599 const auto *CE = dyn_cast<ConstantExpr>(
Op);
7600 if (isa<CastInst>(
Op) || (CE && CE->isCast()))
7611 bool ConsiderFlagsAndMetadata) {
7612 return ::canCreateUndefOrPoison(
Op, UndefPoisonKind::UndefOrPoison,
7613 ConsiderFlagsAndMetadata);
7617 return ::canCreateUndefOrPoison(
Op, UndefPoisonKind::PoisonOnly,
7618 ConsiderFlagsAndMetadata);
7623 if (ValAssumedPoison == V)
7630 if (
const auto *
I = dyn_cast<Instruction>(V)) {
7632 return propagatesPoison(Op) &&
7633 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
7661 const auto *
I = dyn_cast<Instruction>(ValAssumedPoison);
7664 return impliesPoison(Op, V, Depth + 1);
7671 return ::impliesPoison(ValAssumedPoison, V, 0);
7682 if (isa<MetadataAsValue>(V))
7685 if (
const auto *
A = dyn_cast<Argument>(V)) {
7686 if (
A->hasAttribute(Attribute::NoUndef) ||
7687 A->hasAttribute(Attribute::Dereferenceable) ||
7688 A->hasAttribute(Attribute::DereferenceableOrNull))
7692 if (
auto *
C = dyn_cast<Constant>(V)) {
7693 if (isa<PoisonValue>(
C))
7696 if (isa<UndefValue>(
C))
7699 if (isa<ConstantInt>(
C) || isa<GlobalVariable>(
C) || isa<ConstantFP>(V) ||
7700 isa<ConstantPointerNull>(
C) || isa<Function>(
C))
7703 if (
C->getType()->isVectorTy() && !isa<ConstantExpr>(
C)) {
7708 return !
C->containsConstantExpression();
7720 auto *StrippedV = V->stripPointerCastsSameRepresentation();
7721 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
7722 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
7725 auto OpCheck = [&](
const Value *V) {
7729 if (
auto *Opr = dyn_cast<Operator>(V)) {
7732 if (isa<FreezeInst>(V))
7735 if (
const auto *CB = dyn_cast<CallBase>(V)) {
7736 if (CB->hasRetAttr(Attribute::NoUndef) ||
7737 CB->hasRetAttr(Attribute::Dereferenceable) ||
7738 CB->hasRetAttr(Attribute::DereferenceableOrNull))
7742 if (
const auto *PN = dyn_cast<PHINode>(V)) {
7743 unsigned Num = PN->getNumIncomingValues();
7744 bool IsWellDefined =
true;
7745 for (
unsigned i = 0; i < Num; ++i) {
7746 auto *TI = PN->getIncomingBlock(i)->getTerminator();
7748 DT,
Depth + 1, Kind)) {
7749 IsWellDefined =
false;
7757 all_of(Opr->operands(), OpCheck))
7761 if (
auto *
I = dyn_cast<LoadInst>(V))
7762 if (
I->hasMetadata(LLVMContext::MD_noundef) ||
7763 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
7764 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
7784 auto *Dominator = DNode->
getIDom();
7789 auto *TI = Dominator->
getBlock()->getTerminator();
7792 if (
auto BI = dyn_cast_or_null<BranchInst>(TI)) {
7793 if (BI->isConditional())
7794 Cond = BI->getCondition();
7795 }
else if (
auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
7796 Cond = SI->getCondition();
7804 auto *Opr = cast<Operator>(
Cond);
7805 if (
any_of(Opr->operands(), [V](
const Use &U) {
7806 return V == U && propagatesPoison(U);
7812 Dominator = Dominator->getIDom();
7825 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT,
Depth,
7826 UndefPoisonKind::UndefOrPoison);
7832 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT,
Depth,
7833 UndefPoisonKind::PoisonOnly);
7839 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT,
Depth,
7840 UndefPoisonKind::UndefOnly);
7863 while (!Worklist.
empty()) {
7872 if (
I != Root && !
any_of(
I->operands(), [&KnownPoison](
const Use &U) {
7873 return KnownPoison.contains(U) && propagatesPoison(U);
7877 if (KnownPoison.
insert(
I).second)
7889 return ::computeOverflowForSignedAdd(
Add->getOperand(0),
Add->getOperand(1),
7897 return ::computeOverflowForSignedAdd(
LHS,
RHS,
nullptr, SQ);
7906 if (isa<ReturnInst>(
I))
7908 if (isa<UnreachableInst>(
I))
7915 if (isa<CatchPadInst>(
I)) {
7929 return !
I->mayThrow() &&
I->willReturn();
7943 unsigned ScanLimit) {
7950 assert(ScanLimit &&
"scan limit must be non-zero");
7952 if (isa<DbgInfoIntrinsic>(
I))
7954 if (--ScanLimit == 0)
7968 if (
I->getParent() != L->getHeader())
return false;
7971 if (&LI ==
I)
return true;
7974 llvm_unreachable(
"Instruction not contained in its own parent basic block.");
7979 switch (
I->getOpcode()) {
7980 case Instruction::Freeze:
7981 case Instruction::PHI:
7982 case Instruction::Invoke:
7984 case Instruction::Select:
7986 case Instruction::Call:
7987 if (
auto *
II = dyn_cast<IntrinsicInst>(
I)) {
7988 switch (
II->getIntrinsicID()) {
7990 case Intrinsic::sadd_with_overflow:
7991 case Intrinsic::ssub_with_overflow:
7992 case Intrinsic::smul_with_overflow:
7993 case Intrinsic::uadd_with_overflow:
7994 case Intrinsic::usub_with_overflow:
7995 case Intrinsic::umul_with_overflow:
8000 case Intrinsic::ctpop:
8001 case Intrinsic::ctlz:
8002 case Intrinsic::cttz:
8003 case Intrinsic::abs:
8004 case Intrinsic::smax:
8005 case Intrinsic::smin:
8006 case Intrinsic::umax:
8007 case Intrinsic::umin:
8008 case Intrinsic::bitreverse:
8009 case Intrinsic::bswap:
8010 case Intrinsic::sadd_sat:
8011 case Intrinsic::ssub_sat:
8012 case Intrinsic::sshl_sat:
8013 case Intrinsic::uadd_sat:
8014 case Intrinsic::usub_sat:
8015 case Intrinsic::ushl_sat:
8020 case Instruction::ICmp:
8021 case Instruction::FCmp:
8022 case Instruction::GetElementPtr:
8025 if (isa<BinaryOperator>(
I) || isa<UnaryOperator>(
I) || isa<CastInst>(
I))
8036template <
typename CallableT>
8038 const CallableT &Handle) {
8039 switch (
I->getOpcode()) {
8040 case Instruction::Store:
8045 case Instruction::Load:
8052 case Instruction::AtomicCmpXchg:
8057 case Instruction::AtomicRMW:
8062 case Instruction::Call:
8063 case Instruction::Invoke: {
8067 for (
unsigned i = 0; i < CB->
arg_size(); ++i)
8070 CB->
paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8075 case Instruction::Ret:
8076 if (
I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8077 Handle(
I->getOperand(0)))
8080 case Instruction::Switch:
8081 if (Handle(cast<SwitchInst>(
I)->getCondition()))
8084 case Instruction::Br: {
8085 auto *BR = cast<BranchInst>(
I);
8086 if (BR->isConditional() && Handle(BR->getCondition()))
8106template <
typename CallableT>
8108 const CallableT &Handle) {
8111 switch (
I->getOpcode()) {
8113 case Instruction::UDiv:
8114 case Instruction::SDiv:
8115 case Instruction::URem:
8116 case Instruction::SRem:
8117 return Handle(
I->getOperand(1));
8134 I, [&](
const Value *V) {
return KnownPoison.
count(V); });
8148 if (
const auto *Inst = dyn_cast<Instruction>(V)) {
8152 }
else if (
const auto *Arg = dyn_cast<Argument>(V)) {
8153 if (Arg->getParent()->isDeclaration())
8156 Begin = BB->
begin();
8163 unsigned ScanLimit = 32;
8172 if (isa<DbgInfoIntrinsic>(
I))
8174 if (--ScanLimit == 0)
8178 return WellDefinedOp == V;
8198 if (isa<DbgInfoIntrinsic>(
I))
8200 if (--ScanLimit == 0)
8208 for (
const Use &
Op :
I.operands()) {
8218 if (
I.getOpcode() == Instruction::Select &&
8219 YieldsPoison.
count(
I.getOperand(1)) &&
8220 YieldsPoison.
count(
I.getOperand(2))) {
8226 if (!BB || !Visited.
insert(BB).second)
8236 return ::programUndefinedIfUndefOrPoison(Inst,
false);
8240 return ::programUndefinedIfUndefOrPoison(Inst,
true);
8247 if (
auto *
C = dyn_cast<ConstantFP>(V))
8250 if (
auto *
C = dyn_cast<ConstantDataVector>(V)) {
8251 if (!
C->getElementType()->isFloatingPointTy())
8253 for (
unsigned I = 0, E =
C->getNumElements();
I < E; ++
I) {
8254 if (
C->getElementAsAPFloat(
I).isNaN())
8260 if (isa<ConstantAggregateZero>(V))
8267 if (
auto *
C = dyn_cast<ConstantFP>(V))
8268 return !
C->isZero();
8270 if (
auto *
C = dyn_cast<ConstantDataVector>(V)) {
8271 if (!
C->getElementType()->isFloatingPointTy())
8273 for (
unsigned I = 0, E =
C->getNumElements();
I < E; ++
I) {
8274 if (
C->getElementAsAPFloat(
I).isZero())
8297 if (CmpRHS == FalseVal) {
8341 if (CmpRHS != TrueVal) {
8380 Value *
A =
nullptr, *
B =
nullptr;
8385 Value *
C =
nullptr, *
D =
nullptr;
8387 if (L.Flavor != R.Flavor)
8439 return {L.Flavor,
SPNB_NA,
false};
8446 return {L.Flavor,
SPNB_NA,
false};
8453 return {L.Flavor,
SPNB_NA,
false};
8460 return {L.Flavor,
SPNB_NA,
false};
8476 return ConstantInt::get(V->getType(), ~(*
C));
8533 if ((CmpLHS == TrueVal &&
match(FalseVal,
m_APInt(C2))) ||
8553 assert(
X &&
Y &&
"Invalid operand");
8555 auto IsNegationOf = [&](
const Value *
X,
const Value *
Y) {
8559 auto *BO = cast<BinaryOperator>(
X);
8560 if (NeedNSW && !BO->hasNoSignedWrap())
8563 auto *Zero = cast<Constant>(BO->getOperand(0));
8564 if (!AllowPoison && !Zero->isNullValue())
8571 if (IsNegationOf(
X,
Y) || IsNegationOf(
Y,
X))
8591 if (cast<ICmpInst>(
X)->hasSameSign() != cast<ICmpInst>(
Y)->hasSameSign())
8598 const APInt *RHSC1, *RHSC2;
8603 if (cast<ICmpInst>(
X)->hasSameSign() &&
8610 return CR1.inverse() == CR2;
8650 bool HasMismatchedZeros =
false;
8656 Value *OutputZeroVal =
nullptr;
8658 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
8659 OutputZeroVal = TrueVal;
8661 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
8662 OutputZeroVal = FalseVal;
8664 if (OutputZeroVal) {
8666 HasMismatchedZeros =
true;
8667 CmpLHS = OutputZeroVal;
8670 HasMismatchedZeros =
true;
8671 CmpRHS = OutputZeroVal;
8688 if (!HasMismatchedZeros)
8699 bool Ordered =
false;
8710 if (LHSSafe && RHSSafe) {
8740 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
8751 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
8757 auto MaybeSExtCmpLHS =
8761 if (
match(TrueVal, MaybeSExtCmpLHS)) {
8783 else if (
match(FalseVal, MaybeSExtCmpLHS)) {
8823 case Instruction::ZExt:
8827 case Instruction::SExt:
8831 case Instruction::Trunc:
8834 CmpConst->
getType() == SrcTy) {
8856 CastedTo = CmpConst;
8858 unsigned ExtOp = CmpI->
isSigned() ? Instruction::SExt : Instruction::ZExt;
8862 case Instruction::FPTrunc:
8865 case Instruction::FPExt:
8868 case Instruction::FPToUI:
8871 case Instruction::FPToSI:
8874 case Instruction::UIToFP:
8877 case Instruction::SIToFP:
8890 if (CastedBack && CastedBack !=
C)
8914 auto *Cast1 = dyn_cast<CastInst>(V1);
8918 *CastOp = Cast1->getOpcode();
8919 Type *SrcTy = Cast1->getSrcTy();
8920 if (
auto *Cast2 = dyn_cast<CastInst>(V2)) {
8922 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
8923 return Cast2->getOperand(0);
8927 auto *
C = dyn_cast<Constant>(V2);
8931 Value *CastedTo =
nullptr;
8932 if (*CastOp == Instruction::Trunc) {
8945 assert(V2->getType() == Cast1->getType() &&
8946 "V2 and Cast1 should be the same type.");
8962 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
8965 Value *TrueVal = SI->getTrueValue();
8966 Value *FalseVal = SI->getFalseValue();
8979 if (isa<FPMathOperator>(CmpI))
8987 if (CastOp && CmpLHS->
getType() != TrueVal->getType()) {
8991 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
8993 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
8994 cast<CastInst>(TrueVal)->getOperand(0),
C,
9000 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9002 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9003 C, cast<CastInst>(FalseVal)->getOperand(0),
9007 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
9026 return Intrinsic::umin;
9028 return Intrinsic::umax;
9030 return Intrinsic::smin;
9032 return Intrinsic::smax;
9048 case Intrinsic::smax:
return Intrinsic::smin;
9049 case Intrinsic::smin:
return Intrinsic::smax;
9050 case Intrinsic::umax:
return Intrinsic::umin;
9051 case Intrinsic::umin:
return Intrinsic::umax;
9054 case Intrinsic::maximum:
return Intrinsic::minimum;
9055 case Intrinsic::minimum:
return Intrinsic::maximum;
9056 case Intrinsic::maxnum:
return Intrinsic::minnum;
9057 case Intrinsic::minnum:
return Intrinsic::maxnum;
9072std::pair<Intrinsic::ID, bool>
9077 bool AllCmpSingleUse =
true;
9080 if (
all_of(VL, [&SelectPattern, &AllCmpSingleUse](
Value *
I) {
9086 SelectPattern.
Flavor != CurrentPattern.Flavor)
9088 SelectPattern = CurrentPattern;
9093 switch (SelectPattern.
Flavor) {
9095 return {Intrinsic::smin, AllCmpSingleUse};
9097 return {Intrinsic::umin, AllCmpSingleUse};
9099 return {Intrinsic::smax, AllCmpSingleUse};
9101 return {Intrinsic::umax, AllCmpSingleUse};
9103 return {Intrinsic::maxnum, AllCmpSingleUse};
9105 return {Intrinsic::minnum, AllCmpSingleUse};
9118 if (
P->getNumIncomingValues() != 2)
9121 for (
unsigned i = 0; i != 2; ++i) {
9122 Value *L =
P->getIncomingValue(i);
9123 Value *R =
P->getIncomingValue(!i);
9124 auto *LU = dyn_cast<BinaryOperator>(L);
9127 unsigned Opcode = LU->getOpcode();
9133 case Instruction::LShr:
9134 case Instruction::AShr:
9135 case Instruction::Shl:
9136 case Instruction::Add:
9137 case Instruction::Sub:
9138 case Instruction::UDiv:
9139 case Instruction::URem:
9140 case Instruction::And:
9141 case Instruction::Or:
9142 case Instruction::Mul:
9143 case Instruction::FMul: {
9144 Value *LL = LU->getOperand(0);
9145 Value *LR = LU->getOperand(1);
9175 P = dyn_cast<PHINode>(
I->getOperand(0));
9177 P = dyn_cast<PHINode>(
I->getOperand(1));
9198 return !
C->isNegative();
9210 const APInt *CLHS, *CRHS;
9213 return CLHS->
sle(*CRHS);
9251 const APInt *CLHS, *CRHS;
9254 return CLHS->
ule(*CRHS);
9263static std::optional<bool>
9268 return std::nullopt;
9275 return std::nullopt;
9282 return std::nullopt;
9289 return std::nullopt;
9296 return std::nullopt;
9303static std::optional<bool>
9311 return std::nullopt;
9322 if (DomCR.
icmp(RPred, RCR))
9328 return std::nullopt;
9345 LHSIsTrue ?
LHS->getPredicate() :
LHS->getInversePredicate();
9369 const APInt *Unused;
9388 return std::nullopt;
9392 if (L0 == R0 && L1 == R1)
9425 return std::nullopt;
9432static std::optional<bool>
9437 assert((
LHS->getOpcode() == Instruction::And ||
9438 LHS->getOpcode() == Instruction::Or ||
9439 LHS->getOpcode() == Instruction::Select) &&
9440 "Expected LHS to be 'and', 'or', or 'select'.");
9447 const Value *ALHS, *ARHS;
9452 ALHS, RHSPred, RHSOp0, RHSOp1,
DL, LHSIsTrue,
Depth + 1))
9455 ARHS, RHSPred, RHSOp0, RHSOp1,
DL, LHSIsTrue,
Depth + 1))
9457 return std::nullopt;
9459 return std::nullopt;
9468 return std::nullopt;
9473 return std::nullopt;
9476 "Expected integer type only!");
9480 LHSIsTrue = !LHSIsTrue;
9491 if ((LHSI->getOpcode() == Instruction::And ||
9492 LHSI->getOpcode() == Instruction::Or ||
9493 LHSI->getOpcode() == Instruction::Select))
9497 return std::nullopt;
9502 bool LHSIsTrue,
unsigned Depth) {
9508 bool InvertRHS =
false;
9515 if (
const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(
RHS)) {
9517 LHS, RHSCmp->getCmpPredicate(), RHSCmp->getOperand(0),
9518 RHSCmp->getOperand(1),
DL, LHSIsTrue,
Depth))
9519 return InvertRHS ? !*Implied : *Implied;
9520 return std::nullopt;
9524 return std::nullopt;
9528 const Value *RHS1, *RHS2;
9530 if (std::optional<bool> Imp =
9534 if (std::optional<bool> Imp =
9540 if (std::optional<bool> Imp =
9544 if (std::optional<bool> Imp =
9550 return std::nullopt;
9555static std::pair<Value *, bool>
9557 if (!ContextI || !ContextI->
getParent())
9558 return {
nullptr,
false};
9565 return {
nullptr,
false};
9571 return {
nullptr,
false};
9574 if (TrueBB == FalseBB)
9575 return {
nullptr,
false};
9577 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
9578 "Predecessor block does not point to successor?");
9581 return {PredCond, TrueBB == ContextBB};
9587 assert(
Cond->getType()->isIntOrIntVectorTy(1) &&
"Condition must be bool");
9591 return std::nullopt;
9603 return std::nullopt;
9608 bool PreferSignedRange) {
9609 unsigned Width =
Lower.getBitWidth();
9612 case Instruction::Add:
9621 if (PreferSignedRange && HasNSW && HasNUW)
9627 }
else if (HasNSW) {
9628 if (
C->isNegative()) {
9641 case Instruction::And:
9652 case Instruction::Or:
9658 case Instruction::AShr:
9664 unsigned ShiftAmount = Width - 1;
9665 if (!
C->isZero() && IIQ.
isExact(&BO))
9666 ShiftAmount =
C->countr_zero();
9667 if (
C->isNegative()) {
9670 Upper =
C->ashr(ShiftAmount) + 1;
9673 Lower =
C->ashr(ShiftAmount);
9679 case Instruction::LShr:
9685 unsigned ShiftAmount = Width - 1;
9686 if (!
C->isZero() && IIQ.
isExact(&BO))
9687 ShiftAmount =
C->countr_zero();
9688 Lower =
C->lshr(ShiftAmount);
9693 case Instruction::Shl:
9700 if (
C->isNegative()) {
9702 unsigned ShiftAmount =
C->countl_one() - 1;
9703 Lower =
C->shl(ShiftAmount);
9707 unsigned ShiftAmount =
C->countl_zero() - 1;
9709 Upper =
C->shl(ShiftAmount) + 1;
9728 case Instruction::SDiv:
9732 if (
C->isAllOnes()) {
9737 }
else if (
C->countl_zero() < Width - 1) {
9748 if (
C->isMinSignedValue()) {
9760 case Instruction::UDiv:
9770 case Instruction::SRem:
9776 if (
C->isNegative()) {
9787 case Instruction::URem:
9802 unsigned Width =
II.getType()->getScalarSizeInBits();
9804 switch (
II.getIntrinsicID()) {
9805 case Intrinsic::ctpop:
9806 case Intrinsic::ctlz:
9807 case Intrinsic::cttz:
9810 APInt(Width, Width) + 1);
9811 case Intrinsic::uadd_sat:
9817 case Intrinsic::sadd_sat:
9820 if (
C->isNegative())
9831 case Intrinsic::usub_sat:
9841 case Intrinsic::ssub_sat:
9843 if (
C->isNegative())
9853 if (
C->isNegative())
9864 case Intrinsic::umin:
9865 case Intrinsic::umax:
9866 case Intrinsic::smin:
9867 case Intrinsic::smax:
9872 switch (
II.getIntrinsicID()) {
9873 case Intrinsic::umin:
9875 case Intrinsic::umax:
9877 case Intrinsic::smin:
9880 case Intrinsic::smax:
9887 case Intrinsic::abs:
9896 case Intrinsic::vscale:
9897 if (!
II.getParent() || !
II.getFunction())
9900 case Intrinsic::scmp:
9901 case Intrinsic::ucmp:
9908 return ConstantRange::getFull(Width);
9913 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
9917 return ConstantRange::getFull(
BitWidth);
9940 return ConstantRange::getFull(
BitWidth);
9954 return ConstantRange::getFull(
BitWidth);
9961 unsigned BitWidth =
I->getType()->getScalarSizeInBits();
9962 if (!
I->getOperand(0)->getType()->getScalarType()->isHalfTy())
9964 if (isa<FPToSIInst>(
I) &&
BitWidth >= 17) {
9969 if (isa<FPToUIInst>(
I) &&
BitWidth >= 16) {
9980 assert(V->getType()->isIntOrIntVectorTy() &&
"Expected integer instruction");
9983 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
9985 if (
auto *
C = dyn_cast<Constant>(V))
9986 return C->toConstantRange();
9988 unsigned BitWidth = V->getType()->getScalarSizeInBits();
9991 if (
auto *BO = dyn_cast<BinaryOperator>(V)) {
9997 }
else if (
auto *
II = dyn_cast<IntrinsicInst>(V))
9999 else if (
auto *SI = dyn_cast<SelectInst>(V)) {
10001 SI->getTrueValue(), ForSigned, UseInstrInfo, AC, CtxI, DT,
Depth + 1);
10003 SI->getFalseValue(), ForSigned, UseInstrInfo, AC, CtxI, DT,
Depth + 1);
10006 }
else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10012 }
else if (
const auto *
A = dyn_cast<Argument>(V))
10013 if (std::optional<ConstantRange>
Range =
A->getRange())
10016 if (
auto *
I = dyn_cast<Instruction>(V)) {
10020 if (
const auto *CB = dyn_cast<CallBase>(V))
10021 if (std::optional<ConstantRange>
Range = CB->getRange())
10030 CallInst *
I = cast<CallInst>(AssumeVH);
10032 "Got assumption for the wrong function!");
10033 assert(
I->getIntrinsicID() == Intrinsic::assume &&
10034 "must be an assume intrinsic");
10038 Value *Arg =
I->getArgOperand(0);
10039 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10041 if (!Cmp || Cmp->getOperand(0) != V)
10046 UseInstrInfo, AC,
I, DT,
Depth + 1);
10059 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10061 }
else if (
auto *
I = dyn_cast<Instruction>(V)) {
10067 if (isa<Instruction>(
Op) || isa<Argument>(
Op))
10068 InsertAffected(
Op);
10075 auto AddAffected = [&InsertAffected](
Value *V) {
10090 while (!Worklist.
empty()) {
10092 if (!Visited.
insert(V).second)
10115 AddCmpOperands(
A,
B);
10166 if (HasRHSC &&
match(
A, m_Intrinsic<Intrinsic::ctpop>(
m_Value(
X))))
10169 AddCmpOperands(
A,
B);
10179 }
else if (
match(V, m_Intrinsic<Intrinsic::is_fpclass>(
m_Value(
A),
AMDGPU Register Bank Select
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::optional< std::vector< StOtherPiece > > Other
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static const unsigned MaxDepth
static bool hasNoUnsignedWrap(BinaryOperator &I)
mir Rename Register Operands
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
const SmallVectorImpl< MachineOperand > & Cond
static bool mayHaveSideEffects(MachineInstr &MI)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
static SmallVector< VPValue *, 4 > getOperands(ArrayRef< VPValue * > Values, unsigned OperandIndex)
static bool getShuffleDemandedElts(const ShuffleVectorInst *Shuf, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS)
static std::optional< bool > isImpliedCondICmps(const ICmpInst *LHS, CmpInst::Predicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static cl::opt< unsigned > DomConditionsMaxUses("dom-conditions-max-uses", cl::Hidden, cl::init(20))
static unsigned computeNumSignBitsVectorConstant(const Value *V, const APInt &DemandedElts, unsigned TyBits)
For vector constants, loop over the elements and find the constant with the minimum number of sign bi...
static bool isKnownNonZeroFromOperator(const Operator *I, const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q)
static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS, const Value *RHS)
Return true if "icmp Pred LHS RHS" is always true.
static bool isNonZeroMul(const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW)
static bool isKnownNonNullFromDominatingCondition(const Value *V, const Instruction *CtxI, const DominatorTree *DT)
static const Value * getUnderlyingObjectFromInt(const Value *V)
This is the function that does the work of looking through basic ptrtoint+arithmetic+inttoptr sequenc...
static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q, const KnownBits &KnownVal)
static bool rangeMetadataExcludesValue(const MDNode *Ranges, const APInt &Value)
Does the 'Range' metadata (which must be a valid MD_range operand list) ensure that the value it's at...
static bool outputDenormalIsIEEEOrPosZero(const Function &F, const Type *Ty)
static bool inputDenormalIsIEEE(const Function &F, const Type *Ty)
Return true if it's possible to assume IEEE treatment of input denormals in F for Val.
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2, const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q)
static bool isNonEqualShl(const Value *V1, const Value *V2, const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q)
Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and the shift is nuw or nsw.
static void addValueAffectedByCondition(Value *V, function_ref< void(Value *)> InsertAffected)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static std::tuple< Value *, FPClassTest, FPClassTest > exactClass(Value *V, FPClassTest M)
Return the return value for fcmpImpliesClass for a compare that produces an exact class test.
static bool haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower, APInt &Upper, const InstrInfoQuery &IIQ, bool PreferSignedRange)
static Value * lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, Instruction::CastOps *CastOp)
Helps to match a select pattern in case of a type mismatch.
static std::pair< Value *, bool > getDomPredecessorCondition(const Instruction *ContextI)
static bool isKnownNonEqual(const Value *V1, const Value *V2, const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q)
Return true if it is known that V1 != V2.
static bool isKnownNonZero(const Value *V, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if the given value is known to be non-zero when defined.
static bool isNonEqualSelect(const Value *V1, const Value *V2, const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q)
static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q)
static bool includesPoison(UndefPoisonKind Kind)
static bool isNonEqualMul(const Value *V1, const Value *V2, const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q)
Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and the multiplication is nuw o...
static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match clamp pattern for float types without care about NaNs or signed zeros.
static bool includesUndef(UndefPoisonKind Kind)
static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero, unsigned Depth, SimplifyQuery &Q)
Try to detect a recurrence that the value of the induction variable is always a power of two (or zero...
static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2, const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q)
Return true if V1 == (binop V2, X), where X is known non-zero.
static ConstantRange getRangeForSelectPattern(const SelectInst &SI, const InstrInfoQuery &IIQ)
static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred, FastMathFlags FMF, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, unsigned Depth)
static uint64_t GetStringLengthH(const Value *V, SmallPtrSetImpl< const PHINode * > &PHIs, unsigned CharSize)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
static bool onlyUsedByLifetimeMarkersOrDroppableInstsHelper(const Value *V, bool AllowLifetime, bool AllowDroppable)
static std::optional< bool > isImpliedCondAndOr(const Instruction *LHS, CmpPredicate RHSPred, const Value *RHSOp0, const Value *RHSOp1, const DataLayout &DL, bool LHSIsTrue, unsigned Depth)
Return true if LHS implies RHS is true.
static void computeKnownFPClassFromCond(const Value *V, Value *Cond, unsigned Depth, bool CondIsTrue, const Instruction *CxtI, KnownFPClass &KnownFromContext)
static bool isSignedMinMaxClamp(const Value *Select, const Value *&In, const APInt *&CLow, const APInt *&CHigh)
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &KnownOut, KnownBits &Known2, unsigned Depth, const SimplifyQuery &Q)
static void computeKnownBitsFromOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, unsigned Depth, const SimplifyQuery &Q)
static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V, unsigned Depth)
static void computeKnownBitsFromCmp(const Value *V, CmpInst::Predicate Pred, Value *LHS, Value *RHS, KnownBits &Known, const SimplifyQuery &Q)
static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TVal, Value *FVal, unsigned Depth)
Recognize variations of: a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
static void unionWithMinMaxIntrinsicClamp(const IntrinsicInst *II, KnownBits &Known)
static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper)
static bool isSameUnderlyingObjectInLoop(const PHINode *PN, const LoopInfo *LI)
PN defines a loop-variant pointer to an object.
static bool isNonEqualPointersWithRecursiveGEP(const Value *A, const Value *B, const SimplifyQuery &Q)
static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II, const APInt *&CLow, const APInt *&CHigh)
static std::optional< bool > isImpliedCondCommonOperandWithCR(CmpInst::Predicate LPred, const ConstantRange &LCR, CmpInst::Predicate RPred, const ConstantRange &RCR)
Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
static Value * lookThroughCastConst(CmpInst *CmpI, Type *SrcTy, Constant *C, Instruction::CastOps *CastOp)
static void computeKnownFPClassForFPTrunc(const Operator *Op, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, unsigned Depth, const SimplifyQuery &Q)
static bool handleGuaranteedWellDefinedOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be undef or poison.
static void computeKnownBits(const Value *V, const APInt &DemandedElts, KnownBits &Known, unsigned Depth, const SimplifyQuery &Q)
Determine which bits of V are known to be either zero or one and return them in the Known bit set.
static KnownFPClass computeKnownFPClassFromContext(const Value *V, const SimplifyQuery &Q)
static Value * getNotValue(Value *V)
If the input value is the result of a 'not' op, constant integer, or vector splat of a constant integ...
static void computeKnownBitsFromCond(const Value *V, Value *Cond, KnownBits &Known, unsigned Depth, const SimplifyQuery &SQ, bool Invert)
static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp, KnownBits &Known, const SimplifyQuery &SQ, bool Invert)
static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II)
static KnownBits computeKnownBitsForHorizontalOperation(const Operator *I, const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q, const function_ref< KnownBits(const KnownBits &, const KnownBits &)> KnownBitsFunc)
static bool matchOpWithOpEqZero(Value *Op0, Value *Op1)
static bool isNonZeroRecurrence(const PHINode *PN)
Try to detect a recurrence that monotonically increases/decreases from a non-zero starting value.
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, unsigned Depth, const SimplifyQuery &Q)
static SelectPatternResult matchClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal)
Recognize variations of: CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
static bool shiftAmountKnownInRange(const Value *ShiftAmount)
Shifts return poison if shiftwidth is larger than the bitwidth.
static bool isEphemeralValueOf(const Instruction *I, const Value *E)
static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, unsigned Depth)
Match non-obvious integer minimum and maximum sequences.
static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth, const SimplifyQuery &Q)
Test whether a GEP's result is known to be non-null.
static bool handleGuaranteedNonPoisonOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be poison.
static bool isNonZeroSub(const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y)
static std::optional< std::pair< Value *, Value * > > getInvertibleOperands(const Operator *Op1, const Operator *Op2)
If the pair of operators are the same invertible function, return the the operands of the function co...
static void computeKnownBitsFromShiftOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, unsigned Depth, const SimplifyQuery &Q, function_ref< KnownBits(const KnownBits &, const KnownBits &, bool)> KF)
Compute known bits from a shift operator, including those with a non-constant shift amount.
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS)
static bool inputDenormalIsIEEEOrPosZero(const Function &F, const Type *Ty)
static KnownBits getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts, const KnownBits &KnownLHS, const KnownBits &KnownRHS, unsigned Depth, const SimplifyQuery &Q)
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q)
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred ALHS ARHS" is true.
static unsigned ComputeNumSignBitsImpl(const Value *V, const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q)
Return the number of times the sign bit of the register is replicated into the other bits.
static bool isNonZeroAdd(const APInt &DemandedElts, unsigned Depth, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW)
static const Instruction * safeCxtI(const Value *V, const Instruction *CxtI)
static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero, const Value *Cond, bool CondIsTrue)
Return true if we can infer that V is known to be a power of 2 from dominating condition Cond (e....
static bool isKnownNonNaN(const Value *V, FastMathFlags FMF)
static std::optional< bool > isImpliedCondMatchingOperands(CmpInst::Predicate LPred, CmpInst::Predicate RPred)
Return true if "icmp1 LPred X, Y" implies "icmp2 RPred X, Y" is true.
static Value * BuildSubAggregate(Value *From, Value *To, Type *IndexedType, SmallVectorImpl< unsigned > &Idxs, unsigned IdxSkip, BasicBlock::iterator InsertBefore)
void computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, unsigned Depth, const SimplifyQuery &Q)
APInt bitcastToAPInt() const
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
FPClassTest classify() const
Return the FPClassTest which will return true for the value.
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
bool isSmallestNormalized() const
Class for arbitrary precision integers.
APInt udiv(const APInt &RHS) const
Unsigned division operation.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
void clearBit(unsigned BitPosition)
Set a given bit to 0.
bool isMinSignedValue() const
Determine if this is the smallest signed value.
uint64_t getZExtValue() const
Get zero extended value.
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
void setBitsFrom(unsigned loBit)
Set the top bits starting from loBit.
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
unsigned ceilLogBase2() const
bool sgt(const APInt &RHS) const
Signed greater than comparison.
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
unsigned getBitWidth() const
Return the number of bits in the APInt.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
bool isNegative() const
Determine sign of this APInt.
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
void clearAllBits()
Set every bit to 0.
APInt reverseBits() const
bool sle(const APInt &RHS) const
Signed less or equal comparison.
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
unsigned logBase2() const
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
void setAllBits()
Set every bit to 1.
bool getBoolValue() const
Convert APInt to a boolean value.
bool isMaxSignedValue() const
Determine if this is the largest signed value.
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
APInt shl(unsigned shiftAmt) const
Left-shift function.
bool slt(const APInt &RHS) const
Signed less than comparison.
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
void clearSignBit()
Set the sign bit to 0.
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
bool empty() const
empty - Check if the array is empty.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Class to represent array types.
Type * getElementType() const
This represents the llvm.assume intrinsic.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
std::optional< unsigned > getVScaleRangeMax() const
Returns the maximum value for the vscale_range attribute or std::nullopt when unknown.
unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
bool isSingleEdge() const
Check if this is the only edge between Start and End.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
InstListType::const_iterator const_iterator
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
const Function * getParent() const
Return the enclosing method, or null if none.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Conditional or Unconditional Branch instruction.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
This class is the base class for the comparison instructions.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ FCMP_ULT
1 1 0 0 True if unordered or less than
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ ICMP_ULT
unsigned less than
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
@ ICMP_SGE
signed greater or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
static bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
bool isTrueWhenEqual() const
This is just a convenience.
bool isFPPredicate() const
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Predicate getPredicate() const
Return the predicate for this instruction.
static bool isUnordered(Predicate predicate)
Determine if the predicate is an unordered operation.
static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2)
Determine if Pred1 implies Pred2 is true when two compares have matching operands.
bool isIntPredicate() const
static bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2)
Determine if Pred1 implies Pred2 is false when two compares have matching operands.
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
uint64_t getElementAsInteger(unsigned i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ConstantFP - Floating Point Values [float, double].
This is the shared class of boolean and integer constants.
static ConstantInt * getTrue(LLVMContext &Context)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
static ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
bool isAllNegative() const
Return true if all values in this range are negative.
OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
KnownBits toKnownBits() const
Return known bits for values in this range.
APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other? NOTE: false does not mean that inverse pr...
APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
bool isAllNonNegative() const
Return true if all values in this range are non-negative.
static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
This is an important base class in LLVM.
Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
bool isZeroValue() const
Return true if the value is negative zero or null value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
bool isLittleEndian() const
Layout endianness...
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
unsigned getIndexTypeSizeInBits(Type *Ty) const
Layout size of the index used in GEP calculation.
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
ArrayRef< BranchInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
DomTreeNodeBase * getIDom() const
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Utility class for floating point operations which can have information about relaxed accuracy require...
Convenience struct for specifying and reasoning about fast-math flags.
bool noSignedZeros() const
void setNoSignedZeros(bool B=true)
const BasicBlock & getEntryBlock() const
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
bool isEquality() const
Return true if this predicate is either EQ or NE.
This instruction inserts a struct field of array element value into an aggregate value.
Value * getAggregateOperand()
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
const Function * getFunction() const
Return the function this instruction belongs to.
bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
This is a utility class that provides an abstraction for the common functionality between Instruction...
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
iterator_range< const_block_iterator > blocks() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A udiv or sdiv instruction, which can be marked as "exact", indicating that no bits are destroyed.
bool isExact() const
Test whether this division is known to be exact, with zero remainder.
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
This instruction constructs a fixed permutation of two input vectors.
VectorType * getType() const
Overload to return most specific vector type.
static void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
TypeSize getElementOffset(unsigned Idx) const
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Provides information about what library functions are available for the current target.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
The instances of the Type class are immutable: once they are created, they are never changed.
unsigned getIntegerBitWidth() const
const fltSemantics & getFltSemantics() const
bool isVectorTy() const
True if this is an instance of VectorType.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
uint64_t getArrayNumElements() const
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
static IntegerType * getInt16Ty(LLVMContext &C)
static IntegerType * getInt8Ty(LLVMContext &C)
bool isIEEE() const
Return whether the type is IEEE compatible, as defined by the eponymous method in APFloat.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
User * getUser() const
Returns the User that contains this Use.
unsigned getOperandNo() const
Return the operand # of this use in its User.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
iterator_range< user_iterator > users()
const KnownBits & getKnownBits(const SimplifyQuery &Q) const
PointerType getValue() const
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
An efficient, type-erasing, non-owning reference to a callable.
StructType * getStructTypeOrNull() const
TypeSize getSequentialElementStride(const DataLayout &DL) const
Type * getIndexedType() const
const ParentTy * getParent() const
self_iterator getIterator()
A range adaptor for a pair of iterators.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
cst_pred_ty< is_power2_or_zero > m_Power2OrZero()
Match an integer or vector of 0 or power-of-2 values.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
match_combine_or< MaxMin_match< FCmpInst, LHS, RHS, ofmin_pred_ty >, MaxMin_match< FCmpInst, LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
bind_ty< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
deferredval_ty< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
OneUse_match< T > m_OneUse(const T &SubPattern)
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty, true > m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
match_combine_and< class_match< Constant >, match_unless< constantexpr_match > > m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty, true > m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty > m_UMax(const LHS &L, const RHS &R)
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty, true > m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
apfloat_match m_APFloatAllowPoison(const APFloat *&Res)
Match APFloat while allowing poison in splat vector constants.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
match_combine_or< MaxMin_match< FCmpInst, LHS, RHS, ofmax_pred_ty >, MaxMin_match< FCmpInst, LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty, true > m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
VScaleVal_match m_VScale()
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
apfloat_match m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
class_match< BasicBlock > m_BasicBlock()
Match an arbitrary basic block value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
cst_pred_ty< is_nonpositive > m_NonPositive()
Match an integer or vector of non-positive values.
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
BinOpPred_match< LHS, RHS, is_bitwiselogic_op > m_BitwiseLogic(const LHS &L, const RHS &R)
Matches bitwise logic operations.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
m_Intrinsic_Ty< Opnd0 >::Ty m_FAbs(const Opnd0 &Op0)
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty > m_UMin(const LHS &L, const RHS &R)
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
static unsigned decodeVSEW(unsigned VSEW)
unsigned getSEWLMULRatio(unsigned SEW, RISCVII::VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveNullness)
This function returns call pointer argument that is considered the same by aliasing rules.
bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
void getGuaranteedNonPoisonOps(const Instruction *I, SmallVectorImpl< const Value * > &Ops)
Insert operands of I into Ops such that I will trigger undefined behavior if I is executed and that o...
bool isOnlyUsedInZeroComparison(const Instruction *CxtI)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V)
Return true if the only users of this pointer are lifetime markers or droppable instructions.
Constant * ReadByteArrayFromGlobal(const GlobalVariable *GV, uint64_t Offset)
bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
std::pair< Intrinsic::ID, bool > canConvertToMinOrMaxIntrinsic(ArrayRef< Value * > VL)
Check if the values in VL are select instructions that can be converted to a min or max (vector) intr...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given value is known to have exactly one bit set when defined.
bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
gep_type_iterator gep_type_end(const User *GEP)
CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
void computeKnownBitsFromContext(const Value *V, KnownBits &Known, unsigned Depth, const SimplifyQuery &Q)
Merge bits known from context-dependent facts into Known.
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
ConstantRange computeConstantRange(const Value *V, bool ForSigned, bool UseInstrInfo=true, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
RetainedKnowledge getKnowledgeValidInContext(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, const Instruction *CtxI, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr)
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and the know...
RetainedKnowledge getKnowledgeFromBundle(AssumeInst &Assume, const CallBase::BundleOpInfo &BOI)
This extracts the Knowledge from an element of an operand bundle.
bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, unsigned Depth, const SimplifyQuery &SQ)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
constexpr unsigned MaxAnalysisRecursionDepth
bool isKnownNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
void getGuaranteedWellDefinedOps(const Instruction *I, SmallVectorImpl< const Value * > &Ops)
Insert operands of I into Ops such that I will trigger undefined behavior if I is executed and that o...
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
std::tuple< Value *, FPClassTest, FPClassTest > fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS, Value *RHS, bool LookThroughSrc=true)
Compute the possible floating-point classes that LHS could be based on fcmp \Pred LHS,...
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_FMINNUM
Unsigned maximum.
bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveNullness)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, unsigned Depth, const SimplifyQuery &Q)
Adjust Known for the given select Arm to include information from the select Cond.
bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
void getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS)
Compute the demanded elements mask of horizontal binary operations.
SelectPatternResult getSelectPattern(CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior=SPNB_NA, bool Ordered=false)
Determine the pattern for predicate X Pred Y ? X : Y.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool programUndefinedIfPoison(const Instruction *Inst)
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
FPClassTest inverse_fabs(FPClassTest Mask)
Return the test mask which returns true after fabs is applied to the value.
uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
bool isKnownInversion(const Value *X, const Value *Y)
Return true iff:
bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
const Value * getUnderlyingObjectAggressive(const Value *V)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
bool isKnownNonEqual(const Value *V1, const Value *V2, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given values are known to be non-equal when defined.
ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
DWARFExpression::Operation Op
bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
constexpr unsigned BitWidth
SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
gep_type_iterator gep_type_begin(const User *GEP)
std::pair< Value *, FPClassTest > fcmpToClassTest(CmpInst::Predicate Pred, const Function &F, Value *LHS, Value *RHS, bool LookThroughSrc=true)
Returns a pair of values, which if passed to llvm.is.fpclass, returns the same result as an fcmp with...
Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits.
OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
unsigned Log2(Align A)
Returns the log2 of the alignment.
std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
bool isGEPBasedOnPointerToString(const GEPOperator *GEP, unsigned CharSize=8)
Returns true if the GEP is based on a pointer to a string (array of.
bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, unsigned Depth, const SimplifyQuery &SQ)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Get the upper bound on bit size for this Value Op as a signed integer.
bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static unsigned int semanticsPrecision(const fltSemantics &)
static bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
This struct is a compact representation of a valid (non-zero power of two) alignment.
SmallPtrSet< Value *, 4 > AffectedValues
Represents offset+length into a ConstantDataArray.
uint64_t Length
Length of the slice.
uint64_t Offset
Slice starts at this Offset.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
DenormalModeKind Input
Denormal treatment kind for floating point instruction inputs in the default floating-point environme...
constexpr bool outputsAreZero() const
Return true if output denormals should be flushed to 0.
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static constexpr DenormalMode getPositiveZero()
constexpr bool inputsAreZero() const
Return true if input denormals must be implicitly treated as 0.
DenormalModeKind Output
Denormal flushing mode for floating point instruction results in the default floating point environme...
static constexpr DenormalMode getIEEE()
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedZeros(const InstT *Op) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
static KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
static std::optional< bool > eq(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_EQ result.
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
static KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
static KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
static KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
static KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
void makeNegative()
Make this value negative.
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
bool hasConflict() const
Returns true if there is conflicting information.
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
void setAllZero()
Make all bits known to be zero and discard any previous information.
unsigned getBitWidth() const
Get the bit width of this value.
static KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
bool isConstant() const
Returns true if we know the value of all bits.
void resetAll()
Resets the known state of all bits.
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
static KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
unsigned countMinTrailingOnes() const
Returns the minimum number of trailing one bits.
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from addition of LHS and RHS.
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
static KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
static KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
static KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
bool isNegative() const
Returns true if this value is known to be negative.
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
void setAllOnes()
Make all bits known to be one and discard any previous information.
void insertBits(const KnownBits &SubBits, unsigned BitPosition)
Insert the bits from a smaller known bits starting at bitPosition.
static KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
KnownBits sextOrTrunc(unsigned BitWidth) const
Return known bits for a sign extension or truncation of the value we're tracking.
const APInt & getConstant() const
Returns the value when all bits have a known value.
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
bool isKnownNeverInfinity() const
Return true if it's known this can never be an infinity.
bool cannotBeOrderedGreaterThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never greater tha...
static constexpr FPClassTest OrderedGreaterThanZeroMask
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
bool isKnownNeverZero() const
Return true if it's known this can never be a zero.
void copysign(const KnownFPClass &Sign)
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
bool isKnownNeverLogicalNegZero(const Function &F, Type *Ty) const
Return true if it's know this can never be interpreted as a negative zero.
bool isKnownNeverLogicalPosZero(const Function &F, Type *Ty) const
Return true if it's know this can never be interpreted as a positive zero.
void propagateCanonicalizingSrc(const KnownFPClass &Src, const Function &F, Type *Ty)
Report known classes if Src is evaluated through a potentially canonicalizing operation.
void propagateDenormal(const KnownFPClass &Src, const Function &F, Type *Ty)
Propagate knowledge from a source value that could be a denormal or zero.
bool isKnownNeverNegInfinity() const
Return true if it's known this can never be -infinity.
bool isKnownNeverNegSubnormal() const
Return true if it's known this can never be a negative subnormal.
bool isKnownNeverPosZero() const
Return true if it's known this can never be a literal positive zero.
std::optional< bool > SignBit
std::nullopt if the sign bit is unknown, true if the sign bit is definitely set or false if the sign ...
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
bool isKnownNeverNegZero() const
Return true if it's known this can never be a negative zero.
bool isKnownNeverLogicalZero(const Function &F, Type *Ty) const
Return true if it's know this can never be interpreted as a zero.
void propagateNaN(const KnownFPClass &Src, bool PreserveSign=false)
bool cannotBeOrderedLessThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never less than -...
void signBitMustBeOne()
Assume the sign bit is one.
void signBitMustBeZero()
Assume the sign bit is zero.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
bool isKnownNeverPosSubnormal() const
Return true if it's known this can never be a positive subnormal.
Represent one information held inside an operand bundle of an llvm.assume.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
SimplifyQuery getWithoutCondContext() const
SimplifyQuery getWithInstruction(const Instruction *I) const
const DomConditionCache * DC