42 #include "llvm/Config/llvm-config.h" 100 using namespace llvm;
103 #define DEBUG_TYPE "codegenprepare" 105 STATISTIC(NumBlocksElim,
"Number of blocks eliminated");
106 STATISTIC(NumPHIsElim,
"Number of trivial PHIs eliminated");
107 STATISTIC(NumGEPsElim,
"Number of GEPs converted to casts");
108 STATISTIC(NumCmpUses,
"Number of uses of Cmp expressions replaced with uses of " 110 STATISTIC(NumCastUses,
"Number of uses of Cast expressions replaced with uses " 112 STATISTIC(NumMemoryInsts,
"Number of memory instructions whose address " 113 "computations were sunk");
115 "Number of phis created when address " 116 "computations were sunk to memory instructions");
118 "Number of select created when address " 119 "computations were sunk to memory instructions");
120 STATISTIC(NumExtsMoved,
"Number of [s|z]ext instructions combined with loads");
121 STATISTIC(NumExtUses,
"Number of uses of [s|z]ext instructions optimized");
123 "Number of and mask instructions added to form ext loads");
124 STATISTIC(NumAndUses,
"Number of uses of and mask instructions optimized");
125 STATISTIC(NumRetsDup,
"Number of return instructions duplicated");
126 STATISTIC(NumDbgValueMoved,
"Number of debug value instructions moved");
127 STATISTIC(NumSelectsExpanded,
"Number of selects turned into branches");
128 STATISTIC(NumStoreExtractExposed,
"Number of store(extractelement) exposed");
132 cl::desc(
"Disable branch optimizations in CodeGenPrepare"));
136 cl::desc(
"Disable GC optimizations in CodeGenPrepare"));
140 cl::desc(
"Disable select to branch conversion."));
144 cl::desc(
"Address sinking in CGP using GEPs."));
148 cl::desc(
"Enable sinkinig and/cmp into branches."));
152 cl::desc(
"Disable store(extract) optimizations in CodeGenPrepare"));
156 cl::desc(
"Stress test store(extract) optimizations in CodeGenPrepare"));
160 cl::desc(
"Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " 165 cl::desc(
"Stress test ext(promotable(ld)) -> promoted(ext(ld)) " 166 "optimization in CodeGenPrepare"));
170 cl::desc(
"Disable protection against removing loop preheaders"));
174 cl::desc(
"Use profile info to add section prefix for hot/cold functions"));
178 cl::desc(
"Skip merging empty blocks if (frequency of empty block) / " 179 "(frequency of destination block) is greater than this ratio"));
183 cl::desc(
"Force store splitting no matter what the target query says."));
187 cl::desc(
"Enable merging of redundant sexts when one is dominating" 192 cl::desc(
"Disables combining addressing modes with different parts " 193 "in optimizeMemoryInst."));
197 cl::desc(
"Allow creation of Phis in Address sinking."));
201 cl::desc(
"Allow creation of selects in Address sinking."));
205 cl::desc(
"Allow combining of BaseReg field in Address sinking."));
209 cl::desc(
"Allow combining of BaseGV field in Address sinking."));
213 cl::desc(
"Allow combining of BaseOffs field in Address sinking."));
217 cl::desc(
"Allow combining of ScaledReg field in Address sinking."));
222 cl::desc(
"Enable splitting large offset of GEP."));
241 class TypePromotionTransaction;
251 std::unique_ptr<BlockFrequencyInfo>
BFI;
252 std::unique_ptr<BranchProbabilityInfo> BPI;
266 SetOfInstrs InsertedInsts;
270 InstrToOrigTy PromotedInsts;
273 SetOfInstrs RemovedInsts;
293 ValueToSExts ValToSExtendedUses;
313 StringRef getPassName()
const override {
return "CodeGen Prepare"; }
324 bool eliminateFallThrough(
Function &F);
325 bool eliminateMostlyEmptyBlocks(
Function &F);
328 void eliminateMostlyEmptyBlock(
BasicBlock *BB);
331 bool optimizeBlock(
BasicBlock &BB,
bool &ModifiedDT);
334 Type *AccessTy,
unsigned AddrSpace);
335 bool optimizeInlineAsmInst(
CallInst *CS);
336 bool optimizeCallInst(
CallInst *CI,
bool &ModifiedDT);
343 bool optimizeExtractElementInst(
Instruction *Inst);
344 bool dupRetToEnableTailCallOpts(
BasicBlock *BB);
348 bool tryToPromoteExts(TypePromotionTransaction &TPT,
351 unsigned CreatedInstsCost = 0);
353 bool splitLargeGEPOffsets();
354 bool performAddressTypePromotion(
356 bool AllowPromotionWithoutCommonHeader,
357 bool HasPromoted, TypePromotionTransaction &TPT,
359 bool splitBranchCondition(
Function &F);
368 "Optimize for code generation",
false,
false)
381 bool EverMadeChange =
false;
383 InsertedInsts.clear();
384 PromotedInsts.clear();
387 if (
auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
389 SubtargetInfo =
TM->getSubtargetImpl(F);
390 TLI = SubtargetInfo->getTargetLowering();
391 TRI = SubtargetInfo->getRegisterInfo();
393 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
394 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
395 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
401 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
412 TLI->isSlowDivBypassed()) {
414 TLI->getBypassSlowDivWidths();
416 while (BB !=
nullptr) {
427 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
432 EverMadeChange |= placeDbgValues(F);
435 EverMadeChange |= splitBranchCondition(F);
441 bool MadeChange =
true;
444 SeenChainsForSExt.clear();
445 ValToSExtendedUses.clear();
446 RemovedInsts.clear();
447 LargeOffsetGEPMap.clear();
448 LargeOffsetGEPID.clear();
451 bool ModifiedDTOnIteration =
false;
452 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
455 if (ModifiedDTOnIteration)
459 MadeChange |= mergeSExts(F);
460 if (!LargeOffsetGEPMap.empty())
461 MadeChange |= splitLargeGEPOffsets();
467 EverMadeChange |= MadeChange;
481 if (!MadeChange)
continue;
484 II = Successors.
begin(),
IE = Successors.
end(); II !=
IE; ++II)
490 MadeChange |= !WorkList.
empty();
491 while (!WorkList.
empty()) {
498 II = Successors.
begin(),
IE = Successors.
end(); II !=
IE; ++II)
505 if (EverMadeChange || MadeChange)
506 MadeChange |= eliminateFallThrough(F);
508 EverMadeChange |= MadeChange;
517 for (
auto &
I : Statepoints)
518 EverMadeChange |= simplifyOffsetableRelocate(*
I);
521 return EverMadeChange;
527 bool CodeGenPrepare::eliminateFallThrough(
Function &F) {
528 bool Changed =
false;
536 for (
auto &Block : Blocks) {
537 auto *BB = cast_or_null<BasicBlock>(Block);
545 if (!SinglePred || SinglePred == BB || BB->
hasAddressTaken())
continue;
569 if (BBI != BB->
begin()) {
571 while (isa<DbgInfoIntrinsic>(BBI)) {
572 if (BBI == BB->
begin())
576 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
585 if (!canMergeBlocks(BB, DestBB))
595 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(
Function &F) {
598 while (!LoopList.empty()) {
599 Loop *L = LoopList.pop_back_val();
600 LoopList.insert(LoopList.end(), L->
begin(), L->
end());
602 Preheaders.
insert(Preheader);
605 bool MadeChange =
false;
613 for (
auto &Block : Blocks) {
614 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
617 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
619 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.
count(BB)))
622 eliminateMostlyEmptyBlock(BB);
628 bool CodeGenPrepare::isMergingEmptyBlockProfitable(
BasicBlock *BB,
668 if (!isa<PHINode>(DestBB->
begin()))
678 if (DestBBPred == BB)
682 return DestPN.getIncomingValueForBlock(BB) ==
683 DestPN.getIncomingValueForBlock(DestBBPred);
685 SameIncomingValueBBs.
insert(DestBBPred);
691 if (SameIncomingValueBBs.
count(Pred))
697 for (
auto SameValueBB : SameIncomingValueBBs)
698 if (SameValueBB->getUniquePredecessor() == Pred &&
699 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
700 BBFreq +=
BFI->getBlockFreq(SameValueBB);
709 bool CodeGenPrepare::canMergeBlocks(
const BasicBlock *BB,
717 if (UI->
getParent() != DestBB || !isa<PHINode>(UI))
723 if (
const PHINode *UPN = dyn_cast<PHINode>(UI))
724 for (
unsigned I = 0,
E = UPN->getNumIncomingValues();
I !=
E; ++
I) {
727 Insn->
getParent() != UPN->getIncomingBlock(
I))
738 if (!DestBBPN)
return true;
742 if (
const PHINode *BBPN = dyn_cast<PHINode>(BB->
begin())) {
744 for (
unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
745 BBPreds.
insert(BBPN->getIncomingBlock(i));
753 if (BBPreds.
count(Pred)) {
755 const Value *V1 = PN.getIncomingValueForBlock(Pred);
756 const Value *
V2 = PN.getIncomingValueForBlock(BB);
759 if (
const PHINode *V2PN = dyn_cast<PHINode>(V2))
760 if (V2PN->getParent() == BB)
761 V2 = V2PN->getIncomingValueForBlock(Pred);
764 if (V1 != V2)
return false;
774 void CodeGenPrepare::eliminateMostlyEmptyBlock(
BasicBlock *BB) {
784 if (SinglePred != DestBB) {
785 assert(SinglePred == BB &&
786 "Single predecessor not the same as predecessor");
798 for (
PHINode &PN : DestBB->phis()) {
800 Value *InVal = PN.removeIncomingValue(BB,
false);
805 if (InValPhi && InValPhi->
getParent() == BB) {
814 for (
unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
815 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
818 PN.addIncoming(InVal, *PI);
842 for (
auto *ThisRelocate : AllRelocateCalls) {
843 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
844 ThisRelocate->getDerivedPtrIndex());
845 RelocateIdxMap.
insert(std::make_pair(K, ThisRelocate));
847 for (
auto &Item : RelocateIdxMap) {
848 std::pair<unsigned, unsigned>
Key = Item.first;
849 if (Key.first == Key.second)
854 auto BaseKey = std::make_pair(Key.first, Key.first);
857 auto MaybeBase = RelocateIdxMap.find(BaseKey);
858 if (MaybeBase == RelocateIdxMap.end())
863 RelocateInstMap[MaybeBase->second].push_back(I);
874 if (!
Op ||
Op->getZExtValue() > 20)
888 bool MadeChange =
false;
896 &*R != RelocatedBase; ++R)
897 if (
auto RI = dyn_cast<GCRelocateInst>(R))
906 "Not relocating a derived object of the original base object");
907 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
922 if (!Derived || Derived->getPointerOperand() != Base)
931 "Should always have one since it's not a terminator");
958 Value *ActualRelocatedBase = RelocatedBase;
960 ActualRelocatedBase =
961 Builder.CreateBitCast(RelocatedBase, Base->
getType());
963 Value *Replacement = Builder.CreateGEP(
964 Derived->getSourceElementType(), ActualRelocatedBase,
makeArrayRef(OffsetV));
968 Value *ActualReplacement = Replacement;
969 if (Replacement->
getType() != ToReplace->getType()) {
971 Builder.CreateBitCast(Replacement, ToReplace->
getType());
974 ToReplace->eraseFromParent();
998 bool CodeGenPrepare::simplifyOffsetableRelocate(
Instruction &
I) {
999 bool MadeChange =
false;
1002 for (
auto *U : I.
users())
1009 if (AllRelocateCalls.
size() < 2)
1016 if (RelocateInstMap.
empty())
1019 for (
auto &Item : RelocateInstMap)
1033 bool MadeChange =
false;
1036 Use &TheUse = UI.getUse();
1042 if (
PHINode *PN = dyn_cast<PHINode>(User)) {
1043 UserBB = PN->getIncomingBlock(TheUse);
1061 if (UserBB == DefBB)
continue;
1064 CastInst *&InsertedCast = InsertedCasts[UserBB];
1066 if (!InsertedCast) {
1070 CI->
getType(),
"", &*InsertPt);
1075 TheUse = InsertedCast;
1099 if (
auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1101 ASC->getDestAddressSpace()))
1115 if (SrcVT.
bitsLT(DstVT))
return false;
1146 if (!isa<IntegerType>(Ty))
1166 auto *InsertPt = AddI->
hasOneUse() ? CI : AddI;
1168 auto *UAddWithOverflow =
1197 bool MadeChange =
false;
1200 Use &TheUse = UI.getUse();
1207 if (isa<PHINode>(User))
1214 if (UserBB == DefBB)
continue;
1217 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1230 TheUse = InsertedCmp;
1261 SetOfInstrs &InsertedInsts) {
1264 assert(!InsertedInsts.count(AndI) &&
1265 "Attempting to optimize already optimized and instruction");
1266 (void) InsertedInsts;
1275 if (!isa<ConstantInt>(AndI->
getOperand(0)) &&
1280 for (
auto *U : AndI->
users()) {
1284 if (!isa<ICmpInst>(User))
1288 if (!CmpC || !CmpC->isZero())
1303 Use &TheUse = UI.getUse();
1321 TheUse = InsertedAnd;
1337 if (!isa<TruncInst>(User)) {
1338 if (User->
getOpcode() != Instruction::And ||
1342 const APInt &Cimm = cast<ConstantInt>(User->
getOperand(1))->getValue();
1344 if ((Cimm & (Cimm + 1)).getBoolValue())
1358 bool MadeChange =
false;
1362 TruncUI != TruncE;) {
1364 Use &TruncTheUse = TruncUI.getUse();
1365 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1384 if (isa<PHINode>(TruncUser))
1389 if (UserBB == TruncUserBB)
1393 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1395 if (!InsertedShift && !InsertedTrunc) {
1399 if (ShiftI->
getOpcode() == Instruction::AShr)
1400 InsertedShift = BinaryOperator::CreateAShr(ShiftI->
getOperand(0), CI,
1403 InsertedShift = BinaryOperator::CreateLShr(ShiftI->
getOperand(0), CI,
1409 assert(TruncInsertPt != TruncUserBB->
end());
1412 TruncI->
getType(),
"", &*TruncInsertPt);
1416 TruncTheUse = InsertedTrunc;
1449 bool MadeChange =
false;
1452 Use &TheUse = UI.getUse();
1458 if (isa<PHINode>(User))
1466 if (UserBB == DefBB) {
1481 if (isa<TruncInst>(User) && shiftIsLegal
1494 if (!InsertedShift) {
1498 if (ShiftI->
getOpcode() == Instruction::AShr)
1499 InsertedShift = BinaryOperator::CreateAShr(ShiftI->
getOperand(0), CI,
1502 InsertedShift = BinaryOperator::CreateLShr(ShiftI->
getOperand(0), CI,
1509 TheUse = InsertedShift;
1572 Builder.SetCurrentDebugLocation(CountZeros->
getDebugLoc());
1577 Value *Cmp = Builder.CreateICmpEQ(CountZeros->
getOperand(0), Zero,
"cmpz");
1578 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1583 Builder.SetInsertPoint(&EndBlock->
front());
1584 PHINode *PN = Builder.CreatePHI(Ty, 2,
"ctz");
1586 Value *BitWidth = Builder.getInt(
APInt(SizeInBits, SizeInBits));
1598 bool CodeGenPrepare::optimizeCallInst(
CallInst *CI,
bool &ModifiedDT) {
1605 if (TLI->ExpandInlineAsm(CI)) {
1607 CurInstIterator = BB->
begin();
1614 if (optimizeInlineAsmInst(CI))
1620 unsigned MinSize, PrefAlign;
1621 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
1630 cast<PointerType>(
Arg->
getType())->getAddressSpace()),
1634 if ((Offset2 & (PrefAlign-1)) != 0)
1637 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->
getAlignment() < PrefAlign &&
1655 if (DestAlign >
MI->getDestAlignment())
1656 MI->setDestAlignment(DestAlign);
1659 if (SrcAlign > MTI->getSourceAlignment())
1660 MTI->setSourceAlignment(SrcAlign);
1679 switch (II->getIntrinsicID()) {
1681 case Intrinsic::objectsize: {
1689 Value *CurValue = &*CurInstIterator;
1696 if (IterHandle != CurValue) {
1697 CurInstIterator = BB->
begin();
1702 case Intrinsic::aarch64_stlxr:
1703 case Intrinsic::aarch64_stxr: {
1712 InsertedInsts.insert(ExtVal);
1715 case Intrinsic::launder_invariant_group:
1716 case Intrinsic::strip_invariant_group:
1717 II->replaceAllUsesWith(II->getArgOperand(0));
1718 II->eraseFromParent();
1721 case Intrinsic::cttz:
1722 case Intrinsic::ctlz:
1730 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1731 while (!PtrOps.
empty()) {
1734 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
1787 bool CodeGenPrepare::dupRetToEnableTailCallOpts(
BasicBlock *BB) {
1815 do { ++BI; }
while (isa<DbgInfoIntrinsic>(BI));
1823 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1837 TLI->mayBeEmittedAsTailCall(CI) &&
1844 if (!VisitedBBs.
insert(*PI).second)
1850 do { ++RI; }
while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1855 if (CI && CI->
use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1861 bool Changed =
false;
1862 for (
unsigned i = 0, e = TailCalls.
size(); i != e; ++i) {
1884 ModifiedDT = Changed =
true;
1904 Value *BaseReg =
nullptr;
1905 Value *ScaledReg =
nullptr;
1906 Value *OriginalValue =
nullptr;
1910 BaseRegField = 0x01,
1912 BaseOffsField = 0x04,
1913 ScaledRegField = 0x08,
1915 MultipleFields = 0xff
1918 ExtAddrMode() =
default;
1923 FieldName
compare(
const ExtAddrMode &other) {
1926 if (BaseReg && other.BaseReg &&
1927 BaseReg->
getType() != other.BaseReg->getType())
1928 return MultipleFields;
1929 if (BaseGV && other.BaseGV &&
1930 BaseGV->getType() != other.BaseGV->getType())
1931 return MultipleFields;
1932 if (ScaledReg && other.ScaledReg &&
1933 ScaledReg->
getType() != other.ScaledReg->getType())
1934 return MultipleFields;
1937 unsigned Result = NoField;
1938 if (BaseReg != other.BaseReg)
1939 Result |= BaseRegField;
1940 if (BaseGV != other.BaseGV)
1941 Result |= BaseGVField;
1942 if (BaseOffs != other.BaseOffs)
1943 Result |= BaseOffsField;
1944 if (ScaledReg != other.ScaledReg)
1945 Result |= ScaledRegField;
1948 if (Scale && other.Scale && Scale != other.Scale)
1949 Result |= ScaleField;
1952 return MultipleFields;
1954 return static_cast<FieldName
>(Result);
1964 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
1975 case ScaledRegField:
1982 void SetCombinedField(FieldName Field,
Value *V,
1988 case ExtAddrMode::BaseRegField:
1991 case ExtAddrMode::BaseGVField:
1994 assert(BaseReg ==
nullptr);
1998 case ExtAddrMode::ScaledRegField:
2003 for (
const ExtAddrMode &AM : AddrModes)
2009 case ExtAddrMode::BaseOffsField:
2012 assert(ScaledReg ==
nullptr);
2030 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2032 bool NeedPlus =
false;
2035 OS << (NeedPlus ?
" + " :
"")
2037 BaseGV->printAsOperand(OS,
false);
2042 OS << (NeedPlus ?
" + " :
"")
2048 OS << (NeedPlus ?
" + " :
"")
2050 BaseReg->printAsOperand(OS,
false);
2054 OS << (NeedPlus ?
" + " :
"")
2056 ScaledReg->printAsOperand(OS,
false);
2073 class TypePromotionTransaction {
2077 class TypePromotionAction {
2085 TypePromotionAction(
Instruction *Inst) : Inst(Inst) {}
2087 virtual ~TypePromotionAction() =
default;
2094 virtual void undo() = 0;
2099 virtual void commit() {
2105 class InsertionHandler {
2116 bool HasPrevInstruction;
2123 if (HasPrevInstruction)
2124 Point.PrevInst = &*--It;
2131 if (HasPrevInstruction) {
2146 class InstructionMoveBefore :
public TypePromotionAction {
2153 : TypePromotionAction(Inst),
Position(Inst) {
2154 LLVM_DEBUG(
dbgs() <<
"Do: move: " << *Inst <<
"\nbefore: " << *Before
2160 void undo()
override {
2162 Position.insert(Inst);
2167 class OperandSetter :
public TypePromotionAction {
2177 : TypePromotionAction(Inst), Idx(Idx) {
2179 <<
"for:" << *Inst <<
"\n" 2180 <<
"with:" << *NewVal <<
"\n");
2186 void undo()
override {
2188 <<
"for: " << *Inst <<
"\n" 2189 <<
"with: " << *Origin <<
"\n");
2196 class OperandsHider :
public TypePromotionAction {
2202 OperandsHider(
Instruction *Inst) : TypePromotionAction(Inst) {
2205 OriginalValues.
reserve(NumOpnds);
2206 for (
unsigned It = 0; It < NumOpnds; ++It) {
2218 void undo()
override {
2220 for (
unsigned It = 0, EndIt = OriginalValues.
size(); It != EndIt; ++It)
2226 class TruncBuilder :
public TypePromotionAction {
2233 TruncBuilder(
Instruction *Opnd,
Type *Ty) : TypePromotionAction(Opnd) {
2240 Value *getBuiltValue() {
return Val; }
2243 void undo()
override {
2245 if (
Instruction *IVal = dyn_cast<Instruction>(Val))
2246 IVal->eraseFromParent();
2251 class SExtBuilder :
public TypePromotionAction {
2259 : TypePromotionAction(InsertPt) {
2261 Val = Builder.
CreateSExt(Opnd, Ty,
"promoted");
2266 Value *getBuiltValue() {
return Val; }
2269 void undo()
override {
2271 if (
Instruction *IVal = dyn_cast<Instruction>(Val))
2272 IVal->eraseFromParent();
2277 class ZExtBuilder :
public TypePromotionAction {
2285 : TypePromotionAction(InsertPt) {
2287 Val = Builder.
CreateZExt(Opnd, Ty,
"promoted");
2292 Value *getBuiltValue() {
return Val; }
2295 void undo()
override {
2297 if (
Instruction *IVal = dyn_cast<Instruction>(Val))
2298 IVal->eraseFromParent();
2303 class TypeMutator :
public TypePromotionAction {
2310 : TypePromotionAction(Inst), OrigTy(Inst->
getType()) {
2311 LLVM_DEBUG(
dbgs() <<
"Do: MutateType: " << *Inst <<
" with " << *NewTy
2317 void undo()
override {
2318 LLVM_DEBUG(
dbgs() <<
"Undo: MutateType: " << *Inst <<
" with " << *OrigTy
2325 class UsesReplacer :
public TypePromotionAction {
2327 struct InstructionAndIdx {
2334 InstructionAndIdx(
Instruction *Inst,
unsigned Idx)
2335 : Inst(Inst), Idx(Idx) {}
2346 LLVM_DEBUG(
dbgs() <<
"Do: UsersReplacer: " << *Inst <<
" with " << *New
2350 Instruction *UserI = cast<Instruction>(U.getUser());
2351 OriginalUses.
push_back(InstructionAndIdx(UserI, U.getOperandNo()));
2358 void undo()
override {
2360 for (use_iterator UseIt = OriginalUses.
begin(),
2361 EndIt = OriginalUses.
end();
2362 UseIt != EndIt; ++UseIt) {
2363 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2369 class InstructionRemover :
public TypePromotionAction {
2375 OperandsHider Hider;
2378 UsesReplacer *Replacer =
nullptr;
2381 SetOfInstrs &RemovedInsts;
2388 InstructionRemover(
Instruction *Inst, SetOfInstrs &RemovedInsts,
2389 Value *New =
nullptr)
2390 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
2391 RemovedInsts(RemovedInsts) {
2393 Replacer =
new UsesReplacer(Inst, New);
2394 LLVM_DEBUG(
dbgs() <<
"Do: InstructionRemover: " << *Inst <<
"\n");
2395 RemovedInsts.insert(Inst);
2402 ~InstructionRemover()
override {
delete Replacer; }
2406 void undo()
override {
2407 LLVM_DEBUG(
dbgs() <<
"Undo: InstructionRemover: " << *Inst <<
"\n");
2408 Inserter.insert(Inst);
2412 RemovedInsts.erase(Inst);
2420 using ConstRestorationPt =
const TypePromotionAction *;
2422 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2423 : RemovedInsts(RemovedInsts) {}
2429 void rollback(ConstRestorationPt Point);
2432 ConstRestorationPt getRestorationPoint()
const;
2467 SetOfInstrs &RemovedInsts;
2472 void TypePromotionTransaction::setOperand(
Instruction *Inst,
unsigned Idx,
2474 Actions.
push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2475 Inst, Idx, NewVal));
2478 void TypePromotionTransaction::eraseInstruction(
Instruction *Inst,
2481 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2482 Inst, RemovedInsts, NewVal));
2485 void TypePromotionTransaction::replaceAllUsesWith(
Instruction *Inst,
2488 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
2491 void TypePromotionTransaction::mutateType(
Instruction *Inst,
Type *NewTy) {
2493 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
2498 std::unique_ptr<TruncBuilder>
Ptr(
new TruncBuilder(Opnd, Ty));
2499 Value *Val = Ptr->getBuiltValue();
2500 Actions.push_back(std::move(Ptr));
2506 std::unique_ptr<SExtBuilder>
Ptr(
new SExtBuilder(Inst, Opnd, Ty));
2507 Value *Val = Ptr->getBuiltValue();
2508 Actions.push_back(std::move(Ptr));
2514 std::unique_ptr<ZExtBuilder>
Ptr(
new ZExtBuilder(Inst, Opnd, Ty));
2515 Value *Val = Ptr->getBuiltValue();
2516 Actions.push_back(std::move(Ptr));
2520 void TypePromotionTransaction::moveBefore(
Instruction *Inst,
2523 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2527 TypePromotionTransaction::ConstRestorationPt
2528 TypePromotionTransaction::getRestorationPoint()
const {
2529 return !Actions.empty() ? Actions.back().get() :
nullptr;
2532 void TypePromotionTransaction::commit() {
2533 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
2539 void TypePromotionTransaction::rollback(
2540 TypePromotionTransaction::ConstRestorationPt Point) {
2541 while (!Actions.empty() && Point != Actions.back().get()) {
2542 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
2552 class AddressingModeMatcher {
2569 const SetOfInstrs &InsertedInsts;
2572 InstrToOrigTy &PromotedInsts;
2575 TypePromotionTransaction &TPT;
2578 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
2582 bool IgnoreProfitability;
2584 AddressingModeMatcher(
2587 ExtAddrMode &AM,
const SetOfInstrs &InsertedInsts,
2588 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
2590 : AddrModeInsts(AMI), TLI(TLI),
TRI(TRI),
2592 MemoryInst(MI),
AddrMode(AM), InsertedInsts(InsertedInsts),
2593 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
2594 IgnoreProfitability =
false;
2609 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
2610 TypePromotionTransaction &TPT,
2614 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
2615 MemoryInst, Result, InsertedInsts,
2616 PromotedInsts, TPT, LargeOffsetGEP)
2618 (void)Success;
assert(Success &&
"Couldn't select *anything*?");
2623 bool matchScaledValue(
Value *ScaleReg, int64_t Scale,
unsigned Depth);
2624 bool matchAddr(
Value *Addr,
unsigned Depth);
2625 bool matchOperationAddr(
User *AddrInst,
unsigned Opcode,
unsigned Depth,
2626 bool *MovedAway =
nullptr);
2627 bool isProfitableToFoldIntoAddressingMode(
Instruction *I,
2628 ExtAddrMode &AMBefore,
2629 ExtAddrMode &AMAfter);
2630 bool valueAlreadyLiveAtInst(
Value *Val,
Value *KnownLive1,
Value *KnownLive2);
2631 bool isPromotionProfitable(
unsigned NewCost,
unsigned OldCost,
2632 Value *PromotedOperand)
const;
2638 class SimplificationTracker {
2653 auto SV = Storage.
find(V);
2654 if (SV == Storage.
end())
2664 while (!WorkList.
empty()) {
2666 if (!Visited.
insert(
P).second)
2668 if (
auto *PI = dyn_cast<Instruction>(
P))
2670 for (
auto *U : PI->users())
2673 PI->replaceAllUsesWith(V);
2674 if (
auto *PHI = dyn_cast<PHINode>(PI))
2676 if (
auto *
Select = dyn_cast<SelectInst>(PI))
2678 PI->eraseFromParent();
2685 Storage.
insert({ From, To });
2689 Value* OldReplacement = Get(From);
2690 while (OldReplacement != From) {
2693 OldReplacement = Get(From);
2695 assert(Get(To) == To &&
"Replacement PHI node is already replaced.");
2698 AllPhiNodes.
remove(From);
2708 unsigned countNewPhiNodes()
const {
return AllPhiNodes.
size(); }
2710 unsigned countNewSelectNodes()
const {
return AllSelectNodes.
size(); }
2712 void destroyNewNodes(
Type *CommonType) {
2715 for (
auto I : AllPhiNodes) {
2719 AllPhiNodes.
clear();
2720 for (
auto I : AllSelectNodes) {
2724 AllSelectNodes.
clear();
2729 class AddressingModeCombiner {
2730 typedef std::pair<Value *, BasicBlock *> ValueInBB;
2732 typedef std::pair<PHINode *, PHINode *> PHIPair;
2739 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2742 bool AllAddrModesTrivial =
true;
2754 AddressingModeCombiner(
const SimplifyQuery &_SQ, ValueInBB OriginalValue)
2755 : CommonType(
nullptr), SQ(_SQ), Original(OriginalValue) {}
2759 return AddrModes[0];
2765 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2769 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2772 if (AddrModes.
empty()) {
2780 ExtAddrMode::FieldName ThisDifferentField =
2781 AddrModes[0].compare(NewAddrMode);
2782 if (DifferentField == ExtAddrMode::NoField)
2783 DifferentField = ThisDifferentField;
2784 else if (DifferentField != ThisDifferentField)
2785 DifferentField = ExtAddrMode::MultipleFields;
2788 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
2791 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
2796 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
2797 !NewAddrMode.ScaledReg);
2801 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
2802 !NewAddrMode.HasBaseReg);
2819 bool combineAddrModes() {
2821 if (AddrModes.
size() == 0)
2825 if (AddrModes.
size() == 1 || DifferentField == ExtAddrMode::NoField)
2830 if (AllAddrModesTrivial)
2833 if (!addrModeCombiningAllowed())
2839 FoldAddrToValueMapping Map;
2840 if (!initializeMap(Map))
2843 Value *CommonValue = findCommon(Map);
2845 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
2846 return CommonValue !=
nullptr;
2856 bool initializeMap(FoldAddrToValueMapping &Map) {
2861 for (
auto &AM : AddrModes) {
2863 if (
Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2866 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
2869 if (CommonType && CommonType !=
Type)
2872 Map[{ AM.OriginalValue, BB }] = DV;
2874 NullValue.
push_back({ AM.OriginalValue, BB });
2877 assert(CommonType &&
"At least one non-null value must be!");
2878 for (
auto VIBB : NullValue)
2907 Value *findCommon(FoldAddrToValueMapping &Map) {
2913 SimplificationTracker
ST(SQ);
2918 InsertPlaceholders(Map, TraverseOrder, ST);
2921 FillPlaceholders(Map, TraverseOrder, ST);
2924 ST.destroyNewNodes(CommonType);
2929 unsigned PhiNotMatchedCount = 0;
2931 ST.destroyNewNodes(CommonType);
2935 auto *
Result = ST.Get(Map.find(Original)->second);
2937 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
2938 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
2949 Matcher.
insert({ PHI, Candidate });
2952 while (!WorkList.
empty()) {
2954 if (!Visited.
insert(Item).second)
2961 for (
auto B : Item.first->blocks()) {
2962 Value *FirstValue = Item.first->getIncomingValueForBlock(
B);
2963 Value *SecondValue = Item.second->getIncomingValueForBlock(
B);
2964 if (FirstValue == SecondValue)
2974 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.
count(FirstPhi) ||
2979 if (Matcher.
count({ FirstPhi, SecondPhi }))
2983 Matcher.
insert({ FirstPhi, SecondPhi });
2985 WorkList.
push_back({ FirstPhi, SecondPhi });
2994 bool MatchPhiSet(SimplificationTracker &
ST,
bool AllowNewPhiNodes,
2995 unsigned &PhiNotMatchedCount) {
3001 while (PhiNodesToMatch.
size()) {
3005 WillNotMatch.
clear();
3006 WillNotMatch.
insert(PHI);
3009 bool IsMatched =
false;
3013 if ((IsMatched = MatchPhiNode(PHI, &
P, Matched, PhiNodesToMatch)))
3018 for (
auto M : Matched)
3019 WillNotMatch.
insert(M.first);
3024 for (
auto MV : Matched)
3025 ST.ReplacePhi(MV.first, MV.second);
3030 if (!AllowNewPhiNodes)
3033 PhiNotMatchedCount += WillNotMatch.
size();
3034 for (
auto *
P : WillNotMatch)
3040 void FillPlaceholders(FoldAddrToValueMapping &Map,
3042 SimplificationTracker &ST) {
3043 while (!TraverseOrder.
empty()) {
3045 assert(Map.find(Current) != Map.end() &&
"No node to fill!!!");
3046 Value *CurrentValue = Current.first;
3048 Value *V = Map[Current];
3052 auto *CurrentSelect = cast<SelectInst>(CurrentValue);
3053 auto *TrueValue = CurrentSelect->getTrueValue();
3054 ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
3057 assert(Map.find(TrueItem) != Map.end() &&
"No True Value!");
3058 Select->setTrueValue(ST.Get(Map[TrueItem]));
3059 auto *FalseValue = CurrentSelect->getFalseValue();
3060 ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
3063 assert(Map.find(FalseItem) != Map.end() &&
"No False Value!");
3064 Select->setFalseValue(ST.Get(Map[FalseItem]));
3067 PHINode *PHI = cast<PHINode>(V);
3069 bool IsDefinedInThisBB =
3070 cast<Instruction>(CurrentValue)->
getParent() == CurrentBlock;
3073 Value *PV = IsDefinedInThisBB
3074 ? CurrentPhi->getIncomingValueForBlock(
B)
3076 ValueInBB item = { PV, isa<Instruction>(PV) ?
B :
nullptr };
3077 assert(Map.find(item) != Map.end() &&
"No predecessor Value!");
3082 Map[Current] = ST.Simplify(V);
3091 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3093 SimplificationTracker &ST) {
3095 assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3096 "Address must be a Phi or Select node");
3099 while (!Worklist.
empty()) {
3105 if (!isa<Instruction>(Current.first))
3106 Current.second =
nullptr;
3108 if (Map.find(Current) != Map.end())
3112 Value *CurrentValue = Current.first;
3116 Instruction *CurrentI = cast<Instruction>(CurrentValue);
3117 bool IsDefinedInThisBB = CurrentI->
getParent() == CurrentBlock;
3119 unsigned PredCount =
pred_size(CurrentBlock);
3122 if (!IsDefinedInThisBB) {
3123 assert(PredCount &&
"Unreachable block?!");
3125 &CurrentBlock->
front());
3127 ST.insertNewPhi(PHI);
3134 if (
SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3139 OrigSelect->getName(), OrigSelect, OrigSelect);
3141 ST.insertNewSelect(Select);
3143 Worklist.
push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3144 Worklist.
push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3147 auto *CurrentPhi = cast<PHINode>(CurrentI);
3149 assert(PredCount &&
"Unreachable block?!");
3151 &CurrentBlock->
front());
3153 ST.insertNewPhi(PHI);
3157 Worklist.
push_back({ CurrentPhi->getIncomingValueForBlock(
B),
B });
3162 bool addrModeCombiningAllowed() {
3165 switch (DifferentField) {
3168 case ExtAddrMode::BaseRegField:
3170 case ExtAddrMode::BaseGVField:
3172 case ExtAddrMode::BaseOffsField:
3174 case ExtAddrMode::ScaledRegField:
3184 bool AddressingModeMatcher::matchScaledValue(
Value *ScaleReg, int64_t Scale,
3189 return matchAddr(ScaleReg, Depth);
3200 ExtAddrMode TestAddrMode =
AddrMode;
3204 TestAddrMode.Scale += Scale;
3205 TestAddrMode.ScaledReg = ScaleReg;
3208 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3218 if (isa<Instruction>(ScaleReg) &&
3220 TestAddrMode.ScaledReg = AddLHS;
3221 TestAddrMode.BaseOffs += CI->
getSExtValue()*TestAddrMode.Scale;
3225 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3226 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3242 case Instruction::BitCast:
3243 case Instruction::AddrSpaceCast:
3248 case Instruction::PtrToInt:
3251 case Instruction::IntToPtr:
3256 case Instruction::Mul:
3257 case Instruction::Shl:
3260 case Instruction::GetElementPtr:
3288 class TypePromotionHelper {
3291 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
3294 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3295 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
3296 if (It != PromotedInsts.end()) {
3299 if (It->second.getInt() == ExtTy)
3305 ExtTy = BothExtension;
3307 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->
getType(), ExtTy);
3314 static const Type *getOrigType(
const InstrToOrigTy &PromotedInsts,
3317 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3318 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3319 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
3320 return It->second.getPointer();
3335 static bool canGetThrough(
const Instruction *Inst,
Type *ConsideredExtType,
3336 const InstrToOrigTy &PromotedInsts,
bool IsSExt);
3340 static bool shouldExtOperand(
const Instruction *Inst,
int OpIdx) {
3341 return !(isa<SelectInst>(Inst) && OpIdx == 0);
3353 static Value *promoteOperandForTruncAndAnyExt(
3355 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3369 TypePromotionTransaction &TPT,
3370 InstrToOrigTy &PromotedInsts,
3371 unsigned &CreatedInstsCost,
3377 static Value *signExtendOperandForOther(
3379 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3382 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3383 Exts, Truncs, TLI,
true);
3387 static Value *zeroExtendOperandForOther(
3389 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3392 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3393 Exts, Truncs, TLI,
false);
3399 InstrToOrigTy &PromotedInsts,
3400 unsigned &CreatedInstsCost,
3414 static Action getAction(
Instruction *Ext,
const SetOfInstrs &InsertedInsts,
3416 const InstrToOrigTy &PromotedInsts);
3421 bool TypePromotionHelper::canGetThrough(
const Instruction *Inst,
3422 Type *ConsideredExtType,
3423 const InstrToOrigTy &PromotedInsts,
3432 if (isa<ZExtInst>(Inst))
3436 if (IsSExt && isa<SExtInst>(Inst))
3442 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
3448 if ((Inst->
getOpcode() == Instruction::And ||
3453 if (Inst->
getOpcode() == Instruction::Xor) {
3465 if (Inst->
getOpcode() == Instruction::LShr && !IsSExt)
3479 if (AndInst && AndInst->
getOpcode() == Instruction::And) {
3490 if (!isa<TruncInst>(Inst))
3512 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
3515 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3525 TypePromotionHelper::Action TypePromotionHelper::getAction(
3528 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3529 "Unexpected instruction type");
3532 bool IsSExt = isa<SExtInst>(
Ext);
3536 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
3542 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
3547 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3548 isa<ZExtInst>(ExtOpnd))
3549 return promoteOperandForTruncAndAnyExt;
3555 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
3558 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
3560 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3566 Value *ExtVal = SExt;
3567 bool HasMergedNonFreeExt =
false;
3568 if (isa<ZExtInst>(SExtOpnd)) {
3571 HasMergedNonFreeExt = !TLI.
isExtFree(SExtOpnd);
3574 TPT.replaceAllUsesWith(SExt, ZExt);
3575 TPT.eraseInstruction(SExt);
3580 TPT.setOperand(SExt, 0, SExtOpnd->
getOperand(0));
3582 CreatedInstsCost = 0;
3586 TPT.eraseInstruction(SExtOpnd);
3594 CreatedInstsCost = !TLI.
isExtFree(ExtInst) && !HasMergedNonFreeExt;
3602 TPT.eraseInstruction(ExtInst, NextVal);
3606 Value *TypePromotionHelper::promoteOperandForOther(
3608 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3615 CreatedInstsCost = 0;
3621 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->
getType());
3622 if (
Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3624 ITrunc->moveAfter(ExtOpnd);
3629 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
3632 TPT.setOperand(Ext, 0, ExtOpnd);
3642 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
3644 TPT.mutateType(ExtOpnd, Ext->
getType());
3646 TPT.replaceAllUsesWith(Ext, ExtOpnd);
3651 for (
int OpIdx = 0, EndOpIdx = ExtOpnd->
getNumOperands(); OpIdx != EndOpIdx;
3655 !shouldExtOperand(ExtOpnd, OpIdx)) {
3661 if (
const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
3664 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3665 : Cst->getValue().zext(BitWidth);
3670 if (isa<UndefValue>(Opnd)) {
3681 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->
getType())
3682 : TPT.createZExt(Ext, Opnd, Ext->
getType());
3683 if (!isa<Instruction>(ValForExtOpnd)) {
3684 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3687 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
3691 TPT.setOperand(ExtForOpnd, 0, Opnd);
3694 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3695 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
3696 CreatedInstsCost += !TLI.
isExtFree(ExtForOpnd);
3698 ExtForOpnd =
nullptr;
3700 if (ExtForOpnd == Ext) {
3702 TPT.eraseInstruction(Ext);
3715 bool AddressingModeMatcher::isPromotionProfitable(
3716 unsigned NewCost,
unsigned OldCost,
Value *PromotedOperand)
const {
3717 LLVM_DEBUG(
dbgs() <<
"OldCost: " << OldCost <<
"\tNewCost: " << NewCost
3722 if (NewCost > OldCost)
3724 if (NewCost < OldCost)
3743 bool AddressingModeMatcher::matchOperationAddr(
User *AddrInst,
unsigned Opcode,
3747 if (Depth >= 5)
return false;
3754 case Instruction::PtrToInt:
3757 case Instruction::IntToPtr: {
3765 case Instruction::BitCast:
3775 case Instruction::AddrSpaceCast: {
3785 ExtAddrMode BackupAddrMode =
AddrMode;
3786 unsigned OldSize = AddrModeInsts.size();
3791 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3792 TPT.getRestorationPoint();
3794 if (matchAddr(AddrInst->
getOperand(1), Depth+1) &&
3800 AddrModeInsts.resize(OldSize);
3801 TPT.rollback(LastKnownGood);
3804 if (matchAddr(AddrInst->
getOperand(0), Depth+1) &&
3810 AddrModeInsts.resize(OldSize);
3811 TPT.rollback(LastKnownGood);
3817 case Instruction::Mul:
3818 case Instruction::Shl: {
3824 if (Opcode == Instruction::Shl)
3825 Scale = 1LL << Scale;
3829 case Instruction::GetElementPtr: {
3832 int VariableOperand = -1;
3833 unsigned VariableScale = 0;
3835 int64_t ConstantOffset = 0;
3837 for (
unsigned i = 1, e = AddrInst->
getNumOperands(); i != e; ++i, ++GTI) {
3841 cast<ConstantInt>(AddrInst->
getOperand(i))->getZExtValue();
3846 ConstantOffset += CI->getSExtValue() * TypeSize;
3847 }
else if (TypeSize) {
3849 if (VariableOperand != -1)
3853 VariableOperand = i;
3854 VariableScale = TypeSize;
3861 if (VariableOperand == -1) {
3862 AddrMode.BaseOffs += ConstantOffset;
3863 if (ConstantOffset == 0 ||
3866 if (matchAddr(AddrInst->
getOperand(0), Depth+1))
3870 ConstantOffset > 0) {
3877 auto *
GEP = cast<GetElementPtrInst>(AddrInst);
3878 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
3879 (BaseI && !isa<CastInst>(BaseI) &&
3880 !isa<GetElementPtrInst>(BaseI))) {
3890 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
3893 AddrMode.BaseOffs -= ConstantOffset;
3898 ExtAddrMode BackupAddrMode =
AddrMode;
3899 unsigned OldSize = AddrModeInsts.size();
3902 AddrMode.BaseOffs += ConstantOffset;
3905 if (!matchAddr(AddrInst->
getOperand(0), Depth+1)) {
3909 AddrModeInsts.resize(OldSize);
3917 if (!matchScaledValue(AddrInst->
getOperand(VariableOperand), VariableScale,
3922 AddrModeInsts.resize(OldSize);
3927 AddrMode.BaseOffs += ConstantOffset;
3928 if (!matchScaledValue(AddrInst->
getOperand(VariableOperand),
3929 VariableScale,
Depth)) {
3932 AddrModeInsts.resize(OldSize);
3939 case Instruction::SExt:
3940 case Instruction::ZExt: {
3947 TypePromotionHelper::Action TPH =
3948 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
3952 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3953 TPT.getRestorationPoint();
3954 unsigned CreatedInstsCost = 0;
3956 Value *PromotedOperand =
3957 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost,
nullptr,
nullptr, TLI);
3972 assert(PromotedOperand &&
3973 "TypePromotionHelper should have filtered out those cases");
3975 ExtAddrMode BackupAddrMode =
AddrMode;
3976 unsigned OldSize = AddrModeInsts.size();
3978 if (!matchAddr(PromotedOperand, Depth) ||
3983 !isPromotionProfitable(CreatedInstsCost,
3984 ExtCost + (AddrModeInsts.size() - OldSize),
3987 AddrModeInsts.resize(OldSize);
3988 LLVM_DEBUG(
dbgs() <<
"Sign extension does not pay off: rollback\n");
3989 TPT.rollback(LastKnownGood);
4003 bool AddressingModeMatcher::matchAddr(
Value *Addr,
unsigned Depth) {
4006 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4007 TPT.getRestorationPoint();
4008 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4010 AddrMode.BaseOffs += CI->getSExtValue();
4013 AddrMode.BaseOffs -= CI->getSExtValue();
4014 }
else if (
GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4022 }
else if (
Instruction *I = dyn_cast<Instruction>(Addr)) {
4023 ExtAddrMode BackupAddrMode =
AddrMode;
4024 unsigned OldSize = AddrModeInsts.size();
4027 bool MovedAway =
false;
4037 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode,
AddrMode)) {
4038 AddrModeInsts.push_back(I);
4045 AddrModeInsts.resize(OldSize);
4046 TPT.rollback(LastKnownGood);
4048 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
4049 if (matchOperationAddr(CE, CE->getOpcode(),
Depth))
4051 TPT.rollback(LastKnownGood);
4052 }
else if (isa<ConstantPointerNull>(Addr)) {
4078 TPT.rollback(LastKnownGood);
4092 for (
unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4122 if (!ConsideredInsts.
insert(I).second)
4135 if (SeenInsts++ >= MaxMemoryUsesToScan)
4138 Instruction *UserI = cast<Instruction>(U.getUser());
4139 if (
LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4140 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
4145 unsigned opNo = U.getOperandNo();
4148 MemoryUses.push_back(std::make_pair(
SI, opNo));
4153 unsigned opNo = U.getOperandNo();
4156 MemoryUses.push_back(std::make_pair(RMW, opNo));
4161 unsigned opNo = U.getOperandNo();
4164 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4168 if (
CallInst *CI = dyn_cast<CallInst>(UserI)) {
4175 if (!IA)
return true;
4195 bool AddressingModeMatcher::valueAlreadyLiveAtInst(
Value *Val,
Value *KnownLive1,
4196 Value *KnownLive2) {
4198 if (Val ==
nullptr || Val == KnownLive1 || Val == KnownLive2)
4202 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
return true;
4207 if (
AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4208 if (AI->isStaticAlloca())
4238 bool AddressingModeMatcher::
4239 isProfitableToFoldIntoAddressingMode(
Instruction *I, ExtAddrMode &AMBefore,
4240 ExtAddrMode &AMAfter) {
4241 if (IgnoreProfitability)
return true;
4252 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
4256 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4258 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4259 ScaledReg =
nullptr;
4263 if (!BaseReg && !ScaledReg)
4285 for (
unsigned i = 0, e = MemoryUses.
size(); i != e; ++i) {
4287 unsigned OpNo = MemoryUses[i].second;
4302 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(
nullptr,
4304 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4305 TPT.getRestorationPoint();
4306 AddressingModeMatcher Matcher(
4307 MatchedAddrModeInsts, TLI,
TRI, AddressAccessTy, AS, MemoryInst, Result,
4308 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
4309 Matcher.IgnoreProfitability =
true;
4310 bool Success = Matcher.matchAddr(Address, 0);
4311 (void)Success;
assert(Success &&
"Couldn't select *anything*?");
4316 TPT.rollback(LastKnownGood);
4322 MatchedAddrModeInsts.
clear();
4355 bool CodeGenPrepare::optimizeMemoryInst(
Instruction *MemoryInst,
Value *Addr,
4356 Type *AccessTy,
unsigned AddrSpace) {
4368 bool PhiOrSelectSeen =
false;
4371 AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->
getParent() });
4372 TypePromotionTransaction TPT(RemovedInsts);
4373 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4374 TPT.getRestorationPoint();
4375 while (!worklist.
empty()) {
4388 if (!Visited.
insert(V).second)
4392 if (
PHINode *
P = dyn_cast<PHINode>(V)) {
4393 for (
Value *IncValue :
P->incoming_values())
4395 PhiOrSelectSeen =
true;
4402 PhiOrSelectSeen =
true;
4409 AddrModeInsts.
clear();
4410 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(
nullptr,
4413 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *
TRI,
4414 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
4418 !NewGEPBases.count(GEP)) {
4423 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
4424 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
4427 NewAddrMode.OriginalValue = V;
4428 if (!AddrModes.addNewAddrMode(NewAddrMode))
4435 if (!AddrModes.combineAddrModes()) {
4436 TPT.rollback(LastKnownGood);
4442 ExtAddrMode
AddrMode = AddrModes.getAddrMode();
4448 if (!PhiOrSelectSeen &&
none_of(AddrModeInsts, [&](
Value *V) {
4471 LLVM_DEBUG(
dbgs() <<
"CGP: Reusing nonlocal addrmode: " << AddrMode
4472 <<
" for " << *MemoryInst <<
"\n");
4479 LLVM_DEBUG(
dbgs() <<
"CGP: SINKING nonlocal addrmode: " << AddrMode
4480 <<
" for " << *MemoryInst <<
"\n");
4481 Type *IntPtrTy = DL->getIntPtrType(Addr->
getType());
4482 Value *ResultPtr =
nullptr, *ResultIndex =
nullptr;
4485 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4486 ResultPtr = AddrMode.BaseReg;
4487 AddrMode.BaseReg =
nullptr;
4490 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4493 if (ResultPtr || AddrMode.Scale != 1)
4496 ResultPtr = AddrMode.ScaledReg;
4507 if (AddrMode.Scale) {
4508 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4514 if (AddrMode.BaseGV) {
4518 ResultPtr = AddrMode.BaseGV;
4524 if (!DL->isNonIntegralPointerType(Addr->
getType())) {
4525 if (!ResultPtr && AddrMode.BaseReg) {
4528 AddrMode.BaseReg =
nullptr;
4529 }
else if (!ResultPtr && AddrMode.Scale == 1) {
4537 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4539 }
else if (!ResultPtr) {
4551 if (AddrMode.BaseReg) {
4552 Value *V = AddrMode.BaseReg;
4560 if (AddrMode.Scale) {
4561 Value *V = AddrMode.ScaledReg;
4562 if (V->
getType() == IntPtrTy) {
4567 "We can't transform if ScaledReg is too narrow");
4571 if (AddrMode.Scale != 1)
4575 ResultIndex = Builder.
CreateAdd(ResultIndex, V,
"sunkaddr");
4581 if (AddrMode.BaseOffs) {
4586 if (ResultPtr->
getType() != I8PtrTy)
4588 ResultPtr = Builder.
CreateGEP(I8Ty, ResultPtr, ResultIndex,
"sunkaddr");
4595 SunkAddr = ResultPtr;
4597 if (ResultPtr->
getType() != I8PtrTy)
4599 SunkAddr = Builder.
CreateGEP(I8Ty, ResultPtr, ResultIndex,
"sunkaddr");
4608 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() :
nullptr;
4609 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() :
nullptr;
4610 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4611 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4612 if (DL->isNonIntegralPointerType(Addr->
getType()) ||
4613 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4614 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4616 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4619 LLVM_DEBUG(
dbgs() <<
"CGP: SINKING nonlocal addrmode: " << AddrMode
4620 <<
" for " << *MemoryInst <<
"\n");
4621 Type *IntPtrTy = DL->getIntPtrType(Addr->
getType());
4629 if (AddrMode.BaseReg) {
4630 Value *V = AddrMode.BaseReg;
4639 if (AddrMode.Scale) {
4640 Value *V = AddrMode.ScaledReg;
4641 if (V->
getType() == IntPtrTy) {
4645 }
else if (cast<IntegerType>(IntPtrTy)->
getBitWidth() <
4654 Instruction *I = dyn_cast_or_null<Instruction>(Result);
4655 if (I && (Result != AddrMode.BaseReg))
4659 if (AddrMode.Scale != 1)
4663 Result = Builder.
CreateAdd(Result, V,
"sunkaddr");
4669 if (AddrMode.BaseGV) {
4672 Result = Builder.
CreateAdd(Result, V,
"sunkaddr");
4678 if (AddrMode.BaseOffs) {
4681 Result = Builder.
CreateAdd(Result, V,
"sunkaddr");
4702 Value *CurValue = &*CurInstIterator;
4708 if (IterHandle != CurValue) {
4711 CurInstIterator = BB->
begin();
4721 bool CodeGenPrepare::optimizeInlineAsmInst(
CallInst *CS) {
4722 bool MadeChange =
false;
4725 TM->getSubtargetImpl(*CS->
getFunction())->getRegisterInfo();
4729 for (
unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4738 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->
getType(), ~0u);
4751 bool IsSExt = isa<SExtInst>(FirstUser);
4752 Type *ExtTy = FirstUser->getType();
4755 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4778 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4801 bool CodeGenPrepare::tryToPromoteExts(
4804 unsigned CreatedInstsCost) {
4805 bool Promoted =
false;
4808 for (
auto I : Exts) {
4823 TypePromotionHelper::Action TPH =
4824 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
4833 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4834 TPT.getRestorationPoint();
4836 unsigned NewCreatedInstsCost = 0;
4839 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4840 &NewExts,
nullptr, *TLI);
4842 "TypePromotionHelper should have filtered out those cases");
4850 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4853 TotalCreatedInstsCost =
4854 std::max((
long long)0, (TotalCreatedInstsCost - ExtCost));
4856 (TotalCreatedInstsCost > 1 ||
4861 TPT.rollback(LastKnownGood);
4867 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4868 bool NewPromoted =
false;
4869 for (
auto ExtInst : NewlyMovedExts) {
4870 Instruction *MovedExt = cast<Instruction>(ExtInst);
4874 if (isa<LoadInst>(ExtOperand) &&
4876 (ExtOperand->hasOneUse() ||
hasSameExtUse(ExtOperand, *TLI))))
4879 ProfitablyMovedExts.
push_back(MovedExt);
4886 TPT.rollback(LastKnownGood);
4897 bool CodeGenPrepare::mergeSExts(
Function &F) {
4899 bool Changed =
false;
4900 for (
auto &Entry : ValToSExtendedUses) {
4901 SExts &Insts = Entry.second;
4904 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4907 bool inserted =
false;
4908 for (
auto &Pt : CurPts) {
4910 Pt->replaceAllUsesWith(Inst);
4911 RemovedInsts.insert(Pt);
4912 Pt->removeFromParent();
4923 RemovedInsts.insert(Inst);
4930 CurPts.push_back(Inst);
4972 bool CodeGenPrepare::splitLargeGEPOffsets() {
4973 bool Changed =
false;
4974 for (
auto &Entry : LargeOffsetGEPMap) {
4975 Value *OldBase = Entry.first;
4977 &LargeOffsetGEPs = Entry.second;
4978 auto compareGEPOffset =
4979 [&](
const std::pair<GetElementPtrInst *, int64_t> &LHS,
4980 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
4981 if (LHS.first == RHS.first)
4983 if (LHS.second != RHS.second)
4984 return LHS.second < RHS.second;
4985 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
4990 LargeOffsetGEPs.
erase(
4991 std::unique(LargeOffsetGEPs.
begin(), LargeOffsetGEPs.
end()),
4992 LargeOffsetGEPs.
end());
4994 if (LargeOffsetGEPs.
front().second == LargeOffsetGEPs.
back().second)
4997 int64_t BaseOffset = LargeOffsetGEPs.
begin()->second;
4998 Value *NewBaseGEP =
nullptr;
5000 auto LargeOffsetGEP = LargeOffsetGEPs.
begin();
5001 while (LargeOffsetGEP != LargeOffsetGEPs.
end()) {
5003 int64_t
Offset = LargeOffsetGEP->second;
5004 if (Offset != BaseOffset) {
5006 AddrMode.BaseOffs = Offset - BaseOffset;
5017 NewBaseGEP =
nullptr;
5023 Type *IntPtrTy = DL->getIntPtrType(GEP->
getType());
5033 if (
auto *BaseI = dyn_cast<Instruction>(OldBase)) {
5037 if (isa<PHINode>(BaseI))
5039 else if (
InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
5041 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
5044 NewBaseInsertPt = std::next(BaseI->getIterator());
5051 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5054 NewBaseGEP = OldBase;
5055 if (NewBaseGEP->
getType() != I8PtrTy)
5058 NewBaseBuilder.
CreateGEP(I8Ty, NewBaseGEP, BaseIndex,
"splitgep");
5059 NewGEPBases.insert(NewBaseGEP);
5062 Value *NewGEP = NewBaseGEP;
5063 if (Offset == BaseOffset) {
5064 if (GEP->
getType() != I8PtrTy)
5069 NewGEP = Builder.
CreateGEP(I8Ty, NewBaseGEP, Index);
5071 if (GEP->
getType() != I8PtrTy)
5075 LargeOffsetGEPID.erase(GEP);
5076 LargeOffsetGEP = LargeOffsetGEPs.
erase(LargeOffsetGEP);
5086 bool CodeGenPrepare::canFormExtLd(
5089 for (
auto *MovedExtInst : MovedExts) {
5090 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5091 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5092 Inst = MovedExtInst;
5144 bool CodeGenPrepare::optimizeExt(
Instruction *&Inst) {
5150 bool AllowPromotionWithoutCommonHeader =
false;
5154 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5155 *Inst, AllowPromotionWithoutCommonHeader);
5156 TypePromotionTransaction TPT(RemovedInsts);
5157 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5158 TPT.getRestorationPoint();
5163 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
5171 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5172 assert(LI && ExtFedByLoad &&
"Expect a valid load and extension");
5185 Inst = ExtFedByLoad;
5190 if (ATPConsiderable &&
5191 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5192 HasPromoted, TPT, SpeculativelyMovedExts))
5195 TPT.rollback(LastKnownGood);
5204 bool CodeGenPrepare::performAddressTypePromotion(
5205 Instruction *&Inst,
bool AllowPromotionWithoutCommonHeader,
5206 bool HasPromoted, TypePromotionTransaction &TPT,
5208 bool Promoted =
false;
5210 bool AllSeenFirst =
true;
5211 for (
auto I : SpeculativelyMovedExts) {
5214 SeenChainsForSExt.
find(HeadOfChain);
5217 if (AlreadySeen != SeenChainsForSExt.
end()) {
5218 if (AlreadySeen->second !=
nullptr)
5219 UnhandledExts.
insert(AlreadySeen->second);
5220 AllSeenFirst =
false;
5224 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5225 SpeculativelyMovedExts.size() == 1)) {
5229 for (
auto I : SpeculativelyMovedExts) {
5231 SeenChainsForSExt[HeadOfChain] =
nullptr;
5232 ValToSExtendedUses[HeadOfChain].push_back(I);
5235 Inst = SpeculativelyMovedExts.pop_back_val();
5240 for (
auto I : SpeculativelyMovedExts) {
5242 SeenChainsForSExt[HeadOfChain] = Inst;
5247 if (!AllSeenFirst && !UnhandledExts.
empty())
5248 for (
auto VisitedSExt : UnhandledExts) {
5249 if (RemovedInsts.count(VisitedSExt))
5251 TypePromotionTransaction TPT(RemovedInsts);
5255 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5259 for (
auto I : Chains) {
5262 SeenChainsForSExt[HeadOfChain] =
nullptr;
5263 ValToSExtendedUses[HeadOfChain].push_back(I);
5269 bool CodeGenPrepare::optimizeExtUses(
Instruction *I) {
5284 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->
getParent())
5287 bool DefIsLiveOut =
false;
5293 if (UserBB == DefBB)
continue;
5294 DefIsLiveOut =
true;
5304 if (UserBB == DefBB)
continue;
5307 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
5314 bool MadeChange =
false;
5320 if (UserBB == DefBB)
continue;
5323 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5325 if (!InsertedTrunc) {
5327 assert(InsertPt != UserBB->end());
5329 InsertedInsts.insert(InsertedTrunc);
5398 InsertedInsts.count(cast<Instruction>(*Load->
user_begin())))
5406 for (
auto *U : Load->
users())
5407 WorkList.
push_back(cast<Instruction>(U));
5411 APInt DemandBits(BitWidth, 0);
5412 APInt WidestAndBits(BitWidth, 0);
5414 while (!WorkList.
empty()) {
5419 if (!Visited.
insert(I).second)
5423 if (
auto *Phi = dyn_cast<PHINode>(I)) {
5424 for (
auto *U : Phi->users())
5425 WorkList.
push_back(cast<Instruction>(U));
5430 case Instruction::And: {
5434 APInt AndBits = AndC->getValue();
5435 DemandBits |= AndBits;
5437 if (AndBits.
ugt(WidestAndBits))
5438 WidestAndBits = AndBits;
5444 case Instruction::Shl: {
5453 case Instruction::Trunc: {
5477 if (ActiveBits <= 1 || !DemandBits.
isMask(ActiveBits) ||
5478 WidestAndBits != DemandBits)
5495 InsertedInsts.insert(NewAnd);
5500 NewAnd->setOperand(0, Load);
5503 for (
auto *And : AndsToMaybeRemove)
5506 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5507 And->replaceAllUsesWith(NewAnd);
5508 if (&*CurInstIterator == And)
5509 CurInstIterator = std::next(And->getIterator());
5510 And->eraseFromParent();
5541 uint64_t TrueWeight, FalseWeight;
5543 uint64_t Max =
std::max(TrueWeight, FalseWeight);
5544 uint64_t Sum = TrueWeight + FalseWeight;
5578 for (
SelectInst *DefSI = SI; DefSI !=
nullptr && Selects.
count(DefSI);
5581 "The condition of DefSI does not match with SI");
5582 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5589 bool CodeGenPrepare::optimizeSelectInst(
SelectInst *
SI) {
5606 CurInstIterator = std::next(LastSI->
getIterator());
5671 if (TrueBlock ==
nullptr) {
5676 auto *TrueInst = cast<Instruction>(SI->
getTrueValue());
5677 TrueInst->moveBefore(TrueBranch);
5680 if (FalseBlock ==
nullptr) {
5686 FalseInst->moveBefore(FalseBranch);
5692 if (TrueBlock == FalseBlock) {
5693 assert(TrueBlock ==
nullptr &&
5694 "Unexpected basic block transform while optimizing select");
5707 if (TrueBlock ==
nullptr) {
5710 TrueBlock = StartBlock;
5711 }
else if (FalseBlock ==
nullptr) {
5714 FalseBlock = StartBlock;
5722 INS.insert(ASI.begin(), ASI.end());
5726 for (
auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5737 ++NumSelectsExpanded;
5741 CurInstIterator = StartBlock->
end();
5748 for (
unsigned i = 0; i <
Mask.size(); ++i) {
5749 if (SplatElem != -1 &&
Mask[i] != -1 &&
Mask[i] != SplatElem)
5751 SplatElem =
Mask[i];
5776 bool MadeChange =
false;
5782 if (UserBB == DefBB)
continue;
5789 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5791 if (!InsertedShuffle) {
5793 assert(InsertPt != UserBB->end());
5812 bool CodeGenPrepare::optimizeSwitchInst(
SwitchInst *SI) {
5822 if (RegWidth <= cast<IntegerType>(OldType)->
getBitWidth())
5838 if (
auto *
Arg = dyn_cast<Argument>(Cond))
5839 if (
Arg->hasSExtAttr())
5840 ExtType = Instruction::SExt;
5843 ExtInst->insertBefore(SI);
5845 for (
auto Case : SI->
cases()) {
5846 APInt NarrowConst = Case.getCaseValue()->getValue();
5847 APInt WideConst = (ExtType == Instruction::ZExt) ?
5848 NarrowConst.
zext(RegWidth) : NarrowConst.
sext(RegWidth);
5873 class VectorPromoteHelper {
5890 unsigned StoreExtractCombineCost;
5899 if (InstsToBePromoted.
empty())
5901 return InstsToBePromoted.
back();
5907 unsigned getTransitionOriginalValueIdx()
const {
5908 assert(isa<ExtractElementInst>(Transition) &&
5909 "Other kind of transitions are not supported yet");
5916 unsigned getTransitionIdx()
const {
5917 assert(isa<ExtractElementInst>(Transition) &&
5918 "Other kind of transitions are not supported yet");
5926 Type *getTransitionType()
const {
5941 bool isProfitableToPromote() {
5942 Value *ValIdx = Transition->
getOperand(getTransitionOriginalValueIdx());
5943 unsigned Index = isa<ConstantInt>(ValIdx)
5944 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5946 Type *PromotedType = getTransitionType();
5963 uint64_t ScalarCost =
5965 uint64_t VectorCost = StoreExtractCombineCost;
5966 for (
const auto &Inst : InstsToBePromoted) {
5972 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5973 isa<ConstantFP>(Arg0);
5986 dbgs() <<
"Estimated cost of computation to be promoted:\nScalar: " 5987 << ScalarCost <<
"\nVector: " << VectorCost <<
'\n');
5988 return ScalarCost > VectorCost;
6005 if (
ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
6006 ExtractIdx = CstVal->getSExtValue();
6011 unsigned End = getTransitionType()->getVectorNumElements();
6017 for (
unsigned Idx = 0; Idx != End; ++Idx) {
6018 if (Idx == ExtractIdx)
6029 unsigned OperandIdx) {
6032 if (OperandIdx != 1)
6037 case Instruction::SDiv:
6038 case Instruction::UDiv:
6039 case Instruction::SRem:
6040 case Instruction::URem:
6042 case Instruction::FDiv:
6043 case Instruction::FRem:
6052 unsigned CombineCost)
6053 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
6054 StoreExtractCombineCost(CombineCost) {
6055 assert(Transition &&
"Do not know how to promote null");
6059 bool canPromote(
const Instruction *ToBePromoted)
const {
6061 return isa<BinaryOperator>(ToBePromoted);
6069 for (
const Use &U : ToBePromoted->
operands()) {
6070 const Value *Val = U.get();
6071 if (Val == getEndOfTransition()) {
6075 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6079 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6080 !isa<ConstantFP>(Val))
6089 ISDOpcode, TLI.
getValueType(DL, getTransitionType(),
true));
6098 void enqueueForPromotion(
Instruction *ToBePromoted) {
6099 InstsToBePromoted.
push_back(ToBePromoted);
6103 void recordCombineInstruction(
Instruction *ToBeCombined) {
6105 CombineInst = ToBeCombined;
6115 if (InstsToBePromoted.
empty() || !CombineInst)
6123 for (
auto &ToBePromoted : InstsToBePromoted)
6124 promoteImpl(ToBePromoted);
6125 InstsToBePromoted.clear();
6132 void VectorPromoteHelper::promoteImpl(
Instruction *ToBePromoted) {
6142 "The type of the result of the transition does not match " 6147 Type *TransitionTy = getTransitionType();
6153 Value *Val = U.get();
6154 Value *NewVal =
nullptr;
6155 if (Val == Transition)
6156 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6157 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6158 isa<ConstantFP>(Val)) {
6161 cast<Constant>(Val),
6162 isa<UndefValue>(Val) ||
6163 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6167 ToBePromoted->
setOperand(U.getOperandNo(), NewVal);
6169 Transition->moveAfter(ToBePromoted);
6170 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6176 bool CodeGenPrepare::optimizeExtractElementInst(
Instruction *Inst) {
6192 LLVM_DEBUG(
dbgs() <<
"Found an interesting transition: " << *Inst <<
'\n');
6193 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
6200 if (ToBePromoted->
getParent() != Parent) {
6201 LLVM_DEBUG(
dbgs() <<
"Instruction to promote is in a different block (" 6203 <<
") than the transition (" << Parent->
getName()
6208 if (VPH.canCombine(ToBePromoted)) {
6210 <<
"will be combined with: " << *ToBePromoted <<
'\n');
6211 VPH.recordCombineInstruction(ToBePromoted);
6212 bool Changed = VPH.promote();
6213 NumStoreExtractExposed += Changed;
6218 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6221 LLVM_DEBUG(
dbgs() <<
"Promoting is possible... Enqueue for promotion!\n");
6223 VPH.enqueueForPromotion(ToBePromoted);
6224 Inst = ToBePromoted;
6283 Value *LValue, *HValue;
6314 if (LBC && LBC->getParent() != SI.
getParent())
6315 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6316 if (HBC && HBC->getParent() != SI.
getParent())
6317 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6320 auto CreateSplitStore = [&](
Value *V,
bool Upper) {
6321 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6322 Value *Addr = Builder.CreateBitCast(
6326 Addr = Builder.CreateGEP(
6327 SplitStoreType, Addr,
6329 Builder.CreateAlignedStore(
6333 CreateSplitStore(LValue,
false);
6334 CreateSplitStore(HValue,
true);
6424 if (!isa<Instruction>(GEPIOp))
6426 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6427 if (GEPIOpI->getParent() != SrcBlock)
6432 if (
auto *I = dyn_cast<Instruction>(Usr)) {
6438 }) == GEPI->
users().end())
6441 std::vector<GetElementPtrInst *> UGEPIs;
6445 if (Usr == GEPI)
continue;
6447 if (!isa<Instruction>(Usr))
6449 auto *UI = cast<Instruction>(Usr);
6451 if (UI->getParent() == SrcBlock)
6454 if (!isa<GetElementPtrInst>(Usr))
6456 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6462 if (UGEPI->getOperand(0) != GEPIOp)
6465 cast<ConstantInt>(UGEPI->getOperand(1))->
getType())
6467 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6471 UGEPIs.push_back(UGEPI);
6473 if (UGEPIs.size() == 0)
6477 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6485 UGEPI->setOperand(0, GEPI);
6486 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6494 UGEPI->setIsInBounds(
false);
6500 return cast<Instruction>(Usr)->
getParent() != SrcBlock;
6501 }) == GEPIOp->
users().end() &&
"GEPIOp is used outside SrcBlock");
6505 bool CodeGenPrepare::optimizeInst(
Instruction *I,
bool &ModifiedDT) {
6508 if (InsertedInsts.count(I))
6511 if (
PHINode *
P = dyn_cast<PHINode>(I)) {
6516 P->replaceAllUsesWith(V);
6517 P->eraseFromParent();
6524 if (
CastInst *CI = dyn_cast<CastInst>(I)) {
6537 if (isa<ZExtInst>(I) || isa<SExtInst>(
I)) {
6546 bool MadeChange = optimizeExt(I);
6547 return MadeChange | optimizeExtUses(I);
6553 if (
CmpInst *CI = dyn_cast<CmpInst>(I))
6557 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
6560 bool Modified = optimizeLoadExt(LI);
6568 if (
StoreInst *SI = dyn_cast<StoreInst>(I)) {
6573 unsigned AS = SI->getPointerAddressSpace();
6574 return optimizeMemoryInst(I, SI->
getOperand(1),
6581 unsigned AS = RMW->getPointerAddressSpace();
6582 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6587 unsigned AS = CmpX->getPointerAddressSpace();
6588 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6589 CmpX->getCompareOperand()->
getType(),
AS);
6594 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6598 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6599 BinOp->getOpcode() == Instruction::LShr)) {
6608 if (GEPI->hasAllZeroIndices()) {
6611 GEPI->getName(), GEPI);
6613 GEPI->replaceAllUsesWith(NC);
6614 GEPI->eraseFromParent();
6616 optimizeInst(NC, ModifiedDT);
6625 if (
CallInst *CI = dyn_cast<CallInst>(I))
6626 return optimizeCallInst(CI, ModifiedDT);
6628 if (
SelectInst *SI = dyn_cast<SelectInst>(I))
6629 return optimizeSelectInst(SI);
6632 return optimizeShuffleVectorInst(SVI);
6634 if (
auto *Switch = dyn_cast<SwitchInst>(I))
6635 return optimizeSwitchInst(Switch);
6637 if (isa<ExtractElementInst>(I))
6638 return optimizeExtractElementInst(I);
6664 bool CodeGenPrepare::optimizeBlock(
BasicBlock &BB,
bool &ModifiedDT) {
6666 bool MadeChange =
false;
6668 CurInstIterator = BB.
begin();
6669 while (CurInstIterator != BB.
end()) {
6670 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
6675 bool MadeBitReverse =
true;
6676 while (TLI && MadeBitReverse) {
6677 MadeBitReverse =
false;
6680 MadeBitReverse = MadeChange =
true;
6686 MadeChange |= dupRetToEnableTailCallOpts(&BB);
6694 bool CodeGenPrepare::placeDbgValues(
Function &F) {
6695 bool MadeChange =
false;
6707 PrevNonDbgInst = Insn;
6712 if (VI && VI != PrevNonDbgInst && !VI->
isTerminator()) {
6718 << *DVI <<
' ' << *VI);
6720 if (isa<PHINode>(VI))
6734 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
6736 NewTrue = NewTrue / Scale;
6737 NewFalse = NewFalse / Scale;
6762 bool CodeGenPrepare::splitBranchCondition(
Function &F) {
6766 bool MadeChange =
false;
6767 for (
auto &BB : F) {
6783 Value *Cond1, *Cond2;
6786 Opc = Instruction::And;
6789 Opc = Instruction::Or;
6806 Br1->setCondition(Cond1);
6811 if (Opc == Instruction::And)
6812 Br1->setSuccessor(0, TmpBB);
6814 Br1->setSuccessor(1, TmpBB);
6817 auto *Br2 =
IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
6818 if (
auto *I = dyn_cast<Instruction>(Cond2)) {
6832 if (Opc == Instruction::Or)
6838 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
6839 PN.setIncomingBlock(i, TmpBB);
6844 auto *Val = PN.getIncomingValueForBlock(&BB);
6845 PN.addIncoming(Val, TmpBB);
6850 if (Opc == Instruction::Or) {
6870 uint64_t TrueWeight, FalseWeight;
6871 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
6872 uint64_t NewTrueWeight = TrueWeight;
6873 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6876 .createBranchWeights(TrueWeight, FalseWeight));
6878 NewTrueWeight = TrueWeight;
6879 NewFalseWeight = 2 * FalseWeight;
6882 .createBranchWeights(TrueWeight, FalseWeight));
6903 uint64_t TrueWeight, FalseWeight;
6904 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
6905 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6906 uint64_t NewFalseWeight = FalseWeight;
6909 .createBranchWeights(TrueWeight, FalseWeight));
6911 NewTrueWeight = 2 * TrueWeight;
6912 NewFalseWeight = FalseWeight;
6915 .createBranchWeights(TrueWeight, FalseWeight));
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
const Function & getFunction() const
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP)
Return a value (possibly void), from a function.
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static MVT getIntegerVT(unsigned BitWidth)
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
Value * getPointerOperand()
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
unsigned getAddrMode(MCInstrInfo const &MCII, MCInst const &MCI)
static Constant * getConstantVector(MVT VT, const APInt &SplatValue, unsigned SplatBitSize, LLVMContext &C)
iterator_range< use_iterator > uses()
bool MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemoryDependenceResults *MemDep=nullptr, DeferredDominance *DDT=nullptr)
Attempts to merge a block into its predecessor, if possible.
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
virtual bool isCheapAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g.
static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI)
Sink the given CmpInst into user blocks to reduce the number of virtual registers that must be create...
void addIncoming(Value *V, BasicBlock *BB)
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...
APInt sext(unsigned width) const
Sign extend to a new width.
static bool isPromotedInstructionLegal(const TargetLowering &TLI, const DataLayout &DL, Value *Val)
Check whether or not Val is a legal instruction for TLI.
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
static cl::opt< bool > ForceSplitStore("force-split-store", cl::Hidden, cl::init(false), cl::desc("Force store splitting no matter what the target query says."))
static Value * getTrueOrFalseValue(SelectInst *SI, bool isTrue, const SmallPtrSet< const Instruction *, 2 > &Selects)
If isTrue is true, return the true value of SI, otherwise return false value of SI.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
LLVM_NODISCARD T pop_back_val()
Compute iterated dominance frontiers using a linear time algorithm.
BinaryOps getOpcode() const
static bool MightBeFoldableInst(Instruction *I)
This is a little filter, which returns true if an addressing computation involving I might be folded ...
size_type size() const
Determine the number of elements in the SetVector.
static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V)
Check if V (an operand of a select instruction) is an expensive instruction that is only used once...
Value * optimizeCall(CallInst *CI)
Take the given call instruction and return a more optimal value to replace the instruction with or 0 ...
A Module instance is used to store all the information related to an LLVM module. ...
virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const
Return if the target supports combining a chain like:
void setAlignment(unsigned Align)
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
This class represents zero extension of integer types.
static cl::opt< bool > EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden, cl::init(true), cl::desc("Enable splitting large offset of GEP."))
Analysis providing profile information.
APInt zext(unsigned width) const
Zero extend to a new width.
This class represents a function call, abstracting a target machine's calling convention.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Value * getCondition() const
const Value * getTrueValue() const
The two locations do not alias at all.
static cl::opt< bool > EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden, cl::desc("Enable merging of redundant sexts when one is dominating" " the other."), cl::init(true))
virtual bool isSelectSupported(SelectSupportKind) const
bool salvageDebugInfo(Instruction &I)
Assuming the instruction I is going to be deleted, attempt to salvage debug users of I by writing the...
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
static cl::opt< bool > AddrSinkCombineBaseOffs("addr-sink-combine-base-offs", cl::Hidden, cl::init(true), cl::desc("Allow combining of BaseOffs field in Address sinking."))
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.
bool isTerminator() const
void setSectionPrefix(StringRef Prefix)
Set the section prefix for this function.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
static void dump(StringRef Title, SpillInfo const &Spills)
BasicBlock * getSuccessor(unsigned i) const
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, ImmutableCallSite CS) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
bool isInteger() const
Return true if this is an integer or a vector integer type.
static CallInst * Create(Value *Func, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static cl::opt< bool > StressExtLdPromotion("stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " "optimization in CodeGenPrepare"))
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool hasMultipleConditionRegisters() const
Return true if multiple condition registers are available.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
An instruction for reading from memory.
bool hasExtractBitsInsn() const
Return true if the target has BitExtract instructions.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
bool isVectorTy() const
True if this is an instance of VectorType.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
This defines the Use class.
void reserve(size_type N)
Value * CallOperandVal
If this is the result output operand or a clobber, this is null, otherwise it is the incoming operand...
void setAlignment(unsigned Align)
bool isOperationLegalOrCustom(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
LLVMContext & getContext() const
Get the context in which this basic block lives.
unsigned getBitWidth() const
getBitWidth - Return the bitwidth of this constant.
static bool despeculateCountZeros(IntrinsicInst *CountZeros, const TargetLowering *TLI, const DataLayout *DL, bool &ModifiedDT)
If counting leading or trailing zeros is an expensive operation and a zero input is defined...
unsigned getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static cl::opt< unsigned > FreqRatioToSkipMerge("cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), cl::desc("Skip merging empty blocks if (frequency of empty block) / " "(frequency of destination block) is greater than this ratio"))
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
MVT getRegisterType(MVT VT) const
Return the type of registers that this ValueType will eventually require.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
void dump() const
Support for debugging, callable in GDB: V->dump()
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)
bool isFunctionHotInCallGraph(const Function *F, BlockFrequencyInfo &BFI)
Returns true if F contains hot code.
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
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.
'undef' values are things that do not have specified contents.
bool bypassSlowDivision(BasicBlock *BB, const DenseMap< unsigned int, unsigned int > &BypassWidth)
This optimization identifies DIV instructions in a BB that can be profitably bypassed and carried out...
static cl::opt< bool > AddrSinkUsingGEPs("addr-sink-using-gep", cl::Hidden, cl::init(true), cl::desc("Address sinking in CGP using GEPs."))
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
TargetLowering::ConstraintType ConstraintType
Information about the constraint code, e.g.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
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...
static cl::opt< bool > DisableBranchOpts("disable-cgp-branch-opts", cl::Hidden, cl::init(false), cl::desc("Disable branch optimizations in CodeGenPrepare"))
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
This file contains the simple types necessary to represent the attributes associated with functions a...
virtual bool isVectorShiftByScalarCheap(Type *Ty) const
Return true if it's significantly cheaper to shift a vector by a uniform scalar than by an amount whi...
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const
Return true if it is cheaper to split the store of a merged int val from a pair of smaller values int...
bool remove(const value_type &X)
Remove an item from the set vector.
Position
Position to insert a new instruction relative to an existing instruction.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
This file implements a class to represent arbitrary precision integral constant values and operations...
static cl::opt< bool > DisableStoreExtract("disable-cgp-store-extract", cl::Hidden, cl::init(false), cl::desc("Disable store(extract) optimizations in CodeGenPrepare"))
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
static cl::opt< bool > DisablePreheaderProtect("disable-preheader-prot", cl::Hidden, cl::init(false), cl::desc("Disable protection against removing loop preheaders"))
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...
unsigned getSizeInBits() const
static bool shouldPromote(Value *V)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
unsigned getActiveBits() const
Compute the number of active bits in the value.
static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, const DataLayout &DL)
If the specified cast instruction is a noop copy (e.g.
OtherOps getOpcode() const
Get the opcode casted to the right type.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
A constant value that is initialized with an expression using other constant values.
unsigned getSizeInBits() const
Return the size of the specified value type in bits.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
static cl::opt< bool > AddrSinkCombineBaseReg("addr-sink-combine-base-reg", cl::Hidden, cl::init(true), cl::desc("Allow combining of BaseReg field in Address sinking."))
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, SmallVectorImpl< Value *> &OffsetV)
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
This contains information for each constraint that we are lowering.
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
iterator begin()
Get an iterator to the beginning of the SetVector.
virtual bool isCheapToSpeculateCtlz() const
Return true if it is cheap to speculate a call to intrinsic ctlz.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
This class represents a no-op cast from one type to another.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
static CmpInst * Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, const Twine &Name="", Instruction *InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
const APInt & getValue() const
Return the constant as an APInt value reference.
bool isLittleEndian() const
Layout endianness...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static bool hasSameExtUse(Value *Val, const TargetLowering &TLI)
Check if all the uses of Val are equivalent (or free) zero or sign extensions.
An instruction for storing to memory.
static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO, unsigned CombineOpc, unsigned ZeroReg=0, bool CheckZeroReg=false)
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
virtual bool isCheapToSpeculateCttz() const
Return true if it is cheap to speculate a call to intrinsic cttz.
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace, Instruction *I=nullptr) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
ConstraintPrefix Type
Type - The basic type of the constraint: input/output/clobber.
bool pointsToAliveValue() const
Optimize for code generation
void takeName(Value *V)
Transfer the name from V to this value.
This class implements simplifications for calls to fortified library functions (__st*cpy_chk, __memcpy_chk, __memmove_chk, __memset_chk), to, when possible, replace them with their non-checking counterparts.
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.
This class represents a truncation of integer types.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
static cl::opt< bool > AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false), cl::desc("Allow creation of Phis in Address sinking."))
static cl::opt< bool > AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true), cl::desc("Allow creation of selects in Address sinking."))
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Class to represent pointers.
Interval::succ_iterator succ_end(Interval *I)
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
bool isJumpExpensive() const
Return true if Flow Control is an expensive operation that should be avoided.
unsigned getAddressSpace() const
Returns the address space of this instruction's pointer type.
static cl::opt< bool > StressStoreExtract("stress-cgp-store-extract", cl::Hidden, cl::init(false), cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"))
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
iterator find(const_arg_type_t< KeyT > Val)
Value * getOperand(unsigned i_nocapture) const
static bool isExtractBitsCandidateUse(Instruction *User)
Check if the candidates could be combined with a shift instruction, which includes: ...
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI)
static bool simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, const SmallVectorImpl< GCRelocateInst *> &Targets)
virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const
Return true if the target can combine store(extractelement VectorTy, Idx).
const Instruction * getStatepoint() const
The statepoint with which this gc.relocate is associated.
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
OneUse_match< T > m_OneUse(const T &SubPattern)
static bool runOnFunction(Function &F, bool PostInlining)
static unsigned getPointerOperandIndex()
initializer< Ty > init(const Ty &Val)
std::vector< AsmOperandInfo > AsmOperandInfoVector
static cl::opt< bool > DisableExtLdPromotion("disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " "CodeGenPrepare"))
bool isAllOnesValue() const
Determine if all bits are set.
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
bool canIncreaseAlignment() const
static bool isBroadcastShuffle(ShuffleVectorInst *SVI)
static bool CombineUAddWithOverflow(CmpInst *CI)
Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if possible.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static bool FindAllMemoryUses(Instruction *I, SmallVectorImpl< std::pair< Instruction *, unsigned >> &MemoryUses, SmallPtrSetImpl< Instruction *> &ConsideredInsts, const TargetLowering &TLI, const TargetRegisterInfo &TRI, int SeenInsts=0)
Recursively walk all the uses of I until we find a memory use.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
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.
PointerIntPair - This class implements a pair of a pointer and small integer.
The instances of the Type class are immutable: once they are created, they are never changed...
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
static unsigned getPointerOperandIndex()
This is an important class for using LLVM in a threaded context.
Conditional or Unconditional Branch instruction.
bool isIndirect
isIndirect - True if this operand is an indirect operand.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
bool isRound() const
Return true if the size is a power-of-two number of bytes.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
const Instruction & front() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool isMask(unsigned numBits) const
static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, const TargetLowering *TLI, SelectInst *SI)
Returns true if a SelectInst should be turned into an explicit branch.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
bool isUsedInBasicBlock(const BasicBlock *BB) const
Check if this value is used in the specified basic block.
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
Represent the analysis usage information of a pass.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
bool optForSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
unsigned getLargestLegalIntTypeSizeInBits() const
Returns the size of largest legal integer type size, or 0 if none are set.
static bool SinkCast(CastInst *CI)
SinkCast - Sink the specified cast instruction into its user blocks.
static cl::opt< bool > AddrSinkCombineScaledReg("addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true), cl::desc("Allow combining of ScaledReg field in Address sinking."))
FunctionPass class - This class is used to implement most global optimizations.
void setArgOperand(unsigned i, Value *v)
Interval::pred_iterator pred_end(Interval *I)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
const Function * getFunction() const
Return the function this instruction belongs to.
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DeferredDominance *DDT=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
const Value * getCondition() const
static cl::opt< bool > DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), cl::desc("Disable GC optimizations in CodeGenPrepare"))
unsigned getBasePtrIndex() const
The index into the associate statepoint's argument list which contains the base pointer of the pointe...
Type * getIndexedType() const
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
iterator erase(const_iterator CI)
iterator_range< User::op_iterator > arg_operands()
Iteration adapter for range-for loops.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
bool isExtFree(const Instruction *I) const
Return true if the extension represented by I is free.
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.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
void sort(IteratorTy Start, IteratorTy End)
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE, "Optimize for code generation", false, false) INITIALIZE_PASS_END(CodeGenPrepare
void initializeCodeGenPreparePass(PassRegistry &)
A SetVector that performs no allocations if smaller than a certain size.
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
StructType * getStructTypeOrNull() const
unsigned getNumOperands() const
static bool IsNonLocalValue(Value *V, BasicBlock *BB)
Return true if the specified values are defined in a different basic block than BB.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
unsigned countPopulation(T Value)
Count the number of set bits in a value.
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
This is the shared class of boolean and integer constants.
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, unsigned Align=1, bool *=nullptr) const
Determine if the target supports unaligned memory accesses.
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
static void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
Provides information about what library functions are available for the current target.
virtual bool shouldConsiderGEPOffsetSplit() const
static BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static cl::opt< bool > DisableSelectToBranch("disable-cgp-select2branch", cl::Hidden, cl::init(false), cl::desc("Disable select to branch conversion."))
bool isFunctionColdInCallGraph(const Function *F, BlockFrequencyInfo &BFI)
Returns true if F contains only cold code.
LLVM_NODISCARD T pop_back_val()
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, const TargetTransformInfo *TTI)
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.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
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...
pred_range predecessors(BasicBlock *BB)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Value handle that asserts if the Value is deleted.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool enableExtLdPromotion() const
Return true if the target wants to use the optimization that turns ext(promotableInst1(...(promotableInstN(load)))) into promotedInst1(...(promotedInstN(ext(load)))).
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
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...
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
Class for arbitrary precision integers.
static cl::opt< bool > AddrSinkCombineBaseGV("addr-sink-combine-base-gv", cl::Hidden, cl::init(true), cl::desc("Allow combining of BaseGV field in Address sinking."))
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
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.
typename SuperClass::iterator iterator
iterator_range< user_iterator > users()
InstListType::iterator iterator
Instruction iterators...
AddrMode
ARM Addressing Modes.
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
const Value * getFalseValue() const
int InstructionOpcodeToISD(unsigned Opcode) const
Get the ISD node that corresponds to the Instruction class opcode.
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
FunctionPass * createCodeGenPreparePass()
createCodeGenPreparePass - Transform the code to expose more pattern matching during instruction sele...
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
amdgpu Simplify well known AMD library false Value Value * Arg
bool isSequential() const
TargetSubtargetInfo - Generic base class for all target subtargets.
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
virtual bool useSoftFloat() const
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 ...
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
Predicate getPredicate() const
Return the predicate for this instruction.
This class wraps the llvm.memcpy/memmove intrinsics.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Analysis providing branch probability information.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
uint64_t getElementOffset(unsigned Idx) const
void emplace_back(ArgTypes &&... Args)
SelectSupportKind
Enum that describes what type of support for selects the target has.
static IntegerType * getInt32Ty(LLVMContext &C)
void setCondition(Value *V)
unsigned getIntegerBitWidth() const
LLVM_NODISCARD bool empty() const
bool SplitIndirectBrCriticalEdges(Function &F, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr)
This represents the llvm.dbg.value instruction.
Represents a single loop in the control flow graph.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
StringRef getName() const
Return a constant reference to the value's name.
Establish a view to a call site for examination.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
const Function * getParent() const
Return the enclosing method, or null if none.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
unsigned pred_size(const BasicBlock *BB)
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
bool empty() const
Determine if the SetVector is empty or not.
user_iterator_impl< User > user_iterator
Type * getResultElementType() const
static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, const TargetLowering &TLI, const DataLayout &DL)
Sink the shift right instruction into user blocks if the uses could potentially be combined with this...
unsigned getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, const TargetLowering &TLI)
For the instruction sequence of store below, F and I values are bundled together as an i64 value befo...
static unsigned getPointerOperandIndex()
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
bool isUnconditional() const
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
static EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
LLVM_NODISCARD bool empty() const
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
bool isStatepoint(ImmutableCallSite CS)
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse)
Scale down both weights to fit into uint32_t.
void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
user_iterator user_begin()
bool hasHugeWorkingSetSize()
Returns true if the working set size of the code is considered huge.
void DeleteDeadBlock(BasicBlock *BB, DeferredDominance *DDT=nullptr)
Delete the specified block, which must have no predecessors.
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 ...
Represents calls to the gc.relocate intrinsic.
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...
static cl::opt< bool > DisableComplexAddrModes("disable-complex-addr-modes", cl::Hidden, cl::init(false), cl::desc("Disables combining addressing modes with different parts " "in optimizeMemoryInst."))
LLVM Value Representation.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
static cl::opt< bool > EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(true), cl::desc("Enable sinkinig and/cmp into branches."))
static constexpr int MaxMemoryUsesToScan
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.
static const Function * getParent(const Value *V)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
const Value * getCalledValue() const
Get a pointer to the function that is invoked by this instruction.
This class implements an extremely fast bulk output stream that can only output to a stream...
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const
Return true if the specified load with extension is legal on this target.
Primary interface to the complete machine description for the target machine.
static cl::opt< bool > ProfileGuidedSectionPrefix("profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore, cl::desc("Use profile info to add section prefix for hot/cold functions"))
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
The legacy pass manager's analysis pass to compute loop information.
bool hasNoNaNs() const
Determine whether the no-NaNs flag is set.
bool hasOneUse() const
Return true if there is exactly one user of this value.
StringRef - Represent a constant reference to a string, i.e.
AttributeList getAttributes() const
Get the parameter attributes of the call.
bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction *> &InsertedInsts)
Try to match a bswap or bitreverse idiom.
static bool makeBitReverse(Instruction &I, const DataLayout &DL, const TargetLowering &TLI)
Given an OR instruction, check to see if this is a bitreverse idiom.
specific_intval m_SpecificInt(uint64_t V)
Match a specific integer value or vector with all elements equal to the value.
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
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...
virtual BranchProbability getPredictableBranchThreshold() const
If a branch or a select condition is skewed in one direction by more than this factor, it is very likely to be predicted correctly.
bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr)
Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
bool attributesPermitTailCall(const Function *F, const Instruction *I, const ReturnInst *Ret, const TargetLoweringBase &TLI, bool *AllowDifferingSizes=nullptr)
Test if given that the input instruction is in the tail call position, if there is an attribute misma...
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
VectorType * getType() const
Overload to return most specific vector type.
EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
base_list_type::reverse_iterator reverse_iterator
static Constant * get(ArrayRef< Constant *> V)
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Type * getElementType() const
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
static void computeBaseDerivedRelocateMap(const SmallVectorImpl< GCRelocateInst *> &AllRelocateCalls, DenseMap< GCRelocateInst *, SmallVector< GCRelocateInst *, 2 >> &RelocateInstMap)
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
A wrapper class for inspecting calls to intrinsic functions.
This file describes how to lower LLVM code to machine code.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
static bool sinkAndCmp0Expression(Instruction *AndI, const TargetLowering &TLI, SetOfInstrs &InsertedInsts)
Duplicate and sink the given 'and' instruction into user blocks where it is used in a compare to allo...
gep_type_iterator gep_type_begin(const User *GEP)
static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, const TargetLowering &TLI, const TargetRegisterInfo &TRI)
Check to see if all uses of OpVal by the specified inline asm call are due to memory operands...
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
bool isExtLoad(const LoadInst *Load, const Instruction *Ext, const DataLayout &DL) const
Return true if Load and Ext can form an ExtLoad.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
static bool SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, DenseMap< BasicBlock *, BinaryOperator *> &InsertedShifts, const TargetLowering &TLI, const DataLayout &DL)
Sink both shift and truncate instruction to the use of truncate's BB.