80 #define DEBUG_TYPE "licm" 82 STATISTIC(NumCreatedBlocks,
"Number of blocks created");
83 STATISTIC(NumClonedBranches,
"Number of branches cloned");
84 STATISTIC(NumSunk,
"Number of instructions sunk out of loop");
85 STATISTIC(NumHoisted,
"Number of instructions hoisted out of loop");
86 STATISTIC(NumMovedLoads,
"Number of load insts hoisted or sunk");
87 STATISTIC(NumMovedCalls,
"Number of call insts hoisted or sunk");
88 STATISTIC(NumPromoted,
"Number of memory locations promoted to registers");
93 cl::desc(
"Disable memory promotion in LICM pass"));
97 cl::desc(
"Enable control flow (and PHI) hoisting in LICM"));
101 cl::desc(
"Max num uses visited for identifying load " 102 "invariance in loop using invariant start (default = 8)"));
109 cl::desc(
"How many instruction to cross product using AA"));
122 cl::desc(
"Enable imprecision in LICM in pathological cases, in exchange " 123 "for faster compile. Caps the MemorySSA clobbering calls."));
130 cl::desc(
"[LICM & MemorySSA] When MSSA in LICM is disabled, this has no " 131 "effect. When MSSA in LICM is enabled, then this is the maximum " 132 "number of accesses allowed to be present in a loop in order to " 133 "enable memory promotion."));
170 struct LoopInvariantCodeMotion {
177 ASTrackerMapTy &getLoopToAliasSetMap() {
return LoopToAliasSetMap; }
178 LoopInvariantCodeMotion(
unsigned LicmMssaOptCap,
179 unsigned LicmMssaNoAccForPromotionCap)
180 : LicmMssaOptCap(LicmMssaOptCap),
181 LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap) {}
184 ASTrackerMapTy LoopToAliasSetMap;
185 unsigned LicmMssaOptCap;
186 unsigned LicmMssaNoAccForPromotionCap;
188 std::unique_ptr<AliasSetTracker>
190 std::unique_ptr<AliasSetTracker>
195 struct LegacyLICMPass :
public LoopPass {
200 :
LoopPass(ID),
LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap) {
209 LICM.getLoopToAliasSetMap().clear();
213 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
215 ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA())
221 return LICM.runOnLoop(L,
222 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
223 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
224 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
225 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
227 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
229 SE ? &SE->getSE() :
nullptr, MSSA, &ORE,
false);
249 bool doFinalization()
override {
250 auto &AliasSetMap =
LICM.getLoopToAliasSetMap();
256 return !KV.first->getParentLoop();
258 "Didn't free loop alias sets");
264 LoopInvariantCodeMotion
LICM;
272 void deleteAnalysisValue(
Value *V,
Loop *L)
override;
275 void deleteAnalysisLoop(
Loop *L)
override;
283 Function *
F = L.getHeader()->getParent();
289 "cached at a higher level");
291 LoopInvariantCodeMotion
LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap);
292 if (!LICM.runOnLoop(&L, &AR.
AA, &AR.
LI, &AR.
DT, &AR.
TLI, &AR.
TTI, &AR.
SE,
318 unsigned LicmMssaNoAccForPromotionCap) {
319 return new LegacyLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap);
328 bool LoopInvariantCodeMotion::runOnLoop(
332 bool Changed =
false;
342 std::unique_ptr<AliasSetTracker> CurAST;
343 std::unique_ptr<MemorySSAUpdater> MSSAU;
344 bool NoOfMemAccTooLarge =
false;
345 unsigned LicmMssaOptCounter = 0;
349 CurAST = collectAliasInfoForLoop(L, LI, AA);
352 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
354 unsigned AccessCapCount = 0;
357 for (
const auto &MA : *Accesses) {
360 if (AccessCapCount > LicmMssaNoAccForPromotionCap) {
361 NoOfMemAccTooLarge =
true;
366 if (NoOfMemAccTooLarge)
388 LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
392 CurAST.get(), MSSAU.get(), &SafetyInfo, Flags, ORE);
393 Flags.IsSink =
false;
397 CurAST.get(), MSSAU.get(), SE, &SafetyInfo, Flags, ORE);
407 !NoOfMemAccTooLarge) {
417 if (!HasCatchSwitch) {
424 InsertPts.
push_back(&*ExitBlock->getFirstInsertionPt());
431 bool Promoted =
false;
435 CurAST = collectAliasInfoForLoopWithMSSA(L, AA, MSSAU.get());
442 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
448 "Must alias set should have at least one pointer element in it!");
451 for (
const auto &ASI : AS)
452 PointerMustAliases.
insert(ASI.getValue());
455 PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC, LI,
456 DT, TLI, L, CurAST.get(), MSSAU.get(), &SafetyInfo, ORE);
477 "Parent loop not left in LCSSA form after LICM!");
481 if (!MSSAU.get() && CurAST.get() && L->
getParentLoop() && !DeleteAST)
482 LoopToAliasSetMap[L] = std::move(CurAST);
485 MSSAU->getMemorySSA()->verifyMemorySSA();
506 assert(N !=
nullptr && AA !=
nullptr && LI !=
nullptr && DT !=
nullptr &&
507 CurLoop !=
nullptr && SafetyInfo !=
nullptr &&
508 "Unexpected input to sinkRegion.");
509 assert(((CurAST !=
nullptr) ^ (MSSAU !=
nullptr)) &&
510 "Either AliasSetTracker or MemorySSA should be initialized.");
517 bool Changed =
false;
544 bool FreeInLoop =
false;
549 if (
sink(I, LI, DT, CurLoop, SafetyInfo, MSSAU, ORE)) {
572 class ControlFlowHoister {
591 : LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {}
593 void registerPossiblyHoistableBranch(
BranchInst *BI) {
605 TrueDest == FalseDest)
617 if (TrueDestSucc.
count(FalseDest)) {
618 CommonSucc = FalseDest;
619 }
else if (FalseDestSucc.
count(TrueDest)) {
620 CommonSucc = TrueDest;
624 if (TrueDestSucc.
size() == 1)
625 CommonSucc = *TrueDestSucc.
begin();
629 else if (!TrueDestSucc.
empty()) {
633 assert(It != F->
end() &&
"Could not find successor in function");
645 if (CommonSucc && DT->
dominates(BI, CommonSucc))
646 HoistableBranches[BI] = CommonSucc;
649 bool canHoistPHI(
PHINode *PN) {
658 PredecessorBlocks.
insert(PredBB);
666 for (
auto &Pair : HoistableBranches) {
667 if (Pair.second == BB) {
670 if (Pair.first->getSuccessor(0) == BB) {
671 PredecessorBlocks.
erase(Pair.first->getParent());
672 PredecessorBlocks.
erase(Pair.first->getSuccessor(1));
673 }
else if (Pair.first->getSuccessor(1) == BB) {
674 PredecessorBlocks.
erase(Pair.first->getParent());
675 PredecessorBlocks.
erase(Pair.first->getSuccessor(0));
677 PredecessorBlocks.
erase(Pair.first->getSuccessor(0));
678 PredecessorBlocks.
erase(Pair.first->getSuccessor(1));
684 return PredecessorBlocks.
empty();
691 if (HoistDestinationMap.
count(BB))
692 return HoistDestinationMap[BB];
695 auto HasBBAsSuccessor =
697 return BB != Pair.second && (Pair.first->getSuccessor(0) == BB ||
698 Pair.first->getSuccessor(1) == BB);
705 if (It == HoistableBranches.
end()) {
707 <<
" as hoist destination for " << BB->
getName()
709 HoistDestinationMap[BB] = InitialPreheader;
710 return InitialPreheader;
714 HoistableBranches.
end() &&
715 "BB is expected to be the target of at most one branch");
720 BasicBlock *CommonSucc = HoistableBranches[BI];
724 auto CreateHoistedBlock = [&](
BasicBlock *Orig) {
725 if (HoistDestinationMap.
count(Orig))
726 return HoistDestinationMap[Orig];
729 HoistDestinationMap[Orig] = New;
735 <<
" as hoist destination for " << Orig->getName()
739 BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest);
740 BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest);
741 BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc);
748 assert(TargetSucc &&
"Expected hoist target to have a single successor");
763 if (HoistTarget == InitialPreheader) {
765 InitialPreheader->replaceSuccessorsPhiUsesWith(HoistCommonSucc);
775 for (
auto &Pair : HoistDestinationMap)
776 if (Pair.second == InitialPreheader && Pair.first != BI->
getParent())
777 Pair.second = HoistCommonSucc;
787 "Hoisting blocks should not have destroyed preheader");
788 return HoistDestinationMap[BB];
805 assert(N !=
nullptr && AA !=
nullptr && LI !=
nullptr && DT !=
nullptr &&
806 CurLoop !=
nullptr && SafetyInfo !=
nullptr &&
807 "Unexpected input to hoistRegion.");
808 assert(((CurAST !=
nullptr) ^ (MSSAU !=
nullptr)) &&
809 "Either AliasSetTracker or MemorySSA should be initialized.");
811 ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU);
822 bool Changed =
false;
858 I, DT, CurLoop, SafetyInfo, ORE,
860 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
869 if (I.
getOpcode() == Instruction::FDiv &&
874 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
877 ReciprocalDivisor->insertBefore(&I);
880 BinaryOperator::CreateFMul(I.
getOperand(0), ReciprocalDivisor);
883 Product->insertAfter(&I);
887 hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB),
888 SafetyInfo, MSSAU, SE, ORE);
889 HoistedInstructions.
push_back(ReciprocalDivisor);
897 match(&I, m_Intrinsic<Intrinsic::invariant_start>());
899 auto MustExecuteWithoutWritesBefore = [&](
Instruction &
I) {
903 if ((IsInvariantStart(I) ||
isGuard(&I)) &&
905 MustExecuteWithoutWritesBefore(I)) {
906 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
913 if (
PHINode *PN = dyn_cast<PHINode>(&I)) {
914 if (CFH.canHoistPHI(PN)) {
917 for (
unsigned int i = 0; i < PN->getNumIncomingValues(); ++i)
918 PN->setIncomingBlock(
919 i, CFH.getOrCreateHoistedBlock(PN->getIncomingBlock(i)));
920 hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
930 if (
BranchInst *BI = dyn_cast<BranchInst>(&I))
931 CFH.registerPossiblyHoistableBranch(BI);
952 "New hoist point expected to dominate old hoist point");
957 <<
": " << *
I <<
"\n");
969 #ifdef EXPENSIVE_CHECKS 972 "Dominator tree verification failed");
994 unsigned BitcastsVisited = 0;
997 while (Addr->
getType() != PtrInt8Ty) {
1002 Addr = BC->getOperand(0);
1005 unsigned UsesVisited = 0;
1008 for (
auto *U : Addr->
users()) {
1018 unsigned InvariantSizeInBits =
1019 cast<ConstantInt>(II->
getArgOperand(0))->getSExtValue() * 8;
1024 if (LocSizeInBits <= InvariantSizeInBits &&
1038 return (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
1039 isa<FenceInst>(I) || isa<CastInst>(I) ||
1040 isa<UnaryOperator>(I) || isa<BinaryOperator>(I) ||
1041 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
1042 isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
1043 isa<ShuffleVectorInst>(I) || isa<ExtractValueInst>(I) ||
1044 isa<InsertValueInst>(I));
1052 if (!AS.isForwardingAliasSet() && AS.isMod()) {
1071 for (
const auto &Acc : *Accs) {
1072 if (isa<MemoryPhi>(&Acc))
1074 const auto *MUD = cast<MemoryUseOrDef>(&Acc);
1075 if (MUD->getMemoryInst() != I || NotAPhi++ == 1)
1086 bool TargetExecutesOncePerLoop,
1090 if (!isHoistableAndSinkableInst(I))
1095 assert(Flags !=
nullptr &&
"Flags cannot be null.");
1098 if (
LoadInst *LI = dyn_cast<LoadInst>(&I)) {
1099 if (!LI->isUnordered())
1106 if (LI->hasMetadata(LLVMContext::MD_invariant_load))
1109 if (LI->isAtomic() && !TargetExecutesOncePerLoop)
1125 if (ORE && Invalidated && CurLoop->
isLoopInvariant(LI->getPointerOperand()))
1128 DEBUG_TYPE,
"LoadWithLoopInvariantAddressInvalidated", LI)
1129 <<
"failed to move load with loop-invariant address " 1130 "because the loop may invalidate its value";
1133 return !Invalidated;
1134 }
else if (
CallInst *CI = dyn_cast<CallInst>(&I)) {
1136 if (isa<DbgInfoIntrinsic>(I))
1144 if (
match(CI, m_Intrinsic<Intrinsic::assume>()))
1148 if (
match(CI, m_Intrinsic<Intrinsic::experimental_widenable_condition>()))
1162 for (
Value *
Op : CI->arg_operands())
1163 if (
Op->getType()->isPointerTy()) {
1168 CurAST, CurLoop, AA);
1181 if (isReadOnly(CurAST, MSSAU, CurLoop))
1189 }
else if (
auto *FI = dyn_cast<FenceInst>(&I)) {
1193 auto Begin = CurAST->
begin();
1194 assert(Begin != CurAST->
end() &&
"must contain FI");
1195 if (std::next(Begin) != CurAST->
end())
1198 auto *UniqueI = Begin->getUniqueInstruction();
1203 assert(UniqueI == FI &&
"AS must contain FI");
1206 return isOnlyMemoryAccess(FI, CurLoop, MSSAU);
1207 }
else if (
auto *
SI = dyn_cast<StoreInst>(&I)) {
1208 if (!
SI->isUnordered())
1219 if (AS.isRef() || !AS.isMustAlias())
1226 assert(UniqueI ==
SI &&
"AS must contain SI");
1229 if (isOnlyMemoryAccess(
SI, CurLoop, MSSAU))
1246 for (
const auto &MA : *Accesses)
1247 if (
const auto *MU = dyn_cast<MemoryUse>(&MA)) {
1258 }
else if (
const auto *MD = dyn_cast<MemoryDef>(&MA)) {
1259 if (
auto *LI = dyn_cast<LoadInst>(MD->getMemoryInst())) {
1261 assert(!LI->isUnordered() &&
"Expected unordered load");
1265 if (
auto *CI = dyn_cast<CallInst>(MD->getMemoryInst())) {
1315 for (
const User *U :
GEP->users()) {
1319 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
1340 if (
const PHINode *PN = dyn_cast<PHINode>(UI)) {
1348 if (isa<CallInst>(I))
1349 if (!BlockColors.empty() &&
1350 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
1369 if (
auto *CI = dyn_cast<CallInst>(&I)) {
1376 for (
unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
1377 BundleIdx != BundleEnd; ++BundleIdx) {
1385 if (!BlockColors.empty()) {
1386 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
1387 assert(CV.
size() == 1 &&
"non-unique color for exit block!");
1408 if (
auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))
1411 auto *MemUse = cast<MemoryUse>(NewMemAcc);
1426 if (
Instruction *OInst = dyn_cast<Instruction>(*OI))
1428 if (!OLoop->contains(&PN)) {
1431 OInst->getName() +
".lcssa", &ExitBlock.
front());
1471 "Expect only trivially replaceable PHI");
1474 auto It = SunkCopies.
find(ExitBlock);
1475 if (It != SunkCopies.
end())
1479 *I, *ExitBlock, *TPN, LI, SafetyInfo, MSSAU);
1513 assert(ExitBlockSet.count(ExitBB) &&
"Expect the PHI is in an exit block.");
1549 while (!PredBBs.
empty()) {
1552 "Expect all predecessors are in the loop");
1555 ExitBB, PredBB,
".split.loop.exit", DT, LI, MSSAU,
true);
1559 if (!BlockColors.empty())
1580 <<
"sinking " <<
ore::NV(
"Inst", &I);
1582 bool Changed =
false;
1583 if (isa<LoadInst>(I))
1585 else if (isa<CallInst>(I))
1593 auto *
User = cast<Instruction>(*UI);
1594 Use &U = UI.getUse();
1636 if (VisitedUsers.
empty())
1653 for (
auto *UI :
Users) {
1654 auto *
User = cast<Instruction>(UI);
1661 "The LCSSA PHI is not in an exit block!");
1664 PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU);
1697 if (isa<PHINode>(I))
1709 if (isa<LoadInst>(I))
1711 else if (isa<CallInst>(I))
1721 const Loop *CurLoop,
1728 bool GuaranteedToExecute =
1731 if (!GuaranteedToExecute) {
1736 DEBUG_TYPE,
"LoadWithLoopInvariantAddressCondExecuted", LI)
1737 <<
"failed to hoist load with loop-invariant address " 1738 "because load is conditionally executed";
1742 return GuaranteedToExecute;
1758 bool UnorderedAtomic;
1769 I->getName() +
".lcssa", &BB->
front());
1784 DebugLoc dl,
int alignment,
bool UnorderedAtomic,
1787 LoopExitBlocks(LEB), LoopInsertPts(LIP), MSSAInsertPts(MSSAIP),
1788 PredCache(PIC), AST(ast), MSSAU(MSSAU), LI(li), DL(std::move(dl)),
1789 Alignment(alignment), UnorderedAtomic(UnorderedAtomic), AATags(AATags),
1790 SafetyInfo(SafetyInfo) {}
1795 if (
LoadInst *LI = dyn_cast<LoadInst>(I))
1796 Ptr = LI->getOperand(0);
1799 return PointerMustAliases.
count(Ptr);
1802 void doExtraRewritesBeforeFinalDeletion()
override {
1807 for (
unsigned i = 0,
e = LoopExitBlocks.
size(); i !=
e; ++i) {
1809 Value *LiveInValue =
SSA.GetValueInMiddleOfBlock(ExitBlock);
1810 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1811 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1814 if (UnorderedAtomic)
1824 if (!MSSAInsertPoint) {
1831 MSSAInsertPts[i] = NewMemAcc;
1832 MSSAU->
insertDef(cast<MemoryDef>(NewMemAcc),
true);
1838 void replaceLoadWithValue(
LoadInst *LI,
Value *V)
const override {
1842 void instructionDeleted(
Instruction *I)
const override {
1854 if (isa<AllocaInst>(Object))
1889 assert(LI !=
nullptr && DT !=
nullptr && CurLoop !=
nullptr &&
1890 CurAST !=
nullptr && SafetyInfo !=
nullptr &&
1891 "Unexpected Input to promoteLoopAccessesToScalars");
1893 Value *SomePtr = *PointerMustAliases.
begin();
1933 bool DereferenceableInPH =
false;
1934 bool SafeToInsertStore =
false;
1940 unsigned Alignment = 1;
1942 bool SawUnorderedAtomic =
false;
1943 bool SawNotAtomic =
false;
1948 bool IsKnownThreadLocalObject =
false;
1956 if (!isKnownNonEscaping(Object, TLI))
1960 IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
1966 for (
Value *ASIV : PointerMustAliases) {
1970 if (SomePtr->
getType() != ASIV->getType())
1982 if (!
Load->isUnordered())
1985 SawUnorderedAtomic |=
Load->isAtomic();
1986 SawNotAtomic |= !
Load->isAtomic();
1988 unsigned InstAlignment =
Load->getAlignment();
1997 if (!DereferenceableInPH || (InstAlignment > Alignment))
2000 DereferenceableInPH =
true;
2001 Alignment =
std::max(Alignment, InstAlignment);
2008 if (!
Store->isUnordered())
2011 SawUnorderedAtomic |=
Store->isAtomic();
2012 SawNotAtomic |= !
Store->isAtomic();
2019 unsigned InstAlignment =
Store->getAlignment();
2024 if (!DereferenceableInPH || !SafeToInsertStore ||
2025 (InstAlignment > Alignment)) {
2027 DereferenceableInPH =
true;
2028 SafeToInsertStore =
true;
2029 Alignment =
std::max(Alignment, InstAlignment);
2039 if (!SafeToInsertStore)
2046 if (!DereferenceableInPH) {
2048 Store->getPointerOperand(),
Store->getValueOperand()->getType(),
2056 if (LoopUses.
empty()) {
2059 }
else if (AATags) {
2071 if (SawUnorderedAtomic && SawNotAtomic)
2078 if (SawUnorderedAtomic &&
2083 if (!DereferenceableInPH)
2090 if (!SafeToInsertStore) {
2091 if (IsKnownThreadLocalObject)
2092 SafeToInsertStore =
true;
2102 if (!SafeToInsertStore)
2106 LLVM_DEBUG(
dbgs() <<
"LICM: Promoting value stored to in loop: " << *SomePtr
2111 <<
"Moving accesses to memory location out of the loop";
2119 DebugLoc DL = LoopUses[0]->getDebugLoc();
2124 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
2125 InsertPts, MSSAInsertPts, PIC, *CurAST, MSSAU, *LI, DL,
2126 Alignment, SawUnorderedAtomic, AATags, *SafetyInfo);
2133 if (SawUnorderedAtomic)
2144 MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess);
2152 Promoter.run(LoopUses);
2169 std::unique_ptr<AliasSetTracker>
2170 LoopInvariantCodeMotion::collectAliasInfoForLoop(
Loop *L,
LoopInfo *LI,
2172 std::unique_ptr<AliasSetTracker> CurAST;
2175 auto MapI = LoopToAliasSetMap.find(InnerL);
2179 if (MapI == LoopToAliasSetMap.end()) {
2183 std::unique_ptr<AliasSetTracker> InnerAST = std::move(MapI->second);
2189 CurAST->add(*InnerAST);
2191 CurAST = std::move(InnerAST);
2193 LoopToAliasSetMap.erase(MapI);
2196 CurAST = std::make_unique<AliasSetTracker>(*AA);
2199 for (
Loop *InnerL : RecomputeLoops)
2211 std::unique_ptr<AliasSetTracker>
2212 LoopInvariantCodeMotion::collectAliasInfoForLoopWithMSSA(
2215 auto CurAST = std::make_unique<AliasSetTracker>(*AA, MSSA, L);
2216 CurAST->addAllInstructionsInLoopUsingMSSA();
2224 auto ASTIt =
LICM.getLoopToAliasSetMap().find(L);
2225 if (ASTIt ==
LICM.getLoopToAliasSetMap().
end())
2228 ASTIt->second->copyValue(From, To);
2233 void LegacyLICMPass::deleteAnalysisValue(
Value *V,
Loop *L) {
2234 auto ASTIt =
LICM.getLoopToAliasSetMap().find(L);
2235 if (ASTIt ==
LICM.getLoopToAliasSetMap().
end())
2238 ASTIt->second->deleteValue(V);
2243 void LegacyLICMPass::deleteAnalysisLoop(
Loop *L) {
2244 if (!
LICM.getLoopToAliasSetMap().count(L))
2247 LICM.getLoopToAliasSetMap().erase(L);
2257 return isInvalidatedAccordingToAST;
2274 if (CurLoop->
begin() != CurLoop->
end())
2282 << *(MemLoc.
Ptr) <<
"\n");
2289 << *(MemLoc.
Ptr) <<
"\n");
2335 for (
const auto &MA : *Accesses)
2336 if (
const auto *MD = dyn_cast<MemoryDef>(&MA))
2337 if (MU->
getBlock() != MD->getBlock() ||
2347 assert(CurLoop->
contains(BB) &&
"Only valid if BB is IN the loop");
unsigned LicmMssaOptCounter
Pass interface - Implemented by all 'passes'.
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, AliasSetTracker *AST, MemorySSAUpdater *MSSAU)
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
bool canSplitPredecessors() const
void insertInstructionTo(const Instruction *Inst, const BasicBlock *BB)
Inform the safety info that we are planning to insert a new instruction Inst into the basic block BB...
A parsed version of the target data layout string in and methods for querying it. ...
reference emplace_back(ArgTypes &&... Args)
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
bool promoteLoopAccessesToScalars(const SmallSetVector< Value *, 8 > &, SmallVectorImpl< BasicBlock *> &, SmallVectorImpl< Instruction *> &, SmallVectorImpl< MemoryAccess *> &, PredIteratorCache &, LoopInfo *, DominatorTree *, const TargetLibraryInfo *, Loop *, AliasSetTracker *, MemorySSAUpdater *, ICFLoopSafetyInfo *, OptimizationRemarkEmitter *)
Try to promote memory values to scalars by sinking stores out of the loop and moving loads to before ...
static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I)
Returns true if a PHINode is a trivially replaceable with an Instruction.
Helper class for SSA formation on a set of values defined in multiple blocks.
DILocation * get() const
Get the underlying DILocation.
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...
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
DiagnosticInfoOptimizationBase::Argument NV
bool hasDisableLICMTransformsHint(const Loop *L)
Look for the loop attribute that disables the LICM transformation heuristics.
bool VerifyMemorySSA
Enables verification of MemorySSA.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
This is the interface for a simple mod/ref and alias analysis over globals.
const_iterator end() const
bool hasMetadataOtherThanDebugLoc() const
Return true if this instruction has metadata attached to it other than a debug location.
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static constexpr LocationSize unknown()
bool sinkRegion(DomTreeNode *, AliasAnalysis *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, TargetTransformInfo *, Loop *, AliasSetTracker *, MemorySSAUpdater *, ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block...
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
void push_back(const T &Elt)
const AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
The main scalar evolution driver.
static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT, LoopInfo *LI, const Loop *CurLoop, LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU)
void insertUse(MemoryUse *Use, bool RenameUses=false)
This class represents a function call, abstracting a target machine's calling convention.
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this load instruction.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
bool salvageDebugInfo(Instruction &I)
Assuming the instruction I is going to be deleted, attempt to salvage debug users of I by writing the...
bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, MaybeAlign Alignment, const DataLayout &DL, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested...
LLVMContext & getContext() const
All values hold a context through their type.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
BasicBlock * getSuccessor(unsigned i) const
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop, const TargetTransformInfo *TTI)
Return true if the instruction is free in the loop.
STATISTIC(NumFunctions, "Total number of functions")
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
Value * getCondition() const
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
iv Induction Variable Users
void reserve(size_type N)
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
LLVMContext & getContext() const
Get the context in which this basic block lives.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
static bool pointerInvalidatedByLoop(MemoryLocation MemLoc, AliasSetTracker *CurAST, Loop *CurLoop, AliasAnalysis *AA)
iterator begin()
Instruction iterator methods.
Loop Invariant Code Motion
Value * getArgOperand(unsigned i) const
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Represents read-only accesses to memory.
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
ArrayRef< BasicBlock * > get(BasicBlock *BB)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Legacy analysis pass which computes MemorySSA.
virtual void computeLoopSafetyInfo(const Loop *CurLoop)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
This is the interface for a SCEV-based alias analysis.
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
Type * getPointerElementType() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This implementation of LoopSafetyInfo use ImplicitControlFlowTracking to give precise answers on "may...
bool hasAllowReciprocal() const
Determine whether the allow-reciprocal flag is set.
A Use represents the edge between a Value definition and its users.
virtual bool doFinalization(Module &)
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
Encapsulates MemorySSA, including all data associated with memory accesses.
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.
static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
When an instruction is found to only use loop invariant operands that is safe to hoist, this instruction is called to do the dirty work.
const DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
void setName(const Twine &Name)
Change the name of the value.
Analysis pass that exposes the LoopInfo for a function.
bool remove(const value_type &X)
Remove an item from the set vector.
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
virtual bool anyBlockMayThrow() const
Returns true iff any block of the loop for which this info is contains an instruction that may throw ...
BlockT * getHeader() const
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...
FunctionModRefBehavior getModRefBehavior(const CallBase *Call)
Return the behavior of the given call site.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU, Loop *CurLoop, SinkAndHoistLICMFlags &Flags)
INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false, false) INITIALIZE_PASS_END(LegacyLICMPass
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
PredIteratorCache - This class is an extremely trivial cache for predecessor iterator queries...
FunctionModRefBehavior
Summary of how a function affects memory in the program.
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Instruction * getUniqueInstruction()
If this alias set is known to contain a single instruction and only a single unique instruction...
iterator begin()
Get an iterator to the beginning of the SetVector.
This class represents a no-op cast from one type to another.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
static cl::opt< bool > DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false), cl::desc("Disable memory promotion in LICM pass"))
Memory promotion is enabled by default.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void copyColors(BasicBlock *New, BasicBlock *Old)
Copy colors of block Old into the block New.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
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.
void forgetLoopDispositions(const Loop *L)
Called when the client has changed the disposition of values in this loop.
Interval::succ_iterator succ_end(Interval *I)
iterator find(const_arg_type_t< KeyT > Val)
bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal=false)
Checks whether the given location points to constant memory, or if OrLocal is true whether it points ...
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
static Instruction * sinkThroughTriviallyReplaceablePHI(PHINode *TPN, Instruction *I, LoopInfo *LI, SmallDenseMap< BasicBlock *, Instruction *, 32 > &SunkCopies, const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop, MemorySSAUpdater *MSSAU)
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
initializer< Ty > init(const Ty &Val)
virtual bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop) const
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
static cl::opt< int > LICMN2Theshold("licm-n2-threshold", cl::Hidden, cl::init(0), cl::desc("How many instruction to cross product using AA"))
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
A set of analyses that are preserved following a run of a transformation pass.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
virtual bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop) const =0
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
unsigned const MachineRegisterInfo * MRI
MemorySSAWalker * getSkipSelfWalker()
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
void setAAMetadata(const AAMDNodes &N)
Sets the metadata on this instruction from the AAMDNodes structure.
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
Conditional or Unconditional Branch instruction.
size_t size(BasicBlock *BB) const
static void moveInstructionBefore(Instruction &I, Instruction &Dest, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater *MSSAU, ScalarEvolution *SE)
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
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 mayHaveSideEffects() const
Return true if the instruction may have side effects.
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
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...
Represent the analysis usage information of a pass.
cl::opt< unsigned > SetLicmMssaOptCap
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
AliasSet & getAliasSetFor(const MemoryLocation &MemLoc)
Return the alias set which contains the specified memory location.
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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...
void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
bool onlyReadsMemory(const CallBase *Call)
Checks if the specified call is known to only read from non-volatile memory (or not access memory at ...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
MemoryAccess * createMemoryAccessInBB(Instruction *I, MemoryAccess *Definition, const BasicBlock *BB, MemorySSA::InsertionPlace Point)
Create a MemoryAccess in MemorySSA at a specified point in a block, with a specified clobbering defin...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT, Loop *CurLoop)
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
This function does not perform any non-local loads or stores to memory.
void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
TargetTransformInfo & TTI
static cl::opt< uint32_t > MaxNumUsesTraversed("licm-max-num-uses-traversed", cl::Hidden, cl::init(8), cl::desc("Max num uses visited for identifying load " "invariance in loop using invariant start (default = 8)"))
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
const Value * Ptr
The address of the start of the location.
Representation for a specific memory location.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
const InstListType & getInstList() const
Return the underlying instruction list container.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
void removeInstruction(const Instruction *Inst)
Inform safety info that we are planning to remove the instruction Inst from its block.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
bool doesNotWriteMemoryBefore(const BasicBlock *BB, const Loop *CurLoop) const
Returns true if we could not execute a memory-modifying instruction before we enter BB under assumpti...
BlockVerifier::State From
static cl::opt< bool > ControlFlowHoisting("licm-control-flow-hoisting", cl::Hidden, cl::init(false), cl::desc("Enable control flow (and PHI) hoisting in LICM"))
Align max(MaybeAlign Lhs, Align Rhs)
void verifyMemorySSA() const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
void copyValue(Value *From, Value *To)
This method should be used whenever a preexisting value in the program is copied or cloned...
bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
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.
Provides information about what library functions are available for the current target.
void setAlignment(MaybeAlign Alignment)
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
void wireOldPredecessorsToNewImmediatePredecessor(BasicBlock *Old, BasicBlock *New, ArrayRef< BasicBlock *> Preds, bool IdenticalEdgesWereMerged=true)
A new empty BasicBlock (New) now branches directly to Old.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
An analysis that produces MemorySSA for a function.
BasicBlock * getBlock() const
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, TargetTransformInfo *TTI, bool &FreeInLoop)
Return true if the only users of this instruction are outside of the loop.
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)
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental.guard intrinsic.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class that has the common methods + fields of memory uses/defs.
A lightweight accessor for an operand bundle meant to be passed around by value.
iterator_range< user_iterator > users()
static bool isSafeToExecuteUnconditionally(Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE, const Instruction *CtxI=nullptr)
Only sink or hoist an instruction if it is not a trapping instruction, or if the instruction is known...
LoopT * getParentLoop() const
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
LLVM_NODISCARD bool isModSet(const ModRefInfo MRI)
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this store instruction.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool onlyAccessesArgPointees(FunctionModRefBehavior MRB)
Checks if functions with the specified behavior are known to read and write at most from objects poin...
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
cl::opt< unsigned > SetLicmMssaNoAccForPromotionCap
cl::opt< bool > EnableMSSALoopDependency
Enables memory ssa as a dependency for loop passes.
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned pred_size(const BasicBlock *BB)
Get the number of predecessors of BB.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
bool empty() const
Determine if the SetVector is empty or not.
user_iterator_impl< User > user_iterator
bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc...
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
void setAlignment(MaybeAlign Alignment)
MemoryUseOrDef * createMemoryAccessAfter(Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Captures loop safety information.
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
const_iterator begin() const
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
SmallVector< DomTreeNode *, 16 > collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop)
Does a BFS from a given node to all of its children inside a given loop.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
MemoryAccess * getClobberingMemoryAccess(const Instruction *I)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
bool hoistRegion(DomTreeNode *, AliasAnalysis *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, Loop *, AliasSetTracker *, MemorySSAUpdater *, ScalarEvolution *, ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block...
static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI)
Little predicate that returns true if the specified basic block is in a subloop of the current one...
void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
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 ...
void insertDef(MemoryDef *Def, bool RenameUses=false)
Insert a definition into the MemorySSA IR.
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
void initializeLegacyLICMPassPass(PassRegistry &)
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
bool canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, Loop *CurLoop, AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU, bool TargetExecutesOncePerLoop, SinkAndHoistLICMFlags *LICMFlags=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Returns true if is legal to hoist or sink this instruction disregarding the possible introduction of ...
The legacy pass manager's analysis pass to compute loop information.
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
This is the interface for LLVM's primary stateless and local alias analysis.
static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE)
When an instruction is found to only be used outside of the loop, this function moves it to the exit ...
A container for analyses that lazily runs them and caches their results.
static Instruction * CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU)
Legacy analysis pass which computes a DominatorTree.
LLVM_NODISCARD bool isModOrRefSet(const ModRefInfo MRI)
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
op_range incoming_values()
iterator_range< block_iterator > blocks() const
static IntegerType * getInt8Ty(LLVMContext &C)
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
void deleteValue(Value *PtrVal)
This method is used to remove a pointer value from the AliasSetTracker entirely.
loop versioning Loop Versioning For LICM
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures, unsigned MaxUsesToExplore=DefaultMaxUsesToExplore)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.
const DenseMap< BasicBlock *, ColorVector > & getBlockColors() const
Returns block colors map that is used to update funclet operand bundles.