70#define DEBUG_TYPE "loop-fusion"
73STATISTIC(NumFusionCandidates,
"Number of candidates for loop fusion");
74STATISTIC(InvalidLoopStructure,
"Loop has invalid structure");
75STATISTIC(AddressTakenBB,
"Basic block has address taken");
76STATISTIC(MayThrowException,
"Loop may throw an exception");
77STATISTIC(ContainsVolatileAccess,
"Loop contains a volatile access");
78STATISTIC(NotSimplifiedForm,
"Loop is not in simplified form");
79STATISTIC(InvalidDependencies,
"Dependencies prevent fusion");
80STATISTIC(UnknownTripCount,
"Loop has unknown trip count");
81STATISTIC(UncomputableTripCount,
"SCEV cannot compute trip count of loop");
82STATISTIC(NonEqualTripCount,
"Loop trip counts are not the same");
85 "Loop has a non-empty preheader with instructions that cannot be moved");
86STATISTIC(FusionNotBeneficial,
"Fusion is not beneficial");
87STATISTIC(NonIdenticalGuards,
"Candidates have different guards");
88STATISTIC(NonEmptyExitBlock,
"Candidate has a non-empty exit block with "
89 "instructions that cannot be moved");
90STATISTIC(NonEmptyGuardBlock,
"Candidate has a non-empty guard block with "
91 "instructions that cannot be moved");
94 "The second candidate is guarded while the first one is not");
95STATISTIC(NumHoistedInsts,
"Number of hoisted preheader instructions.");
96STATISTIC(NumSunkInsts,
"Number of hoisted preheader instructions.");
101 cl::desc(
"Max number of iterations to be peeled from a loop, such that "
102 "fusion can take place"));
107 cl::desc(
"Enable verbose debugging for Loop Fusion"),
122struct FusionCandidate {
161 : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
162 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
163 Latch(L->getLoopLatch()), L(L), Valid(
true),
164 GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(
canPeel(L)),
165 Peeled(
false), DT(DT), PDT(PDT), ORE(ORE) {
172 if (BB->hasAddressTaken()) {
174 reportInvalidCandidate(AddressTakenBB);
185 if (
SI->isVolatile()) {
192 if (LI->isVolatile()) {
198 if (
I.mayWriteToMemory())
199 MemWrites.push_back(&
I);
200 if (
I.mayReadFromMemory())
201 MemReads.push_back(&
I);
208 return Preheader && ExitingBlock && ExitBlock && Latch &&
L &&
215 assert(!
L->isInvalid() &&
"Loop is invalid!");
216 assert(Preheader ==
L->getLoopPreheader() &&
"Preheader is out of sync");
217 assert(Header ==
L->getHeader() &&
"Header is out of sync");
218 assert(ExitingBlock ==
L->getExitingBlock() &&
219 "Exiting Blocks is out of sync");
220 assert(ExitBlock ==
L->getExitBlock() &&
"Exit block is out of sync");
221 assert(Latch ==
L->getLoopLatch() &&
"Latch is out of sync");
231 return GuardBranch->getParent();
237 void updateAfterPeeling() {
238 Preheader =
L->getLoopPreheader();
239 Header =
L->getHeader();
240 ExitingBlock =
L->getExitingBlock();
241 ExitBlock =
L->getExitBlock();
242 Latch =
L->getLoopLatch();
254 assert(GuardBranch &&
"Only valid on guarded loops.");
262#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
264 dbgs() <<
"\tGuardBranch: ";
266 dbgs() << *GuardBranch;
270 << (GuardBranch ? GuardBranch->getName() :
"nullptr") <<
"\n"
271 <<
"\tPreheader: " << (Preheader ? Preheader->
getName() :
"nullptr")
273 <<
"\tHeader: " << (Header ? Header->getName() :
"nullptr") <<
"\n"
275 << (ExitingBlock ? ExitingBlock->
getName() :
"nullptr") <<
"\n"
276 <<
"\tExitBB: " << (ExitBlock ? ExitBlock->
getName() :
"nullptr")
278 <<
"\tLatch: " << (Latch ? Latch->
getName() :
"nullptr") <<
"\n"
280 << (getEntryBlock() ? getEntryBlock()->getName() :
"nullptr")
291 assert(Header &&
"Header should be guaranteed to exist!");
292 ++InvalidLoopStructure;
299 <<
" trip count not computable!\n");
303 if (!
L->isLoopSimplifyForm()) {
305 <<
" is not in simplified form!\n");
309 if (!
L->isRotatedForm()) {
333 L->getStartLoc(),
L->getHeader())
334 <<
"Loop is not a candidate for fusion");
339 L->getStartLoc(),
L->getHeader())
340 <<
"[" <<
L->getHeader()->getParent()->getName() <<
"]: "
341 <<
"Loop is not a candidate for fusion: " << Stat.getDesc());
358 dbgs() <<
"****************************\n";
359 for (
const Loop *L : LV)
361 dbgs() <<
"****************************\n";
366 OS << FC.Preheader->getName();
375 for (
const FusionCandidate &FC : CandList)
383 dbgs() <<
"Fusion Candidates: \n";
384 for (
const auto &CandidateList : FusionCandidates) {
385 dbgs() <<
"*** Fusion Candidate List ***\n";
386 dbgs() << CandidateList;
387 dbgs() <<
"****************************\n";
400struct LoopDepthTree {
401 using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
405 LoopDepthTree(LoopInfo &LI) : Depth(1) {
412 bool isRemovedLoop(
const Loop *L)
const {
return RemovedLoops.count(L); }
416 void removeLoop(
const Loop *L) { RemovedLoops.insert(L); }
420 LoopsOnLevelTy LoopsOnNextLevel;
424 if (!isRemovedLoop(L) &&
L->begin() !=
L->end())
425 LoopsOnNextLevel.emplace_back(
LoopVector(
L->begin(),
L->end()));
427 LoopsOnLevel = LoopsOnNextLevel;
428 RemovedLoops.clear();
432 bool empty()
const {
return size() == 0; }
433 size_t size()
const {
return LoopsOnLevel.size() - RemovedLoops.size(); }
434 unsigned getDepth()
const {
return Depth; }
436 iterator
begin() {
return LoopsOnLevel.begin(); }
437 iterator
end() {
return LoopsOnLevel.end(); }
438 const_iterator
begin()
const {
return LoopsOnLevel.begin(); }
439 const_iterator
end()
const {
return LoopsOnLevel.end(); }
444 SmallPtrSet<const Loop *, 8> RemovedLoops;
450 LoopsOnLevelTy LoopsOnLevel;
465 PostDominatorTree &PDT;
466 OptimizationRemarkEmitter &ORE;
468 const TargetTransformInfo &TTI;
471 LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
472 ScalarEvolution &SE, PostDominatorTree &PDT,
473 OptimizationRemarkEmitter &ORE,
const DataLayout &
DL,
474 AssumptionCache &AC,
const TargetTransformInfo &TTI)
475 : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
476 DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC), TTI(TTI) {}
481 bool fuseLoops(Function &
F) {
488 LLVM_DEBUG(
dbgs() <<
"Performing Loop Fusion on function " <<
F.getName()
492 while (!LDT.empty()) {
493 LLVM_DEBUG(
dbgs() <<
"Got " << LDT.size() <<
" loop sets for depth "
494 << LDT.getDepth() <<
"\n";);
497 assert(LV.size() > 0 &&
"Empty loop set was build!");
506 dbgs() <<
" Visit loop set (#" << LV.size() <<
"):\n";
512 collectFusionCandidates(LV);
517 FusionCandidates.clear();
543 void collectFusionCandidates(
const LoopVector &LV) {
547 FusionCandidate CurrCand(L, DT, &PDT, ORE, PP);
548 if (!CurrCand.isEligibleForFusion(SE))
556 bool FoundAdjacent =
false;
557 for (
auto &CurrCandList : FusionCandidates) {
558 if (isStrictlyAdjacent(CurrCandList.back(), CurrCand)) {
559 CurrCandList.push_back(CurrCand);
560 FoundAdjacent =
true;
561 NumFusionCandidates++;
565 <<
" to existing candidate list\n");
570 if (!FoundAdjacent) {
577 NewCandList.push_back(CurrCand);
578 FusionCandidates.push_back(NewCandList);
588 bool isBeneficialFusion(
const FusionCandidate &FC0,
589 const FusionCandidate &FC1) {
601 std::pair<bool, std::optional<unsigned>>
602 haveIdenticalTripCounts(
const FusionCandidate &FC0,
603 const FusionCandidate &FC1)
const {
604 const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
606 UncomputableTripCount++;
607 LLVM_DEBUG(
dbgs() <<
"Trip count of first loop could not be computed!");
608 return {
false, std::nullopt};
611 const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
613 UncomputableTripCount++;
614 LLVM_DEBUG(
dbgs() <<
"Trip count of second loop could not be computed!");
615 return {
false, std::nullopt};
619 << *TripCount1 <<
" are "
620 << (TripCount0 == TripCount1 ?
"identical" :
"different")
623 if (TripCount0 == TripCount1)
627 "determining the difference between trip counts\n");
631 const unsigned TC0 = SE.getSmallConstantTripCount(FC0.L);
632 const unsigned TC1 = SE.getSmallConstantTripCount(FC1.L);
636 if (TC0 == 0 || TC1 == 0) {
637 LLVM_DEBUG(
dbgs() <<
"Loop(s) do not have a single exit point or do not "
638 "have a constant number of iterations. Peeling "
639 "is not benefical\n");
640 return {
false, std::nullopt};
643 std::optional<unsigned> Difference;
644 int Diff = TC0 - TC1;
650 dbgs() <<
"Difference is less than 0. FC1 (second loop) has more "
651 "iterations than the first one. Currently not supported\n");
654 LLVM_DEBUG(
dbgs() <<
"Difference in loop trip count is: " << Difference
657 return {
false, Difference};
660 void peelFusionCandidate(FusionCandidate &FC0,
const FusionCandidate &FC1,
661 unsigned PeelCount) {
662 assert(FC0.AbleToPeel &&
"Should be able to peel loop");
665 <<
" iterations of the first loop. \n");
668 peelLoop(FC0.L, PeelCount,
false, &LI, &SE, DT, &AC,
true, VMap);
673 auto IdenticalTripCount = haveIdenticalTripCounts(FC0, FC1);
675 assert(IdenticalTripCount.first && *IdenticalTripCount.second == 0 &&
676 "Loops should have identical trip counts after peeling");
682 PDT.recalculate(*FC0.Preheader->
getParent());
684 FC0.updateAfterPeeling();
698 SmallVector<Instruction *, 8> WorkList;
700 if (Pred != FC0.ExitBlock) {
703 DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
708 for (Instruction *CurrentBranch : WorkList) {
709 BasicBlock *Succ = CurrentBranch->getSuccessor(0);
711 Succ = CurrentBranch->getSuccessor(1);
715 DTU.applyUpdates(TreeUpdates);
720 <<
" iterations from the first loop.\n"
721 "Both Loops have the same number of iterations now.\n");
731 bool fuseCandidates() {
734 for (
auto &CandidateList : FusionCandidates) {
735 if (CandidateList.size() < 2)
739 << CandidateList <<
"\n");
741 for (
auto It = CandidateList.begin(), NextIt = std::next(It);
742 NextIt != CandidateList.end(); It = NextIt, NextIt = std::next(It)) {
747 assert(!LDT.isRemovedLoop(FC0.L) &&
748 "Should not have removed loops in CandidateList!");
749 assert(!LDT.isRemovedLoop(FC1.L) &&
750 "Should not have removed loops in CandidateList!");
752 LLVM_DEBUG(
dbgs() <<
"Attempting to fuse candidate \n"; FC0.dump();
753 dbgs() <<
" with\n"; FC1.dump();
dbgs() <<
"\n");
763 std::pair<bool, std::optional<unsigned>> IdenticalTripCountRes =
764 haveIdenticalTripCounts(FC0, FC1);
765 bool SameTripCount = IdenticalTripCountRes.first;
766 std::optional<unsigned> TCDifference = IdenticalTripCountRes.second;
770 if (FC0.AbleToPeel && !SameTripCount && TCDifference) {
773 <<
"Difference in loop trip counts: " << *TCDifference
774 <<
" is greater than maximum peel count specificed: "
779 SameTripCount =
true;
783 if (!SameTripCount) {
784 LLVM_DEBUG(
dbgs() <<
"Fusion candidates do not have identical trip "
785 "counts. Not fusing.\n");
786 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
791 if ((!FC0.GuardBranch && FC1.GuardBranch) ||
792 (FC0.GuardBranch && !FC1.GuardBranch)) {
794 "another one is not. Not fusing.\n");
795 reportLoopFusion<OptimizationRemarkMissed>(
796 FC0, FC1, OnlySecondCandidateIsGuarded);
803 if (!TCDifference || *TCDifference == 0) {
804 if (FC0.GuardBranch && FC1.GuardBranch &&
805 !haveIdenticalGuards(FC0, FC1)) {
807 "guards. Not Fusing.\n");
808 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
814 if (FC0.GuardBranch) {
815 assert(FC1.GuardBranch &&
"Expecting valid FC1 guard branch");
821 "instructions in exit block. Not fusing.\n");
822 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
828 *FC1.GuardBranch->getParent(),
829 *FC0.GuardBranch->getParent()->getTerminator(), DT, &PDT,
832 "instructions in guard block. Not fusing.\n");
833 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
841 if (!dependencesAllowFusion(FC0, FC1)) {
842 LLVM_DEBUG(
dbgs() <<
"Memory dependencies do not allow fusion!\n");
843 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
844 InvalidDependencies);
851 SmallVector<Instruction *, 4> SafeToHoist;
852 SmallVector<Instruction *, 4> SafeToSink;
856 if (!isEmptyPreheader(FC1)) {
862 if (!collectMovablePreheaderInsts(FC0, FC1, SafeToHoist,
865 "Fusion Candidate Pre-header.\n"
867 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
873 bool BeneficialToFuse = isBeneficialFusion(FC0, FC1);
875 << (BeneficialToFuse ?
"" :
"un") <<
"profitable!\n");
876 if (!BeneficialToFuse) {
877 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
878 FusionNotBeneficial);
886 movePreheaderInsts(FC0, FC1, SafeToHoist, SafeToSink);
888 LLVM_DEBUG(
dbgs() <<
"\tFusion is performed: " << FC0 <<
" and " << FC1
891 FusionCandidate FC0Copy = FC0;
894 bool Peel = TCDifference && *TCDifference > 0;
896 peelFusionCandidate(FC0Copy, FC1, *TCDifference);
902 reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : FC0), FC1,
905 FusionCandidate FusedCand(performFusion((Peel ? FC0Copy : FC0), FC1),
906 DT, &PDT, ORE, FC0Copy.PP);
908 assert(FusedCand.isEligibleForFusion(SE) &&
909 "Fused candidate should be eligible for fusion!");
912 LDT.removeLoop(FC1.L);
915 It = CandidateList.erase(It);
916 It = CandidateList.erase(It);
917 It = CandidateList.insert(It, FusedCand);
922 LLVM_DEBUG(
dbgs() <<
"Candidate List (after fusion): " << CandidateList
936 bool canHoistInst(Instruction &
I,
937 const SmallVector<Instruction *, 4> &SafeToHoist,
938 const SmallVector<Instruction *, 4> &NotHoisting,
939 const FusionCandidate &FC0)
const {
941 assert(FC0PreheaderTarget &&
942 "Expected single successor for loop preheader.");
944 for (Use &
Op :
I.operands()) {
949 if (!(OpHoisted || DT.dominates(OpInst, FC0PreheaderTarget))) {
961 if (!
I.mayReadOrWriteMemory())
964 LLVM_DEBUG(
dbgs() <<
"Checking if this mem inst can be hoisted.\n");
965 for (Instruction *NotHoistedInst : NotHoisting) {
966 if (
auto D = DI.depends(&
I, NotHoistedInst)) {
969 if (
D->isFlow() ||
D->isAnti() ||
D->isOutput()) {
971 "preheader that is not being hoisted.\n");
977 for (Instruction *ReadInst : FC0.MemReads) {
978 if (
auto D = DI.depends(ReadInst, &
I)) {
981 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC0.\n");
987 for (Instruction *WriteInst : FC0.MemWrites) {
988 if (
auto D = DI.depends(WriteInst, &
I)) {
990 if (
D->isFlow() ||
D->isOutput()) {
991 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC0.\n");
1002 bool canSinkInst(Instruction &
I,
const FusionCandidate &FC1)
const {
1003 for (User *U :
I.users()) {
1016 if (!
I.mayReadOrWriteMemory())
1019 for (Instruction *ReadInst : FC1.MemReads) {
1020 if (
auto D = DI.depends(&
I, ReadInst)) {
1023 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC1.\n");
1029 for (Instruction *WriteInst : FC1.MemWrites) {
1030 if (
auto D = DI.depends(&
I, WriteInst)) {
1032 if (
D->isOutput() ||
D->isAnti()) {
1033 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC1.\n");
1044 bool collectMovablePreheaderInsts(
1045 const FusionCandidate &FC0,
const FusionCandidate &FC1,
1046 SmallVector<Instruction *, 4> &SafeToHoist,
1047 SmallVector<Instruction *, 4> &SafeToSink)
const {
1051 SmallVector<Instruction *, 4> NotHoisting;
1053 for (Instruction &
I : *FC1Preheader) {
1055 if (&
I == FC1Preheader->getTerminator())
1061 if (
I.mayThrow() || !
I.willReturn()) {
1062 LLVM_DEBUG(
dbgs() <<
"Inst: " <<
I <<
" may throw or won't return.\n");
1068 if (
I.isAtomic() ||
I.isVolatile()) {
1070 dbgs() <<
"\tInstruction is volatile or atomic. Cannot move it.\n");
1074 if (canHoistInst(
I, SafeToHoist, NotHoisting, FC0)) {
1081 if (canSinkInst(
I, FC1)) {
1091 dbgs() <<
"All preheader instructions could be sunk or hoisted!\n");
1097 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1098 const FusionCandidate &FC1, Instruction &I0,
1102 LLVM_DEBUG(
dbgs() <<
"Check dep: " << I0 <<
" vs " << I1 <<
"\n");
1105 auto DepResult = DI.depends(&I0, &I1);
1111 dbgs() <<
" [#l: " << DepResult->getLevels() <<
"][Ordered: "
1112 << (DepResult->isOrdered() ?
"true" :
"false")
1114 LLVM_DEBUG(
dbgs() <<
"DepResult Levels: " << DepResult->getLevels()
1118 unsigned Levels = DepResult->getLevels();
1119 unsigned SameSDLevels = DepResult->getSameSDLevels();
1123 if (CurLoopLevel > Levels + SameSDLevels)
1127 for (
unsigned Level = 1;
Level <= std::min(CurLoopLevel - 1, Levels);
1129 unsigned Direction = DepResult->getDirection(Level,
false);
1135 LLVM_DEBUG(
dbgs() <<
"Safe to fuse due to non-equal acceses in the "
1142 assert(CurLoopLevel > Levels &&
"Fusion candidates are not separated");
1144 if (DepResult->isScalar(CurLoopLevel,
true)) {
1145 if (DepResult->isInput() || DepResult->isOutput()) {
1147 << (DepResult->isInput() ?
"input" :
"output")
1148 <<
" dependency\n");
1153 dbgs() <<
"Not safe to fuse due to a scalar flow dependency\n");
1157 unsigned CurDir = DepResult->getDirection(CurLoopLevel,
true);
1167 LLVM_DEBUG(
dbgs() <<
"Safe to fuse with no backward loop-carried "
1173 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
1174 LLVM_DEBUG(
dbgs() <<
"TODO: Implement pred/succ dependence handling!\n");
1180 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1181 const FusionCandidate &FC1) {
1182 LLVM_DEBUG(
dbgs() <<
"Check if " << FC0 <<
" can be fused with " << FC1
1185 assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
1187 for (Instruction *WriteL0 : FC0.MemWrites) {
1188 for (Instruction *WriteL1 : FC1.MemWrites)
1189 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1192 for (Instruction *ReadL1 : FC1.MemReads)
1193 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1)) {
1198 for (Instruction *WriteL1 : FC1.MemWrites) {
1199 for (Instruction *WriteL0 : FC0.MemWrites)
1200 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1203 for (Instruction *ReadL0 : FC0.MemReads)
1204 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1)) {
1211 for (BasicBlock *BB : FC1.L->
blocks())
1212 for (Instruction &
I : *BB)
1213 for (
auto &
Op :
I.operands())
1234 bool isStrictlyAdjacent(
const FusionCandidate &FC0,
1235 const FusionCandidate &FC1)
const {
1237 if (FC0.GuardBranch)
1238 return DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()) &&
1240 return FC0.ExitBlock == FC1.getEntryBlock();
1243 bool isEmptyPreheader(
const FusionCandidate &FC)
const {
1244 return FC.Preheader->size() == 1;
1249 void movePreheaderInsts(
const FusionCandidate &FC0,
1250 const FusionCandidate &FC1,
1251 SmallVector<Instruction *, 4> &HoistInsts,
1252 SmallVector<Instruction *, 4> &SinkInsts)
const {
1255 "Attempting to sink and hoist preheader instructions, but not all "
1256 "the preheader instructions are accounted for.");
1258 NumHoistedInsts += HoistInsts.
size();
1259 NumSunkInsts += SinkInsts.
size();
1262 if (!HoistInsts.
empty())
1263 dbgs() <<
"Hoisting: \n";
1264 for (Instruction *
I : HoistInsts)
1265 dbgs() << *
I <<
"\n";
1266 if (!SinkInsts.
empty())
1267 dbgs() <<
"Sinking: \n";
1268 for (Instruction *
I : SinkInsts)
1269 dbgs() << *
I <<
"\n";
1272 for (Instruction *
I : HoistInsts) {
1273 assert(
I->getParent() == FC1.Preheader);
1274 I->moveBefore(*FC0.Preheader,
1278 for (Instruction *
I :
reverse(SinkInsts)) {
1279 assert(
I->getParent() == FC1.Preheader);
1287 "Expected the sunk PHI node to have 1 incoming value.");
1288 I->replaceAllUsesWith(
I->getOperand(0));
1289 I->eraseFromParent();
1307 bool haveIdenticalGuards(
const FusionCandidate &FC0,
1308 const FusionCandidate &FC1)
const {
1309 assert(FC0.GuardBranch && FC1.GuardBranch &&
1310 "Expecting FC0 and FC1 to be guarded loops.");
1314 if ((!FC0CmpInst || !FC1CmpInst) &&
1318 if (FC0CmpInst && FC1CmpInst && !FC0CmpInst->isIdenticalTo(FC1CmpInst))
1325 return (FC1.GuardBranch->
getSuccessor(0) == FC1.Preheader);
1327 return (FC1.GuardBranch->
getSuccessor(1) == FC1.Preheader);
1332 void simplifyLatchBranch(
const FusionCandidate &FC)
const {
1334 if (FCLatchBranch) {
1336 "Expecting the two successors of FCLatchBranch to be the same");
1337 UncondBrInst *NewBranch =
1345 void mergeLatch(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1382 Loop *performFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1383 assert(FC0.isValid() && FC1.isValid() &&
1384 "Expecting valid fusion candidates");
1387 dbgs() <<
"Fusion Candidate 1: \n"; FC1.dump(););
1396 if (FC0.GuardBranch)
1397 return fuseGuardedLoops(FC0, FC1);
1414 if (FC0.ExitingBlock != FC0.Latch)
1415 for (PHINode &
PHI : FC0.Header->
phis())
1446 DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1448 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1451 DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
1457 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1460 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1461 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1467 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1469 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1473 if (SE.isSCEVable(
PHI->getType()))
1474 SE.forgetValue(
PHI);
1475 if (
PHI->hasNUsesOrMore(1))
1478 PHI->eraseFromParent();
1486 for (PHINode *LCPHI : OriginalFC0PHIs) {
1487 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1488 assert(L1LatchBBIdx >= 0 &&
1489 "Expected loop carried value to be rewired at this point!");
1491 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1493 PHINode *L1HeaderPHI =
1500 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1509 simplifyLatchBranch(FC0);
1513 if (FC0.Latch != FC0.ExitingBlock)
1515 DominatorTree::Insert, FC0.Latch, FC1.Header));
1517 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1518 FC0.Latch, FC0.Header));
1519 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1520 FC1.Latch, FC0.Header));
1521 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1522 FC1.Latch, FC1.Header));
1525 DTU.applyUpdates(TreeUpdates);
1527 LI.removeBlock(FC1.Preheader);
1528 DTU.deleteBB(FC1.Preheader);
1530 LI.removeBlock(FC0.ExitBlock);
1531 DTU.deleteBB(FC0.ExitBlock);
1540 SE.forgetLoop(FC1.L);
1541 SE.forgetLoop(FC0.L);
1544 SmallVector<BasicBlock *, 8> Blocks(FC1.L->
blocks());
1545 for (BasicBlock *BB : Blocks) {
1548 if (LI.getLoopFor(BB) != FC1.L)
1550 LI.changeLoopFor(BB, FC0.L);
1553 const auto &ChildLoopIt = FC1.L->
begin();
1554 Loop *ChildLoop = *ChildLoopIt;
1565 SE.forgetBlockAndLoopDispositions();
1569 mergeLatch(FC0, FC1);
1573 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1596 template <
typename RemarkKind>
1597 void reportLoopFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1,
1599 assert(FC0.Preheader && FC1.Preheader &&
1600 "Expecting valid fusion candidates");
1601 using namespace ore;
1602#if LLVM_ENABLE_STATS
1607 <<
"]: " <<
NV(
"Cand1", StringRef(FC0.Preheader->
getName()))
1608 <<
" and " <<
NV(
"Cand2", StringRef(FC1.Preheader->
getName()))
1609 <<
": " << Stat.getDesc());
1628 Loop *fuseGuardedLoops(
const FusionCandidate &FC0,
1629 const FusionCandidate &FC1) {
1630 assert(FC0.GuardBranch && FC1.GuardBranch &&
"Expecting guarded loops");
1632 BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
1633 BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
1634 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1635 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1643 (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
1650 assert(FC0NonLoopBlock == FC1GuardBlock &&
"Loops are not adjacent");
1663 FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
1665 BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
1669 FC1.GuardBranch->eraseFromParent();
1670 new UnreachableInst(FC1GuardBlock->
getContext(), FC1GuardBlock);
1673 DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1675 DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1677 DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1679 DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1683 DominatorTree::Delete, FC0.ExitBlock, FC0ExitBlockSuccessor));
1686 DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
1688 new UnreachableInst(FC0ExitBlockSuccessor->
getContext(),
1689 FC0ExitBlockSuccessor);
1693 "Expecting guard block to have no predecessors");
1695 "Expecting guard block to have no successors");
1710 if (FC0.ExitingBlock != FC0.Latch)
1711 for (PHINode &
PHI : FC0.Header->
phis())
1714 assert(OriginalFC0PHIs.
empty() &&
"Expecting OriginalFC0PHIs to be empty!");
1737 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1739 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1750 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1756 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1758 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1762 if (SE.isSCEVable(
PHI->getType()))
1763 SE.forgetValue(
PHI);
1764 if (
PHI->hasNUsesOrMore(1))
1767 PHI->eraseFromParent();
1775 for (PHINode *LCPHI : OriginalFC0PHIs) {
1776 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1777 assert(L1LatchBBIdx >= 0 &&
1778 "Expected loop carried value to be rewired at this point!");
1780 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1782 PHINode *L1HeaderPHI =
1789 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1800 simplifyLatchBranch(FC0);
1804 if (FC0.Latch != FC0.ExitingBlock)
1806 DominatorTree::Insert, FC0.Latch, FC1.Header));
1808 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1809 FC0.Latch, FC0.Header));
1810 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1811 FC1.Latch, FC0.Header));
1812 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1813 FC1.Latch, FC1.Header));
1822 DTU.applyUpdates(TreeUpdates);
1824 LI.removeBlock(FC1GuardBlock);
1825 LI.removeBlock(FC1.Preheader);
1826 LI.removeBlock(FC0.ExitBlock);
1828 LI.removeBlock(FC0ExitBlockSuccessor);
1829 DTU.deleteBB(FC0ExitBlockSuccessor);
1831 DTU.deleteBB(FC1GuardBlock);
1832 DTU.deleteBB(FC1.Preheader);
1833 DTU.deleteBB(FC0.ExitBlock);
1840 SE.forgetLoop(FC1.L);
1841 SE.forgetLoop(FC0.L);
1844 SmallVector<BasicBlock *, 8> Blocks(FC1.L->
blocks());
1845 for (BasicBlock *BB : Blocks) {
1848 if (LI.getLoopFor(BB) != FC1.L)
1850 LI.changeLoopFor(BB, FC0.L);
1853 const auto &ChildLoopIt = FC1.L->
begin();
1854 Loop *ChildLoop = *ChildLoopIt;
1865 SE.forgetBlockAndLoopDispositions();
1869 mergeLatch(FC0, FC1);
1873 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1901 for (
auto &L : LI) {
1908 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 LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
static void printFusionCandidates(const FusionCandidateCollection &FusionCandidates)
std::list< FusionCandidate > FusionCandidateList
SmallVector< FusionCandidateList, 4 > FusionCandidateCollection
static void printLoopVector(const LoopVector &LV)
SmallVector< Loop *, 4 > LoopVector
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
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
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; assumes that the block is well-formed.
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
A parsed version of the target data layout string in and methods for querying it.
AnalysisPass to compute dependence information in a function.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
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.
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.
LLVM_ABI 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.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
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.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
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.
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
@ BasicBlock
Various leaf nodes.
@ Valid
The data is already valid.
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
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.
LLVM_ABI void moveInstructionsToTheEnd(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI, ScalarEvolution &SE)
Move instructions, in an order-preserving manner, from FromBB to the end of ToBB when proven safe.
LLVM_ABI void moveInstructionsToTheBeginning(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI, ScalarEvolution &SE)
Move instructions, in an order-preserving manner, from FromBB to the beginning of ToBB when proven sa...
LLVM_ABI bool canPeel(const Loop *L)
auto reverse(ContainerTy &&C)
LLVM_ABI 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.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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 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 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.
LLVM_ABI void printLoop(const Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
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.