70#define DEBUG_TYPE "loop-fusion"
73STATISTIC(NumFusionCandidates,
"Number of candidates for loop fusion");
74STATISTIC(InvalidPreheader,
"Loop has invalid preheader");
76STATISTIC(InvalidExitingBlock,
"Loop has invalid exiting blocks");
77STATISTIC(InvalidExitBlock,
"Loop has invalid exit block");
80STATISTIC(AddressTakenBB,
"Basic block has address taken");
81STATISTIC(MayThrowException,
"Loop may throw an exception");
82STATISTIC(ContainsVolatileAccess,
"Loop contains a volatile access");
83STATISTIC(NotSimplifiedForm,
"Loop is not in simplified form");
84STATISTIC(InvalidDependencies,
"Dependencies prevent fusion");
85STATISTIC(UnknownTripCount,
"Loop has unknown trip count");
86STATISTIC(UncomputableTripCount,
"SCEV cannot compute trip count of loop");
87STATISTIC(NonEqualTripCount,
"Loop trip counts are not the same");
91 "Loop has a non-empty preheader with instructions that cannot be moved");
92STATISTIC(FusionNotBeneficial,
"Fusion is not beneficial");
93STATISTIC(NonIdenticalGuards,
"Candidates have different guards");
94STATISTIC(NonEmptyExitBlock,
"Candidate has a non-empty exit block with "
95 "instructions that cannot be moved");
96STATISTIC(NonEmptyGuardBlock,
"Candidate has a non-empty guard block with "
97 "instructions that cannot be moved");
100 "The second candidate is guarded while the first one is not");
101STATISTIC(NumHoistedInsts,
"Number of hoisted preheader instructions.");
102STATISTIC(NumSunkInsts,
"Number of hoisted preheader instructions.");
112 "loop-fusion-dependence-analysis",
113 cl::desc(
"Which dependence analysis should loop fusion use?"),
115 "Use the scalar evolution interface"),
117 "Use the dependence analysis interface"),
119 "Use all available analyses")),
124 cl::desc(
"Max number of iterations to be peeled from a loop, such that "
125 "fusion can take place"));
130 cl::desc(
"Enable verbose debugging for Loop Fusion"),
145struct FusionCandidate {
188 : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
189 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
190 Latch(L->getLoopLatch()), L(L), Valid(
true),
191 GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(
canPeel(L)),
192 Peeled(
false), DT(DT), PDT(PDT), ORE(ORE) {
199 if (BB->hasAddressTaken()) {
201 reportInvalidCandidate(AddressTakenBB);
212 if (
SI->isVolatile()) {
219 if (LI->isVolatile()) {
225 if (
I.mayWriteToMemory())
226 MemWrites.push_back(&
I);
227 if (
I.mayReadFromMemory())
228 MemReads.push_back(&
I);
235 return Preheader && Header && ExitingBlock && ExitBlock && Latch &&
L &&
236 !
L->isInvalid() && Valid;
242 assert(!
L->isInvalid() &&
"Loop is invalid!");
243 assert(Preheader ==
L->getLoopPreheader() &&
"Preheader is out of sync");
244 assert(Header ==
L->getHeader() &&
"Header is out of sync");
245 assert(ExitingBlock ==
L->getExitingBlock() &&
246 "Exiting Blocks is out of sync");
247 assert(ExitBlock ==
L->getExitBlock() &&
"Exit block is out of sync");
248 assert(Latch ==
L->getLoopLatch() &&
"Latch is out of sync");
265 void updateAfterPeeling() {
266 Preheader =
L->getLoopPreheader();
267 Header =
L->getHeader();
268 ExitingBlock =
L->getExitingBlock();
269 ExitBlock =
L->getExitBlock();
270 Latch =
L->getLoopLatch();
282 assert(GuardBranch &&
"Only valid on guarded loops.");
284 "Expecting guard to be a conditional branch.");
292#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
294 dbgs() <<
"\tGuardBranch: ";
296 dbgs() << *GuardBranch;
300 << (GuardBranch ? GuardBranch->
getName() :
"nullptr") <<
"\n"
301 <<
"\tPreheader: " << (Preheader ? Preheader->
getName() :
"nullptr")
303 <<
"\tHeader: " << (Header ? Header->getName() :
"nullptr") <<
"\n"
305 << (ExitingBlock ? ExitingBlock->
getName() :
"nullptr") <<
"\n"
306 <<
"\tExitBB: " << (ExitBlock ? ExitBlock->
getName() :
"nullptr")
308 <<
"\tLatch: " << (Latch ? Latch->
getName() :
"nullptr") <<
"\n"
310 << (getEntryBlock() ? getEntryBlock()->getName() :
"nullptr")
326 ++InvalidExitingBlock;
340 <<
" trip count not computable!\n");
344 if (!
L->isLoopSimplifyForm()) {
346 <<
" is not in simplified form!\n");
350 if (!
L->isRotatedForm()) {
373 assert(L && Preheader &&
"Fusion candidate not initialized properly!");
377 L->getStartLoc(), Preheader)
379 <<
"Loop is not a candidate for fusion: " << Stat.getDesc());
385struct FusionCandidateCompare {
396 bool operator()(
const FusionCandidate &
LHS,
397 const FusionCandidate &
RHS)
const {
398 const DominatorTree *DT = &(
LHS.DT);
405 assert(DT &&
LHS.PDT &&
"Expecting valid dominator tree");
408 if (DT->
dominates(RHSEntryBlock, LHSEntryBlock)) {
411 assert(
LHS.PDT->dominates(LHSEntryBlock, RHSEntryBlock));
415 if (DT->
dominates(LHSEntryBlock, RHSEntryBlock)) {
417 assert(
LHS.PDT->dominates(RHSEntryBlock, LHSEntryBlock));
429 if (WrongOrder && RightOrder) {
436 }
else if (WrongOrder)
445 "No dominance relationship between these fusion candidates!");
461using FusionCandidateSet = std::set<FusionCandidate, FusionCandidateCompare>;
466 const FusionCandidate &FC) {
468 OS <<
FC.Preheader->getName();
476 const FusionCandidateSet &CandSet) {
477 for (
const FusionCandidate &FC : CandSet)
484printFusionCandidates(
const FusionCandidateCollection &FusionCandidates) {
485 dbgs() <<
"Fusion Candidates: \n";
486 for (
const auto &CandidateSet : FusionCandidates) {
487 dbgs() <<
"*** Fusion Candidate Set ***\n";
488 dbgs() << CandidateSet;
489 dbgs() <<
"****************************\n";
500struct LoopDepthTree {
501 using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
505 LoopDepthTree(LoopInfo &LI) : Depth(1) {
507 LoopsOnLevel.emplace_back(LoopVector(LI.
rbegin(), LI.
rend()));
512 bool isRemovedLoop(
const Loop *L)
const {
return RemovedLoops.count(L); }
516 void removeLoop(
const Loop *L) { RemovedLoops.insert(L); }
520 LoopsOnLevelTy LoopsOnNextLevel;
522 for (
const LoopVector &LV : *
this)
524 if (!isRemovedLoop(L) &&
L->begin() !=
L->end())
525 LoopsOnNextLevel.emplace_back(LoopVector(
L->begin(),
L->end()));
527 LoopsOnLevel = LoopsOnNextLevel;
528 RemovedLoops.clear();
532 bool empty()
const {
return size() == 0; }
533 size_t size()
const {
return LoopsOnLevel.size() - RemovedLoops.size(); }
534 unsigned getDepth()
const {
return Depth; }
536 iterator
begin() {
return LoopsOnLevel.begin(); }
537 iterator
end() {
return LoopsOnLevel.end(); }
538 const_iterator
begin()
const {
return LoopsOnLevel.begin(); }
539 const_iterator
end()
const {
return LoopsOnLevel.end(); }
544 SmallPtrSet<const Loop *, 8> RemovedLoops;
550 LoopsOnLevelTy LoopsOnLevel;
554static void printLoopVector(
const LoopVector &LV) {
555 dbgs() <<
"****************************\n";
558 dbgs() <<
"****************************\n";
565 FusionCandidateCollection FusionCandidates;
574 PostDominatorTree &PDT;
575 OptimizationRemarkEmitter &ORE;
577 const TargetTransformInfo &TTI;
580 LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
581 ScalarEvolution &SE, PostDominatorTree &PDT,
582 OptimizationRemarkEmitter &ORE,
const DataLayout &
DL,
583 AssumptionCache &AC,
const TargetTransformInfo &TTI)
584 : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
585 DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC), TTI(TTI) {}
590 bool fuseLoops(Function &
F) {
597 LLVM_DEBUG(
dbgs() <<
"Performing Loop Fusion on function " <<
F.getName()
601 while (!LDT.empty()) {
602 LLVM_DEBUG(
dbgs() <<
"Got " << LDT.size() <<
" loop sets for depth "
603 << LDT.getDepth() <<
"\n";);
605 for (
const LoopVector &LV : LDT) {
606 assert(LV.size() > 0 &&
"Empty loop set was build!");
615 dbgs() <<
" Visit loop set (#" << LV.size() <<
"):\n";
621 collectFusionCandidates(LV);
633 FusionCandidates.clear();
658 const FusionCandidate &FC1)
const {
659 assert(FC0.Preheader && FC1.Preheader &&
"Expecting valid preheaders");
661 return ::isControlFlowEquivalent(*FC0.getEntryBlock(), *FC1.getEntryBlock(),
668 void collectFusionCandidates(
const LoopVector &LV) {
672 FusionCandidate CurrCand(L, DT, &PDT, ORE, PP);
673 if (!CurrCand.isEligibleForFusion(SE))
681 bool FoundSet =
false;
683 for (
auto &CurrCandSet : FusionCandidates) {
685 CurrCandSet.insert(CurrCand);
690 <<
" to existing candidate set\n");
701 FusionCandidateSet NewCandSet;
702 NewCandSet.insert(CurrCand);
703 FusionCandidates.push_back(NewCandSet);
705 NumFusionCandidates++;
714 bool isBeneficialFusion(
const FusionCandidate &FC0,
715 const FusionCandidate &FC1) {
727 std::pair<bool, std::optional<unsigned>>
728 haveIdenticalTripCounts(
const FusionCandidate &FC0,
729 const FusionCandidate &FC1)
const {
730 const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
732 UncomputableTripCount++;
733 LLVM_DEBUG(
dbgs() <<
"Trip count of first loop could not be computed!");
734 return {
false, std::nullopt};
737 const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
739 UncomputableTripCount++;
740 LLVM_DEBUG(
dbgs() <<
"Trip count of second loop could not be computed!");
741 return {
false, std::nullopt};
745 << *TripCount1 <<
" are "
746 << (TripCount0 == TripCount1 ?
"identical" :
"different")
749 if (TripCount0 == TripCount1)
753 "determining the difference between trip counts\n");
757 const unsigned TC0 = SE.getSmallConstantTripCount(FC0.L);
758 const unsigned TC1 = SE.getSmallConstantTripCount(FC1.L);
762 if (TC0 == 0 || TC1 == 0) {
763 LLVM_DEBUG(
dbgs() <<
"Loop(s) do not have a single exit point or do not "
764 "have a constant number of iterations. Peeling "
765 "is not benefical\n");
766 return {
false, std::nullopt};
769 std::optional<unsigned> Difference;
770 int Diff = TC0 - TC1;
776 dbgs() <<
"Difference is less than 0. FC1 (second loop) has more "
777 "iterations than the first one. Currently not supported\n");
780 LLVM_DEBUG(
dbgs() <<
"Difference in loop trip count is: " << Difference
783 return {
false, Difference};
786 void peelFusionCandidate(FusionCandidate &FC0,
const FusionCandidate &FC1,
787 unsigned PeelCount) {
788 assert(FC0.AbleToPeel &&
"Should be able to peel loop");
791 <<
" iterations of the first loop. \n");
795 peelLoop(FC0.L, PeelCount,
false, &LI, &SE, DT, &AC,
true, VMap);
800 auto IdenticalTripCount = haveIdenticalTripCounts(FC0, FC1);
802 assert(IdenticalTripCount.first && *IdenticalTripCount.second == 0 &&
803 "Loops should have identical trip counts after peeling");
809 PDT.recalculate(*FC0.Preheader->
getParent());
811 FC0.updateAfterPeeling();
825 SmallVector<Instruction *, 8> WorkList;
827 if (Pred != FC0.ExitBlock) {
830 DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
835 for (Instruction *CurrentBranch : WorkList) {
836 BasicBlock *Succ = CurrentBranch->getSuccessor(0);
838 Succ = CurrentBranch->getSuccessor(1);
842 DTU.applyUpdates(TreeUpdates);
847 <<
" iterations from the first loop.\n"
848 "Both Loops have the same number of iterations now.\n");
859 bool fuseCandidates() {
861 LLVM_DEBUG(printFusionCandidates(FusionCandidates));
862 for (
auto &CandidateSet : FusionCandidates) {
863 if (CandidateSet.size() < 2)
867 << CandidateSet <<
"\n");
869 for (
auto FC0 = CandidateSet.begin(); FC0 != CandidateSet.end(); ++FC0) {
870 assert(!LDT.isRemovedLoop(FC0->L) &&
871 "Should not have removed loops in CandidateSet!");
873 for (++FC1; FC1 != CandidateSet.end(); ++FC1) {
874 assert(!LDT.isRemovedLoop(FC1->L) &&
875 "Should not have removed loops in CandidateSet!");
877 LLVM_DEBUG(
dbgs() <<
"Attempting to fuse candidate \n"; FC0->dump();
878 dbgs() <<
" with\n"; FC1->dump();
dbgs() <<
"\n");
888 std::pair<bool, std::optional<unsigned>> IdenticalTripCountRes =
889 haveIdenticalTripCounts(*FC0, *FC1);
890 bool SameTripCount = IdenticalTripCountRes.first;
891 std::optional<unsigned> TCDifference = IdenticalTripCountRes.second;
895 if (FC0->AbleToPeel && !SameTripCount && TCDifference) {
898 <<
"Difference in loop trip counts: " << *TCDifference
899 <<
" is greater than maximum peel count specificed: "
904 SameTripCount =
true;
908 if (!SameTripCount) {
909 LLVM_DEBUG(
dbgs() <<
"Fusion candidates do not have identical trip "
910 "counts. Not fusing.\n");
911 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
916 if (!isAdjacent(*FC0, *FC1)) {
918 <<
"Fusion candidates are not adjacent. Not fusing.\n");
919 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, NonAdjacent);
923 if ((!FC0->GuardBranch && FC1->GuardBranch) ||
924 (FC0->GuardBranch && !FC1->GuardBranch)) {
926 "another one is not. Not fusing.\n");
927 reportLoopFusion<OptimizationRemarkMissed>(
928 *FC0, *FC1, OnlySecondCandidateIsGuarded);
934 if (FC0->GuardBranch && FC1->GuardBranch &&
935 !haveIdenticalGuards(*FC0, *FC1) && !TCDifference) {
937 "guards. Not Fusing.\n");
938 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
943 if (FC0->GuardBranch) {
944 assert(FC1->GuardBranch &&
"Expecting valid FC1 guard branch");
950 "instructions in exit block. Not fusing.\n");
951 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
958 *FC0->GuardBranch->
getParent()->getTerminator(), DT, &PDT,
961 <<
"Fusion candidate contains unsafe "
962 "instructions in guard block. Not fusing.\n");
963 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
971 if (!dependencesAllowFusion(*FC0, *FC1)) {
972 LLVM_DEBUG(
dbgs() <<
"Memory dependencies do not allow fusion!\n");
973 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
974 InvalidDependencies);
981 SmallVector<Instruction *, 4> SafeToHoist;
982 SmallVector<Instruction *, 4> SafeToSink;
986 if (!isEmptyPreheader(*FC1)) {
992 if (!collectMovablePreheaderInsts(*FC0, *FC1, SafeToHoist,
995 "Fusion Candidate Pre-header.\n"
997 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
1003 bool BeneficialToFuse = isBeneficialFusion(*FC0, *FC1);
1005 <<
"\tFusion appears to be "
1006 << (BeneficialToFuse ?
"" :
"un") <<
"profitable!\n");
1007 if (!BeneficialToFuse) {
1008 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
1009 FusionNotBeneficial);
1017 movePreheaderInsts(*FC0, *FC1, SafeToHoist, SafeToSink);
1019 LLVM_DEBUG(
dbgs() <<
"\tFusion is performed: " << *FC0 <<
" and "
1022 FusionCandidate FC0Copy = *FC0;
1025 bool Peel = TCDifference && *TCDifference > 0;
1027 peelFusionCandidate(FC0Copy, *FC1, *TCDifference);
1033 reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : *FC0), *FC1,
1036 FusionCandidate FusedCand(
1037 performFusion((Peel ? FC0Copy : *FC0), *FC1), DT, &PDT, ORE,
1040 assert(FusedCand.isEligibleForFusion(SE) &&
1041 "Fused candidate should be eligible for fusion!");
1044 LDT.removeLoop(FC1->L);
1046 CandidateSet.erase(FC0);
1047 CandidateSet.erase(FC1);
1049 auto InsertPos = CandidateSet.insert(FusedCand);
1051 assert(InsertPos.second &&
1052 "Unable to insert TargetCandidate in CandidateSet!");
1057 FC0 = FC1 = InsertPos.first;
1059 LLVM_DEBUG(
dbgs() <<
"Candidate Set (after fusion): " << CandidateSet
1074 bool canHoistInst(Instruction &
I,
1075 const SmallVector<Instruction *, 4> &SafeToHoist,
1076 const SmallVector<Instruction *, 4> &NotHoisting,
1077 const FusionCandidate &FC0)
const {
1079 assert(FC0PreheaderTarget &&
1080 "Expected single successor for loop preheader.");
1082 for (Use &
Op :
I.operands()) {
1087 if (!(OpHoisted || DT.dominates(OpInst, FC0PreheaderTarget))) {
1099 if (!
I.mayReadOrWriteMemory())
1102 LLVM_DEBUG(
dbgs() <<
"Checking if this mem inst can be hoisted.\n");
1103 for (Instruction *NotHoistedInst : NotHoisting) {
1104 if (
auto D = DI.depends(&
I, NotHoistedInst)) {
1107 if (
D->isFlow() ||
D->isAnti() ||
D->isOutput()) {
1109 "preheader that is not being hoisted.\n");
1115 for (Instruction *ReadInst : FC0.MemReads) {
1116 if (
auto D = DI.depends(ReadInst, &
I)) {
1119 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC0.\n");
1125 for (Instruction *WriteInst : FC0.MemWrites) {
1126 if (
auto D = DI.depends(WriteInst, &
I)) {
1128 if (
D->isFlow() ||
D->isOutput()) {
1129 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC0.\n");
1140 bool canSinkInst(Instruction &
I,
const FusionCandidate &FC1)
const {
1141 for (User *U :
I.users()) {
1154 if (!
I.mayReadOrWriteMemory())
1157 for (Instruction *ReadInst : FC1.MemReads) {
1158 if (
auto D = DI.depends(&
I, ReadInst)) {
1161 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC1.\n");
1167 for (Instruction *WriteInst : FC1.MemWrites) {
1168 if (
auto D = DI.depends(&
I, WriteInst)) {
1170 if (
D->isOutput() ||
D->isAnti()) {
1171 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC1.\n");
1186 const FusionCandidate &FC0,
1187 const FusionCandidate &FC1)
const {
1188 for (Instruction *Inst : SafeToSink) {
1193 for (
unsigned I = 0;
I <
Phi->getNumIncomingValues();
I++) {
1194 if (
Phi->getIncomingBlock(
I) != FC0.Latch)
1196 assert(FC1.Latch &&
"FC1 latch is not set");
1197 Phi->setIncomingBlock(
I, FC1.Latch);
1204 bool collectMovablePreheaderInsts(
1205 const FusionCandidate &FC0,
const FusionCandidate &FC1,
1206 SmallVector<Instruction *, 4> &SafeToHoist,
1207 SmallVector<Instruction *, 4> &SafeToSink)
const {
1211 SmallVector<Instruction *, 4> NotHoisting;
1213 for (Instruction &
I : *FC1Preheader) {
1215 if (&
I == FC1Preheader->getTerminator())
1221 if (
I.mayThrow() || !
I.willReturn()) {
1222 LLVM_DEBUG(
dbgs() <<
"Inst: " <<
I <<
" may throw or won't return.\n");
1228 if (
I.isAtomic() ||
I.isVolatile()) {
1230 dbgs() <<
"\tInstruction is volatile or atomic. Cannot move it.\n");
1234 if (canHoistInst(
I, SafeToHoist, NotHoisting, FC0)) {
1241 if (canSinkInst(
I, FC1)) {
1251 dbgs() <<
"All preheader instructions could be sunk or hoisted!\n");
1256 class AddRecLoopReplacer :
public SCEVRewriteVisitor<AddRecLoopReplacer> {
1258 AddRecLoopReplacer(ScalarEvolution &SE,
const Loop &OldL,
const Loop &NewL,
1260 : SCEVRewriteVisitor(SE), Valid(
true), UseMax(UseMax), OldL(OldL),
1263 const SCEV *visitAddRecExpr(
const SCEVAddRecExpr *Expr) {
1264 const Loop *ExprL = Expr->
getLoop();
1266 if (ExprL == &OldL) {
1271 if (OldL.contains(ExprL)) {
1273 if (!UseMax || !Pos || !Expr->
isAffine()) {
1285 bool wasValidSCEV()
const {
return Valid; }
1289 const Loop &OldL, &NewL;
1294 bool accessDiffIsPositive(
const Loop &L0,
const Loop &L1, Instruction &I0,
1295 Instruction &I1,
bool EqualIsInvalid) {
1301 const SCEV *SCEVPtr0 = SE.getSCEVAtScope(Ptr0, &L0);
1302 const SCEV *SCEVPtr1 = SE.getSCEVAtScope(Ptr1, &L1);
1305 LLVM_DEBUG(
dbgs() <<
" Access function check: " << *SCEVPtr0 <<
" vs "
1306 << *SCEVPtr1 <<
"\n");
1308 AddRecLoopReplacer
Rewriter(SE, L0, L1);
1309 SCEVPtr0 =
Rewriter.visit(SCEVPtr0);
1312 LLVM_DEBUG(
dbgs() <<
" Access function after rewrite: " << *SCEVPtr0
1313 <<
" [Valid: " <<
Rewriter.wasValidSCEV() <<
"]\n");
1323 auto HasNonLinearDominanceRelation = [&](
const SCEV *S) {
1333 ICmpInst::Predicate Pred =
1334 EqualIsInvalid ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_SGE;
1335 bool IsAlwaysGE = SE.isKnownPredicate(Pred, SCEVPtr0, SCEVPtr1);
1339 << (IsAlwaysGE ?
" >= " :
" may < ") << *SCEVPtr1
1348 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1349 const FusionCandidate &FC1, Instruction &I0,
1350 Instruction &I1,
bool AnyDep,
1354 LLVM_DEBUG(
dbgs() <<
"Check dep: " << I0 <<
" vs " << I1 <<
" : "
1355 << DepChoice <<
"\n");
1358 switch (DepChoice) {
1360 return accessDiffIsPositive(*FC0.L, *FC1.L, I0, I1, AnyDep);
1362 auto DepResult = DI.depends(&I0, &I1);
1368 dbgs() <<
" [#l: " << DepResult->getLevels() <<
"][Ordered: "
1369 << (DepResult->isOrdered() ?
"true" :
"false")
1371 LLVM_DEBUG(
dbgs() <<
"DepResult Levels: " << DepResult->getLevels()
1375 unsigned Levels = DepResult->getLevels();
1376 unsigned SameSDLevels = DepResult->getSameSDLevels();
1380 if (CurLoopLevel > Levels + SameSDLevels)
1384 for (
unsigned Level = 1;
Level <= std::min(CurLoopLevel - 1, Levels);
1386 unsigned Direction = DepResult->getDirection(Level,
false);
1392 LLVM_DEBUG(
dbgs() <<
"Safe to fuse due to non-equal acceses in the "
1399 assert(CurLoopLevel > Levels &&
"Fusion candidates are not separated");
1401 unsigned CurDir = DepResult->getDirection(CurLoopLevel,
true);
1411 LLVM_DEBUG(
dbgs() <<
"Safe to fuse with no backward loop-carried "
1417 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
1419 dbgs() <<
"TODO: Implement pred/succ dependence handling!\n");
1426 return dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
1428 dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
1436 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1437 const FusionCandidate &FC1) {
1438 LLVM_DEBUG(
dbgs() <<
"Check if " << FC0 <<
" can be fused with " << FC1
1441 assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
1443 for (Instruction *WriteL0 : FC0.MemWrites) {
1444 for (Instruction *WriteL1 : FC1.MemWrites)
1445 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
1448 InvalidDependencies++;
1451 for (Instruction *ReadL1 : FC1.MemReads)
1452 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1,
1455 InvalidDependencies++;
1460 for (Instruction *WriteL1 : FC1.MemWrites) {
1461 for (Instruction *WriteL0 : FC0.MemWrites)
1462 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
1465 InvalidDependencies++;
1468 for (Instruction *ReadL0 : FC0.MemReads)
1469 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1,
1472 InvalidDependencies++;
1479 for (BasicBlock *BB : FC1.L->
blocks())
1480 for (Instruction &
I : *BB)
1481 for (
auto &
Op :
I.operands())
1484 InvalidDependencies++;
1500 bool isAdjacent(
const FusionCandidate &FC0,
1501 const FusionCandidate &FC1)
const {
1503 if (FC0.GuardBranch)
1504 return FC0.getNonLoopBlock() == FC1.getEntryBlock();
1506 return FC0.ExitBlock == FC1.getEntryBlock();
1509 bool isEmptyPreheader(
const FusionCandidate &FC)
const {
1510 return FC.Preheader->size() == 1;
1515 void movePreheaderInsts(
const FusionCandidate &FC0,
1516 const FusionCandidate &FC1,
1517 SmallVector<Instruction *, 4> &HoistInsts,
1518 SmallVector<Instruction *, 4> &SinkInsts)
const {
1521 "Attempting to sink and hoist preheader instructions, but not all "
1522 "the preheader instructions are accounted for.");
1524 NumHoistedInsts += HoistInsts.
size();
1525 NumSunkInsts += SinkInsts.
size();
1528 if (!HoistInsts.
empty())
1529 dbgs() <<
"Hoisting: \n";
1530 for (Instruction *
I : HoistInsts)
1531 dbgs() << *
I <<
"\n";
1532 if (!SinkInsts.
empty())
1533 dbgs() <<
"Sinking: \n";
1534 for (Instruction *
I : SinkInsts)
1535 dbgs() << *
I <<
"\n";
1538 for (Instruction *
I : HoistInsts) {
1539 assert(
I->getParent() == FC1.Preheader);
1540 I->moveBefore(*FC0.Preheader,
1544 for (Instruction *
I :
reverse(SinkInsts)) {
1545 assert(
I->getParent() == FC1.Preheader);
1550 fixPHINodes(SinkInsts, FC0, FC1);
1565 bool haveIdenticalGuards(
const FusionCandidate &FC0,
1566 const FusionCandidate &FC1)
const {
1567 assert(FC0.GuardBranch && FC1.GuardBranch &&
1568 "Expecting FC0 and FC1 to be guarded loops.");
1570 if (
auto FC0CmpInst =
1572 if (
auto FC1CmpInst =
1574 if (!FC0CmpInst->isIdenticalTo(FC1CmpInst))
1581 return (FC1.GuardBranch->
getSuccessor(0) == FC1.Preheader);
1583 return (FC1.GuardBranch->
getSuccessor(1) == FC1.Preheader);
1588 void simplifyLatchBranch(
const FusionCandidate &FC)
const {
1590 if (FCLatchBranch) {
1593 "Expecting the two successors of FCLatchBranch to be the same");
1594 BranchInst *NewBranch =
1602 void mergeLatch(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1639 Loop *performFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1640 assert(FC0.isValid() && FC1.isValid() &&
1641 "Expecting valid fusion candidates");
1644 dbgs() <<
"Fusion Candidate 1: \n"; FC1.dump(););
1653 if (FC0.GuardBranch)
1654 return fuseGuardedLoops(FC0, FC1);
1671 if (FC0.ExitingBlock != FC0.Latch)
1672 for (PHINode &
PHI : FC0.Header->
phis())
1703 DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1705 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1708 DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
1714 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1717 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1718 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1724 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1726 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1730 if (SE.isSCEVable(
PHI->getType()))
1731 SE.forgetValue(
PHI);
1732 if (
PHI->hasNUsesOrMore(1))
1735 PHI->eraseFromParent();
1743 for (PHINode *LCPHI : OriginalFC0PHIs) {
1744 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1745 assert(L1LatchBBIdx >= 0 &&
1746 "Expected loop carried value to be rewired at this point!");
1748 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1750 PHINode *L1HeaderPHI =
1757 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1766 simplifyLatchBranch(FC0);
1770 if (FC0.Latch != FC0.ExitingBlock)
1772 DominatorTree::Insert, FC0.Latch, FC1.Header));
1774 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1775 FC0.Latch, FC0.Header));
1776 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1777 FC1.Latch, FC0.Header));
1778 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1779 FC1.Latch, FC1.Header));
1782 DTU.applyUpdates(TreeUpdates);
1784 LI.removeBlock(FC1.Preheader);
1785 DTU.deleteBB(FC1.Preheader);
1787 LI.removeBlock(FC0.ExitBlock);
1788 DTU.deleteBB(FC0.ExitBlock);
1797 SE.forgetLoop(FC1.L);
1798 SE.forgetLoop(FC0.L);
1801 SE.forgetBlockAndLoopDispositions();
1805 mergeLatch(FC0, FC1);
1808 SmallVector<BasicBlock *, 8> Blocks(FC1.L->
blocks());
1809 for (BasicBlock *BB : Blocks) {
1812 if (LI.getLoopFor(BB) != FC1.L)
1814 LI.changeLoopFor(BB, FC0.L);
1817 const auto &ChildLoopIt = FC1.L->
begin();
1818 Loop *ChildLoop = *ChildLoopIt;
1828 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1851 template <
typename RemarkKind>
1852 void reportLoopFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1,
1854 assert(FC0.Preheader && FC1.Preheader &&
1855 "Expecting valid fusion candidates");
1856 using namespace ore;
1857#if LLVM_ENABLE_STATS
1862 <<
"]: " <<
NV(
"Cand1", StringRef(FC0.Preheader->
getName()))
1863 <<
" and " <<
NV(
"Cand2", StringRef(FC1.Preheader->
getName()))
1864 <<
": " << Stat.getDesc());
1883 Loop *fuseGuardedLoops(
const FusionCandidate &FC0,
1884 const FusionCandidate &FC1) {
1885 assert(FC0.GuardBranch && FC1.GuardBranch &&
"Expecting guarded loops");
1889 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1890 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1898 (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
1905 assert(FC0NonLoopBlock == FC1GuardBlock &&
"Loops are not adjacent");
1920 BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
1925 new UnreachableInst(FC1GuardBlock->
getContext(), FC1GuardBlock);
1928 DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1930 DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1932 DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1934 DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1939 DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
1941 new UnreachableInst(FC0ExitBlockSuccessor->
getContext(),
1942 FC0ExitBlockSuccessor);
1946 "Expecting guard block to have no predecessors");
1948 "Expecting guard block to have no successors");
1963 if (FC0.ExitingBlock != FC0.Latch)
1964 for (PHINode &
PHI : FC0.Header->
phis())
1967 assert(OriginalFC0PHIs.
empty() &&
"Expecting OriginalFC0PHIs to be empty!");
1990 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1992 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
2003 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
2009 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
2011 DominatorTree::Delete, FC1.Preheader, FC1.Header));
2015 if (SE.isSCEVable(
PHI->getType()))
2016 SE.forgetValue(
PHI);
2017 if (
PHI->hasNUsesOrMore(1))
2020 PHI->eraseFromParent();
2028 for (PHINode *LCPHI : OriginalFC0PHIs) {
2029 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
2030 assert(L1LatchBBIdx >= 0 &&
2031 "Expected loop carried value to be rewired at this point!");
2033 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
2035 PHINode *L1HeaderPHI =
2042 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
2053 simplifyLatchBranch(FC0);
2057 if (FC0.Latch != FC0.ExitingBlock)
2059 DominatorTree::Insert, FC0.Latch, FC1.Header));
2061 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
2062 FC0.Latch, FC0.Header));
2063 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
2064 FC1.Latch, FC0.Header));
2065 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
2066 FC1.Latch, FC1.Header));
2075 DTU.applyUpdates(TreeUpdates);
2077 LI.removeBlock(FC1GuardBlock);
2078 LI.removeBlock(FC1.Preheader);
2079 LI.removeBlock(FC0.ExitBlock);
2081 LI.removeBlock(FC0ExitBlockSuccessor);
2082 DTU.deleteBB(FC0ExitBlockSuccessor);
2084 DTU.deleteBB(FC1GuardBlock);
2085 DTU.deleteBB(FC1.Preheader);
2086 DTU.deleteBB(FC0.ExitBlock);
2093 SE.forgetLoop(FC1.L);
2094 SE.forgetLoop(FC0.L);
2097 SE.forgetBlockAndLoopDispositions();
2101 mergeLatch(FC0, FC1);
2104 SmallVector<BasicBlock *, 8> Blocks(FC1.L->
blocks());
2105 for (BasicBlock *BB : Blocks) {
2108 if (LI.getLoopFor(BB) != FC1.L)
2110 LI.changeLoopFor(BB, FC0.L);
2113 const auto &ChildLoopIt = FC1.L->
begin();
2114 Loop *ChildLoop = *ChildLoopIt;
2124 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2152 for (
auto &L : LI) {
2159 LoopFuser LF(LI, DT, DI, SE, PDT, ORE,
DL, AC,
TTI);
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static bool reportInvalidCandidate(const Instruction &I, llvm::Statistic &Stat)
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
static cl::opt< FusionDependenceAnalysisChoice > FusionDependenceAnalysis("loop-fusion-dependence-analysis", cl::desc("Which dependence analysis should loop fusion use?"), cl::values(clEnumValN(FUSION_DEPENDENCE_ANALYSIS_SCEV, "scev", "Use the scalar evolution interface"), clEnumValN(FUSION_DEPENDENCE_ANALYSIS_DA, "da", "Use the dependence analysis interface"), clEnumValN(FUSION_DEPENDENCE_ANALYSIS_ALL, "all", "Use all available analyses")), cl::Hidden, cl::init(FUSION_DEPENDENCE_ANALYSIS_ALL))
FusionDependenceAnalysisChoice
@ FUSION_DEPENDENCE_ANALYSIS_DA
@ FUSION_DEPENDENCE_ANALYSIS_ALL
@ FUSION_DEPENDENCE_ANALYSIS_SCEV
static cl::opt< bool > VerboseFusionDebugging("loop-fusion-verbose-debug", cl::desc("Enable verbose debugging for Loop Fusion"), cl::Hidden, cl::init(false))
static cl::opt< unsigned > FusionPeelMaxCount("loop-fusion-peel-max-count", cl::init(0), cl::Hidden, cl::desc("Max number of iterations to be peeled from a loop, such that " "fusion can take place"))
This file implements the Loop Fusion pass.
Loop::LoopBounds::Direction Direction
mir Rename Register Operands
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
void visit(MachineFunction &MF, MachineBasicBlock &Start, std::function< void(MachineBasicBlock *)> op)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Virtual Register Rewriter
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
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.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
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.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
const Instruction & front() const
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
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...
Conditional or Unconditional Branch instruction.
bool isConditional() const
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
Value * getCondition() const
A parsed version of the target data layout string in and methods for querying it.
AnalysisPass to compute dependence information in a function.
unsigned getLevel() const
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
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.
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.
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.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
iterator_range< block_iterator > blocks() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
reverse_iterator rend() const
reverse_iterator rbegin() const
Represents a single loop in the control flow graph.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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 PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
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.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
const SCEV * getStart() const
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
const Loop * getLoop() const
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
ArrayRef< const SCEV * > operands() const
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
const ParentTy * getParent() const
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< DefNode * > Def
NodeAddr< PhiNode * > Phi
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
LLVM_ABI void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
FunctionAddr VTableAddr Value
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
bool succ_empty(const Instruction *I)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
bool canPeel(const Loop *L)
LLVM_ABI void moveInstructionsToTheEnd(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI)
Move instructions, in an order-preserving manner, from FromBB to the end of ToBB when proven safe.
DomTreeNodeBase< BasicBlock > DomTreeNode
auto reverse(ContainerTy &&C)
TargetTransformInfo::PeelingPreferences gatherPeelingPreferences(Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, std::optional< bool > UserAllowPeeling, std::optional< bool > UserAllowProfileBasedPeeling, bool UnrollingSpecficValues=false)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI bool isControlFlowEquivalent(const Instruction &I0, const Instruction &I1, const DominatorTree &DT, const PostDominatorTree &PDT)
Return true if I0 and I1 are control flow equivalent.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI bool nonStrictlyPostDominate(const BasicBlock *ThisBlock, const BasicBlock *OtherBlock, const DominatorTree *DT, const PostDominatorTree *PDT)
In case that two BBs ThisBlock and OtherBlock are control flow equivalent but they do not strictly do...
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 raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void moveInstructionsToTheBeginning(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI)
Move instructions, in an order-preserving manner, from FromBB to the beginning of ToBB when proven sa...
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
bool pred_empty(const BasicBlock *BB)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isSafeToMoveBefore(Instruction &I, Instruction &InsertPoint, DominatorTree &DT, const PostDominatorTree *PDT=nullptr, DependenceInfo *DI=nullptr, bool CheckForEntireBlock=false)
Return true if I can be safely moved before InsertPoint.
bool peelLoop(Loop *L, unsigned PeelCount, bool PeelLast, LoopInfo *LI, ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC, bool PreserveLCSSA, ValueToValueMapTy &VMap)
VMap is the value-map that maps instructions from the original loop to instructions in the last peele...
LLVM_ABI void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.