72#define DEBUG_TYPE "loop-fusion"
75STATISTIC(NumFusionCandidates,
"Number of candidates for loop fusion");
76STATISTIC(InvalidLoopStructure,
"Loop has invalid structure");
77STATISTIC(AddressTakenBB,
"Basic block has address taken");
78STATISTIC(MayThrowException,
"Loop may throw an exception");
79STATISTIC(ContainsVolatileAccess,
"Loop contains a volatile access");
80STATISTIC(ContainsAtomicAccess,
"Loop contains an atomic access");
81STATISTIC(NotSimplifiedForm,
"Loop is not in simplified form");
82STATISTIC(InvalidDependencies,
"Dependencies prevent fusion");
83STATISTIC(UnknownTripCount,
"Loop has unknown trip count");
84STATISTIC(UncomputableTripCount,
"SCEV cannot compute trip count of loop");
85STATISTIC(NonEqualTripCount,
"Loop trip counts are not the same");
88 "Loop has a non-empty preheader with instructions that cannot be moved");
89STATISTIC(FusionNotBeneficial,
"Fusion is not beneficial");
90STATISTIC(NonIdenticalGuards,
"Candidates have different guards");
91STATISTIC(NonEmptyExitBlock,
"Candidate has a non-empty exit block with "
92 "instructions that cannot be moved");
93STATISTIC(NonEmptyGuardBlock,
"Candidate has a non-empty guard block with "
94 "instructions that cannot be moved");
97 "The second candidate is guarded while the first one is not");
98STATISTIC(NumHoistedInsts,
"Number of hoisted preheader instructions.");
99STATISTIC(NumSunkInsts,
"Number of sunk preheader instructions.");
113struct FusionCandidate {
152 : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
153 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
154 Latch(L->getLoopLatch()), L(L), Valid(
true),
155 GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(
canPeel(L)),
156 Peeled(
false), DT(DT), PDT(PDT), ORE(ORE) {
163 if (BB->hasAddressTaken()) {
166 reportInvalidCandidate(
"AddressTakenBB",
167 "Basic block has address taken");
176 "Loop may throw an exception");
179 if (
I.isVolatile()) {
181 ++ContainsVolatileAccess;
183 "Loop contains a volatile access");
191 ++ContainsAtomicAccess;
193 "Loop contains an atomic access");
196 if (
I.mayWriteToMemory())
197 MemWrites.push_back(&
I);
198 if (
I.mayReadFromMemory())
199 MemReads.push_back(&
I);
206 return Preheader && ExitingBlock && ExitBlock && Latch &&
L &&
213 assert(!
L->isInvalid() &&
"Loop is invalid!");
214 assert(Preheader ==
L->getLoopPreheader() &&
"Preheader is out of sync");
215 assert(Header ==
L->getHeader() &&
"Header is out of sync");
216 assert(ExitingBlock ==
L->getExitingBlock() &&
217 "Exiting Blocks is out of sync");
218 assert(ExitBlock ==
L->getExitBlock() &&
"Exit block is out of sync");
219 assert(Latch ==
L->getLoopLatch() &&
"Latch is out of sync");
235 void updateAfterPeeling() {
236 Preheader =
L->getLoopPreheader();
237 Header =
L->getHeader();
238 ExitingBlock =
L->getExitingBlock();
239 ExitBlock =
L->getExitBlock();
240 Latch =
L->getLoopLatch();
252 assert(GuardBranch &&
"Only valid on guarded loops.");
260#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
262 dbgs() <<
"\tGuardBranch: ";
264 dbgs() << *GuardBranch;
268 << (GuardBranch ? GuardBranch->
getName() :
"nullptr") <<
"\n"
269 <<
"\tPreheader: " << (Preheader ? Preheader->
getName() :
"nullptr")
271 <<
"\tHeader: " << (Header ? Header->getName() :
"nullptr") <<
"\n"
273 << (ExitingBlock ? ExitingBlock->
getName() :
"nullptr") <<
"\n"
274 <<
"\tExitBB: " << (ExitBlock ? ExitBlock->
getName() :
"nullptr")
276 <<
"\tLatch: " << (Latch ? Latch->
getName() :
"nullptr") <<
"\n"
278 << (getEntryBlock() ? getEntryBlock()->getName() :
"nullptr")
289 assert(Header &&
"Header should be guaranteed to exist!");
290 ++InvalidLoopStructure;
297 <<
" trip count not computable!\n");
300 "Loop has unknown trip count");
303 if (!
L->isLoopSimplifyForm()) {
305 <<
" is not in simplified form!\n");
308 "Loop is not in simplified form");
311 if (!
L->isRotatedForm()) {
340 L->getStartLoc(),
L->getHeader())
341 <<
"Loop is not a candidate for fusion");
344 L->getStartLoc(),
L->getHeader())
345 <<
"[" <<
L->getHeader()->getParent()->getName() <<
"]: "
346 <<
"Loop is not a candidate for fusion: " << RemarkMsg);
362 dbgs() <<
"****************************\n";
363 for (
const Loop *L : LV)
365 dbgs() <<
"****************************\n";
370 OS << FC.Preheader->getName();
379 for (
const FusionCandidate &FC : CandList)
387 dbgs() <<
"Fusion Candidates: \n";
388 for (
const auto &CandidateList : FusionCandidates) {
389 dbgs() <<
"*** Fusion Candidate List ***\n";
390 dbgs() << CandidateList;
391 dbgs() <<
"****************************\n";
418 if (!L->isLoopSimplifyForm() || !L->isRotatedForm())
421 BasicBlock *Preheader = L->getLoopPreheader();
422 BasicBlock *ExitBlock = L->getUniqueExitBlock();
434 BasicBlock *SkipBB = GuardBI->getSuccessor(0) == Preheader
435 ? GuardBI->getSuccessor(1)
436 : GuardBI->getSuccessor(0);
437 if (SkipBB == Preheader)
448 if (!MergeBB || MergeBB == SkipBB || MergeBB == GuardBB ||
459 <<
" of loop " << L->getHeader()->getName() <<
"\n");
462 GuardBI->replaceSuccessorWith(SkipBB, MergeBB);
484struct LoopDepthTree {
485 using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
489 LoopDepthTree(LoopInfo &LI) : Depth(1) {
496 bool isRemovedLoop(
const Loop *L)
const {
return RemovedLoops.count(L); }
500 void removeLoop(
const Loop *L) { RemovedLoops.insert(L); }
504 LoopsOnLevelTy LoopsOnNextLevel;
508 if (!isRemovedLoop(L) &&
L->begin() !=
L->end())
509 LoopsOnNextLevel.emplace_back(
LoopVector(
L->begin(),
L->end()));
511 LoopsOnLevel = LoopsOnNextLevel;
512 RemovedLoops.clear();
516 bool empty()
const {
return size() == 0; }
517 size_t size()
const {
return LoopsOnLevel.size() - RemovedLoops.size(); }
518 unsigned getDepth()
const {
return Depth; }
520 iterator
begin() {
return LoopsOnLevel.begin(); }
521 iterator
end() {
return LoopsOnLevel.end(); }
522 const_iterator
begin()
const {
return LoopsOnLevel.begin(); }
523 const_iterator
end()
const {
return LoopsOnLevel.end(); }
528 SmallPtrSet<const Loop *, 8> RemovedLoops;
534 LoopsOnLevelTy LoopsOnLevel;
539 const ScalarOptions &Opts;
551 PostDominatorTree &PDT;
552 OptimizationRemarkEmitter &ORE;
554 const TargetTransformInfo &TTI;
557 LoopFuser(
const ScalarOptions &Opts, LoopInfo &LI, DominatorTree &DT,
558 DependenceInfo &DI, ScalarEvolution &SE, PostDominatorTree &PDT,
559 OptimizationRemarkEmitter &ORE, AssumptionCache &AC,
560 const TargetTransformInfo &TTI)
561 : Opts(Opts), LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy),
562 LI(LI), DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC), TTI(TTI) {}
569 if (Opts.loop_fusion_verbose_debug) {
574 LLVM_DEBUG(
dbgs() <<
"Performing Loop Fusion on function " <<
F.getName()
578 while (!LDT.empty()) {
579 LLVM_DEBUG(
dbgs() <<
"Got " << LDT.size() <<
" loop sets for depth "
580 << LDT.getDepth() <<
"\n";);
583 assert(LV.size() > 0 &&
"Empty loop set was build!");
590 if (Opts.loop_fusion_verbose_debug) {
592 dbgs() <<
" Visit loop set (#" << LV.size() <<
"):\n";
598 collectFusionCandidates(LV);
603 FusionCandidates.clear();
629 void collectFusionCandidates(
const LoopVector &LV) {
633 FusionCandidate CurrCand(L, DT, &PDT, ORE, PP);
634 if (!CurrCand.isEligibleForFusion(SE))
642 bool FoundAdjacent =
false;
643 for (
auto &CurrCandList : FusionCandidates) {
644 if (isStrictlyAdjacent(CurrCandList.back(), CurrCand)) {
645 CurrCandList.push_back(CurrCand);
646 FoundAdjacent =
true;
647 NumFusionCandidates++;
649 if (Opts.loop_fusion_verbose_debug)
651 <<
" to existing candidate list\n");
656 if (!FoundAdjacent) {
659 if (Opts.loop_fusion_verbose_debug)
663 NewCandList.push_back(CurrCand);
664 FusionCandidates.push_back(NewCandList);
674 bool isBeneficialFusion(
const FusionCandidate &FC0,
675 const FusionCandidate &FC1) {
684 std::optional<int64_t>
685 calculateTripCountDiff(
const FusionCandidate &FC0,
686 const FusionCandidate &FC1)
const {
687 const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
689 UncomputableTripCount++;
690 LLVM_DEBUG(
dbgs() <<
"Trip count of first loop could not be computed!");
694 const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
696 UncomputableTripCount++;
697 LLVM_DEBUG(
dbgs() <<
"Trip count of second loop could not be computed!");
702 << *TripCount1 <<
" are "
703 << (TripCount0 == TripCount1 ?
"identical" :
"different")
706 if (TripCount0 == TripCount1)
710 "determining the difference between trip counts\n");
717 static_cast<int64_t
>(SE.getSmallConstantTripCount(FC0.L));
719 static_cast<int64_t
>(SE.getSmallConstantTripCount(FC1.L));
723 if (TC0 == 0 || TC1 == 0) {
724 LLVM_DEBUG(
dbgs() <<
"Loop(s) do not have a single exit point or do not "
725 "have a constant number of iterations. Peeling "
726 "is not benefical\n");
733 void peelFusionCandidate(FusionCandidate &FC0,
const FusionCandidate &FC1,
734 unsigned PeelCount) {
735 assert(FC0.AbleToPeel &&
"Should be able to peel loop");
738 <<
" iterations of the first loop. \n");
744 peelLoop(FC0.L, PeelCount,
false, &LI, &SE, DT, &AC,
750 auto TCDiff = calculateTripCountDiff(FC0, FC1);
752 assert(TCDiff && *TCDiff == 0 &&
753 "Loops should have identical trip counts after peeling");
759 PDT.recalculate(*FC0.Preheader->
getParent());
761 FC0.updateAfterPeeling();
775 SmallVector<Instruction *, 8> WorkList;
777 if (Pred != FC0.ExitBlock) {
780 DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
785 for (Instruction *CurrentBranch : WorkList) {
786 BasicBlock *Succ = CurrentBranch->getSuccessor(0);
788 Succ = CurrentBranch->getSuccessor(1);
792 DTU.applyUpdates(TreeUpdates);
797 <<
" iterations from the first loop.\n"
798 "Both Loops have the same number of iterations now.\n");
808 bool fuseCandidates() {
811 for (
auto &CandidateList : FusionCandidates) {
812 if (CandidateList.size() < 2)
816 << CandidateList <<
"\n");
818 for (
auto It = CandidateList.begin(), NextIt = std::next(It);
819 NextIt != CandidateList.end(); It = NextIt, NextIt = std::next(It)) {
821 const FusionCandidate &FC0 = *It;
822 const FusionCandidate &FC1 = *NextIt;
824 assert(!LDT.isRemovedLoop(FC0.L) &&
825 "Should not have removed loops in CandidateList!");
826 assert(!LDT.isRemovedLoop(FC1.L) &&
827 "Should not have removed loops in CandidateList!");
829 LLVM_DEBUG(
dbgs() <<
"Attempting to fuse candidate \n"; FC0.dump();
830 dbgs() <<
" with\n"; FC1.dump();
dbgs() <<
"\n");
835 std::optional<int64_t> TCDifference = calculateTripCountDiff(FC0, FC1);
840 bool WillPeel = FC0.AbleToPeel && TCDifference && *TCDifference > 0 &&
841 *TCDifference <= static_cast<int64_t>(
842 Opts.loop_fusion_peel_max_count);
844 if (!WillPeel && (!TCDifference || *TCDifference != 0)) {
845 LLVM_DEBUG(
dbgs() <<
"Fusion candidates do not have identical trip "
846 "counts and peeling is not supported for this "
847 "case. Not fusing.\n");
849 reportLoopFusion<OptimizationRemarkMissed>(
850 FC0, FC1,
"NonEqualTripCount",
851 "Loop trip counts are not the same");
855 if ((!FC0.GuardBranch && FC1.GuardBranch) ||
856 (FC0.GuardBranch && !FC1.GuardBranch)) {
858 "another one is not. Not fusing.\n");
859 ++OnlySecondCandidateIsGuarded;
860 reportLoopFusion<OptimizationRemarkMissed>(
861 FC0, FC1,
"OnlySecondCandidateIsGuarded",
862 "The second candidate is guarded while the first one is not");
872 if (FC0.GuardBranch && FC1.GuardBranch &&
873 !haveIdenticalGuards(FC0, FC1)) {
875 "guards. Not Fusing.\n");
876 ++NonIdenticalGuards;
877 reportLoopFusion<OptimizationRemarkMissed>(
878 FC0, FC1,
"NonIdenticalGuards",
879 "Candidates have different guards");
883 if (FC0.GuardBranch) {
884 assert(FC1.GuardBranch &&
"Expecting valid FC1 guard branch");
890 "instructions in exit block. Not fusing.\n");
892 reportLoopFusion<OptimizationRemarkMissed>(
893 FC0, FC1,
"NonEmptyExitBlock",
894 "Candidate has a non-empty exit block with "
895 "instructions that cannot be moved");
901 *FC0.GuardBranch->
getParent()->getTerminator(), DT, &PDT,
904 "instructions in guard block. Not fusing.\n");
905 ++NonEmptyGuardBlock;
906 reportLoopFusion<OptimizationRemarkMissed>(
907 FC0, FC1,
"NonEmptyGuardBlock",
908 "Candidate has a non-empty guard block with "
909 "instructions that cannot be moved");
916 if (!dependencesAllowFusion(FC0, FC1)) {
917 LLVM_DEBUG(
dbgs() <<
"Memory dependencies do not allow fusion!\n");
918 ++InvalidDependencies;
919 reportLoopFusion<OptimizationRemarkMissed>(
920 FC0, FC1,
"InvalidDependencies",
"Dependencies prevent fusion");
927 SmallVector<Instruction *, 4> SafeToHoist;
928 SmallVector<Instruction *, 4> SafeToSink;
932 if (!isEmptyPreheader(FC1)) {
938 if (!collectMovablePreheaderInsts(FC0, FC1, SafeToHoist,
941 "Fusion Candidate Pre-header.\n"
944 reportLoopFusion<OptimizationRemarkMissed>(
945 FC0, FC1,
"NonEmptyPreheader",
946 "Loop has a non-empty preheader with instructions that "
952 bool BeneficialToFuse = isBeneficialFusion(FC0, FC1);
954 << (BeneficialToFuse ?
"" :
"un") <<
"profitable!\n");
955 if (!BeneficialToFuse) {
956 ++FusionNotBeneficial;
957 reportLoopFusion<OptimizationRemarkMissed>(
958 FC0, FC1,
"FusionNotBeneficial",
"Fusion is not beneficial");
966 movePreheaderInsts(FC0, FC1, SafeToHoist, SafeToSink);
968 LLVM_DEBUG(
dbgs() <<
"\tFusion is performed: " << FC0 <<
" and " << FC1
971 FusionCandidate FC0Copy = FC0;
974 bool Peel = TCDifference && *TCDifference > 0;
976 peelFusionCandidate(FC0Copy, FC1, *TCDifference);
983 reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : FC0), FC1,
984 "FuseCounter",
"Loops fused");
986 FusionCandidate FusedCand(performFusion((Peel ? FC0Copy : FC0), FC1),
987 DT, &PDT, ORE, FC0Copy.PP);
989 assert(FusedCand.isEligibleForFusion(SE) &&
990 "Fused candidate should be eligible for fusion!");
993 LDT.removeLoop(FC1.L);
996 It = CandidateList.erase(It);
997 It = CandidateList.erase(It);
998 It = CandidateList.insert(It, FusedCand);
1003 LLVM_DEBUG(
dbgs() <<
"Candidate List (after fusion): " << CandidateList
1017 bool canHoistInst(Instruction &
I,
1018 const SmallVector<Instruction *, 4> &SafeToHoist,
1019 const SmallVector<Instruction *, 4> &NotHoisting,
1020 const FusionCandidate &FC0)
const {
1022 assert(FC0PreheaderTarget &&
1023 "Expected single successor for loop preheader.");
1025 for (Use &
Op :
I.operands()) {
1030 if (!(OpHoisted || DT.dominates(OpInst, FC0PreheaderTarget))) {
1042 if (!
I.mayReadOrWriteMemory())
1045 LLVM_DEBUG(
dbgs() <<
"Checking if this mem inst can be hoisted.\n");
1046 for (Instruction *NotHoistedInst : NotHoisting) {
1047 if (
auto D = DI.depends(&
I, NotHoistedInst)) {
1050 if (
D->isFlow() ||
D->isAnti() ||
D->isOutput()) {
1052 "preheader that is not being hoisted.\n");
1058 for (Instruction *ReadInst : FC0.MemReads) {
1059 if (
auto D = DI.depends(ReadInst, &
I)) {
1062 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC0.\n");
1068 for (Instruction *WriteInst : FC0.MemWrites) {
1069 if (
auto D = DI.depends(WriteInst, &
I)) {
1071 if (
D->isFlow() ||
D->isOutput()) {
1072 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC0.\n");
1083 bool canSinkInst(Instruction &
I,
const FusionCandidate &FC1)
const {
1084 for (User *U :
I.users()) {
1097 if (!
I.mayReadOrWriteMemory())
1100 for (Instruction *ReadInst : FC1.MemReads) {
1101 if (
auto D = DI.depends(&
I, ReadInst)) {
1104 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC1.\n");
1110 for (Instruction *WriteInst : FC1.MemWrites) {
1111 if (
auto D = DI.depends(&
I, WriteInst)) {
1113 if (
D->isOutput() ||
D->isAnti()) {
1114 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC1.\n");
1125 bool collectMovablePreheaderInsts(
1126 const FusionCandidate &FC0,
const FusionCandidate &FC1,
1127 SmallVector<Instruction *, 4> &SafeToHoist,
1128 SmallVector<Instruction *, 4> &SafeToSink)
const {
1132 SmallVector<Instruction *, 4> NotHoisting;
1134 for (Instruction &
I : *FC1Preheader) {
1136 if (&
I == FC1Preheader->getTerminator())
1142 if (
I.mayThrow() || !
I.willReturn()) {
1143 LLVM_DEBUG(
dbgs() <<
"Inst: " <<
I <<
" may throw or won't return.\n");
1149 if (
I.isAtomic() ||
I.isVolatile()) {
1151 dbgs() <<
"\tInstruction is volatile or atomic. Cannot move it.\n");
1155 if (canHoistInst(
I, SafeToHoist, NotHoisting, FC0)) {
1162 if (canSinkInst(
I, FC1)) {
1172 dbgs() <<
"All preheader instructions could be sunk or hoisted!\n");
1178 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1179 const FusionCandidate &FC1, Instruction &I0,
1182 if (Opts.loop_fusion_verbose_debug) {
1183 LLVM_DEBUG(
dbgs() <<
"Check dep: " << I0 <<
" vs " << I1 <<
"\n");
1186 auto DepResult = DI.depends(&I0, &I1);
1194 if (S0->getValueOperand() ==
S1->getValueOperand())
1198 if (Opts.loop_fusion_verbose_debug) {
1200 dbgs() <<
" [#l: " << DepResult->getLevels() <<
"][Ordered: "
1201 << (DepResult->isOrdered() ?
"true" :
"false")
1203 LLVM_DEBUG(
dbgs() <<
"DepResult Levels: " << DepResult->getLevels()
1207 unsigned Levels = DepResult->getLevels();
1208 unsigned SameSDLevels = DepResult->getSameSDLevels();
1212 if (CurLoopLevel > Levels + SameSDLevels)
1216 for (
unsigned Level = 1;
Level <= std::min(CurLoopLevel - 1, Levels);
1218 unsigned Direction = DepResult->getDirection(Level,
false);
1224 LLVM_DEBUG(
dbgs() <<
"Safe to fuse due to non-equal acceses in the "
1231 assert(CurLoopLevel > Levels &&
"Fusion candidates are not separated");
1233 if (DepResult->isScalar(CurLoopLevel,
true)) {
1234 if (DepResult->isInput() || DepResult->isOutput()) {
1236 << (DepResult->isInput() ?
"input" :
"output")
1237 <<
" dependency\n");
1248 unsigned CurDir = DepResult->getDirection(CurLoopLevel,
true);
1251 LLVM_DEBUG(
dbgs() <<
"Safe to fuse same-iteration scalar dependence\n");
1256 dbgs() <<
"Not safe to fuse due to a scalar flow dependency\n");
1260 unsigned CurDir = DepResult->getDirection(CurLoopLevel,
true);
1270 LLVM_DEBUG(
dbgs() <<
"Safe to fuse with no backward loop-carried "
1276 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
1277 LLVM_DEBUG(
dbgs() <<
"TODO: Implement pred/succ dependence handling!\n");
1283 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1284 const FusionCandidate &FC1) {
1285 LLVM_DEBUG(
dbgs() <<
"Check if " << FC0 <<
" can be fused with " << FC1
1288 assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
1292 for (BasicBlock *BB : FC1.L->
blocks())
1293 for (Instruction &
I : *BB)
1294 for (
auto &
Op :
I.operands())
1300 for (Instruction *WriteL0 : FC0.MemWrites) {
1301 for (Instruction *WriteL1 : FC1.MemWrites)
1302 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1305 for (Instruction *ReadL1 : FC1.MemReads)
1306 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1)) {
1313 for (Instruction *ReadL0 : FC0.MemReads)
1314 for (Instruction *WriteL1 : FC1.MemWrites)
1315 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1)) {
1334 bool isStrictlyAdjacent(
const FusionCandidate &FC0,
1335 const FusionCandidate &FC1)
const {
1337 if (FC0.GuardBranch)
1338 return DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()) &&
1340 return FC0.ExitBlock == FC1.getEntryBlock();
1343 bool isEmptyPreheader(
const FusionCandidate &FC)
const {
1344 return FC.Preheader->size() == 1;
1349 void movePreheaderInsts(
const FusionCandidate &FC0,
1350 const FusionCandidate &FC1,
1351 SmallVector<Instruction *, 4> &HoistInsts,
1352 SmallVector<Instruction *, 4> &SinkInsts)
const {
1355 "Attempting to sink and hoist preheader instructions, but not all "
1356 "the preheader instructions are accounted for.");
1358 NumHoistedInsts += HoistInsts.
size();
1359 NumSunkInsts += SinkInsts.
size();
1361 LLVM_DEBUG(
if (Opts.loop_fusion_verbose_debug) {
1362 if (!HoistInsts.empty())
1363 dbgs() <<
"Hoisting: \n";
1364 for (Instruction *I : HoistInsts)
1365 dbgs() << *I <<
"\n";
1366 if (!SinkInsts.empty())
1367 dbgs() <<
"Sinking: \n";
1368 for (Instruction *I : SinkInsts)
1369 dbgs() << *I <<
"\n";
1372 for (Instruction *
I : HoistInsts) {
1373 assert(
I->getParent() == FC1.Preheader);
1374 I->moveBefore(*FC0.Preheader,
1378 for (Instruction *
I :
reverse(SinkInsts)) {
1379 assert(
I->getParent() == FC1.Preheader);
1387 "Expected the sunk PHI node to have 1 incoming value.");
1388 I->replaceAllUsesWith(
I->getOperand(0));
1389 I->eraseFromParent();
1407 bool haveIdenticalGuards(
const FusionCandidate &FC0,
1408 const FusionCandidate &FC1)
const {
1409 assert(FC0.GuardBranch && FC1.GuardBranch &&
1410 "Expecting FC0 and FC1 to be guarded loops.");
1414 if ((!FC0CmpInst || !FC1CmpInst) &&
1418 if (FC0CmpInst && FC1CmpInst && !FC0CmpInst->isIdenticalTo(FC1CmpInst))
1425 return (FC1.GuardBranch->
getSuccessor(0) == FC1.Preheader);
1426 return (FC1.GuardBranch->
getSuccessor(1) == FC1.Preheader);
1431 void simplifyLatchBranch(
const FusionCandidate &FC)
const {
1433 if (FCLatchBranch) {
1435 "Expecting the two successors of FCLatchBranch to be the same");
1436 UncondBrInst *NewBranch =
1444 void mergeLatch(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1456 void rewireFusedHeaderPHIsAndLatches(
1457 const FusionCandidate &FC0,
const FusionCandidate &FC1,
1458 const SmallVectorImpl<PHINode *> &OriginalFC0PHIs,
1459 SmallVectorImpl<DominatorTree::UpdateType> &TreeUpdates) {
1462 if (SE.isSCEVable(
PHI->getType()))
1463 SE.forgetValue(
PHI);
1464 if (
PHI->hasNUsesOrMore(1))
1467 PHI->eraseFromParent();
1475 for (PHINode *LCPHI : OriginalFC0PHIs) {
1476 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1477 assert(L1LatchBBIdx >= 0 &&
1478 "Expected loop carried value to be rewired at this point!");
1480 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1482 PHINode *L1HeaderPHI =
1489 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1498 simplifyLatchBranch(FC0);
1502 if (FC0.Latch != FC0.ExitingBlock)
1504 DominatorTree::Insert, FC0.Latch, FC1.Header));
1506 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1507 FC0.Latch, FC0.Header));
1508 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1509 FC1.Latch, FC0.Header));
1510 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1511 FC1.Latch, FC1.Header));
1517 Loop *finalizeFusedLoop(
const FusionCandidate &FC0,
1518 const FusionCandidate &FC1) {
1523 SE.forgetLoop(FC1.L);
1524 SE.forgetLoop(FC0.L);
1527 SmallVector<BasicBlock *, 8> Blocks(FC1.L->
blocks());
1528 for (BasicBlock *BB : Blocks) {
1531 if (LI.getLoopFor(BB) != FC1.L)
1533 LI.changeLoopFor(BB, FC0.L);
1536 const auto &ChildLoopIt = FC1.L->
begin();
1537 Loop *ChildLoop = *ChildLoopIt;
1548 SE.forgetBlockAndLoopDispositions();
1552 mergeLatch(FC0, FC1);
1556 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1596 Loop *performFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1597 assert(FC0.isValid() && FC1.isValid() &&
1598 "Expecting valid fusion candidates");
1601 dbgs() <<
"Fusion Candidate 1: \n"; FC1.dump(););
1610 if (FC0.GuardBranch)
1611 return fuseGuardedLoops(FC0, FC1);
1628 if (FC0.ExitingBlock != FC0.Latch)
1629 for (PHINode &
PHI : FC0.Header->
phis())
1660 DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1662 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1665 DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
1671 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1674 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1675 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1681 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1683 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1685 rewireFusedHeaderPHIsAndLatches(FC0, FC1, OriginalFC0PHIs, TreeUpdates);
1688 DTU.applyUpdates(TreeUpdates);
1690 LI.removeBlock(FC1.Preheader);
1691 DTU.deleteBB(FC1.Preheader);
1693 LI.removeBlock(FC0.ExitBlock);
1694 DTU.deleteBB(FC0.ExitBlock);
1699 return finalizeFusedLoop(FC0, FC1);
1714 template <
typename RemarkKind>
1715 void reportLoopFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1,
1716 StringRef RemarkName, StringRef RemarkMsg) {
1717 assert(FC0.Preheader && FC1.Preheader &&
1718 "Expecting valid fusion candidates");
1719 using namespace ore;
1723 <<
"]: " <<
NV(
"Cand1", StringRef(FC0.Preheader->
getName())) <<
" and "
1724 <<
NV(
"Cand2", StringRef(FC1.Preheader->
getName())) <<
": "
1743 Loop *fuseGuardedLoops(
const FusionCandidate &FC0,
1744 const FusionCandidate &FC1) {
1745 assert(FC0.GuardBranch && FC1.GuardBranch &&
"Expecting guarded loops");
1749 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1750 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1758 (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
1765 assert(FC0NonLoopBlock == FC1GuardBlock &&
"Loops are not adjacent");
1780 BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
1785 new UnreachableInst(FC1GuardBlock->
getContext(), FC1GuardBlock);
1788 DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1790 DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1792 DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1794 DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1798 DominatorTree::Delete, FC0.ExitBlock, FC0ExitBlockSuccessor));
1801 DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
1803 new UnreachableInst(FC0ExitBlockSuccessor->
getContext(),
1804 FC0ExitBlockSuccessor);
1808 "Expecting guard block to have no predecessors");
1810 "Expecting guard block to have no successors");
1825 if (FC0.ExitingBlock != FC0.Latch)
1826 for (PHINode &
PHI : FC0.Header->
phis())
1829 assert(OriginalFC0PHIs.
empty() &&
"Expecting OriginalFC0PHIs to be empty!");
1852 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1854 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1865 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1871 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1873 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1875 rewireFusedHeaderPHIsAndLatches(FC0, FC1, OriginalFC0PHIs, TreeUpdates);
1884 DTU.applyUpdates(TreeUpdates);
1886 LI.removeBlock(FC1GuardBlock);
1887 LI.removeBlock(FC1.Preheader);
1888 LI.removeBlock(FC0.ExitBlock);
1890 LI.removeBlock(FC0ExitBlockSuccessor);
1891 DTU.deleteBB(FC0ExitBlockSuccessor);
1893 DTU.deleteBB(FC1GuardBlock);
1894 DTU.deleteBB(FC1.Preheader);
1895 DTU.deleteBB(FC0.ExitBlock);
1898 return finalizeFusedLoop(FC0, FC1);
1918 for (
auto &L : LI) {
1922 for (
Loop *L : LI.getLoopsInPreorder()) {
1929 LoopFuser LF(ScalarOptions::Global, LI, DT, DI, SE, PDT, ORE, AC,
TTI);
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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
static bool simplifyLoopGuard(Loop *L, DomTreeUpdater &DTU, LoopInfo &LI, ScalarEvolution &SE)
Fold away an empty block on the "skip" edge of L's loop guard, if any.
SmallVector< FusionCandidateList, 4 > FusionCandidateCollection
static void printLoopVector(const LoopVector &LV)
SmallVector< Loop *, 4 > LoopVector
This file implements the Loop Fusion pass.
Loop::LoopBounds::Direction Direction
This file defines the interface for the loop nest analysis.
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.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
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 * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
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
AnalysisPass to compute dependence information in a function.
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Analysis pass which computes a DominatorTree.
static constexpr UpdateKind Delete
static constexpr UpdateKind Insert
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
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 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
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
bool isLoopHeader(const BlockT *BB) const
reverse_iterator rbegin() const
static const BasicBlock & skipEmptyBlockUntil(const BasicBlock *From, const BasicBlock *End, bool CheckUniquePred=false)
Recursivelly traverse all empty 'single successor' basic blocks of From (if there are any).
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.
Represent a constant reference to a string, i.e.
Analysis pass providing the TargetTransformInfo.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
This function has undefined behavior.
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.
@ BasicBlock
Various leaf nodes.
@ Valid
The data is already valid.
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)
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)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
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.