94#define DEBUG_TYPE "licm"
96STATISTIC(NumCreatedBlocks,
"Number of blocks created");
97STATISTIC(NumClonedBranches,
"Number of branches cloned");
98STATISTIC(NumSunk,
"Number of instructions sunk out of loop");
99STATISTIC(NumHoisted,
"Number of instructions hoisted out of loop");
100STATISTIC(NumMovedLoads,
"Number of load insts hoisted or sunk");
101STATISTIC(NumMovedCalls,
"Number of call insts hoisted or sunk");
102STATISTIC(NumPromotionCandidates,
"Number of promotion candidates");
103STATISTIC(NumLoadPromoted,
"Number of load-only promotions");
104STATISTIC(NumLoadStorePromoted,
"Number of load and store promotions");
106 "Number of min/max expressions hoisted out of the loop");
108 "Number of geps reassociated and hoisted out of the loop");
109STATISTIC(NumAddSubHoisted,
"Number of add/subtract expressions reassociated "
110 "and hoisted out of the loop");
111STATISTIC(NumFPAssociationsHoisted,
"Number of invariant FP expressions "
112 "reassociated and hoisted out of the loop");
114 "Number of invariant int expressions "
115 "reassociated and hoisted out of the loop");
116STATISTIC(NumBOAssociationsHoisted,
"Number of invariant BinaryOp expressions "
117 "reassociated and hoisted out of the loop");
122 cl::desc(
"Disable memory promotion in LICM pass"));
126 cl::desc(
"Enable control flow (and PHI) hoisting in LICM"));
130 cl::desc(
"Force thread model single in LICM pass"));
134 cl::desc(
"Max num uses visited for identifying load "
135 "invariance in loop using invariant start (default = 8)"));
140 "Set upper limit for the number of transformations performed "
141 "during a single round of hoisting the reassociated expressions."));
146 "Set upper limit for the number of transformations performed "
147 "during a single round of hoisting the reassociated expressions."));
159 cl::desc(
"Enable imprecision in LICM in pathological cases, in exchange "
160 "for faster compile. Caps the MemorySSA clobbering calls."));
167 cl::desc(
"[LICM & MemorySSA] When MSSA in LICM is disabled, this has no "
168 "effect. When MSSA in LICM is enabled, then this is the maximum "
169 "number of accesses allowed to be present in a loop in order to "
170 "enable memory promotion."));
180 bool &FoldableInLoop,
bool LoopNestMode);
199 bool InvariantGroup);
227 std::pair<SmallSetVector<Value *, 8>,
bool>;
232struct LoopInvariantCodeMotion {
238 LoopInvariantCodeMotion(
unsigned LicmMssaOptCap,
239 unsigned LicmMssaNoAccForPromotionCap,
240 bool LicmAllowSpeculation)
241 : LicmMssaOptCap(LicmMssaOptCap),
242 LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap),
243 LicmAllowSpeculation(LicmAllowSpeculation) {}
246 unsigned LicmMssaOptCap;
247 unsigned LicmMssaNoAccForPromotionCap;
248 bool LicmAllowSpeculation;
251struct LegacyLICMPass :
public LoopPass {
256 bool LicmAllowSpeculation =
true)
257 : LoopPass(ID), LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
258 LicmAllowSpeculation) {
262 bool runOnLoop(Loop *L, LPPassManager &LPM)
override {
267 <<
L->getHeader()->getNameOrAsOperand() <<
"\n");
271 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
272 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
276 OptimizationRemarkEmitter ORE(
L->getHeader()->getParent());
277 return LICM.runOnLoop(
278 L, &getAnalysis<AAResultsWrapperPass>().getAAResults(),
279 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
280 &getAnalysis<DominatorTreeWrapperPass>().
getDomTree(),
281 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*
F),
282 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(*
F),
283 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*
F),
284 SE ? &SE->getSE() :
nullptr, MSSA, &ORE);
290 void getAnalysisUsage(AnalysisUsage &AU)
const override {
305 LoopInvariantCodeMotion LICM;
319 LoopInvariantCodeMotion LICM(Opts.MssaOptCap, Opts.MssaNoAccForPromotionCap,
320 Opts.AllowSpeculation);
321 if (!LICM.runOnLoop(&L, &AR.
AA, &AR.
LI, &AR.
DT, &AR.
AC, &AR.
TLI, &AR.
TTI,
334 OS, MapClassName2PassName);
337 OS << (Opts.AllowSpeculation ?
"" :
"no-") <<
"allowspeculation";
352 LoopInvariantCodeMotion LICM(Opts.MssaOptCap, Opts.MssaNoAccForPromotionCap,
353 Opts.AllowSpeculation);
356 bool Changed = LICM.runOnLoop(&OutermostLoop, &AR.
AA, &AR.
LI, &AR.
DT, &AR.
AC,
374 OS, MapClassName2PassName);
377 OS << (Opts.AllowSpeculation ?
"" :
"no-") <<
"allowspeculation";
381char LegacyLICMPass::ID = 0;
405 unsigned AccessCapCount = 0;
406 for (
auto *BB : L.getBlocks())
430 assert(L->isLCSSAForm(*DT) &&
"Loop is not in LCSSA form.");
448 using namespace PatternMatch;
449 return any_of(make_pointer_range(*BB),
450 match_fn(m_Intrinsic<Intrinsic::coro_suspend>()));
458 BasicBlock *Preheader = L->getLoopPreheader();
473 if (L->hasDedicatedExits())
477 TLI,
TTI, L, MSSAU, &SafetyInfo, Flags, ORE)
479 MSSAU, &SafetyInfo, Flags, ORE);
480 Flags.setIsSink(
false);
483 MSSAU, SE, &SafetyInfo, Flags, ORE, LoopNestMode,
484 LicmAllowSpeculation);
494 !Flags.tooManyMemoryAccesses() && !HasCoroSuspendInst) {
496 SmallVector<BasicBlock *, 8> ExitBlocks;
497 L->getUniqueExitBlocks(ExitBlocks);
500 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
501 return isa<CatchSwitchInst>(Exit->getTerminator());
504 if (!HasCatchSwitch) {
507 InsertPts.
reserve(ExitBlocks.size());
508 MSSAInsertPts.
reserve(ExitBlocks.size());
510 InsertPts.
push_back(ExitBlock->getFirstInsertionPt());
518 bool Promoted =
false;
521 LocalPromoted =
false;
522 for (
auto [PointerMustAliases, HasReadsOutsideSet] :
525 PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts,
PIC, LI,
526 DT, AC, TLI,
TTI, L, MSSAU, &SafetyInfo, ORE,
527 LicmAllowSpeculation, HasReadsOutsideSet);
529 Promoted |= LocalPromoted;
530 }
while (LocalPromoted);
548 assert(
L->isLCSSAForm(*DT) &&
"Loop not left in LCSSA form after LICM!");
549 assert((
L->isOutermost() ||
L->getParentLoop()->isLCSSAForm(*DT)) &&
550 "Parent loop not left in LCSSA form after LICM!");
573 assert(
N !=
nullptr &&
AA !=
nullptr && LI !=
nullptr && DT !=
nullptr &&
574 CurLoop !=
nullptr && SafetyInfo !=
nullptr &&
575 "Unexpected input to sinkRegion.");
609 bool FoldableInLoop =
false;
610 bool LoopNestMode = OutermostLoop !=
nullptr;
611 if (!
I.mayHaveSideEffects() &&
613 SafetyInfo,
TTI, FoldableInLoop,
616 if (
sink(
I, LI, DT, CurLoop, SafetyInfo, MSSAU, ORE)) {
617 if (!FoldableInLoop) {
644 while (!Worklist.
empty()) {
647 MSSAU, SafetyInfo, Flags, ORE, CurLoop);
660class ControlFlowHoister {
679 : LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {}
681 void registerPossiblyHoistableBranch(CondBrInst *BI) {
692 TrueDest == FalseDest)
705 if (TrueDestSucc.count(FalseDest)) {
706 CommonSucc = FalseDest;
707 }
else if (FalseDestSucc.count(TrueDest)) {
708 CommonSucc = TrueDest;
712 if (TrueDestSucc.size() == 1)
713 CommonSucc = *TrueDestSucc.
begin();
717 else if (!TrueDestSucc.empty()) {
719 auto IsSucc = [&](
BasicBlock &BB) {
return TrueDestSucc.count(&BB); };
721 assert(It !=
F->end() &&
"Could not find successor in function");
733 if (CommonSucc && DT->
dominates(BI, CommonSucc))
734 HoistableBranches[BI] = CommonSucc;
737 bool canHoistPHI(PHINode *PN) {
751 if (PredecessorBlocks.size() !=
pred_size(BB))
753 for (
auto &Pair : HoistableBranches) {
754 if (Pair.second == BB) {
757 if (Pair.first->getSuccessor(0) == BB) {
758 PredecessorBlocks.erase(Pair.first->getParent());
759 PredecessorBlocks.erase(Pair.first->getSuccessor(1));
760 }
else if (Pair.first->getSuccessor(1) == BB) {
761 PredecessorBlocks.erase(Pair.first->getParent());
762 PredecessorBlocks.erase(Pair.first->getSuccessor(0));
764 PredecessorBlocks.erase(Pair.first->getSuccessor(0));
765 PredecessorBlocks.erase(Pair.first->getSuccessor(1));
771 return PredecessorBlocks.empty();
774 BasicBlock *getOrCreateHoistedBlock(BasicBlock *BB) {
778 if (
auto It = HoistDestinationMap.
find(BB); It != HoistDestinationMap.
end())
782 auto HasBBAsSuccessor =
783 [&](DenseMap<CondBrInst *, BasicBlock *>::value_type &Pair) {
784 return BB != Pair.second && (Pair.first->getSuccessor(0) == BB ||
785 Pair.first->getSuccessor(1) == BB);
787 auto It =
llvm::find_if(HoistableBranches, HasBBAsSuccessor);
791 if (It == HoistableBranches.end()) {
794 <<
" as hoist destination for "
796 HoistDestinationMap[BB] = InitialPreheader;
797 return InitialPreheader;
799 CondBrInst *BI = It->first;
800 assert(std::none_of(std::next(It), HoistableBranches.end(),
802 "BB is expected to be the target of at most one branch");
807 BasicBlock *CommonSucc = HoistableBranches[BI];
808 BasicBlock *HoistTarget = getOrCreateHoistedBlock(BI->getParent());
811 auto CreateHoistedBlock = [&](
BasicBlock *Orig) {
823 <<
" as hoist destination for " << Orig->getName()
827 BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest);
828 BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest);
829 BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc);
836 assert(TargetSucc &&
"Expected hoist target to have a single successor");
851 if (HoistTarget == InitialPreheader) {
862 for (
auto &Pair : HoistDestinationMap)
863 if (Pair.second == InitialPreheader && Pair.first != BI->getParent())
864 Pair.second = HoistCommonSucc;
875 NewBI->copyMetadata(*BI, {LLVMContext::MD_prof});
883 "Hoisting blocks should not have destroyed preheader");
884 return HoistDestinationMap[BB];
901 bool AllowSpeculation) {
903 assert(
N !=
nullptr &&
AA !=
nullptr && LI !=
nullptr && DT !=
nullptr &&
904 CurLoop !=
nullptr && SafetyInfo !=
nullptr &&
905 "Unexpected input to hoistRegion.");
907 ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU);
923 if (!LoopNestMode &&
inSubLoop(BB, CurLoop, LI))
938 hoist(
I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
947 CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
948 MSSAU, SE, ORE, HoistedInstructions)) {
955 if (
I.getOpcode() == Instruction::FDiv &&
I.hasAllowReciprocal() &&
957 auto Divisor =
I.getOperand(1);
958 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
959 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
960 ReciprocalDivisor->setFastMathFlags(
I.getFastMathFlags());
962 ReciprocalDivisor->insertBefore(
I.getIterator());
963 ReciprocalDivisor->setDebugLoc(
I.getDebugLoc());
966 BinaryOperator::CreateFMul(
I.getOperand(0), ReciprocalDivisor);
967 Product->setFastMathFlags(
I.getFastMathFlags());
969 Product->insertAfter(
I.getIterator());
970 Product->setDebugLoc(
I.getDebugLoc());
971 I.replaceAllUsesWith(Product);
974 hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB),
975 SafetyInfo, MSSAU, SE, ORE);
976 HoistedInstructions.
push_back(ReciprocalDivisor);
983 return I.use_empty() &&
986 auto MustExecuteWithoutWritesBefore = [&](
Instruction &
I) {
990 if ((IsInvariantStart(
I) ||
isGuard(&
I)) &&
992 MustExecuteWithoutWritesBefore(
I)) {
993 hoist(
I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
1001 if (CFH.canHoistPHI(PN)) {
1007 hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
1025 CFH.registerPossiblyHoistableBranch(BI);
1040 [&](
Use &U) { return DT->dominates(I, U); })) {
1046 "New hoist point expected to dominate old hoist point");
1050 << HoistPoint->
getParent()->getNameOrAsOperand()
1051 <<
": " << *
I <<
"\n");
1064#ifdef EXPENSIVE_CHECKS
1066 assert(DT->
verify(DominatorTree::VerificationLevel::Fast) &&
1067 "Dominator tree verification failed");
1075static std::optional<uint64_t>
1080 return std::nullopt;
1084 if (InsertedIdxCI->isNegative() ||
1085 InsertedIdxCI->getValue().uge(
1086 VecTy->getElementCount().getKnownMinValue()))
1087 return std::nullopt;
1088 return InsertedIdxCI->getValue().getLimitedValue();
1119 if (!InnerIns || InnerIns->getParent() != Ins->
getParent())
1124 if (!InsertIdx || *InsertIdx == *HoistIdx)
1128 if (!InnerIns->hasOneUse())
1143 hoist(*Ins, DT, CurLoop, HoistDest, SafetyInfo, MSSAU, SE, ORE);
1175 unsigned UsesVisited = 0;
1178 for (
auto *U : Addr->
users()) {
1185 if (!
II ||
II->getIntrinsicID() != Intrinsic::invariant_start ||
1223 for (
auto *BB : L->getBlocks())
1226 for (
const auto &Acc : *Accs) {
1230 if (MUD->getMemoryInst() !=
I || NotAPhi++ == 1)
1242 if (Flags.tooManyClobberingCalls())
1247 Flags.incrementClobberingCalls();
1253 bool TargetExecutesOncePerLoop,
1263 if (LI.
hasMetadata(LLVMContext::MD_invariant_load))
1266 if (LI.
isAtomic() && !TargetExecutesOncePerLoop)
1275 bool InvariantGroup = LI.
hasMetadata(LLVMContext::MD_invariant_group);
1284 DEBUG_TYPE,
"LoadWithLoopInvariantAddressInvalidated", &LI)
1285 <<
"failed to move load with loop-invariant address "
1286 "because the loop may invalidate its value";
1289 return !Invalidated;
1294 bool TargetExecutesOncePerLoop,
1304 return canHoistLoad(*LI,
AA, DT, CurLoop, *MSSA, TargetExecutesOncePerLoop,
1315 if (CI->isConvergent())
1323 if (CI->getFunction()->isPresplitCoroutine())
1346 MSSA, MU, CurLoop,
I, Flags,
false);
1361 if (!
SI->isUnordered())
1374 assert(!
I.mayReadOrWriteMemory() &&
"unhandled aliasing");
1406 for (
const User *U :
GEP->users()) {
1428 bool &FoldableInLoop,
bool LoopNestMode) {
1431 for (
const User *U :
I.users()) {
1442 if (!BlockColors.empty() &&
1443 BlockColors.find(
const_cast<BasicBlock *
>(BB))->second.size() != 1)
1458 FoldableInLoop =
true;
1478 for (
unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
1479 BundleIdx != BundleEnd; ++BundleIdx) {
1487 if (!BlockColors.empty()) {
1488 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
1489 assert(CV.
size() == 1 &&
"non-unique color for exit block!");
1492 if (EHPad->isEHPad())
1497 New->copyMetadata(*CI);
1503 if (!
I.getName().empty())
1504 New->setName(
I.getName() +
".le");
1530 for (
Use &
Op : New->operands())
1535 OInst->getName() +
".lcssa");
1548 I.eraseFromParent();
1557 I.moveBefore(*Dest->getParent(), Dest);
1572 "Expect only trivially replaceable PHI");
1574 auto [It, Inserted] = SunkCopies.
try_emplace(ExitBlock);
1609 assert(ExitBlockSet.
count(ExitBB) &&
"Expect the PHI is in an exit block.");
1646 while (!PredBBs.
empty()) {
1649 "Expect all predecessors are in the loop");
1652 ExitBB, PredBB,
".split.loop.exit", &DTU, LI, MSSAU,
true);
1656 if (!BlockColors.empty())
1682 Use &U = UI.getUse();
1720 UI =
I.user_begin();
1724 if (VisitedUsers.
empty())
1729 <<
"sinking " <<
ore::NV(
"Inst", &
I);
1752 for (
auto *UI :
Users) {
1760 "The LCSSA PHI is not in an exit block!");
1764 PN, &
I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU);
1766 New->dropLocation();
1801 I.dropUBImplyingAttrsAndMetadata();
1812 I.updateLocationAfterHoist();
1829 if (AllowSpeculation &&
1833 bool GuaranteedToExecute =
1836 if (!GuaranteedToExecute) {
1841 DEBUG_TYPE,
"LoadWithLoopInvariantAddressCondExecuted", LI)
1842 <<
"failed to hoist load with loop-invariant address "
1843 "because load is conditionally executed";
1847 return GuaranteedToExecute;
1853 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1854 SmallVectorImpl<BasicBlock::iterator> &LoopInsertPts;
1855 SmallVectorImpl<MemoryAccess *> &MSSAInsertPts;
1856 PredIteratorCache &PredCache;
1857 MemorySSAUpdater &MSSAU;
1861 bool UnorderedAtomic;
1863 ICFLoopSafetyInfo &SafetyInfo;
1864 bool CanInsertStoresInExitBlocks;
1870 Value *maybeInsertLCSSAPHI(
Value *V, BasicBlock *BB)
const {
1878 I->getName() +
".lcssa");
1880 for (BasicBlock *Pred : PredCache.
get(BB))
1887 SmallVectorImpl<BasicBlock *> &LEB,
1888 SmallVectorImpl<BasicBlock::iterator> &LIP,
1889 SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &
PIC,
1890 MemorySSAUpdater &MSSAU, LoopInfo &li,
DebugLoc dl,
1891 Align Alignment,
bool UnorderedAtomic,
const AAMDNodes &AATags,
1892 ICFLoopSafetyInfo &SafetyInfo,
bool CanInsertStoresInExitBlocks)
1893 : LoadAndStorePromoter(Insts, S), SomePtr(
SP), LoopExitBlocks(LEB),
1894 LoopInsertPts(LIP), MSSAInsertPts(MSSAIP), PredCache(
PIC), MSSAU(MSSAU),
1895 LI(li),
DL(std::
move(dl)), Alignment(Alignment),
1896 UnorderedAtomic(UnorderedAtomic), AATags(AATags),
1897 SafetyInfo(SafetyInfo),
1898 CanInsertStoresInExitBlocks(CanInsertStoresInExitBlocks),
Uses(Insts) {}
1900 void insertStoresInLoopExitBlocks() {
1905 DIAssignID *NewID =
nullptr;
1906 for (
unsigned i = 0, e = LoopExitBlocks.
size(); i != e; ++i) {
1908 Value *LiveInValue =
SSA.GetValueInMiddleOfBlock(ExitBlock);
1909 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1910 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1912 StoreInst *NewSI =
new StoreInst(LiveInValue, Ptr, InsertPos);
1913 if (UnorderedAtomic)
1929 NewSI->
setMetadata(LLVMContext::MD_DIAssignID, NewID);
1935 MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i];
1936 MemoryAccess *NewMemAcc;
1937 if (!MSSAInsertPoint) {
1939 NewSI,
nullptr, NewSI->
getParent(), MemorySSA::Beginning);
1944 MSSAInsertPts[i] = NewMemAcc;
1950 void doExtraRewritesBeforeFinalDeletion()
override {
1951 if (CanInsertStoresInExitBlocks)
1952 insertStoresInLoopExitBlocks();
1955 void instructionDeleted(Instruction *
I)
const override {
1960 bool shouldDelete(Instruction *
I)
const override {
1962 return CanInsertStoresInExitBlocks;
1967bool isNotCapturedBeforeOrInLoop(
const Value *V,
const Loop *L,
1974 V,
true,
L->getHeader()->getTerminator(), DT,
1980bool isNotVisibleOnUnwindInLoop(
const Value *Object,
const Loop *L,
1982 bool RequiresNoCaptureBeforeUnwind;
1986 return !RequiresNoCaptureBeforeUnwind ||
1987 isNotCapturedBeforeOrInLoop(Object, L, DT);
1995 isNotCapturedBeforeOrInLoop(Object, L, DT)) ||
2015 bool HasReadsOutsideSet) {
2017 assert(LI !=
nullptr && DT !=
nullptr && CurLoop !=
nullptr &&
2018 SafetyInfo !=
nullptr &&
2019 "Unexpected Input to promoteLoopAccessesToScalars");
2022 dbgs() <<
"Trying to promote set of must-aliased pointers:\n";
2023 for (
Value *Ptr : PointerMustAliases)
2024 dbgs() <<
" " << *Ptr <<
"\n";
2026 ++NumPromotionCandidates;
2028 Value *SomePtr = *PointerMustAliases.
begin();
2068 bool DereferenceableInPH =
false;
2069 bool StoreIsGuaranteedToExecute =
false;
2070 bool LoadIsGuaranteedToExecute =
false;
2071 bool FoundLoadToPromote =
false;
2078 } StoreSafety = StoreSafetyUnknown;
2086 bool SawUnorderedAtomic =
false;
2087 bool SawNotAtomic =
false;
2094 if (HasReadsOutsideSet)
2095 StoreSafety = StoreUnsafe;
2104 if (!isNotVisibleOnUnwindInLoop(Object, CurLoop, DT))
2105 StoreSafety = StoreUnsafe;
2111 Type *AccessTy =
nullptr;
2112 for (
Value *ASIV : PointerMustAliases) {
2122 if (!Load->isUnordered())
2125 SawUnorderedAtomic |= Load->isAtomic();
2126 SawNotAtomic |= !Load->isAtomic();
2127 FoundLoadToPromote =
true;
2129 Align InstAlignment = Load->getAlign();
2131 if (!LoadIsGuaranteedToExecute)
2132 LoadIsGuaranteedToExecute =
2139 if (!DereferenceableInPH || (InstAlignment > Alignment))
2141 *Load, DT, TLI, CurLoop, SafetyInfo, ORE,
2143 DereferenceableInPH =
true;
2144 Alignment = std::max(Alignment, InstAlignment);
2151 if (!Store->isUnordered())
2154 SawUnorderedAtomic |= Store->isAtomic();
2155 SawNotAtomic |= !Store->isAtomic();
2162 Align InstAlignment = Store->getAlign();
2163 bool GuaranteedToExecute =
2165 StoreIsGuaranteedToExecute |= GuaranteedToExecute;
2166 if (GuaranteedToExecute) {
2167 DereferenceableInPH =
true;
2168 if (StoreSafety == StoreSafetyUnknown)
2169 StoreSafety = StoreSafe;
2170 Alignment = std::max(Alignment, InstAlignment);
2179 if (StoreSafety == StoreSafetyUnknown &&
2181 return DT->
dominates(Store->getParent(), Exit);
2183 StoreSafety = StoreSafe;
2187 if (!DereferenceableInPH) {
2189 Store->getPointerOperand(), Store->getValueOperand()->getType(),
2202 if (LoopUses.
empty()) {
2205 }
else if (AATags) {
2217 if (SawUnorderedAtomic && SawNotAtomic)
2227 if (!DereferenceableInPH) {
2228 LLVM_DEBUG(
dbgs() <<
"Not promoting: Not dereferenceable in preheader\n");
2236 if (StoreSafety == StoreSafetyUnknown) {
2238 bool ExplicitlyDereferenceableOnly;
2243 (!ExplicitlyDereferenceableOnly ||
2246 isThreadLocalObject(Object, CurLoop, DT,
TTI))
2247 StoreSafety = StoreSafe;
2252 if (StoreSafety != StoreSafe && !FoundLoadToPromote)
2257 if (StoreSafety == StoreSafe) {
2258 LLVM_DEBUG(
dbgs() <<
"LICM: Promoting load/store of the value: " << *SomePtr
2260 ++NumLoadStorePromoted;
2262 LLVM_DEBUG(
dbgs() <<
"LICM: Promoting load of the value: " << *SomePtr
2270 <<
"Moving accesses to memory location out of the loop";
2274 std::vector<DebugLoc> LoopUsesLocs;
2275 for (
auto U : LoopUses)
2276 LoopUsesLocs.push_back(U->getDebugLoc());
2282 LoopPromoter Promoter(SomePtr, LoopUses,
SSA, ExitBlocks, InsertPts,
2283 MSSAInsertPts,
PIC, MSSAU, *LI,
DL, Alignment,
2285 StoreIsGuaranteedToExecute ? AATags :
AAMDNodes(),
2286 *SafetyInfo, StoreSafety == StoreSafe);
2291 if (FoundLoadToPromote || !StoreIsGuaranteedToExecute) {
2295 if (SawUnorderedAtomic)
2299 if (AATags && LoadIsGuaranteedToExecute)
2306 SSA.AddAvailableValue(Preheader, PreheaderLoad);
2315 Promoter.run(LoopUses);
2320 if (PreheaderLoad && PreheaderLoad->
use_empty())
2332 Fn(MUD->getMemoryInst());
2342 auto IsPotentiallyPromotable = [L](
const Instruction *
I) {
2344 const Value *PtrOp =
SI->getPointerOperand();
2348 const Value *PtrOp = LI->getPointerOperand();
2357 if (IsPotentiallyPromotable(
I)) {
2358 AttemptingPromotion.
insert(
I);
2366 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias())
2394 for (
auto [Set, HasReadsOutsideSet] : Sets) {
2396 for (
const auto &MemLoc : *Set)
2397 PointerMustAliases.
insert(
const_cast<Value *
>(MemLoc.Ptr));
2398 Result.emplace_back(std::move(PointerMustAliases), HasReadsOutsideSet);
2413 if (Flags.tooManyMemoryAccesses())
2432 if (!Flags.getIsSink() && MSSA->
dominates(IMD, &MA))
2450 bool InvariantGroup) {
2452 if (!Flags.getIsSink()) {
2465 CurLoop->
contains(Source->getBlock()) &&
2486 if (Flags.tooManyMemoryAccesses())
2514 Value *Cond1, *Cond2;
2526 if (!
LHS->getType()->isIntegerTy())
2530 if (L.isLoopInvariant(
LHS)) {
2534 if (L.isLoopInvariant(
LHS) || !L.isLoopInvariant(
RHS))
2541 Value *LHS1, *LHS2, *RHS1, *RHS2;
2542 if (!MatchICmpAgainstInvariant(Cond1, P1, LHS1, RHS1) ||
2543 !MatchICmpAgainstInvariant(Cond2, P2, LHS2, RHS2))
2546 if (!MatchingPred || LHS1 != LHS2)
2554 "Relational predicate is either less (or equal) or greater (or equal)!");
2556 ? (UseMin ? Intrinsic::smin : Intrinsic::smax)
2557 : (UseMin ? Intrinsic::umin : Intrinsic::umax);
2558 auto *Preheader = L.getLoopPreheader();
2559 assert(Preheader &&
"Loop is not in simplify form?");
2566 RHS2 = Builder.CreateFreeze(RHS2, RHS2->
getName() +
".fr");
2567 Value *NewRHS = Builder.CreateBinaryIntrinsic(
2568 id, RHS1, RHS2,
nullptr,
2571 (UseMin ?
"min" :
"max"));
2572 Builder.SetInsertPoint(&
I);
2576 Value *NewCond = Builder.CreateICmp(
P, LHS1, NewRHS);
2578 I.replaceAllUsesWith(NewCond);
2601 if (
GEP->hasAllConstantIndices())
2605 if (!Src || !Src->hasOneUse() || !L.contains(Src))
2608 Value *SrcPtr = Src->getPointerOperand();
2609 auto LoopInvariant = [&](
Value *V) {
return L.isLoopInvariant(V); };
2610 if (!L.isLoopInvariant(SrcPtr) || !
all_of(
GEP->indices(), LoopInvariant))
2617 if (
all_of(Src->indices(), LoopInvariant))
2627 bool IsInBounds = Src->isInBounds() &&
GEP->isInBounds() &&
2631 BasicBlock *Preheader = L.getLoopPreheader();
2633 Value *NewSrc = Builder.CreateGEP(
GEP->getSourceElementType(), SrcPtr,
2635 "invariant.gep", IsInBounds);
2636 Builder.SetInsertPoint(
GEP);
2637 Value *NewGEP = Builder.CreateGEP(Src->getSourceElementType(), NewSrc,
2640 GEP->replaceAllUsesWith(NewGEP);
2653 assert(!L.isLoopInvariant(VariantLHS) &&
"Precondition.");
2654 assert(L.isLoopInvariant(InvariantRHS) &&
"Precondition.");
2660 Value *VariantOp, *InvariantOp;
2670 if (L.isLoopInvariant(VariantOp))
2672 if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))
2679 auto &
DL = L.getHeader()->getDataLayout();
2688 auto *Preheader = L.getLoopPreheader();
2689 assert(Preheader &&
"Loop is not in simplify form?");
2692 Builder.CreateSub(InvariantRHS, InvariantOp,
"invariant.op",
2693 !IsSigned, IsSigned);
2714 assert(!L.isLoopInvariant(VariantLHS) &&
"Precondition.");
2715 assert(L.isLoopInvariant(InvariantRHS) &&
"Precondition.");
2721 Value *VariantOp, *InvariantOp;
2729 bool VariantSubtracted =
false;
2733 if (L.isLoopInvariant(VariantOp)) {
2735 VariantSubtracted =
true;
2738 if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))
2746 auto &
DL = L.getHeader()->getDataLayout();
2748 if (VariantSubtracted && IsSigned) {
2753 }
else if (VariantSubtracted && !IsSigned) {
2758 }
else if (!VariantSubtracted && IsSigned) {
2769 auto *Preheader = L.getLoopPreheader();
2770 assert(Preheader &&
"Loop is not in simplify form?");
2774 ? Builder.CreateSub(InvariantOp, InvariantRHS,
"invariant.op",
2775 !IsSigned, IsSigned)
2776 : Builder.CreateAdd(InvariantOp, InvariantRHS,
"invariant.op",
2777 !IsSigned, IsSigned);
2802 if (L.isLoopInvariant(
LHS)) {
2808 if (L.isLoopInvariant(
LHS) || !L.isLoopInvariant(
RHS) || !
LHS->hasOneUse())
2823 unsigned FPOpcode) {
2824 if (
I->getOpcode() == IntOpcode)
2826 if (
I->getOpcode() == FPOpcode &&
I->hasAllowReassoc() &&
2827 I->hasNoSignedZeros())
2843 Value *VariantOp =
I.getOperand(0);
2844 Value *InvariantOp =
I.getOperand(1);
2845 if (L.isLoopInvariant(VariantOp))
2847 if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))
2849 Value *Factor = InvariantOp;
2857 while (!Worklist.
empty()) {
2870 L.isLoopInvariant(BO))
2874 if (L.isLoopInvariant(U0))
2876 else if (L.isLoopInvariant(U1))
2880 unsigned Limit =
I.getType()->isIntOrIntVectorTy()
2883 if (Changes.
size() > Limit)
2886 if (Changes.
empty())
2890 if (
I.getType()->isIntOrIntVectorTy()) {
2891 for (
auto *
Add : Adds)
2892 Add->dropPoisonGeneratingFlags();
2896 auto *Preheader = L.getLoopPreheader();
2897 assert(Preheader &&
"Loop is not in simplify form?");
2899 for (
auto *U : Changes) {
2900 assert(L.isLoopInvariant(U->get()));
2903 if (
I.getType()->isIntOrIntVectorTy()) {
2904 Mul = Builder.CreateMul(U->get(), Factor,
"factor.op.mul");
2906 Ins->dropPoisonGeneratingFlags();
2908 Mul = Builder.CreateFMulFMF(U->get(), Factor, Ins,
"factor.op.fmul");
2911 unsigned OpIdx = U->getOperandNo();
2912 auto *
LHS =
OpIdx == 0 ?
Mul : Ins->getOperand(0);
2913 auto *
RHS =
OpIdx == 1 ?
Mul : Ins->getOperand(1);
2916 Ins->getName() +
".reass", Ins->getIterator());
2918 NewBO->copyIRFlags(Ins);
2919 if (VariantOp == Ins)
2925 I.replaceAllUsesWith(VariantOp);
2945 if (!BO || !BO->isAssociative())
2949 bool LVInRHS = L.isLoopInvariant(BO->getOperand(0));
2951 if (!BO0 || BO0->getOpcode() != Opcode || !BO0->isAssociative() ||
2952 BO0->hasNUsesOrMore(BO0->getType()->isIntegerTy() ? 2 : 3))
2955 Value *LV = BO0->getOperand(0);
2956 Value *C1 = BO0->getOperand(1);
2957 Value *C2 = BO->getOperand(!LVInRHS);
2959 assert(BO->isCommutative() && BO0->isCommutative() &&
2960 "Associativity implies commutativity");
2961 if (L.isLoopInvariant(LV) && !L.isLoopInvariant(C1))
2963 if (L.isLoopInvariant(LV) || !L.isLoopInvariant(C1) || !L.isLoopInvariant(C2))
2966 auto *Preheader = L.getLoopPreheader();
2967 assert(Preheader &&
"Loop is not in simplify form?");
2970 auto *Inv = Builder.CreateBinOp(Opcode, C1, C2,
"invariant.op");
2973 Opcode, LV, Inv, BO->
getName() +
".reass", BO->getIterator());
2976 if (Opcode == Instruction::FAdd || Opcode == Instruction::FMul) {
2978 FastMathFlags Intersect = BO->getFastMathFlags() & BO0->getFastMathFlags();
2980 I->setFastMathFlags(Intersect);
2981 NewBO->setFastMathFlags(Intersect);
2985 Flags.AllKnownNonZero =
false;
2986 Flags.mergeFlags(*BO);
2987 Flags.mergeFlags(*BO0);
2990 Flags.applyFlags(*
I);
2991 Flags.applyFlags(*NewBO);
2994 BO->replaceAllUsesWith(NewBO);
2999 if (BO0->use_empty()) {
3023 Value *LV, *C1, *C2;
3043 if (L.isLoopInvariant(LV) && !L.isLoopInvariant(C1))
3045 InvOp = Instruction::Sub;
3046 ResultOp = Instruction::Add;
3051 InvOp = Instruction::Add;
3052 ResultOp = Instruction::Sub;
3062 InvOp = Instruction::Sub;
3063 ResultOp = Instruction::Add;
3068 if (L.isLoopInvariant(LV) || !L.isLoopInvariant(C1) || !L.isLoopInvariant(C2))
3071 auto *Preheader = L.getLoopPreheader();
3072 assert(Preheader &&
"Loop is not in simplify form?");
3075 auto *Inv = Builder.CreateBinOp(InvOp, C1, C2,
"invariant.op");
3078 I.getName() +
".reass",
I.getIterator());
3084 I.replaceAllUsesWith(NewBO);
3107 if (
hoistGEP(
I, L, SafetyInfo, MSSAU, AC, DT)) {
3120 bool IsInt =
I.getType()->isIntOrIntVectorTy();
3124 ++NumIntAssociationsHoisted;
3126 ++NumFPAssociationsHoisted;
3132 ++NumBOAssociationsHoisted;
3138 ++NumBOAssociationsHoisted;
3149 assert(CurLoop->
contains(BB) &&
"Only valid if BB is IN the loop");
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Forward Handle Accesses
early cse Early CSE w MemorySSA
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
iv Induction Variable Users
static bool isReassociableOp(Instruction *I, unsigned IntOpcode, unsigned FPOpcode)
static bool isNotUsedOrFoldableInLoop(const Instruction &I, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, TargetTransformInfo *TTI, bool &FoldableInLoop, bool LoopNestMode)
Return true if the only users of this instruction are outside of the loop.
static bool hoistGEP(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Reassociate gep (gep ptr, idx1), idx2 to gep (gep ptr, idx2), idx1 if this allows hoisting the inner ...
static cl::opt< bool > SingleThread("licm-force-thread-model-single", cl::Hidden, cl::init(false), cl::desc("Force thread model single in LICM pass"))
static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT, LoopInfo *LI, const Loop *CurLoop, LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU)
static bool hoistInsertPastInsert(InsertElementInst *Ins, Loop *CurLoop, DominatorTree *DT, BasicBlock *HoistDest, ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE, SmallVectorImpl< Instruction * > &HoistedInstructions)
static cl::opt< unsigned > FPAssociationUpperLimit("licm-max-num-fp-reassociations", cl::init(5U), cl::Hidden, cl::desc("Set upper limit for the number of transformations performed " "during a single round of hoisting the reassociated expressions."))
static bool isFoldableInLoop(const Instruction &I, const Loop *CurLoop, const TargetTransformInfo *TTI)
Return true if the instruction is foldable in the loop.
static bool hoistMinMax(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU)
Try to simplify things like (A < INV_1 AND icmp A < INV_2) into (A < min(INV_1, INV_2)),...
static void moveInstructionBefore(Instruction &I, BasicBlock::iterator Dest, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, ScalarEvolution *SE)
static Instruction * cloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU)
static cl::opt< bool > ControlFlowHoisting("licm-control-flow-hoisting", cl::Hidden, cl::init(false), cl::desc("Enable control flow (and PHI) hoisting in LICM"))
static bool pointerInvalidatedByLoop(MemorySSA *MSSA, MemoryUse *MU, Loop *CurLoop, Instruction &I, SinkAndHoistLICMFlags &Flags, bool InvariantGroup)
static bool hoistSubAddAssociation(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Reassociate add/sub expressions of the form:
static bool hoistAdd(ICmpInst::Predicate Pred, Value *VariantLHS, Value *InvariantRHS, ICmpInst &ICmp, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Try to turn things like "LV + C1 < C2" into "LV < C2 - C1".
static MemoryAccess * getClobberingMemoryAccess(MemorySSA &MSSA, BatchAAResults &BAA, SinkAndHoistLICMFlags &Flags, MemoryUseOrDef *MA)
static SmallVector< PointersAndHasReadsOutsideSet, 0 > collectPromotionCandidates(MemorySSA *MSSA, AliasAnalysis *AA, Loop *L)
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,...
static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo)
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 ...
static bool hoistAddSub(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Reassociate and hoist add/sub expressions.
static bool hoistMulAddAssociation(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Try to reassociate expressions like ((A1 * B1) + (A2 * B2) + ...) * C where A1, A2,...
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)"))
static bool isOnlyMemoryAccess(const Instruction *I, const Loop *L, const MemorySSAUpdater &MSSAU)
Return true if I is the only Instruction with a MemoryAccess in L.
static cl::opt< unsigned > IntAssociationUpperLimit("licm-max-num-int-reassociations", cl::init(5U), cl::Hidden, cl::desc("Set upper limit for the number of transformations performed " "during a single round of hoisting the reassociated expressions."))
static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L, function_ref< void(Instruction *)> Fn)
static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT, Loop *CurLoop)
static bool isHoistableAndSinkableInst(Instruction &I)
Return true if-and-only-if we know how to (mechanically) both hoist and sink a given instruction out ...
static Instruction * sinkThroughTriviallyReplaceablePHI(PHINode *TPN, Instruction *I, LoopInfo *LI, SmallDenseMap< BasicBlock *, Instruction *, 32 > &SunkCopies, const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop, MemorySSAUpdater &MSSAU)
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,...
static bool hoistSub(ICmpInst::Predicate Pred, Value *VariantLHS, Value *InvariantRHS, ICmpInst &ICmp, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Try to reassociate and hoist the following two patterns: LV - C1 < C2 --> LV < C1 + C2,...
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU)
static bool isSafeToExecuteUnconditionally(Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE, const Instruction *CtxI, AssumptionCache *AC, bool AllowSpeculation)
Only sink or hoist an instruction if it is not a trapping instruction, or if the instruction is known...
static bool hoistArithmetics(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Aggregates various functions for hoisting computations out of loop.
static bool noConflictingReadWrites(Instruction *I, MemorySSA *MSSA, AAResults *AA, Loop *CurLoop, SinkAndHoistLICMFlags &Flags)
static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I)
Returns true if a PHINode is a trivially replaceable with an Instruction.
std::pair< SmallSetVector< Value *, 8 >, bool > PointersAndHasReadsOutsideSet
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.
static std::optional< uint64_t > getConstantInsertionIndex(InsertElementInst *Ins)
static bool hoistBOAssociation(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Reassociate associative binary expressions of the form.
static bool pointerInvalidatedByBlock(BasicBlock &BB, MemorySSA &MSSA, MemoryUse &MU)
This file defines the interface for the loop nest analysis.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
PassInstrumentationCallbacks PIC
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file provides a priority worklist.
static DominatorTree getDomTree(Function &F)
Remove Loads Into Fake Uses
This file defines generic set operations that may be used on set's of different types,...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
LLVM_ABI void add(const MemoryLocation &Loc)
These methods are used to add different types of instructions to the alias sets.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
LLVM_ABI void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of basic bl...
iterator begin()
Instruction iterator methods.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
bool hasTerminator() const LLVM_READONLY
Returns whether the block has a terminator.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
LLVM_ABI bool canSplitPredecessors() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
Conditional Branch instruction.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
This is the shared class of boolean and integer constants.
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
A parsed version of the target data layout string in and methods for querying it.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
static LLVM_ABI DebugLoc getMergedLocations(ArrayRef< DebugLoc > Locs)
Try to combine the vector of locations passed as input in a single one.
static DebugLoc getDropped()
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
DomTreeNodeBase * getIDom() const
Analysis pass which computes a DominatorTree.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Convenience struct for specifying and reasoning about fast-math flags.
This implementation of LoopSafetyInfo use ImplicitControlFlowTracking to give precise answers on "may...
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...
void removeInstruction(const Instruction *Inst)
Inform safety info that we are planning to remove the instruction Inst from its block.
bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop) const override
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
bool anyBlockMayThrow() const override
Returns true iff any block of the loop for which this info is contains an instruction that may throw ...
void computeLoopSafetyInfo(const Loop *CurLoop) override
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
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.
This instruction compares its operands according to the predicate given to the constructor.
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This instruction inserts a single (scalar) element into a VectorType value.
VectorType * getType() const
Overload to return most specific vector type.
LLVM_ABI void mergeDIAssignID(ArrayRef< const Instruction * > SourceInstructions)
Merge the DIAssignID metadata from this instruction and those attached to instructions in SourceInstr...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
LLVM_ABI PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
An instruction for reading from memory.
void setAlignment(Align Align)
Value * getPointerOperand()
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this load instruction.
Analysis pass that exposes the LoopInfo for a function.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
void getUniqueExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI bool wouldBeOutOfLoopUseRequiringLCSSA(const Value *V, const BasicBlock *ExitBB) const
This class represents a loop nest and can be used to query its properties.
Function * getParent() const
Return the function to which the loop-nest belongs.
Loop & getOutermostLoop() const
Return the outermost loop in the loop nest.
Captures loop safety information.
LLVM_ABI void copyColors(BasicBlock *New, BasicBlock *Old)
Copy colors of block Old into the block New.
LLVM_ABI const DenseMap< BasicBlock *, ColorVector > & getBlockColors() const
Returns block colors map that is used to update funclet operand bundles.
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...
Represents a single loop in the control flow graph.
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
BasicBlock * getBlock() const
bool onlyWritesMemory() const
Whether this function only (at most) writes memory.
bool doesNotAccessMemory() const
Whether this function accesses no memory.
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
An analysis that produces MemorySSA for a function.
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI void insertDef(MemoryDef *Def, bool RenameUses=false)
Insert a definition into the MemorySSA IR.
LLVM_ABI void insertUse(MemoryUse *Use, bool RenameUses=false)
LLVM_ABI MemoryAccess * createMemoryAccessInBB(Instruction *I, MemoryAccess *Definition, const BasicBlock *BB, MemorySSA::InsertionPlace Point, bool CreationMustSucceed=true)
Create a MemoryAccess in MemorySSA at a specified point in a block.
LLVM_ABI void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
LLVM_ABI MemoryUseOrDef * createMemoryAccessAfter(Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt)
Create a MemoryAccess in MemorySSA after an existing MemoryAccess.
LLVM_ABI void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
LLVM_ABI void wireOldPredecessorsToNewImmediatePredecessor(BasicBlock *Old, BasicBlock *New, ArrayRef< BasicBlock * > Preds, bool IdenticalEdgesWereMerged=true)
A new empty BasicBlock (New) now branches directly to Old.
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Legacy analysis pass which computes MemorySSA.
Encapsulates MemorySSA, including all data associated with memory accesses.
DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
LLVM_ABI MemorySSAWalker * getSkipSelfWalker()
AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
LLVM_ABI bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Class that has the common methods + fields of memory uses/defs.
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
Represents read-only accesses to memory.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
void setIncomingBlock(unsigned i, BasicBlock *BB)
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
PointerIntPair - This class implements a pair of a pointer and small integer.
void setInt(IntType IntVal) &
PointerTy getPointer() const
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
PredIteratorCache - This class is an extremely trivial cache for predecessor iterator queries.
size_t size(BasicBlock *BB)
ArrayRef< BasicBlock * > get(BasicBlock *BB)
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
bool empty() const
Determine if the PriorityWorklist is empty or not.
bool insert(const T &X)
Insert a new element into the PriorityWorklist.
Helper class for SSA formation on a set of values defined in multiple blocks.
The main scalar evolution driver.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
bool remove(const value_type &X)
Remove an item from the set vector.
bool empty() const
Determine if the SetVector is empty or not.
iterator begin()
Get an iterator to the beginning of the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Flags controlling how much is checked when sinking or hoisting instructions.
LLVM_ABI SinkAndHoistLICMFlags(unsigned LicmMssaOptCap, unsigned LicmMssaNoAccForPromotionCap, bool IsSink, Loop &L, MemorySSA &MSSA)
unsigned LicmMssaNoAccForPromotionCap
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
void setAlignment(Align Align)
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this store instruction.
static unsigned getPointerOperandIndex()
Represent a constant reference to a string, i.e.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
A Use represents the edge between a Value definition and its users.
const Use & getOperandUse(unsigned i) const
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
LLVM_ABI std::string getNameOrAsOperand() const
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
iterator_range< use_iterator > uses()
user_iterator_impl< User > user_iterator
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
constexpr ScalarTy getFixedValue() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
Abstract Attribute helper functions.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ C
The default llvm calling convention, compatible with C.
@ BasicBlock
Various leaf nodes.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
initializer< Ty > init(const Ty &Val)
DiagnosticInfoOptimizationBase::Argument NV
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
@ NeverOverflows
Never overflows.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, Loop *CurLoop, MemorySSAUpdater &MSSAU, bool TargetExecutesOncePerLoop, SinkAndHoistLICMFlags &LICMFlags, OptimizationRemarkEmitter *ORE=nullptr)
Returns true if is legal to hoist or sink this instruction disregarding the possible introduction of ...
auto pred_end(const MachineBasicBlock *BB)
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<>...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
auto successors(const MachineBasicBlock *BB)
constexpr from_range_t from_range
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
auto pred_size(const MachineBasicBlock *BB)
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI bool PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures, const Instruction *I, const DominatorTree *DT, bool IncludeI=false, unsigned MaxUsesToExplore=0, const LoopInfo *LI=nullptr)
PointerMayBeCapturedBefore - Return true if this pointer value may be captured by the enclosing funct...
LLVM_ABI Pass * createLICMPass()
LLVM_ABI SmallVector< BasicBlock *, 16 > collectChildrenInLoop(DominatorTree *DT, DomTreeNode *N, const Loop *CurLoop)
Does a BFS from a given node to all of its children inside a given loop.
DomTreeNodeBase< BasicBlock > DomTreeNode
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
LLVM_ABI bool hoistRegion(DomTreeNode *, AAResults *, LoopInfo *, DominatorTree *, AssumptionCache *, TargetLibraryInfo *, Loop *, MemorySSAUpdater &, ScalarEvolution *, ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *, bool, bool AllowSpeculation)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block,...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
auto reverse(ContainerTy &&C)
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI void initializeLegacyLICMPassPass(PassRegistry &)
bool isModSet(const ModRefInfo MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_TEMPLATE_ABI void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
LLVM_ABI bool isNotVisibleOnUnwind(const Value *Object, bool &RequiresNoCaptureBeforeUnwind)
Return true if Object memory is not visible after an unwind, in the sense that program semantics cann...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, 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...
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
LLVM_ABI bool salvageKnowledge(Instruction *I, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Calls BuildAssumeFromInst and if the resulting llvm.assume is valid insert if before I.
LLVM_ABI bool hasDisableLICMTransformsHint(const Loop *L)
Look for the loop attribute that disables the LICM transformation heuristics.
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
DWARFExpression::Operation Op
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool isIdentifiedFunctionLocal(const Value *V)
Return true if V is umabigously identified at the function-level.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
TinyPtrVector< BasicBlock * > ColorVector
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
auto predecessors(const MachineBasicBlock *BB)
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
LLVM_ABI bool sinkRegion(DomTreeNode *, AAResults *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, TargetTransformInfo *, Loop *CurLoop, MemorySSAUpdater &, ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *, Loop *OutermostLoop=nullptr)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block,...
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI cl::opt< unsigned > SetLicmMssaNoAccForPromotionCap
LLVM_ABI bool canHoistLoad(LoadInst &LI, AAResults *AA, DominatorTree *DT, Loop *CurLoop, MemorySSA &MSSA, bool TargetExecutesOncePerLoop, SinkAndHoistLICMFlags &LICMFlags, OptimizationRemarkEmitter *ORE=nullptr)
Returns true if it is legal to hoist LI out of CurLoop.
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Return true if this is always a dereferenceable pointer.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
bool capturesNothing(CaptureComponents CC)
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool promoteLoopAccessesToScalars(const SmallSetVector< Value *, 8 > &, SmallVectorImpl< BasicBlock * > &, SmallVectorImpl< BasicBlock::iterator > &, SmallVectorImpl< MemoryAccess * > &, PredIteratorCache &, LoopInfo *, DominatorTree *, AssumptionCache *AC, const TargetLibraryInfo *, TargetTransformInfo *, Loop *, MemorySSAUpdater &, ICFLoopSafetyInfo *, OptimizationRemarkEmitter *, bool AllowSpeculation, bool HasReadsOutsideSet)
Try to promote memory values to scalars by sinking stores out of the loop and moving loads to before ...
bool isNoModRef(const ModRefInfo MRI)
LLVM_ABI cl::opt< unsigned > SetLicmMssaOptCap
LLVM_ABI bool sinkRegionForLoopNest(DomTreeNode *, AAResults *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, TargetTransformInfo *, Loop *, MemorySSAUpdater &, ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *)
Call sinkRegion on loops contained within the specified loop in order from innermost to outermost.
bool isRefSet(const ModRefInfo MRI)
LLVM_ABI bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly)
Return true if the Object is writable, in the sense that any location based on this pointer that can ...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
This struct is a compact representation of a valid (non-zero power of two) alignment.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
TargetTransformInfo & TTI
A lightweight accessor for an operand bundle meant to be passed around by value.
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.
A CRTP mix-in to automatically provide informational APIs needed for passes.