66 using namespace llvm::PatternMatch;
68 #define DEBUG_TYPE "instcombine"
70 STATISTIC(NumCombined ,
"Number of insts combined");
71 STATISTIC(NumConstProp,
"Number of constant folds");
72 STATISTIC(NumDeadInst ,
"Number of dead inst eliminated");
73 STATISTIC(NumSunkInst ,
"Number of instructions sunk");
74 STATISTIC(NumExpand,
"Number of expansions");
75 STATISTIC(NumFactor ,
"Number of factorizations");
76 STATISTIC(NumReassoc ,
"Number of reassociations");
85 bool InstCombiner::ShouldChangeType(
Type *From,
Type *To)
const {
90 bool FromLegal =
DL.isLegalInteger(FromWidth);
91 bool ToLegal =
DL.isLegalInteger(ToWidth);
95 if (FromLegal && !ToLegal)
100 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
119 if (Opcode != Instruction::Add &&
120 Opcode != Instruction::Sub) {
132 const APInt &CVal = CC->getValue();
133 bool Overflow =
false;
135 if (Opcode == Instruction::Add) {
180 bool InstCombiner::SimplifyAssociativeOrCommutative(
BinaryOperator &
I) {
182 bool Changed =
false;
226 if (Op1 && Op1->getOpcode() == Opcode) {
228 Value *B = Op1->getOperand(0);
229 Value *C = Op1->getOperand(1);
268 if (Op1 && Op1->getOpcode() == Opcode) {
270 Value *B = Op1->getOperand(0);
271 Value *C = Op1->getOperand(1);
290 Op0->
getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
292 isa<Constant>(Op1->getOperand(1)) &&
296 Value *B = Op1->getOperand(0);
297 Constant *C2 = cast<Constant>(Op1->getOperand(1));
301 if (isa<FPMathOperator>(New)) {
304 Flags &= Op1->getFastMathFlags();
307 InsertNewInstWith(New, I);
343 case Instruction::Mul:
348 case Instruction::Add:
349 case Instruction::Sub:
383 case Instruction::Shl:
384 case Instruction::LShr:
385 case Instruction::AShr:
398 if (isa<Constant>(V))
401 if (OpCode == Instruction::Mul)
419 return Instruction::BinaryOpsEnd;
424 switch (TopLevelOpcode) {
428 case Instruction::Add:
429 case Instruction::Sub:
430 if (Op->
getOpcode() == Instruction::Shl) {
434 return Instruction::Mul;
452 if (!A || !C || !B || !D)
456 Value *SimplifiedInst =
nullptr;
467 if (A == C || (InnerCommutative && A == D)) {
475 if (!V && LHS->
hasOneUse() && RHS->hasOneUse())
478 SimplifiedInst = Builder->
CreateBinOp(InnerOpcode, A, V);
486 if (B == D || (InnerCommutative && B == C)) {
495 if (!V && LHS->
hasOneUse() && RHS->hasOneUse())
498 SimplifiedInst = Builder->
CreateBinOp(InnerOpcode, V, B);
502 if (SimplifiedInst) {
508 if (
BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
509 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
511 if (isa<OverflowingBinaryOperator>(&I))
515 if (isa<OverflowingBinaryOperator>(Op0))
519 if (isa<OverflowingBinaryOperator>(Op1))
520 HasNSW &= Op1->hasNoSignedWrap();
530 if (TopLevelOpcode == Instruction::Add &&
531 InnerOpcode == Instruction::Mul)
533 BO->setHasNoSignedWrap(HasNSW);
537 return SimplifiedInst;
551 Value *A =
nullptr, *B =
nullptr, *C =
nullptr, *D =
nullptr;
558 if (LHSOpcode == RHSOpcode) {
588 if ((L == A && R == B) ||
595 C = Builder->CreateBinOp(InnerOpcode, L, R);
604 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
613 if ((L == B && R == C) ||
620 A = Builder->CreateBinOp(InnerOpcode, L, R);
632 Value *InstCombiner::dyn_castNegVal(
Value *V)
const {
651 Value *InstCombiner::dyn_castFNegVal(
Value *V,
bool IgnoreZeroSign)
const {
668 if (
CastInst *CI = dyn_cast<CastInst>(&I)) {
673 bool ConstIsRHS = isa<Constant>(I.
getOperand(1));
676 if (
Constant *SOC = dyn_cast<Constant>(SO)) {
682 Value *Op0 = SO, *Op1 = ConstOperand;
690 if (FPInst && isa<FPMathOperator>(FPInst))
694 if (
ICmpInst *CI = dyn_cast<ICmpInst>(&I))
697 if (
FCmpInst *CI = dyn_cast<FCmpInst>(&I))
713 if (isa<Constant>(TV) || isa<Constant>(FV)) {
719 if (
BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
724 if ((SrcTy ==
nullptr) != (DestTy ==
nullptr))
return nullptr;
738 if (CI->hasOneUse()) {
750 SelectTrueVal, SelectFalseVal);
762 if (NumPHIValues == 0)
784 for (
unsigned i = 0; i != NumPHIValues; ++i) {
786 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
789 if (isa<PHINode>(InVal))
return nullptr;
790 if (NonConstBB)
return nullptr;
796 if (
InvokeInst *II = dyn_cast<InvokeInst>(InVal))
797 if (II->getParent() == NonConstBB)
811 if (NonConstBB !=
nullptr) {
818 InsertNewInstBefore(NewPN, *PN);
827 if (
SelectInst *SI = dyn_cast<SelectInst>(&I)) {
833 for (
unsigned i = 0; i != NumPHIValues; ++i) {
837 Value *InV =
nullptr;
841 if (InC && !isa<ConstantExpr>(InC))
842 InV = InC->
isNullValue() ? FalseVInPred : TrueVInPred;
845 TrueVInPred, FalseVInPred,
"phitmp");
848 }
else if (
CmpInst *CI = dyn_cast<CmpInst>(&I)) {
850 for (
unsigned i = 0; i != NumPHIValues; ++i) {
851 Value *InV =
nullptr;
854 else if (isa<ICmpInst>(CI))
864 for (
unsigned i = 0; i != NumPHIValues; ++i) {
865 Value *InV =
nullptr;
869 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
876 for (
unsigned i = 0; i != NumPHIValues; ++i) {
881 InV = Builder->CreateCast(CI->
getOpcode(),
889 if (User == &I)
continue;
890 ReplaceInstUsesWith(*User, NewPN);
891 EraseInstFromFunction(*User);
893 return ReplaceInstUsesWith(I, NewPN);
900 Type *InstCombiner::FindElementAtOffset(
PointerType *PtrTy, int64_t Offset,
909 Type *IntPtrTy =
DL.getIntPtrType(PtrTy);
910 int64_t FirstIdx = 0;
911 if (int64_t TySize =
DL.getTypeAllocSize(Ty)) {
912 FirstIdx = Offset/TySize;
913 Offset -= FirstIdx*TySize;
921 assert((uint64_t)Offset < (uint64_t)TySize &&
"Out of range offset");
929 if (uint64_t(Offset * 8) >=
DL.getTypeSizeInBits(Ty))
932 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
935 "Offset must stay within the indexed type");
942 Ty = STy->getElementType(Elt);
943 }
else if (
ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
944 uint64_t EltSize =
DL.getTypeAllocSize(AT->getElementType());
945 assert(EltSize &&
"Cannot index into a zero-sized array");
948 Ty = AT->getElementType();
970 Value *InstCombiner::Descale(
Value *Val,
APInt Scale,
bool &NoSignedWrap) {
971 assert(isa<IntegerType>(Val->
getType()) &&
"Can only descale integers!");
973 Scale.
getBitWidth() &&
"Scale not compatible with value!");
1009 std::pair<Instruction*, unsigned> Parent;
1013 bool RequireNoSignedWrap =
false;
1018 for (;; Op = Parent.first->getOperand(Parent.second)) {
1020 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1022 APInt Quotient(Scale), Remainder(Scale);
1024 if (!Remainder.isMinValue())
1029 NoSignedWrap =
true;
1035 if (BO->getOpcode() == Instruction::Mul) {
1037 NoSignedWrap = BO->hasNoSignedWrap();
1038 if (RequireNoSignedWrap && !NoSignedWrap)
1044 Value *LHS = BO->getOperand(0);
1045 Value *RHS = BO->getOperand(1);
1047 if (
ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1049 if (CI->getValue() == Scale) {
1060 Parent = std::make_pair(BO, 1);
1069 Parent = std::make_pair(BO, 0);
1073 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1074 isa<ConstantInt>(BO->getOperand(1))) {
1076 NoSignedWrap = BO->hasNoSignedWrap();
1077 if (RequireNoSignedWrap && !NoSignedWrap)
1080 Value *LHS = BO->getOperand(0);
1081 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1085 if (Amt == logScale) {
1091 if (Amt < logScale || !Op->hasOneUse())
1096 Parent = std::make_pair(BO, 1);
1105 if (
CastInst *Cast = dyn_cast<CastInst>(Op)) {
1106 if (Cast->getOpcode() == Instruction::SExt) {
1108 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1120 RequireNoSignedWrap =
true;
1123 Parent = std::make_pair(Cast, 0);
1128 if (Cast->getOpcode() == Instruction::Trunc) {
1135 if (RequireNoSignedWrap)
1139 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1140 Parent = std::make_pair(Cast, 0);
1141 Scale = Scale.
sext(LargeSize);
1142 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1155 NoSignedWrap =
true;
1169 assert(Parent.first->hasOneUse() &&
"Drilled down when more than one use!");
1170 assert(Op != Parent.first->getOperand(Parent.second) &&
1171 "Descaling was a no-op?");
1172 Parent.first->setOperand(Parent.second, Op);
1173 Worklist.Add(Parent.first);
1187 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1188 NoSignedWrap &= OpNoSignedWrap;
1189 if (NoSignedWrap != OpNoSignedWrap) {
1190 BO->setHasNoSignedWrap(NoSignedWrap);
1191 Worklist.Add(Ancestor);
1193 }
else if (Ancestor->
getOpcode() == Instruction::Trunc) {
1197 NoSignedWrap =
false;
1199 assert((Ancestor->
getOpcode() != Instruction::SExt || NoSignedWrap) &&
1200 "Failed to keep proper track of nsw flags while drilling down?");
1202 if (Ancestor == Val)
1207 assert(Ancestor->
hasOneUse() &&
"Drilled down when more than one use!");
1218 if (isa<OverflowingBinaryOperator>(NewBO)) {
1222 if (isa<PossiblyExactOperator>(NewBO))
1223 NewBO->setIsExact(Inst.
isExact());
1241 unsigned VWidth = cast<VectorType>(Inst.
getType())->getNumElements();
1243 assert(cast<VectorType>(LHS->
getType())->getNumElements() == VWidth);
1244 assert(cast<VectorType>(RHS->
getType())->getNumElements() == VWidth);
1250 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1254 isa<UndefValue>(RShuf->getOperand(1)) &&
1256 LShuf->
getMask() == RShuf->getMask()) {
1258 RShuf->getOperand(0), Builder);
1259 Value *Res = Builder->CreateShuffleVector(NewBO,
1269 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1270 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1271 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1272 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1273 if (Shuffle && C1 &&
1274 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1284 bool MayChange =
true;
1285 for (
unsigned I = 0; I < VWidth; ++
I) {
1286 if (ShMask[I] >= 0) {
1287 assert(ShMask[I] < (
int)VWidth);
1288 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1297 Value *NewLHS, *NewRHS;
1298 if (isa<Constant>(LHS)) {
1306 Value *Res = Builder->CreateShuffleVector(NewBO,
1319 return ReplaceInstUsesWith(GEP, V);
1325 bool MadeChange =
false;
1340 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1345 Type *IndexTy = (*I)->getType();
1346 if (IndexTy != IntPtrTy) {
1350 *I = Builder->CreateIntCast(*I, IntPtrTy,
true);
1358 if (
PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1416 CurTy = CT->getTypeAtIndex(Op1->
getOperand(J));
1435 Instruction *InsertPt = Builder->GetInsertPoint();
1436 Builder->SetInsertPoint(PN);
1439 Builder->SetInsertPoint(InsertPt);
1442 NewPN->
addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1459 if (
GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1467 dyn_cast<GEPOperator>(Src->getOperand(0)))
1474 bool EndsWithSequential =
false;
1477 EndsWithSequential = !(*I)->isStructTy();
1480 if (EndsWithSequential) {
1485 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1501 if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
1503 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->
getName()+
".sum");
1507 if (Src->getNumOperands() == 2) {
1512 Indices.
append(Src->op_begin()+1, Src->op_end()-1);
1515 }
else if (isa<Constant>(*GEP.
idx_begin()) &&
1516 cast<Constant>(*GEP.
idx_begin())->isNullValue() &&
1517 Src->getNumOperands() != 1) {
1519 Indices.
append(Src->op_begin()+1, Src->op_end());
1523 if (!Indices.
empty())
1526 Src->getSourceElementType(), Src->getOperand(0), Indices,
1529 Src->getOperand(0), Indices,
1536 DL.getPointerSizeInBits(AS)) {
1539 uint64_t TyAllocSize =
DL.getTypeAllocSize(Ty);
1541 bool Matched =
false;
1544 if (TyAllocSize == 1) {
1549 if (TyAllocSize == 1ULL << C)
1553 if (TyAllocSize == C)
1563 Operator *Index = cast<Operator>(V);
1564 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->
getType());
1588 if (StrippedPtr != PtrOp) {
1589 bool HasZeroPointerIndex =
false;
1591 HasZeroPointerIndex = C->isZero();
1600 if (HasZeroPointerIndex) {
1625 if (CATy->getElementType() == XATy->getElementType()) {
1647 ? Builder->CreateInBoundsGEP(
1648 nullptr, StrippedPtr, Idx, GEP.
getName())
1649 : Builder->CreateGEP(
nullptr, StrippedPtr, Idx,
1663 DL.getTypeAllocSize(ResElTy)) {
1668 ? Builder->CreateInBoundsGEP(
nullptr, StrippedPtr, Idx,
1670 : Builder->CreateGEP(
nullptr, StrippedPtr, Idx, GEP.
getName());
1684 uint64_t ResSize =
DL.getTypeAllocSize(ResElTy);
1685 uint64_t SrcSize =
DL.getTypeAllocSize(SrcElTy);
1686 if (ResSize && SrcSize % ResSize == 0) {
1689 uint64_t Scale = SrcSize / ResSize;
1694 "Index not cast to pointer width?");
1697 if (
Value *NewIdx = Descale(Idx,
APInt(BitWidth, Scale), NSW)) {
1703 ? Builder->CreateInBoundsGEP(
nullptr, StrippedPtr, NewIdx,
1705 : Builder->CreateGEP(
nullptr, StrippedPtr, NewIdx,
1722 uint64_t ResSize =
DL.getTypeAllocSize(ResElTy);
1723 uint64_t ArrayEltSize =
1725 if (ResSize && ArrayEltSize % ResSize == 0) {
1728 uint64_t Scale = ArrayEltSize / ResSize;
1733 "Index not cast to pointer width?");
1736 if (
Value *NewIdx = Descale(Idx,
APInt(BitWidth, Scale), NSW)) {
1745 ? Builder->CreateInBoundsGEP(
1746 SrcElTy, StrippedPtr, Off, GEP.
getName())
1747 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1766 if (
BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1775 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1776 Value *Operand = BCI->getOperand(0);
1778 unsigned OffsetBits =
DL.getPointerTypeSizeInBits(GEP.
getType());
1779 APInt Offset(OffsetBits, 0);
1780 if (!isa<BitCastInst>(Operand) &&
1793 BCI->getParent()->getInstList().insert(BCI, I);
1794 ReplaceInstUsesWith(*BCI, I);
1809 if (FindElementAtOffset(OpType, Offset.
getSExtValue(), NewIndices)) {
1812 ? Builder->CreateInBoundsGEP(
nullptr, Operand, NewIndices)
1813 : Builder->CreateGEP(
nullptr, Operand, NewIndices);
1816 return ReplaceInstUsesWith(GEP, NGEP);
1844 case Instruction::BitCast:
1845 case Instruction::GetElementPtr:
1850 case Instruction::ICmp: {
1862 switch (II->getIntrinsicID()) {
1866 case Intrinsic::memmove:
1867 case Intrinsic::memcpy:
1868 case Intrinsic::memset: {
1874 case Intrinsic::dbg_declare:
1875 case Intrinsic::dbg_value:
1876 case Intrinsic::invariant_start:
1877 case Intrinsic::invariant_end:
1878 case Intrinsic::lifetime_start:
1879 case Intrinsic::lifetime_end:
1880 case Intrinsic::objectsize:
1902 }
while (!Worklist.
empty());
1912 for (
unsigned i = 0, e = Users.
size(); i != e; ++i) {
1913 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1916 if (
ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1917 ReplaceInstUsesWith(*C,
1919 C->isFalseWhenEqual()));
1920 }
else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1922 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1923 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1924 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1925 uint64_t DontKnow = CI->
isZero() ? -1ULL : 0;
1929 EraseInstFromFunction(*I);
1932 if (
InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1934 Module *M = II->getParent()->getParent()->getParent();
1937 None,
"", II->getParent());
1939 return EraseInstFromFunction(MI);
1976 if (FreeInstrBB->
size() != 2)
1995 "Broken CFG: missing edge from predecessor to successor");
2006 if (isa<UndefValue>(Op)) {
2010 return EraseInstFromFunction(FI);
2015 if (isa<ConstantPointerNull>(Op))
2016 return EraseInstFromFunction(FI);
2043 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2045 if ((KnownZero|KnownOne).isAllOnesValue())
2057 !isa<Constant>(X)) {
2076 TrueDest, FalseDest)) &&
2092 TrueDest, FalseDest)) &&
2111 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2113 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2117 for (
auto &C : SI.
cases()) {
2119 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2121 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2124 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2130 bool TruncCond =
false;
2131 if (NewWidth > 0 && BitWidth > NewWidth &&
2132 NewWidth >=
DL.getLargestLegalIntTypeSize()) {
2135 Builder->SetInsertPoint(&SI);
2139 for (
auto &C : SI.
cases())
2141 SI.
getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2144 if (
Instruction *I = dyn_cast<Instruction>(Cond)) {
2154 LHS = LeadingKnownZeros
2158 assert(isa<ConstantInt>(NewCaseVal) &&
2159 "Result of expression should be constant");
2160 i.setValue(cast<ConstantInt>(NewCaseVal));
2168 return TruncCond ? &SI :
nullptr;
2175 return ReplaceInstUsesWith(EV, Agg);
2179 return ReplaceInstUsesWith(EV, V);
2183 const unsigned *exti, *exte, *insi, *inse;
2184 for (exti = EV.
idx_begin(), insi = IV->idx_begin(),
2185 exte = EV.
idx_end(), inse = IV->idx_end();
2186 exti != exte && insi != inse;
2200 if (exti == exte && insi == inse)
2205 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2215 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2236 if (II->hasOneUse()) {
2240 switch (II->getIntrinsicID()) {
2241 case Intrinsic::uadd_with_overflow:
2242 case Intrinsic::sadd_with_overflow:
2244 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2246 EraseInstFromFunction(*II);
2253 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2254 if (
ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2258 case Intrinsic::usub_with_overflow:
2259 case Intrinsic::ssub_with_overflow:
2261 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2263 EraseInstFromFunction(*II);
2264 return BinaryOperator::CreateSub(LHS, RHS);
2267 case Intrinsic::umul_with_overflow:
2268 case Intrinsic::smul_with_overflow:
2270 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2272 EraseInstFromFunction(*II);
2281 if (
LoadInst *L = dyn_cast<LoadInst>(Agg))
2286 if (L->isSimple() && L->hasOneUse()) {
2290 Indices.
push_back(Builder->getInt32(0));
2293 Indices.
push_back(Builder->getInt32(*I));
2297 Builder->SetInsertPoint(L->getParent(), L);
2298 Value *
GEP = Builder->CreateInBoundsGEP(L->getType(),
2299 L->getPointerOperand(), Indices);
2302 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2317 switch (Personality) {
2340 cast<ArrayType>(LHS->
getType())->getNumElements()
2342 cast<ArrayType>(RHS->
getType())->getNumElements();
2354 bool MakeNewInstruction =
false;
2360 bool isLastClause = i + 1 == e;
2368 if (AlreadyCaught.
insert(TypeInfo).second) {
2373 MakeNewInstruction =
true;
2380 MakeNewInstruction =
true;
2381 CleanupFlag =
false;
2392 assert(LI.
isFilter(i) &&
"Unsupported landingpad clause!");
2394 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2400 if (!NumTypeInfos) {
2403 MakeNewInstruction =
true;
2404 CleanupFlag =
false;
2408 bool MakeNewFilter =
false;
2410 if (isa<ConstantAggregateZero>(FilterClause)) {
2412 assert(NumTypeInfos > 0 &&
"Should have handled empty filter already!");
2418 MakeNewInstruction =
true;
2425 if (NumTypeInfos > 1)
2426 MakeNewFilter =
true;
2430 NewFilterElts.
reserve(NumTypeInfos);
2435 bool SawCatchAll =
false;
2436 for (
unsigned j = 0; j != NumTypeInfos; ++j) {
2444 if (AlreadyCaught.
count(TypeInfo))
2450 if (SeenInFilter.insert(TypeInfo).second)
2451 NewFilterElts.
push_back(cast<Constant>(Elt));
2456 MakeNewInstruction =
true;
2461 if (NewFilterElts.
size() < NumTypeInfos)
2462 MakeNewFilter =
true;
2464 if (MakeNewFilter) {
2466 NewFilterElts.
size());
2468 MakeNewInstruction =
true;
2477 if (MakeNewFilter && !NewFilterElts.
size()) {
2478 assert(MakeNewInstruction &&
"New filter but not a new instruction!");
2479 CleanupFlag =
false;
2490 for (
unsigned i = 0, e = NewClauses.
size(); i + 1 < e; ) {
2493 for (j = i; j != e; ++j)
2494 if (!isa<ArrayType>(NewClauses[j]->
getType()))
2500 for (
unsigned k = i; k + 1 < j; ++k)
2504 std::stable_sort(NewClauses.
begin() + i, NewClauses.
begin() + j,
2506 MakeNewInstruction =
true;
2525 for (
unsigned i = 0; i + 1 < NewClauses.
size(); ++i) {
2527 Value *Filter = NewClauses[i];
2535 for (
unsigned j = NewClauses.
size() - 1; j != i; --j) {
2536 Value *LFilter = NewClauses[j];
2547 NewClauses.
erase(J);
2548 MakeNewInstruction =
true;
2558 if (isa<ConstantAggregateZero>(LFilter)) {
2561 if (isa<ConstantAggregateZero>(Filter)) {
2562 assert(FElts <= LElts &&
"Should have handled this case earlier!");
2564 NewClauses.
erase(J);
2565 MakeNewInstruction =
true;
2571 if (isa<ConstantAggregateZero>(Filter)) {
2574 assert(FElts > 0 &&
"Should have eliminated the empty filter earlier!");
2575 for (
unsigned l = 0; l != LElts; ++l)
2578 NewClauses.
erase(J);
2579 MakeNewInstruction =
true;
2590 bool AllFound =
true;
2591 for (
unsigned f = 0; f != FElts; ++f) {
2594 for (
unsigned l = 0; l != LElts; ++l) {
2596 if (LTypeInfo == FTypeInfo) {
2606 NewClauses.
erase(J);
2607 MakeNewInstruction =
true;
2615 if (MakeNewInstruction) {
2618 for (
unsigned i = 0, e = NewClauses.
size(); i != e; ++i)
2623 if (NewClauses.
empty())
2632 assert(!CleanupFlag &&
"Adding a cleanup, not removing one?!");
2645 assert(I->
hasOneUse() &&
"Invariants didn't hold!");
2649 isa<TerminatorInst>(
I))
2653 if (isa<AllocaInst>(I) && I->
getParent() ==
2662 if (Scan->mayWriteToMemory())
2673 while (!Worklist.isEmpty()) {
2675 if (I ==
nullptr)
continue;
2679 DEBUG(
dbgs() <<
"IC: DCE: " << *I <<
'\n');
2680 EraseInstFromFunction(*I);
2682 MadeIRChange =
true;
2690 DEBUG(
dbgs() <<
"IC: ConstFold to: " << *C <<
" from: " << *I <<
'\n');
2693 ReplaceInstUsesWith(*I, C);
2695 EraseInstFromFunction(*I);
2696 MadeIRChange =
true;
2708 if (
PHINode *PN = dyn_cast<PHINode>(UserInst))
2713 if (UserParent != BB) {
2714 bool UserIsSuccessor =
false;
2717 if (*SI == UserParent) {
2718 UserIsSuccessor =
true;
2725 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
2728 MadeIRChange =
true;
2733 if (
Instruction *OpI = dyn_cast<Instruction>(U.get()))
2742 Builder->SetCurrentDebugLocation(I->
getDebugLoc());
2748 DEBUG(
dbgs() <<
"IC: Visiting: " << OrigI <<
'\n');
2754 DEBUG(
dbgs() <<
"IC: Old = " << *I <<
'\n'
2755 <<
" New = " << *Result <<
'\n');
2763 Result->takeName(I);
2766 Worklist.Add(Result);
2767 Worklist.AddUsersToWorkList(*Result);
2775 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2780 EraseInstFromFunction(*I);
2783 DEBUG(
dbgs() <<
"IC: Mod = " << OrigI <<
'\n'
2784 <<
" New = " << *I <<
'\n');
2790 EraseInstFromFunction(*I);
2793 Worklist.AddUsersToWorkList(*I);
2796 MadeIRChange =
true;
2801 return MadeIRChange;
2817 bool MadeIRChange =
false;
2828 if (!Visited.
insert(BB).second)
2837 DEBUG(
dbgs() <<
"IC: DCE: " << *Inst <<
'\n');
2846 DEBUG(
dbgs() <<
"IC: ConstFold to: " << *C <<
" from: "
2861 Constant *&FoldRes = FoldedConstants[CE];
2867 if (FoldRes != CE) {
2869 MadeIRChange =
true;
2873 InstrsForInstCombineWorklist.
push_back(Inst);
2879 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2881 bool CondVal = cast<ConstantInt>(BI->
getCondition())->getZExtValue();
2886 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2891 if (i.getCaseValue() == Cond) {
2892 BasicBlock *ReachableBB = i.getCaseSuccessor();
2898 Worklist.
push_back(SI->getDefaultDest());
2905 }
while (!Worklist.
empty());
2913 InstrsForInstCombineWorklist.
size());
2915 return MadeIRChange;
2926 bool MadeIRChange =
false;
2939 if (Visited.count(BB))
2945 while (EndInst != BB->begin()) {
2951 if (isa<LandingPadInst>(Inst)) {
2955 if (!isa<DbgInfoIntrinsic>(Inst)) {
2957 MadeIRChange =
true;
2963 return MadeIRChange;
2988 DEBUG(
dbgs() <<
"\n\nINSTCOMBINE ITERATION #" << Iteration <<
" on "
2991 bool Changed =
false;
2996 AA, &AC, &TLI, &DT,
DL, LI);
3004 return DbgDeclaresChanged || Iteration > 1;
3043 bool runOnFunction(
Function &
F)
override;
3047 void InstructionCombiningPass::getAnalysisUsage(
AnalysisUsage &AU)
const {
3056 bool InstructionCombiningPass::runOnFunction(
Function &
F) {
3057 if (skipOptnoneFunction(F))
3061 auto AA = &getAnalysis<AliasAnalysis>();
3062 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3063 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3064 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3067 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3068 auto *LI = LIWP ? &LIWP->getLoopInfo() :
nullptr;
3075 "Combine redundant instructions",
false,
false)
3093 return new InstructionCombiningPass();
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type (if unknown returns 0).
ConstantDataVector - A vector constant whose element type is a simple 1/2/4/8-byte integer or float/d...
Value * EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the code necessary to compute th...
ReturnInst - Return a value (possibly void), from a function.
iplist< Instruction >::iterator eraseFromParent()
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...
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.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
This class is the base class for the comparison instructions.
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
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)
void addIncoming(Value *V, BasicBlock *BB)
addIncoming - Add an incoming value to the end of the PHI list
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
iterator_range< CaseIt > cases()
cases - iteration adapter for range-for loops.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
static const Value * getFNegArgument(const Value *BinOp)
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
void LLVMInitializeInstCombine(LLVMPassRegistryRef R)
STATISTIC(NumFunctions,"Total number of functions")
bool isVolatile() const
isVolatile - Return true if this is a store to a volatile memory location.
void swapSuccessors()
Swap the successors of this branch instruction.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for this module.
A Module instance is used to store all the information related to an LLVM module. ...
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
static void ClearSubclassDataAfterReassociation(BinaryOperator &I)
Conservatively clears subclassOptionalData after a reassociation or commutation.
match_zero m_Zero()
Match an arbitrary zero/null constant.
This file provides the primary interface to the instcombine pass.
INITIALIZE_PASS_BEGIN(InstructionCombiningPass,"instcombine","Combine redundant instructions", false, false) INITIALIZE_PASS_END(InstructionCombiningPass
unsigned getNumOperands() const
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
br_match m_UnconditionalBr(BasicBlock *&Succ)
A global registry used in conjunction with static constructors to make pluggable components (like tar...
static Value * tryFactorization(InstCombiner::BuilderTy *Builder, const DataLayout &DL, BinaryOperator &I, Instruction::BinaryOps InnerOpcode, Value *A, Value *B, Value *C, Value *D)
This tries to simplify binary operations by factorizing out common terms (e.
CallInst - This class represents a function call, abstracting a target machine's calling convention...
size_type count(PtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
An immutable pass that tracks lazily created AssumptionCache objects.
void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
gep_type_iterator gep_type_end(const User *GEP)
CaseIt case_begin()
Returns a read/write iterator that points to the first case in SwitchInst.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
bool mayHaveSideEffects() const
mayHaveSideEffects - Return true if the instruction may have side effects.
A cache of .assume calls within a function.
static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
ShuffleVectorInst - This instruction constructs a fixed permutation of two input vectors.
static bool RightDistributesOverLeft(Instruction::BinaryOps LOp, Instruction::BinaryOps ROp)
RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to "(X ROp Z) LOp (Y ROp Z)"...
static bool isEquality(Predicate P)
isEquality - Return true if this predicate is either EQ or NE.
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
const Function * getParent() const
Return the enclosing method, or null if none.
Analysis pass which computes a DominatorTree.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
LoadInst - an instruction for reading from memory.
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
Return the function type for an intrinsic.
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
iv Induction Variable Users
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
void reserve(size_type N)
Constant * ConstantFoldConstantExpression(const ConstantExpr *CE, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstantExpression - Attempt to fold the constant expression using the specified DataLayo...
static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C)
static Value * CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS, InstCombiner::BuilderTy *B)
Creates node of binary operation with the same attributes as the specified one but with other operand...
unsigned getNumIndices() const
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
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...
Constant * getMask() const
Type * getPointerElementType() const
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
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)
StringRef getName() const
Return a constant reference to the value's name.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
bool swapOperands()
Exchange the two operands to this instruction.
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
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...
CmpClass_match< LHS, RHS, FCmpInst, FCmpInst::Predicate > m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R)
bool isUnconditional() const
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.
SelectInst - This class represents the LLVM 'select' instruction.
bool isIdenticalTo(const Instruction *I) const
isIdenticalTo - Return true if the specified instruction is exactly identical to the current one...
This is the base class for all instructions that perform data casts.
const APInt & getValue() const
Return the constant as an APInt value reference.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
StructType - Class to represent struct types.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Type * getArrayElementType() const
A Use represents the edge between a Value definition and its users.
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
static Constant * get(ArrayRef< Constant * > V)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
The core instruction combiner logic.
0 1 0 1 True if ordered and less than or equal
bool isSized(SmallPtrSetImpl< const Type * > *Visited=nullptr) const
isSized - Return true if it makes sense to take the size of this type.
static Constant * getSExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Number of individual test Apply this number of consecutive mutations to each input exit after the first new interesting input is found the minimized corpus is saved into the first input directory Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
void print(raw_ostream &O) const
Implement operator<< on Value.
Analysis pass that exposes the LoopInfo for a function.
Instruction * clone() const
clone() - Create a copy of 'this' instruction that is identical in all ways except the following: ...
static bool shorter_filter(const Value *LHS, const Value *RHS)
Type * getPointerOperandType() const
getPointerOperandType - Method to return the pointer operand as a PointerType.
not_match< LHS > m_Not(const LHS &L)
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)
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
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. ...
ConstantExpr - a constant value that is initialized with an expression using other constant values...
static GetElementPtrInst * CreateInBounds(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Create an "inbounds" getelementptr.
void setCleanup(bool V)
setCleanup - Indicate that this landingpad instruction is a cleanup.
bool mayReadFromMemory() const
mayReadFromMemory - Return true if this instruction may read memory.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
LLVMContext & getContext() const
getContext - Return the LLVMContext in which this type was uniqued.
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
bool isAssociative() const
isAssociative - Return true if the instruction is associative:
ArrayType - Class to represent array types.
This instruction compares its operands according to the predicate given to the constructor.
BasicBlock * getSuccessor(unsigned i) 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.
bool isFloatingPointTy() const
isFloatingPointTy - Return true if this is one of the six floating point types
TargetFolder - Create constants with target dependent folding.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
unsigned getNumClauses() const
getNumClauses - Get the number of clauses for this landing pad.
StoreInst - an instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isArrayTy() const
isArrayTy - True if this is an instance of ArrayType.
static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL, SmallPtrSetImpl< BasicBlock * > &Visited, InstCombineWorklist &ICWorklist, const TargetLibraryInfo *TLI)
AddReachableCodeToWorklist - Walk the function in depth-first order, adding all reachable code to the...
unsigned getNumElements() const
Return the number of elements in the Vector type.
FunctionPass * createInstructionCombiningPass()
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...
Type * getElementType() const
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
bool isInBounds() const
isInBounds - Determine whether the GEP has the inbounds flag.
PointerType - Class to represent pointers.
Interval::succ_iterator succ_end(Interval *I)
unsigned getNumIncomingValues() const
getNumIncomingValues - Return the number of incoming edges
uint64_t getElementOffset(unsigned Idx) const
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
GetElementPtrInst - an instruction for type-safe pointer arithmetic to access elements of arrays and ...
bool isFilter(unsigned Idx) const
isFilter - Return 'true' if the clause and index Idx is a filter clause.
static Constant * getFNeg(Constant *C)
DataLayout * unwrap(LLVMTargetDataRef P)
LandingPadInst - The landingpad instruction holds all of the information necessary to generate correc...
static Instruction::BinaryOps getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode, BinaryOperator *Op, Value *&LHS, Value *&RHS)
This function factors binary ops which can be combined using distributive laws.
Subclasses of this class are all able to terminate a basic block.
An abstract set of preserved analyses following a transformation pass run.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
Constant * stripPointerCasts()
bool run()
Run the combiner over the entire worklist until it is empty.
APInt LLVM_ATTRIBUTE_UNUSED_RESULT trunc(unsigned width) const
Truncate to new width.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
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 *...
BranchInst - Conditional or Unconditional Branch instruction.
bool isVectorTy() const
isVectorTy - True if this is an instance of VectorType.
static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo)
isCatchAll - Return 'true' if the given typeinfo will match anything.
This is an important base class in LLVM.
const Value * getCondition() const
int64_t getSExtValue() const
Get sign extended value.
static bool LeftDistributesOverRight(Instruction::BinaryOps LOp, Instruction::BinaryOps ROp)
LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to "(X LOp Y) ROp (X LOp Z)"...
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
ConstantFP - Floating Point Values [float, double].
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
APInt Xor(const APInt &LHS, const APInt &RHS)
Bitwise XOR function for APInt.
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
Value * getRawDest() const
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
const DebugLoc & getDebugLoc() const
getDebugLoc - Return the debug location for this node as a DebugLoc.
APInt LLVM_ATTRIBUTE_UNUSED_RESULT sext(unsigned width) const
Sign extend to a new width.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
getIncomingBlock - Return incoming basic block number i.
const InstListType & getInstList() const
Return the underlying instruction list container.
uint64_t getNumElements() const
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Utility class for integer arithmetic operators which may exhibit overflow - Add, Sub, and Mul.
iterator insert(iterator where, NodeTy *New)
unsigned getBitWidth() const
Return the number of bits in the APInt.
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.
Value * getOperand(unsigned i) const
static CastInst * CreatePointerBitCastOrAddrSpaceCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
Create a BitCast or an AddrSpaceCast cast instruction.
bool isCommutative() const
isCommutative - Return true if the instruction is commutative:
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.
Class to represent integer types.
static Constant * getNot(Constant *C)
void setSourceElementType(Type *Ty)
Constant * getAggregateElement(unsigned Elt) const
getAggregateElement - For aggregates (struct/array/vector) return the constant that corresponds to th...
#define INITIALIZE_AG_DEPENDENCY(depName)
static Value * FoldOperationIntoSelectOperand(Instruction &I, Value *SO, InstCombiner *IC)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
InstCombineWorklist - This is the worklist management logic for InstCombine.
static UndefValue * get(Type *T)
get() - Static factory methods - Return an 'undef' object of the specified type.
iterator erase(iterator I)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
LLVMContext & getContext() const
All values hold a context through their type.
bool LowerDbgDeclare(Function &F)
LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set of llvm.dbg.value intrinsics.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
const Value * getTrueValue() const
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static Constant * getIntegerValue(Type *Ty, const APInt &V)
getIntegerValue - Return the value for an integer or pointer constant, or a vector thereof...
unsigned getAddressSpace() const
Returns the address space of this instruction's pointer type.
neg_match< LHS > m_Neg(const LHS &L)
Match an integer negate.
bool isConditional() const
SequentialType - This is the superclass of the array, pointer and vector type classes.
A function analysis which provides an AssumptionCache.
BinaryOps getOpcode() const
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
static InvokeInst * Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
MemIntrinsic - This is the common base class for memset/memcpy/memmove.
static PointerType * getInt1PtrTy(LLVMContext &C, unsigned AS=0)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
struct LLVMOpaquePassRegistry * LLVMPassRegistryRef
Value * getIncomingValue(unsigned i) const
getIncomingValue - Return incoming value number x
Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB)
Translate PHI node to its predecessor from the given basic block.
unsigned getScalarSizeInBits() const LLVM_READONLY
getScalarSizeInBits - If this is a vector type, return the getPrimitiveSizeInBits value for the eleme...
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...
Type * getType() const
All values are typed, get the type of this value.
Instruction * user_back()
user_back - Specialize the methods defined in Value, as we know that an instruction can only be used ...
Provides information about what library functions are available for the current target.
bool hasAllZeroIndices() const
Return true if all of the indices of this GEP are zeros.
Value * SimplifyGEPInst(ArrayRef< Value * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr)
SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can fold the result...
uint64_t getSizeInBytes() const
SequentialType * getType() const
PassT::Result & getResult(IRUnitT &IR)
Get the result of an analysis pass for this module.
Value * stripPointerCasts()
Strip off pointer casts, all-zero GEPs, and aliases.
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
Instruction * visitFree(CallInst &FI)
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 isZero() const
This is just a convenience method to make client code smaller for a common code.
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:
int32_t exactLogBase2() const
const BasicBlock & getEntryBlock() const
void initializeInstCombine(PassRegistry &)
initializeInstCombine - Initialize all passes linked into the InstCombine library.
bool isNullValue() const
isNullValue - Return true if this is the value that would be returned by getNullValue.
bool isExact() const
Determine whether the exact flag is set.
static ConstantInt * getTrue(LLVMContext &Context)
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
VectorType - Class to represent vector types.
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 isIntegerTy() const
isIntegerTy - True if this is an instance of IntegerType.
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.
iterator_range< user_iterator > users()
BasicBlock * getSinglePredecessor()
Return the predecessor of this block if it has a single predecessor block.
Instruction * visitSwitchInst(SwitchInst &SI)
Value * SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr)
SimplifyBinOp - Given operands for a BinaryOperator, see if we can fold the result.
static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock)
TryToSinkInstruction - Try to move the specified instruction from its current block into the beginnin...
Instruction * visitExtractValueInst(ExtractValueInst &EV)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Value * getCondition() const
bool isMinValue() const
Determine if this is the smallest unsigned value.
CompositeType - Common super class of ArrayType, StructType, PointerType and VectorType.
void AddInitialGroup(Instruction *const *List, unsigned NumEntries)
AddInitialGroup - Add the specified batch of stuff in reverse order.
const Type * getScalarType() const LLVM_READONLY
getScalarType - If this is a vector type, return the element type, otherwise return 'this'...
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
bool isStructTy() const
isStructTy - True if this is an instance of StructType.
Instruction * visitLandingPadInst(LandingPadInst &LI)
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
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 ...
unsigned countLeadingOnes() const
Count the number of leading one bits.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Value * getCondition() const
void emplace_back(ArgTypes &&...Args)
bool isMinSignedValue() const
Determine if this is the smallest signed value.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
static IntegerType * getInt32Ty(LLVMContext &C)
void setCondition(Value *V)
Constant * getPersonalityFn() const
Combine redundant instructions
unsigned greater or equal
static bool isFNeg(const Value *V, bool IgnoreZeroSign=false)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
bool isCatch(unsigned Idx) const
isCatch - Return 'true' if the clause and index Idx is a catch clause.
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool hasOneUse() const
Return true if there is exactly one user of this value.
0 1 1 0 True if ordered and operands are unequal
PreservedAnalyses run(Function &F, AnalysisManager< Function > *AM)
static ArrayType * get(Type *ElementType, uint64_t NumElements)
ArrayType::get - This static method is the primary way to construct an ArrayType. ...
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
VectorType * getType() const
getType - Overload to return most specific vector type.
void preserve()
Mark a particular pass as preserved, adding it to the set.
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Value * SimplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr)
Given operands for an ExtractValueInst, see if we can fold the result.
void initializeInstructionCombiningPassPass(PassRegistry &)
void setCondition(Value *V)
Analysis pass providing the TargetLibraryInfo.
SwitchInst - Multiway switch.
static bool isAllocSiteRemovable(Instruction *AI, SmallVectorImpl< WeakVH > &Users, const TargetLibraryInfo *TLI)
user_iterator user_begin()
A raw_ostream that writes to an std::string.
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
getPrimitiveSizeInBits - Return the basic size of this type if it is a primitive type.
static bool combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA, AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT, LoopInfo *LI=nullptr)
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
isInstructionTriviallyDead - Return true if the result produced by the instruction is not used...
LLVM Value Representation.
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
This file provides internal interfaces used to implement the InstCombine.
unsigned getOpcode() const
getOpcode() returns a member of one of the enums like Instruction::Add.
An IRBuilder inserter that adds new instructions to the instcombine worklist.
void clearSubclassOptionalData()
Clear the optional flags contained in this value.
void moveBefore(Instruction *MovePos)
moveBefore - Unlink this instruction from its current basic block and insert it into the basic block ...
static Instruction * tryToMoveFreeBeforeNullTest(CallInst &FI)
Move the call to free before a NULL test.
InvokeInst - Invoke instruction.
Instruction * visitGetElementPtrInst(GetElementPtrInst &GEP)
bool isCleanup() const
isCleanup - Return 'true' if this landingpad instruction is a cleanup.
C - The default llvm calling convention, compatible with C.
const Value * getFalseValue() const
Convenience struct for specifying and reasoning about fast-math flags.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
A generic analysis pass manager with lazy running and caching of results.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
isSafeToSpeculativelyExecute - Return true if the instruction does not have any effects besides calcu...
Legacy analysis pass which computes a DominatorTree.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml","ocaml 3.10-compatible collector")
iterator getFirstInsertionPt()
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
static BinaryOperator * CreateMul(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src)
static void getShuffleMask(Constant *Mask, SmallVectorImpl< int > &Result)
getShuffleMask - Return the full mask for this instruction, where each element is the element number ...
0 0 1 1 True if ordered and greater than or equal
Value * getPointerOperand()
Instruction * visitAllocSite(Instruction &FI)
const BasicBlock * getParent() const
IntrinsicInst - A useful wrapper class for inspecting calls to intrinsic functions.
InsertValueInst - This instruction inserts a struct field of array element value into an aggregate va...
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
gep_type_iterator gep_type_begin(const User *GEP)
Function must be optimized for size first.