107 using namespace llvm;
110 #define DEBUG_TYPE "instcombine" 112 STATISTIC(NumCombined ,
"Number of insts combined");
113 STATISTIC(NumConstProp,
"Number of constant folds");
114 STATISTIC(NumDeadInst ,
"Number of dead inst eliminated");
115 STATISTIC(NumSunkInst ,
"Number of instructions sunk");
116 STATISTIC(NumExpand,
"Number of expansions");
117 STATISTIC(NumFactor ,
"Number of factorizations");
118 STATISTIC(NumReassoc ,
"Number of reassociations");
120 "Controls which instructions are visited");
124 cl::desc(
"Enable expensive instruction combines"));
128 cl::desc(
"Maximum array size considered when doing a combine"));
153 bool InstCombiner::shouldChangeType(
unsigned FromWidth,
154 unsigned ToWidth)
const {
155 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
156 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
160 if (ToWidth < FromWidth && (ToWidth == 8 || ToWidth == 16 || ToWidth == 32))
165 if (FromLegal && !ToLegal)
170 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
181 bool InstCombiner::shouldChangeType(
Type *From,
Type *To)
const {
186 return shouldChangeType(FromWidth, ToWidth);
204 const APInt *BVal, *CVal;
208 bool Overflow =
false;
210 (void)BVal->
sadd_ov(*CVal, Overflow);
212 (
void)BVal->
ssub_ov(*CVal, Overflow);
238 if (!Cast || !Cast->hasOneUse())
243 if (CastOpcode != Instruction::ZExt)
252 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
269 Cast->setOperand(0, BinOp2->getOperand(0));
294 bool InstCombiner::SimplifyAssociativeOrCommutative(
BinaryOperator &
I) {
296 bool Changed =
false;
340 if (Op1 && Op1->getOpcode() == Opcode) {
342 Value *
B = Op1->getOperand(0);
388 if (Op1 && Op1->getOpcode() == Opcode) {
390 Value *
B = Op1->getOperand(0);
412 Op0->
getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
416 if (isa<FPMathOperator>(NewBO)) {
419 Flags &= Op1->getFastMathFlags();
422 InsertNewInstWith(NewBO, I);
446 if (LOp == Instruction::And)
447 return ROp == Instruction::Or || ROp == Instruction::Xor;
450 if (LOp == Instruction::Or)
451 return ROp == Instruction::And;
455 if (LOp == Instruction::Mul)
479 if (isa<Constant>(V))
493 assert(Op &&
"Expected a binary operator");
501 return Instruction::Mul;
513 assert(A && B && C && D &&
"All values must be provided");
516 Value *SimplifiedInst =
nullptr;
527 if (A == C || (InnerCommutative && A == D)) {
532 V =
SimplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));
535 if (!V && LHS->
hasOneUse() && RHS->hasOneUse())
536 V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->
getName());
538 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, A, V);
546 if (B == D || (InnerCommutative && B == C)) {
551 V =
SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
555 if (!V && LHS->
hasOneUse() && RHS->hasOneUse())
556 V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->
getName());
558 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, V, B);
562 if (SimplifiedInst) {
568 if (
BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
569 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
571 if (isa<OverflowingBinaryOperator>(&I))
574 if (
auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS))
575 HasNSW &= LOBO->hasNoSignedWrap();
577 if (
auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS))
578 HasNSW &= ROBO->hasNoSignedWrap();
589 InnerOpcode == Instruction::Mul)
591 BO->setHasNoSignedWrap(HasNSW);
595 return SimplifiedInst;
620 if (Op0 && Op1 && LHSOpcode == RHSOpcode)
621 if (
Value *V = tryFactorization(I, LHSOpcode, A, B, C, D))
628 if (
Value *V = tryFactorization(I, LHSOpcode, A, B, RHS, Ident))
635 if (
Value *V = tryFactorization(I, RHSOpcode, LHS, Ident, C, D))
653 C = Builder.CreateBinOp(InnerOpcode, L, R);
662 C = Builder.CreateBinOp(TopLevelOpcode, B, C);
671 C = Builder.CreateBinOp(TopLevelOpcode, A, C);
680 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
690 A = Builder.CreateBinOp(InnerOpcode, L, R);
699 A = Builder.CreateBinOp(TopLevelOpcode, A, C);
708 A = Builder.CreateBinOp(TopLevelOpcode, A, B);
714 return SimplifySelectsFeedingBinaryOp(I, LHS, RHS);
728 if (isa<FPMathOperator>(&I))
734 SI = Builder.CreateSelect(A, V2, V1);
735 else if (V2 && SelectsHaveOneUse)
736 SI = Builder.CreateSelect(A, V2, Builder.CreateBinOp(Opcode, C, E));
737 else if (V1 && SelectsHaveOneUse)
738 SI = Builder.CreateSelect(A, Builder.CreateBinOp(Opcode, B, D), V1);
749 Value *InstCombiner::dyn_castNegVal(
Value *V)
const {
762 for (
unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
767 if (isa<UndefValue>(Elt))
770 if (!isa<ConstantInt>(Elt))
781 if (
auto *Cast = dyn_cast<CastInst>(&I))
787 bool ConstIsRHS = isa<Constant>(I.
getOperand(1));
790 if (
auto *SOC = dyn_cast<Constant>(SO)) {
796 Value *Op0 = SO, *Op1 = ConstOperand;
800 auto *BO = cast<BinaryOperator>(&
I);
804 if (FPInst && isa<FPMathOperator>(FPInst))
816 if (!(isa<Constant>(TV) || isa<Constant>(FV)))
825 if (
auto *BC = dyn_cast<BitCastInst>(&Op)) {
830 if ((SrcTy ==
nullptr) != (DestTy ==
nullptr))
846 if (CI->hasOneUse()) {
847 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
861 bool ConstIsRHS = isa<Constant>(I->
getOperand(1));
864 if (
auto *InC = dyn_cast<Constant>(InV)) {
870 Value *Op0 = InV, *Op1 =
C;
876 if (FPInst && isa<FPMathOperator>(FPInst))
883 if (NumPHIValues == 0)
905 for (
unsigned i = 0; i != NumPHIValues; ++i) {
907 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
910 if (isa<PHINode>(InVal))
return nullptr;
911 if (NonConstBB)
return nullptr;
917 if (
InvokeInst *II = dyn_cast<InvokeInst>(InVal))
918 if (II->getParent() == NonConstBB)
932 if (NonConstBB !=
nullptr) {
939 InsertNewInstBefore(NewPN, *PN);
948 if (
SelectInst *SI = dyn_cast<SelectInst>(&I)) {
954 for (
unsigned i = 0; i != NumPHIValues; ++i) {
958 Value *InV =
nullptr;
966 if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC))
967 InV = InC->
isNullValue() ? FalseVInPred : TrueVInPred;
979 FalseVInPred,
"phitmp");
983 }
else if (
CmpInst *CI = dyn_cast<CmpInst>(&I)) {
985 for (
unsigned i = 0; i != NumPHIValues; ++i) {
986 Value *InV =
nullptr;
989 else if (isa<ICmpInst>(CI))
997 }
else if (
auto *BO = dyn_cast<BinaryOperator>(&I)) {
998 for (
unsigned i = 0; i != NumPHIValues; ++i) {
1006 for (
unsigned i = 0; i != NumPHIValues; ++i) {
1019 if (User == &I)
continue;
1020 replaceInstUsesWith(*User, NewPN);
1021 eraseInstFromFunction(*User);
1023 return replaceInstUsesWith(I, NewPN);
1030 if (
auto *Sel = dyn_cast<SelectInst>(I.
getOperand(0))) {
1031 if (
Instruction *NewSel = FoldOpIntoSelect(I, Sel))
1033 }
else if (
auto *PN = dyn_cast<PHINode>(I.
getOperand(0))) {
1053 Type *IndexTy = DL.getIndexType(PtrTy);
1054 int64_t FirstIdx = 0;
1055 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
1056 FirstIdx = Offset/TySize;
1057 Offset -= FirstIdx*TySize;
1065 assert((uint64_t)Offset < (uint64_t)TySize &&
"Out of range offset");
1073 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
1076 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
1079 "Offset must stay within the indexed type");
1086 Ty = STy->getElementType(Elt);
1087 }
else if (
ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1088 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
1089 assert(EltSize &&
"Cannot index into a zero-sized array");
1092 Ty = AT->getElementType();
1114 Value *InstCombiner::Descale(
Value *Val,
APInt Scale,
bool &NoSignedWrap) {
1115 assert(isa<IntegerType>(Val->
getType()) &&
"Can only descale integers!");
1117 Scale.
getBitWidth() &&
"Scale not compatible with value!");
1121 NoSignedWrap =
true;
1153 std::pair<Instruction *, unsigned> Parent;
1157 bool RequireNoSignedWrap =
false;
1162 for (;; Op = Parent.first->getOperand(Parent.second)) {
1163 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1165 APInt Quotient(Scale), Remainder(Scale);
1172 NoSignedWrap =
true;
1177 if (BO->getOpcode() == Instruction::Mul) {
1179 NoSignedWrap = BO->hasNoSignedWrap();
1180 if (RequireNoSignedWrap && !NoSignedWrap)
1186 Value *LHS = BO->getOperand(0);
1187 Value *RHS = BO->getOperand(1);
1189 if (
ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1191 if (CI->getValue() == Scale) {
1202 Parent = std::make_pair(BO, 1);
1211 Parent = std::make_pair(BO, 0);
1215 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1216 isa<ConstantInt>(BO->getOperand(1))) {
1218 NoSignedWrap = BO->hasNoSignedWrap();
1219 if (RequireNoSignedWrap && !NoSignedWrap)
1222 Value *LHS = BO->getOperand(0);
1223 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1227 if (Amt == logScale) {
1233 if (Amt < logScale || !Op->hasOneUse())
1238 Parent = std::make_pair(BO, 1);
1247 if (
CastInst *Cast = dyn_cast<CastInst>(Op)) {
1248 if (Cast->getOpcode() == Instruction::SExt) {
1250 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1262 RequireNoSignedWrap =
true;
1265 Parent = std::make_pair(Cast, 0);
1270 if (Cast->getOpcode() == Instruction::Trunc) {
1277 if (RequireNoSignedWrap)
1281 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1282 Parent = std::make_pair(Cast, 0);
1283 Scale = Scale.
sext(LargeSize);
1284 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1297 NoSignedWrap =
true;
1311 assert(Parent.first->hasOneUse() &&
"Drilled down when more than one use!");
1312 assert(Op != Parent.first->getOperand(Parent.second) &&
1313 "Descaling was a no-op?");
1314 Parent.first->setOperand(Parent.second, Op);
1315 Worklist.Add(Parent.first);
1330 NoSignedWrap &= OpNoSignedWrap;
1331 if (NoSignedWrap != OpNoSignedWrap) {
1332 BO->setHasNoSignedWrap(NoSignedWrap);
1333 Worklist.Add(Ancestor);
1335 }
else if (Ancestor->
getOpcode() == Instruction::Trunc) {
1339 NoSignedWrap =
false;
1341 assert((Ancestor->
getOpcode() != Instruction::SExt || NoSignedWrap) &&
1342 "Failed to keep proper track of nsw flags while drilling down?");
1344 if (Ancestor == Val)
1349 assert(Ancestor->
hasOneUse() &&
"Drilled down when more than one use!");
1363 unsigned VWidth = cast<VectorType>(Inst.
getType())->getNumElements();
1365 assert(cast<VectorType>(LHS->
getType())->getNumElements() == VWidth);
1366 assert(cast<VectorType>(RHS->
getType())->getNumElements() == VWidth);
1370 if (
auto *BO = dyn_cast<BinaryOperator>(XY))
1371 BO->copyIRFlags(&Inst);
1384 return createBinOpShuffle(V1, V2, Mask);
1406 bool MayChange =
true;
1407 for (
unsigned I = 0; I < VWidth; ++
I) {
1408 if (ShMask[I] >= 0) {
1409 assert(ShMask[I] < (
int)VWidth);
1412 if (!CElt || (!isa<UndefValue>(NewCElt) && NewCElt != CElt)) {
1416 NewVecC[ShMask[
I]] = CElt;
1424 bool ConstOp1 = isa<Constant>(Inst.
getOperand(1));
1430 Value *NewLHS = isa<Constant>(LHS) ? NewC : V1;
1431 Value *NewRHS = isa<Constant>(LHS) ? V1 : NewC;
1432 return createBinOpShuffle(NewLHS, NewRHS, Mask);
1444 return replaceInstUsesWith(GEP, V);
1450 bool MadeChange =
false;
1454 Type *NewScalarIndexTy =
1464 Type *IndexTy = (*I)->getType();
1465 Type *NewIndexType =
1473 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
1474 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1479 if (IndexTy != NewIndexType) {
1483 *I = Builder.CreateIntCast(*I, NewIndexType,
true);
1491 if (
auto *PN = dyn_cast<PHINode>(PtrOp)) {
1509 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1517 Type *CurTy =
nullptr;
1519 for (
unsigned J = 0,
F = Op1->getNumOperands(); J !=
F; ++J) {
1520 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1523 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1549 CurTy = Op1->getSourceElementType();
1550 }
else if (
auto *CT = dyn_cast<CompositeType>(CurTy)) {
1551 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1565 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1578 Builder.SetInsertPoint(PN);
1579 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
1584 NewPN->
addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1587 NewGEP->setOperand(DI, NewPN);
1590 NewGEP->setOperand(DI, NewPN);
1600 if (
auto *Src = dyn_cast<GEPOperator>(PtrOp)) {
1605 if (LI && Src->getNumOperands() == 2 && GEP.
getNumOperands() == 2 &&
1609 Value *SO1 = Src->getOperand(1);
1613 if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) {
1631 auto *SO0 = Src->getOperand(0);
1633 if (!isa<VectorType>(GEPType) ||
1634 isa<VectorType>(SO0Ty)) {
1635 Src->setOperand(1, GO1);
1642 Builder.SetInsertPoint(cast<Instruction>(PtrOp));
1643 auto *NewSrc = cast<GetElementPtrInst>(
1644 Builder.CreateGEP(SO0, GO1, Src->
getName()));
1645 NewSrc->setIsInBounds(Src->isInBounds());
1657 if (
auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0)))
1664 bool EndsWithSequential =
false;
1667 EndsWithSequential = I.isSequential();
1670 if (EndsWithSequential) {
1673 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1691 if (Src->getNumOperands() == 2) {
1696 Indices.
append(Src->op_begin()+1, Src->op_end()-1);
1699 }
else if (isa<Constant>(*GEP.
idx_begin()) &&
1700 cast<Constant>(*GEP.
idx_begin())->isNullValue() &&
1701 Src->getNumOperands() != 1) {
1703 Indices.
append(Src->op_begin()+1, Src->op_end());
1707 if (!Indices.
empty())
1710 Src->getSourceElementType(), Src->getOperand(0), Indices,
1713 Src->getOperand(0), Indices,
1720 DL.getIndexSizeInBits(AS)) {
1721 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType);
1723 bool Matched =
false;
1726 if (TyAllocSize == 1) {
1731 if (TyAllocSize == 1ULL << C)
1735 if (TyAllocSize == C)
1746 Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->
getType());
1761 if (GEPType->isVectorTy())
1768 if (StrippedPtr != PtrOp) {
1769 bool HasZeroPointerIndex =
false;
1770 if (
auto *C = dyn_cast<ConstantInt>(GEP.
getOperand(1)))
1771 HasZeroPointerIndex = C->isZero();
1780 if (HasZeroPointerIndex) {
1781 if (
auto *CATy = dyn_cast<ArrayType>(GEPEltType)) {
1800 if (
auto *XATy = dyn_cast<ArrayType>(StrippedPtrTy->
getElementType())) {
1802 if (CATy->getElementType() == XATy->getElementType()) {
1824 ? Builder.CreateInBoundsGEP(
1825 nullptr, StrippedPtr, Idx, GEP.
getName())
1826 : Builder.CreateGEP(
nullptr, StrippedPtr, Idx,
1839 DL.getTypeAllocSize(GEPEltType)) {
1840 Type *IdxType = DL.getIndexType(GEPType);
1844 ? Builder.CreateInBoundsGEP(
nullptr, StrippedPtr, Idx,
1846 : Builder.CreateGEP(
nullptr, StrippedPtr, Idx, GEP.
getName());
1859 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType);
1860 uint64_t SrcSize = DL.getTypeAllocSize(SrcEltTy);
1861 if (ResSize && SrcSize % ResSize == 0) {
1864 uint64_t Scale = SrcSize / ResSize;
1870 "Index type does not match the Data Layout preferences");
1873 if (
Value *NewIdx = Descale(Idx,
APInt(BitWidth, Scale), NSW)) {
1879 ? Builder.CreateInBoundsGEP(
nullptr, StrippedPtr, NewIdx,
1881 : Builder.CreateGEP(
nullptr, StrippedPtr, NewIdx,
1899 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType);
1900 uint64_t ArrayEltSize =
1902 if (ResSize && ArrayEltSize % ResSize == 0) {
1905 uint64_t Scale = ArrayEltSize / ResSize;
1911 "Index type does not match the Data Layout preferences");
1914 if (
Value *NewIdx = Descale(Idx,
APInt(BitWidth, Scale), NSW)) {
1918 Type *IndTy = DL.getIndexType(GEPType);
1922 ? Builder.CreateInBoundsGEP(
1923 SrcEltTy, StrippedPtr, Off, GEP.
getName())
1924 : Builder.CreateGEP(SrcEltTy, StrippedPtr, Off,
1938 Value *ASCStrippedPtrOp = PtrOp;
1939 if (
auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1944 if (
auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1945 ASCStrippedPtrOp = BC;
1948 if (
auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) {
1949 Value *SrcOp = BCI->getOperand(0);
1950 PointerType *SrcType = cast<PointerType>(BCI->getSrcTy());
1957 auto areMatchingArrayAndVecTypes = [](
Type *ArrTy,
Type *VecTy) {
1962 ((GEPEltType->
isArrayTy() && SrcEltType->isVectorTy() &&
1963 areMatchingArrayAndVecTypes(GEPEltType, SrcEltType)) ||
1964 (GEPEltType->
isVectorTy() && SrcEltType->isArrayTy() &&
1965 areMatchingArrayAndVecTypes(SrcEltType, GEPEltType)))) {
1976 unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType);
1989 BCI->getParent()->getInstList().insert(BCI->getIterator(),
I);
1990 replaceInstUsesWith(*BCI, I);
2005 if (FindElementAtOffset(SrcType, Offset.
getSExtValue(), NewIndices)) {
2008 ? Builder.CreateInBoundsGEP(
nullptr, SrcOp, NewIndices)
2009 : Builder.CreateGEP(
nullptr, SrcOp, NewIndices);
2011 if (NGEP->
getType() == GEPType)
2012 return replaceInstUsesWith(GEP, NGEP);
2025 APInt BasePtrOffset(IdxWidth, 0);
2026 Value *UnderlyingPtrOp =
2029 if (
auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
2032 APInt AllocSize(IdxWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
2033 if (BasePtrOffset.
ule(AllocSize)) {
2046 if (isa<ConstantPointerNull>(V))
2048 if (
auto *LI = dyn_cast<LoadInst>(V))
2049 return isa<GlobalVariable>(LI->getPointerOperand());
2073 case Instruction::AddrSpaceCast:
2074 case Instruction::BitCast:
2075 case Instruction::GetElementPtr:
2080 case Instruction::ICmp: {
2087 unsigned OtherIndex = (ICI->
getOperand(0) == PI) ? 1 : 0;
2097 switch (II->getIntrinsicID()) {
2101 case Intrinsic::memmove:
2102 case Intrinsic::memcpy:
2103 case Intrinsic::memset: {
2109 case Intrinsic::invariant_start:
2110 case Intrinsic::invariant_end:
2111 case Intrinsic::lifetime_start:
2112 case Intrinsic::lifetime_end:
2113 case Intrinsic::objectsize:
2135 }
while (!Worklist.
empty());
2148 std::unique_ptr<DIBuilder> DIB;
2149 if (isa<AllocaInst>(MI)) {
2155 for (
unsigned i = 0, e = Users.
size(); i != e; ++i) {
2164 if (II->getIntrinsicID() == Intrinsic::objectsize) {
2167 replaceInstUsesWith(*I, Result);
2168 eraseInstFromFunction(*I);
2173 for (
unsigned i = 0, e = Users.
size(); i != e; ++i) {
2179 if (
ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2180 replaceInstUsesWith(*C,
2182 C->isFalseWhenEqual()));
2183 }
else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I) ||
2184 isa<AddrSpaceCastInst>(I)) {
2186 }
else if (
auto *SI = dyn_cast<StoreInst>(I)) {
2187 for (
auto *DII : DIIs)
2190 eraseInstFromFunction(*I);
2193 if (
InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2195 Module *M = II->getModule();
2198 None,
"", II->getParent());
2201 for (
auto *DII : DIIs)
2202 eraseInstFromFunction(*DII);
2204 return eraseInstFromFunction(MI);
2241 if (FreeInstrBB->
size() != 2)
2260 "Broken CFG: missing edge from predecessor to successor");
2270 if (isa<UndefValue>(Op)) {
2274 return eraseInstFromFunction(FI);
2279 if (isa<ConstantPointerNull>(Op))
2280 return eraseInstFromFunction(FI);
2319 !isa<Constant>(X)) {
2356 for (
auto Case : SI.
cases()) {
2358 assert(isa<ConstantInt>(NewCase) &&
2359 "Result of expression should be constant");
2360 Case.setValue(cast<ConstantInt>(NewCase));
2372 for (
auto &C : SI.
cases()) {
2373 LeadingKnownZeros = std::min(
2374 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2375 LeadingKnownOnes = std::min(
2376 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2384 if (NewWidth > 0 && NewWidth < Known.
getBitWidth()) {
2386 Builder.SetInsertPoint(&SI);
2387 Value *NewCond = Builder.CreateTrunc(Cond, Ty,
"trunc");
2390 for (
auto Case : SI.
cases()) {
2391 APInt TruncatedCase = Case.getCaseValue()->getValue().
trunc(NewWidth);
2404 return replaceInstUsesWith(EV, Agg);
2407 SQ.getWithInstruction(&EV)))
2408 return replaceInstUsesWith(EV, V);
2412 const unsigned *exti, *exte, *insi, *inse;
2413 for (exti = EV.
idx_begin(), insi = IV->idx_begin(),
2414 exte = EV.
idx_end(), inse = IV->idx_end();
2415 exti != exte && insi != inse;
2429 if (exti == exte && insi == inse)
2434 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2444 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
2465 if (II->hasOneUse()) {
2469 switch (II->getIntrinsicID()) {
2470 case Intrinsic::uadd_with_overflow:
2471 case Intrinsic::sadd_with_overflow:
2473 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2475 eraseInstFromFunction(*II);
2482 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2483 if (
ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2487 case Intrinsic::usub_with_overflow:
2488 case Intrinsic::ssub_with_overflow:
2490 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2492 eraseInstFromFunction(*II);
2493 return BinaryOperator::CreateSub(LHS, RHS);
2496 case Intrinsic::umul_with_overflow:
2497 case Intrinsic::smul_with_overflow:
2499 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2501 eraseInstFromFunction(*II);
2510 if (
LoadInst *L = dyn_cast<LoadInst>(Agg))
2516 if (L->isSimple() && L->hasOneUse()) {
2523 Indices.
push_back(Builder.getInt32(*I));
2527 Builder.SetInsertPoint(L);
2528 Value *
GEP = Builder.CreateInBoundsGEP(L->getType(),
2529 L->getPointerOperand(), Indices);
2534 L->getAAMetadata(Nodes);
2538 return replaceInstUsesWith(EV, NL);
2553 switch (Personality) {
2581 cast<ArrayType>(LHS->
getType())->getNumElements()
2583 cast<ArrayType>(RHS->
getType())->getNumElements();
2595 bool MakeNewInstruction =
false;
2601 bool isLastClause = i + 1 == e;
2609 if (AlreadyCaught.
insert(TypeInfo).second) {
2614 MakeNewInstruction =
true;
2621 MakeNewInstruction =
true;
2622 CleanupFlag =
false;
2635 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2641 if (!NumTypeInfos) {
2644 MakeNewInstruction =
true;
2645 CleanupFlag =
false;
2649 bool MakeNewFilter =
false;
2651 if (isa<ConstantAggregateZero>(FilterClause)) {
2653 assert(NumTypeInfos > 0 &&
"Should have handled empty filter already!");
2659 MakeNewInstruction =
true;
2666 if (NumTypeInfos > 1)
2667 MakeNewFilter =
true;
2671 NewFilterElts.
reserve(NumTypeInfos);
2676 bool SawCatchAll =
false;
2677 for (
unsigned j = 0; j != NumTypeInfos; ++j) {
2705 if (SeenInFilter.insert(TypeInfo).second)
2706 NewFilterElts.
push_back(cast<Constant>(Elt));
2711 MakeNewInstruction =
true;
2716 if (NewFilterElts.
size() < NumTypeInfos)
2717 MakeNewFilter =
true;
2719 if (MakeNewFilter) {
2721 NewFilterElts.
size());
2723 MakeNewInstruction =
true;
2732 if (MakeNewFilter && !NewFilterElts.
size()) {
2733 assert(MakeNewInstruction &&
"New filter but not a new instruction!");
2734 CleanupFlag =
false;
2745 for (
unsigned i = 0, e = NewClauses.
size(); i + 1 < e; ) {
2748 for (j = i; j != e; ++j)
2749 if (!isa<ArrayType>(NewClauses[j]->
getType()))
2755 for (
unsigned k = i; k + 1 < j; ++k)
2759 std::stable_sort(NewClauses.
begin() + i, NewClauses.
begin() + j,
2761 MakeNewInstruction =
true;
2780 for (
unsigned i = 0; i + 1 < NewClauses.
size(); ++i) {
2790 for (
unsigned j = NewClauses.
size() - 1; j != i; --j) {
2791 Value *LFilter = NewClauses[j];
2802 NewClauses.
erase(J);
2803 MakeNewInstruction =
true;
2813 if (isa<ConstantAggregateZero>(LFilter)) {
2816 if (isa<ConstantAggregateZero>(Filter)) {
2817 assert(FElts <= LElts &&
"Should have handled this case earlier!");
2819 NewClauses.
erase(J);
2820 MakeNewInstruction =
true;
2826 if (isa<ConstantAggregateZero>(Filter)) {
2829 assert(FElts > 0 &&
"Should have eliminated the empty filter earlier!");
2830 for (
unsigned l = 0; l != LElts; ++l)
2833 NewClauses.
erase(J);
2834 MakeNewInstruction =
true;
2845 bool AllFound =
true;
2846 for (
unsigned f = 0; f != FElts; ++f) {
2849 for (
unsigned l = 0; l != LElts; ++l) {
2851 if (LTypeInfo == FTypeInfo) {
2861 NewClauses.
erase(J);
2862 MakeNewInstruction =
true;
2870 if (MakeNewInstruction) {
2873 for (
unsigned i = 0, e = NewClauses.
size(); i != e; ++i)
2878 if (NewClauses.
empty())
2887 assert(!CleanupFlag &&
"Adding a cleanup, not removing one?!");
2905 isa<TerminatorInst>(
I))
2909 if (isa<AllocaInst>(I) && I->
getParent() ==
2918 if (
auto *CI = dyn_cast<CallInst>(I)) {
2919 if (CI->isConvergent())
2928 if (Scan->mayWriteToMemory())
2939 for (
auto *DII : DbgUsers) {
2940 if (DII->getParent() == SrcBlock) {
2941 DII->moveBefore(&*InsertPos);
2949 while (!Worklist.isEmpty()) {
2951 if (I ==
nullptr)
continue;
2956 eraseInstFromFunction(*I);
2958 MadeIRChange =
true;
2969 LLVM_DEBUG(
dbgs() <<
"IC: ConstFold to: " << *C <<
" from: " << *I
2973 replaceInstUsesWith(*I, C);
2976 eraseInstFromFunction(*I);
2977 MadeIRChange =
true;
2990 <<
" from: " << *I <<
'\n');
2993 replaceInstUsesWith(*I, C);
2996 eraseInstFromFunction(*I);
2997 MadeIRChange =
true;
3009 if (
PHINode *PN = dyn_cast<PHINode>(UserInst))
3014 if (UserParent != BB) {
3015 bool UserIsSuccessor =
false;
3018 if (*SI == UserParent) {
3019 UserIsSuccessor =
true;
3026 if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
3030 MadeIRChange =
true;
3035 if (
Instruction *OpI = dyn_cast<Instruction>(U.get()))
3043 Builder.SetInsertPoint(I);
3044 Builder.SetCurrentDebugLocation(I->
getDebugLoc());
3057 <<
" New = " << *
Result <<
'\n');
3068 Worklist.AddUsersToWorkList(*
Result);
3077 if (!isa<PHINode>(
Result) && isa<PHINode>(InsertPos))
3082 eraseInstFromFunction(*I);
3085 <<
" New = " << *I <<
'\n');
3090 eraseInstFromFunction(*I);
3092 Worklist.AddUsersToWorkList(*I);
3096 MadeIRChange =
true;
3101 return MadeIRChange;
3116 bool MadeIRChange =
false;
3127 if (!Visited.
insert(BB).second)
3139 MadeIRChange =
true;
3147 LLVM_DEBUG(
dbgs() <<
"IC: ConstFold to: " << *C <<
" from: " << *Inst
3153 MadeIRChange =
true;
3159 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3162 auto *C = cast<Constant>(U);
3163 Constant *&FoldRes = FoldedConstants[
C];
3171 <<
"\n Old = " << *C
3172 <<
"\n New = " << *FoldRes <<
'\n');
3174 MadeIRChange =
true;
3180 if (!isa<DbgInfoIntrinsic>(Inst))
3181 InstrsForInstCombineWorklist.
push_back(Inst);
3187 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3188 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3189 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3190 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3194 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3196 Worklist.
push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3203 }
while (!Worklist.
empty());
3212 return MadeIRChange;
3223 bool MadeIRChange =
false;
3236 if (Visited.count(&BB))
3240 MadeIRChange |= NumDeadInstInBB > 0;
3241 NumDeadInst += NumDeadInstInBB;
3244 return MadeIRChange;
3261 if (
match(I, m_Intrinsic<Intrinsic::assume>()))
3267 bool MadeIRChange =
false;
3275 LLVM_DEBUG(
dbgs() <<
"\n\nINSTCOMBINE ITERATION #" << Iteration <<
" on " 3281 AC, TLI, DT, ORE, DL, LI);
3288 return MadeIRChange || Iteration > 1;
3302 ExpensiveCombines, LI))
3329 if (skipFunction(F))
3333 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3334 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3335 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3336 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3337 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
3340 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3341 auto *LI = LIWP ? &LIWP->getLoopInfo() :
nullptr;
3344 ExpensiveCombines, LI);
3350 "Combine redundant instructions",
false,
false)
Legacy wrapper pass to provide the GlobalsAAResult object.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Type * getVectorElementType() const
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double, and whose elements are just simple data values (i.e.
Value * EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
bool isAllocationFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
A parsed version of the target data layout string in and methods for querying it. ...
static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL, TargetLibraryInfo *TLI, InstCombineWorklist &ICWorklist)
Populate the IC worklist from a function, and prune any dead basic blocks discovered in the process...
static ConstantInt * getFalse(LLVMContext &Context)
void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction, which must be an operator which supports these flags.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
class_match< UndefValue > m_Undef()
Match an arbitrary undef constant.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static IntegerType * getInt1Ty(LLVMContext &C)
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
APInt sext(unsigned width) const
Sign extend to a new width.
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void LLVMInitializeInstCombine(LLVMPassRegistryRef R)
Compute iterated dominance frontiers using a linear time algorithm.
BinaryOps getOpcode() const
void swapSuccessors()
Swap the successors of this branch instruction.
static bool isAllocSiteRemovable(Instruction *AI, SmallVectorImpl< WeakTrackingVH > &Users, const TargetLibraryInfo *TLI)
This is the interface for a simple mod/ref and alias analysis over globals.
A Module instance is used to store all the information related to an LLVM module. ...
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
static Value * foldOperationIntoPhiValue(BinaryOperator *I, Value *InV, InstCombiner::BuilderTy &Builder)
static void ClearSubclassDataAfterReassociation(BinaryOperator &I)
Conservatively clears subclassOptionalData after a reassociation or commutation.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
br_match m_UnconditionalBr(BasicBlock *&Succ)
A global registry used in conjunction with static constructors to make pluggable components (like tar...
This class represents a function call, abstracting a target machine's calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
Value * getCondition() const
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
static bool isCanonicalPredicate(CmpInst::Predicate Pred)
Predicate canonicalization reduces the number of patterns that need to be matched by other transforms...
gep_type_iterator gep_type_end(const User *GEP)
const Value * getTrueValue() const
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
A cache of @llvm.assume calls within a function.
bool salvageDebugInfo(Instruction &I)
Assuming the instruction I is going to be deleted, attempt to salvage debug users of I by writing the...
static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
This instruction constructs a fixed permutation of two input vectors.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
LLVMContext & getContext() const
All values hold a context through their type.
struct LLVMOpaquePassRegistry * LLVMPassRegistryRef
void Add(Instruction *I)
Add - Add the specified instruction to the worklist if it isn't already in it.
BasicBlock * getSuccessor(unsigned i) const
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
APInt trunc(unsigned width) const
Truncate to new width.
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
uint64_t MaxArraySizeForCombine
Maximum size of array considered when transforming.
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
Value * getCondition() const
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
bool isVectorTy() const
True if this is an instance of VectorType.
iv Induction Variable Users
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
This defines the Use class.
void reserve(size_type N)
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
unsigned getBitWidth() const
Get the bit width of this value.
static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C)
const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
static bool isBitwiseLogicOp(unsigned Opcode)
Determine if the Opcode is and/or/xor.
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
static LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
unsigned getBitWidth() const
Return the number of bits in the APInt.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
bool swapOperands()
Exchange the two operands to this instruction.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
Value * SimplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
#define INITIALIZE_PASS_DEPENDENCY(depName)
static const Value * getNegArgument(const Value *BinOp)
Helper functions to extract the unary argument of a NEG, FNEG or NOT operation implemented via Sub...
This class represents a conversion between pointers from one address space to another.
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
This class represents the LLVM 'select' instruction.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Attribute unwrap(LLVMAttributeRef Attr)
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
This is the base class for all instructions that perform data casts.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
uint64_t getArrayNumElements() const
Class to represent struct types.
Value * SimplifyGEPInst(Type *SrcTy, ArrayRef< Value *> Ops, const SimplifyQuery &Q)
Given operands for a GetElementPtrInst, fold the result or return null.
A Use represents the edge between a Value definition and its users.
void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
bool isIntegerTy() const
True if this is an instance of IntegerType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
The core instruction combiner logic.
static cl::opt< bool > EnableExpensiveCombines("expensive-combines", cl::desc("Enable expensive instruction combines"))
Analysis pass that exposes the LoopInfo for a function.
This file provides an implementation of debug counters.
static bool shorter_filter(const Value *LHS, const Value *RHS)
uint64_t getNumElements() const
Type * getSourceElementType() const
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
This file implements a class to represent arbitrary precision integral constant values and operations...
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
Instruction * visitReturnInst(ReturnInst &RI)
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Instruction * visitBranchInst(BranchInst &BI)
bool isBitwiseLogicOp() const
Return true if this is and/or/xor.
unsigned getNumIndices() const
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible. ...
static Value * getIdentityValue(Instruction::BinaryOps Opcode, Value *V)
This function returns identity value for given opcode, which can be used to factor patterns like (X *...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
int64_t getSExtValue() const
Get sign extended value.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI, Instruction *AI)
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
Class to represent array types.
static Constant * getSafeVectorConstantForBinop(BinaryOperator::BinaryOps Opcode, Constant *In, bool IsRHSConstant)
Some binary operators require special handling to avoid poison and undefined behavior.
int32_t exactLogBase2() const
This class represents a no-op cast from one type to another.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
TargetFolder - Create constants with target dependent folding.
An instruction for storing to memory.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
SelectClass_match< Cond, LHS, RHS > m_Select(const Cond &C, const LHS &L, const RHS &R)
FunctionPass * createInstructionCombiningPass(bool ExpensiveCombines=true)
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
ShuffleVectorClass_match< V1_t, V2_t, Mask_t > m_ShuffleVector(const V1_t &v1, const V2_t &v2, const Mask_t &m)
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
Value * getOperand(unsigned i) const
static Instruction::BinaryOps getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op, Value *&LHS, Value *&RHS)
This function predicates factorization using distributive laws.
Class to represent pointers.
Interval::succ_iterator succ_end(Interval *I)
unsigned getAddressSpace() const
Returns the address space of this instruction's pointer type.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Value * getOperand(unsigned i_nocapture) const
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
OneUse_match< T > m_OneUse(const T &SubPattern)
bool hasAllZeroIndices() const
Return true if all of the indices of this GEP are zeros.
initializer< Ty > init(const Ty &Val)
The landingpad instruction holds all of the information necessary to generate correct exception handl...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
bool run()
Run the combiner over the entire worklist until it is empty.
void setAAMetadata(const AAMDNodes &N)
Sets the metadata on this instruction from the AAMDNodes structure.
ConstantInt * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo)
Return 'true' if the given typeinfo will match anything.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
const APInt & getConstant() const
Returns the value when all bits have a known value.
void ConvertDebugDeclareToDebugValue(DbgInfoIntrinsic *DII, StoreInst *SI, DIBuilder &Builder)
===---------------------------------------------------------------——===// Dbg Intrinsic utilities ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
A manager for alias analyses.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
void AddInitialGroup(ArrayRef< Instruction *> List)
AddInitialGroup - Add the specified batch of stuff in reverse order.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Value * SimplifyAddInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Represent the analysis usage information of a pass.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
bool isConstant() const
Returns true if we know the value of all bits.
This instruction compares its operands according to the predicate given to the constructor.
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl...
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false)
Return the identity constant for a binary opcode.
void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
FunctionPass class - This class is used to implement most global optimizations.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
static CastInst * CreatePointerBitCastOrAddrSpaceCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
Create a BitCast or an AddrSpaceCast cast instruction.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr)
Determine whether instruction 'To' is reachable from 'From', returning true if uncertain.
self_iterator getIterator()
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
static bool shouldExecute(unsigned CounterName)
Class to represent integer types.
Constant Vector Declarations.
The legacy pass manager's instcombine pass.
static Constant * getNot(Constant *C)
void setSourceElementType(Type *Ty)
static cl::opt< unsigned > MaxArraySize("instcombine-maxarray-size", cl::init(1024), cl::desc("Maximum array size considered when doing a combine"))
const Value * getCondition() const
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Type * getPointerOperandType() const
Method to return the pointer operand as a PointerType.
Type * getIndexedType() const
InstCombineWorklist - This is the worklist management logic for InstCombine.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Constant * stripPointerCasts() const
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
bool LowerDbgDeclare(Function &F)
Lowers llvm.dbg.declare intrinsics into appropriate set of llvm.dbg.value intrinsics.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static InvokeInst * Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value *> Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
A function analysis which provides an AssumptionCache.
const InstListType & getInstList() const
Return the underlying instruction list container.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
static PointerType * getInt1PtrTy(LLVMContext &C, unsigned AS=0)
This is the shared class of boolean and integer constants.
static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1)
Combine constant operands of associative operations either before or after a cast to eliminate one of...
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Utility class for floating point operations which can have information about relaxed accuracy require...
This is a utility class that provides an abstraction for the common functionality between Instruction...
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Provides information about what library functions are available for the current target.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
LLVM_NODISCARD T pop_back_val()
uint64_t getSizeInBytes() const
Instruction * visitFree(CallInst &FI)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
bool isConditional() const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
void initializeInstCombine(PassRegistry &)
Initialize all passes linked into the InstCombine library.
unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than it's terminator and any present EH pad instruct...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static ConstantInt * getTrue(LLVMContext &Context)
bool isCommutative() const
Return true if the instruction is commutative:
static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL, SmallPtrSetImpl< BasicBlock *> &Visited, InstCombineWorklist &ICWorklist, const TargetLibraryInfo *TLI)
Walk the function in depth-first order, adding all reachable code to the worklist.
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
unsigned getVectorNumElements() const
struct LLVMOpaquePassManager * LLVMPassManagerRef
static Value * foldOperationIntoSelectOperand(Instruction &I, Value *SO, InstCombiner::BuilderTy &Builder)
Class to represent vector types.
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
Accumulate offsets from stripInBoundsConstantOffsets().
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static bool isNeg(const Value *V)
Check if the given Value is a NEG, FNeg, or NOT instruction.
ConstantArray - Constant Array Declarations.
Class for arbitrary precision integers.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
CastClass_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
typename SuperClass::iterator iterator
iterator_range< user_iterator > users()
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property...
Instruction * visitSwitchInst(SwitchInst &SI)
TinyPtrVector< DbgInfoIntrinsic * > FindDbgAddrUses(Value *V)
Finds all intrinsics declaring local variables as living in the memory that 'V' points to...
static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock)
Try to move the specified instruction from its current block into the beginning of DestBlock...
Instruction * visitExtractValueInst(ExtractValueInst &EV)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Represents analyses that only rely on functions' control flow.
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
const Value * getFalseValue() const
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Instruction * visitLandingPadInst(LandingPadInst &LI)
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
Analysis pass providing a never-invalidated alias analysis result.
static bool leftDistributesOverRight(Instruction::BinaryOps LOp, Instruction::BinaryOps ROp)
Return whether "X LOp (Y ROp Z)" is always equal to "(X LOp Y) ROp (X LOp Z)".
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
bool isVolatile() const
Return true if this is a store to a volatile memory location.
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
static bool combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA, AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT, OptimizationRemarkEmitter &ORE, bool ExpensiveCombines=true, LoopInfo *LI=nullptr)
uint64_t getElementOffset(unsigned Idx) const
void emplace_back(ArgTypes &&... Args)
static IntegerType * getInt32Ty(LLVMContext &C)
void setCondition(Value *V)
bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void preserveSet()
Mark an analysis set as preserved.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
bool optForMinSize() const
Optimize this function for minimum size (-Oz).
bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc...
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
void preserve()
Mark an analysis as preserved.
DEBUG_COUNTER(VisitCounter, "instcombine-visit", "Controls which instructions are visited")
bool isUnconditional() const
void initializeInstructionCombiningPassPass(PassRegistry &)
void findDbgUsers(SmallVectorImpl< DbgInfoIntrinsic *> &DbgInsts, Value *V)
Finds the debug info intrinsics describing a value.
static cl::opt< unsigned > ShouldLowerDbgDeclare("instcombine-lower-dbg-declare", cl::Hidden, cl::init(true))
bool isMinValue() const
Determine if this is the smallest unsigned value.
void setCondition(Value *V)
Analysis pass providing the TargetLibraryInfo.
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
Value * SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
static GetElementPtrInst * CreateInBounds(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Create an "inbounds" getelementptr.
INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine", "Combine redundant instructions", false, false) INITIALIZE_PASS_END(InstructionCombiningPass
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
const BasicBlock & front() const
SmallVector< int, 16 > getShuffleMask() const
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
A raw_ostream that writes to an std::string.
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
This file provides internal interfaces used to implement the InstCombine.
void clearSubclassOptionalData()
Clear the optional flags contained in this value.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
static Instruction * tryToMoveFreeBeforeNullTest(CallInst &FI)
Move the call to free before a NULL test.
Instruction * visitGetElementPtrInst(GetElementPtrInst &GEP)
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Type * getElementType() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Convenience struct for specifying and reasoning about fast-math flags.
This is the interface for LLVM's primary stateless and local alias analysis.
inst_range instructions(Function *F)
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
A container for analyses that lazily runs them and caches their results.
Type * getArrayElementType() const
Legacy analysis pass which computes a DominatorTree.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This header defines various interfaces for pass management in LLVM.
static BinaryOperator * CreateMul(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src)
Value * getPointerOperand()
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Instruction * visitAllocSite(Instruction &FI)
Value * getRawDest() const
static Constant * get(ArrayRef< Constant *> V)
Type * getElementType() const
static bool rightDistributesOverLeft(Instruction::BinaryOps LOp, Instruction::BinaryOps ROp)
Return whether "(X LOp Y) ROp Z" is always equal to "(X ROp Z) LOp (Y ROp Z)".
BinaryOp_match< ValTy, cst_pred_ty< is_all_ones >, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
bool isStructTy() const
True if this is an instance of StructType.
bool isArrayTy() const
True if this is an instance of ArrayType.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
This instruction inserts a struct field of array element value into an aggregate value.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
Legacy wrapper pass to provide the BasicAAResult object.
gep_type_iterator gep_type_begin(const User *GEP)