#include "llvm/Transforms/Scalar/LoopFuse.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/DependenceAnalysis.h"
#include "llvm/Analysis/DomTreeUpdater.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Verifier.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/CodeMoverUtils.h"
#include "llvm/Transforms/Utils/LoopPeel.h"
using namespace llvm;
#define DEBUG_TYPE "loop-fusion"
STATISTIC(FuseCounter, "Loops fused");
STATISTIC(NumFusionCandidates, "Number of candidates for loop fusion");
STATISTIC(InvalidPreheader, "Loop has invalid preheader");
STATISTIC(InvalidHeader, "Loop has invalid header");
STATISTIC(InvalidExitingBlock, "Loop has invalid exiting blocks");
STATISTIC(InvalidExitBlock, "Loop has invalid exit block");
STATISTIC(InvalidLatch, "Loop has invalid latch");
STATISTIC(InvalidLoop, "Loop is invalid");
STATISTIC(AddressTakenBB, "Basic block has address taken");
STATISTIC(MayThrowException, "Loop may throw an exception");
STATISTIC(ContainsVolatileAccess, "Loop contains a volatile access");
STATISTIC(NotSimplifiedForm, "Loop is not in simplified form");
STATISTIC(InvalidDependencies, "Dependencies prevent fusion");
STATISTIC(UnknownTripCount, "Loop has unknown trip count");
STATISTIC(UncomputableTripCount, "SCEV cannot compute trip count of loop");
STATISTIC(NonEqualTripCount, "Loop trip counts are not the same");
STATISTIC(NonAdjacent, "Loops are not adjacent");
STATISTIC(
NonEmptyPreheader,
"Loop has a non-empty preheader with instructions that cannot be moved");
STATISTIC(FusionNotBeneficial, "Fusion is not beneficial");
STATISTIC(NonIdenticalGuards, "Candidates have different guards");
STATISTIC(NonEmptyExitBlock, "Candidate has a non-empty exit block with "
"instructions that cannot be moved");
STATISTIC(NonEmptyGuardBlock, "Candidate has a non-empty guard block with "
"instructions that cannot be moved");
STATISTIC(NotRotated, "Candidate is not rotated");
STATISTIC(OnlySecondCandidateIsGuarded,
"The second candidate is guarded while the first one is not");
enum FusionDependenceAnalysisChoice {
FUSION_DEPENDENCE_ANALYSIS_SCEV,
FUSION_DEPENDENCE_ANALYSIS_DA,
FUSION_DEPENDENCE_ANALYSIS_ALL,
};
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));
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"));
#ifndef NDEBUG
static cl::opt<bool>
VerboseFusionDebugging("loop-fusion-verbose-debug",
cl::desc("Enable verbose debugging for Loop Fusion"),
cl::Hidden, cl::init(false));
#endif
namespace {
struct FusionCandidate {
BasicBlock *Preheader;
BasicBlock *Header;
BasicBlock *ExitingBlock;
BasicBlock *ExitBlock;
BasicBlock *Latch;
Loop *L;
SmallVector<Instruction *, 16> MemReads;
SmallVector<Instruction *, 16> MemWrites;
bool Valid;
BranchInst *GuardBranch;
TTI::PeelingPreferences PP;
bool AbleToPeel;
bool Peeled;
DominatorTree &DT;
const PostDominatorTree *PDT;
OptimizationRemarkEmitter &ORE;
FusionCandidate(Loop *L, DominatorTree &DT,
const PostDominatorTree *PDT, OptimizationRemarkEmitter &ORE,
TTI::PeelingPreferences PP)
: Preheader(L->getLoopPreheader()), Header(L->getHeader()),
ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
Latch(L->getLoopLatch()), L(L), Valid(true),
GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(canPeel(L)),
Peeled(false), DT(DT), PDT(PDT), ORE(ORE) {
for (BasicBlock *BB : L->blocks()) {
if (BB->hasAddressTaken()) {
invalidate();
reportInvalidCandidate(AddressTakenBB);
return;
}
for (Instruction &I : *BB) {
if (I.mayThrow()) {
invalidate();
reportInvalidCandidate(MayThrowException);
return;
}
if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
if (SI->isVolatile()) {
invalidate();
reportInvalidCandidate(ContainsVolatileAccess);
return;
}
}
if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
if (LI->isVolatile()) {
invalidate();
reportInvalidCandidate(ContainsVolatileAccess);
return;
}
}
if (I.mayWriteToMemory())
MemWrites.push_back(&I);
if (I.mayReadFromMemory())
MemReads.push_back(&I);
}
}
}
bool isValid() const {
return Preheader && Header && ExitingBlock && ExitBlock && Latch && L &&
!L->isInvalid() && Valid;
}
void verify() const {
assert(isValid() && "Candidate is not valid!!");
assert(!L->isInvalid() && "Loop is invalid!");
assert(Preheader == L->getLoopPreheader() && "Preheader is out of sync");
assert(Header == L->getHeader() && "Header is out of sync");
assert(ExitingBlock == L->getExitingBlock() &&
"Exiting Blocks is out of sync");
assert(ExitBlock == L->getExitBlock() && "Exit block is out of sync");
assert(Latch == L->getLoopLatch() && "Latch is out of sync");
}
BasicBlock *getEntryBlock() const {
if (GuardBranch)
return GuardBranch->getParent();
else
return Preheader;
}
void updateAfterPeeling() {
Preheader = L->getLoopPreheader();
Header = L->getHeader();
ExitingBlock = L->getExitingBlock();
ExitBlock = L->getExitBlock();
Latch = L->getLoopLatch();
verify();
}
BasicBlock *getNonLoopBlock() const {
assert(GuardBranch && "Only valid on guarded loops.");
assert(GuardBranch->isConditional() &&
"Expecting guard to be a conditional branch.");
if (Peeled)
return GuardBranch->getSuccessor(1);
return (GuardBranch->getSuccessor(0) == Preheader)
? GuardBranch->getSuccessor(1)
: GuardBranch->getSuccessor(0);
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void dump() const {
dbgs() << "\tGuardBranch: ";
if (GuardBranch)
dbgs() << *GuardBranch;
else
dbgs() << "nullptr";
dbgs() << "\n"
<< (GuardBranch ? GuardBranch->getName() : "nullptr") << "\n"
<< "\tPreheader: " << (Preheader ? Preheader->getName() : "nullptr")
<< "\n"
<< "\tHeader: " << (Header ? Header->getName() : "nullptr") << "\n"
<< "\tExitingBB: "
<< (ExitingBlock ? ExitingBlock->getName() : "nullptr") << "\n"
<< "\tExitBB: " << (ExitBlock ? ExitBlock->getName() : "nullptr")
<< "\n"
<< "\tLatch: " << (Latch ? Latch->getName() : "nullptr") << "\n"
<< "\tEntryBlock: "
<< (getEntryBlock() ? getEntryBlock()->getName() : "nullptr")
<< "\n";
}
#endif
bool isEligibleForFusion(ScalarEvolution &SE) const {
if (!isValid()) {
LLVM_DEBUG(dbgs() << "FC has invalid CFG requirements!\n");
if (!Preheader)
++InvalidPreheader;
if (!Header)
++InvalidHeader;
if (!ExitingBlock)
++InvalidExitingBlock;
if (!ExitBlock)
++InvalidExitBlock;
if (!Latch)
++InvalidLatch;
if (L->isInvalid())
++InvalidLoop;
return false;
}
if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
LLVM_DEBUG(dbgs() << "Loop " << L->getName()
<< " trip count not computable!\n");
return reportInvalidCandidate(UnknownTripCount);
}
if (!L->isLoopSimplifyForm()) {
LLVM_DEBUG(dbgs() << "Loop " << L->getName()
<< " is not in simplified form!\n");
return reportInvalidCandidate(NotSimplifiedForm);
}
if (!L->isRotatedForm()) {
LLVM_DEBUG(dbgs() << "Loop " << L->getName() << " is not rotated!\n");
return reportInvalidCandidate(NotRotated);
}
return true;
}
private:
void invalidate() {
MemWrites.clear();
MemReads.clear();
Valid = false;
}
bool reportInvalidCandidate(llvm::Statistic &Stat) const {
using namespace ore;
assert(L && Preheader && "Fusion candidate not initialized properly!");
#if LLVM_ENABLE_STATS
++Stat;
ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, Stat.getName(),
L->getStartLoc(), Preheader)
<< "[" << Preheader->getParent()->getName() << "]: "
<< "Loop is not a candidate for fusion: " << Stat.getDesc());
#endif
return false;
}
};
struct FusionCandidateCompare {
bool operator()(const FusionCandidate &LHS,
const FusionCandidate &RHS) const {
const DominatorTree *DT = &(LHS.DT);
BasicBlock *LHSEntryBlock = LHS.getEntryBlock();
BasicBlock *RHSEntryBlock = RHS.getEntryBlock();
assert(DT && LHS.PDT && "Expecting valid dominator tree");
if (DT->dominates(RHSEntryBlock, LHSEntryBlock)) {
assert(LHS.PDT->dominates(LHSEntryBlock, RHSEntryBlock));
return false;
}
if (DT->dominates(LHSEntryBlock, RHSEntryBlock)) {
assert(LHS.PDT->dominates(RHSEntryBlock, LHSEntryBlock));
return true;
}
llvm_unreachable(
"No dominance relationship between these fusion candidates!");
}
};
using LoopVector = SmallVector<Loop *, 4>;
using FusionCandidateSet = std::set<FusionCandidate, FusionCandidateCompare>;
using FusionCandidateCollection = SmallVector<FusionCandidateSet, 4>;
#if !defined(NDEBUG)
static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
const FusionCandidate &FC) {
if (FC.isValid())
OS << FC.Preheader->getName();
else
OS << "<Invalid>";
return OS;
}
static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
const FusionCandidateSet &CandSet) {
for (const FusionCandidate &FC : CandSet)
OS << FC << '\n';
return OS;
}
static void
printFusionCandidates(const FusionCandidateCollection &FusionCandidates) {
dbgs() << "Fusion Candidates: \n";
for (const auto &CandidateSet : FusionCandidates) {
dbgs() << "*** Fusion Candidate Set ***\n";
dbgs() << CandidateSet;
dbgs() << "****************************\n";
}
}
#endif
struct LoopDepthTree {
using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
using iterator = LoopsOnLevelTy::iterator;
using const_iterator = LoopsOnLevelTy::const_iterator;
LoopDepthTree(LoopInfo &LI) : Depth(1) {
if (!LI.empty())
LoopsOnLevel.emplace_back(LoopVector(LI.rbegin(), LI.rend()));
}
bool isRemovedLoop(const Loop *L) const { return RemovedLoops.count(L); }
void removeLoop(const Loop *L) { RemovedLoops.insert(L); }
void descend() {
LoopsOnLevelTy LoopsOnNextLevel;
for (const LoopVector &LV : *this)
for (Loop *L : LV)
if (!isRemovedLoop(L) && L->begin() != L->end())
LoopsOnNextLevel.emplace_back(LoopVector(L->begin(), L->end()));
LoopsOnLevel = LoopsOnNextLevel;
RemovedLoops.clear();
Depth++;
}
bool empty() const { return size() == 0; }
size_t size() const { return LoopsOnLevel.size() - RemovedLoops.size(); }
unsigned getDepth() const { return Depth; }
iterator begin() { return LoopsOnLevel.begin(); }
iterator end() { return LoopsOnLevel.end(); }
const_iterator begin() const { return LoopsOnLevel.begin(); }
const_iterator end() const { return LoopsOnLevel.end(); }
private:
SmallPtrSet<const Loop *, 8> RemovedLoops;
unsigned Depth;
LoopsOnLevelTy LoopsOnLevel;
};
#ifndef NDEBUG
static void printLoopVector(const LoopVector &LV) {
dbgs() << "****************************\n";
for (auto L : LV)
printLoop(*L, dbgs());
dbgs() << "****************************\n";
}
#endif
struct LoopFuser {
private:
FusionCandidateCollection FusionCandidates;
LoopDepthTree LDT;
DomTreeUpdater DTU;
LoopInfo &LI;
DominatorTree &DT;
DependenceInfo &DI;
ScalarEvolution &SE;
PostDominatorTree &PDT;
OptimizationRemarkEmitter &ORE;
AssumptionCache &AC;
const TargetTransformInfo &TTI;
public:
LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
ScalarEvolution &SE, PostDominatorTree &PDT,
OptimizationRemarkEmitter &ORE, const DataLayout &DL,
AssumptionCache &AC, const TargetTransformInfo &TTI)
: LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC), TTI(TTI) {}
bool fuseLoops(Function &F) {
#ifndef NDEBUG
if (VerboseFusionDebugging) {
LI.print(dbgs());
}
#endif
LLVM_DEBUG(dbgs() << "Performing Loop Fusion on function " << F.getName()
<< "\n");
bool Changed = false;
while (!LDT.empty()) {
LLVM_DEBUG(dbgs() << "Got " << LDT.size() << " loop sets for depth "
<< LDT.getDepth() << "\n";);
for (const LoopVector &LV : LDT) {
assert(LV.size() > 0 && "Empty loop set was build!");
if (LV.size() == 1)
continue;
#ifndef NDEBUG
if (VerboseFusionDebugging) {
LLVM_DEBUG({
dbgs() << " Visit loop set (#" << LV.size() << "):\n";
printLoopVector(LV);
});
}
#endif
collectFusionCandidates(LV);
Changed |= fuseCandidates();
}
LLVM_DEBUG(dbgs() << "Descend one level!\n");
LDT.descend();
FusionCandidates.clear();
}
if (Changed)
LLVM_DEBUG(dbgs() << "Function after Loop Fusion: \n"; F.dump(););
#ifndef NDEBUG
assert(DT.verify());
assert(PDT.verify());
LI.verify(DT);
SE.verify();
#endif
LLVM_DEBUG(dbgs() << "Loop Fusion complete\n");
return Changed;
}
private:
bool isControlFlowEquivalent(const FusionCandidate &FC0,
const FusionCandidate &FC1) const {
assert(FC0.Preheader && FC1.Preheader && "Expecting valid preheaders");
return ::isControlFlowEquivalent(*FC0.getEntryBlock(), *FC1.getEntryBlock(),
DT, PDT);
}
void collectFusionCandidates(const LoopVector &LV) {
for (Loop *L : LV) {
TTI::PeelingPreferences PP =
gatherPeelingPreferences(L, SE, TTI, None, None);
FusionCandidate CurrCand(L, DT, &PDT, ORE, PP);
if (!CurrCand.isEligibleForFusion(SE))
continue;
bool FoundSet = false;
for (auto &CurrCandSet : FusionCandidates) {
if (isControlFlowEquivalent(*CurrCandSet.begin(), CurrCand)) {
CurrCandSet.insert(CurrCand);
FoundSet = true;
#ifndef NDEBUG
if (VerboseFusionDebugging)
LLVM_DEBUG(dbgs() << "Adding " << CurrCand
<< " to existing candidate set\n");
#endif
break;
}
}
if (!FoundSet) {
#ifndef NDEBUG
if (VerboseFusionDebugging)
LLVM_DEBUG(dbgs() << "Adding " << CurrCand << " to new set\n");
#endif
FusionCandidateSet NewCandSet;
NewCandSet.insert(CurrCand);
FusionCandidates.push_back(NewCandSet);
}
NumFusionCandidates++;
}
}
bool isBeneficialFusion(const FusionCandidate &FC0,
const FusionCandidate &FC1) {
return true;
}
std::pair<bool, Optional<unsigned>>
haveIdenticalTripCounts(const FusionCandidate &FC0,
const FusionCandidate &FC1) const {
const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
if (isa<SCEVCouldNotCompute>(TripCount0)) {
UncomputableTripCount++;
LLVM_DEBUG(dbgs() << "Trip count of first loop could not be computed!");
return {false, None};
}
const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
if (isa<SCEVCouldNotCompute>(TripCount1)) {
UncomputableTripCount++;
LLVM_DEBUG(dbgs() << "Trip count of second loop could not be computed!");
return {false, None};
}
LLVM_DEBUG(dbgs() << "\tTrip counts: " << *TripCount0 << " & "
<< *TripCount1 << " are "
<< (TripCount0 == TripCount1 ? "identical" : "different")
<< "\n");
if (TripCount0 == TripCount1)
return {true, 0};
LLVM_DEBUG(dbgs() << "The loops do not have the same tripcount, "
"determining the difference between trip counts\n");
const unsigned TC0 = SE.getSmallConstantTripCount(FC0.L);
const unsigned TC1 = SE.getSmallConstantTripCount(FC1.L);
if (TC0 == 0 || TC1 == 0) {
LLVM_DEBUG(dbgs() << "Loop(s) do not have a single exit point or do not "
"have a constant number of iterations. Peeling "
"is not benefical\n");
return {false, None};
}
Optional<unsigned> Difference = None;
int Diff = TC0 - TC1;
if (Diff > 0)
Difference = Diff;
else {
LLVM_DEBUG(
dbgs() << "Difference is less than 0. FC1 (second loop) has more "
"iterations than the first one. Currently not supported\n");
}
LLVM_DEBUG(dbgs() << "Difference in loop trip count is: " << Difference
<< "\n");
return {false, Difference};
}
void peelFusionCandidate(FusionCandidate &FC0, const FusionCandidate &FC1,
unsigned PeelCount) {
assert(FC0.AbleToPeel && "Should be able to peel loop");
LLVM_DEBUG(dbgs() << "Attempting to peel first " << PeelCount
<< " iterations of the first loop. \n");
FC0.Peeled = peelLoop(FC0.L, PeelCount, &LI, &SE, DT, &AC, true);
if (FC0.Peeled) {
LLVM_DEBUG(dbgs() << "Done Peeling\n");
#ifndef NDEBUG
auto IdenticalTripCount = haveIdenticalTripCounts(FC0, FC1);
assert(IdenticalTripCount.first && *IdenticalTripCount.second == 0 &&
"Loops should have identical trip counts after peeling");
#endif
FC0.PP.PeelCount += PeelCount;
PDT.recalculate(*FC0.Preheader->getParent());
FC0.updateAfterPeeling();
BasicBlock *BB =
FC0.GuardBranch ? FC0.ExitBlock->getUniqueSuccessor() : FC1.Preheader;
if (BB) {
SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
SmallVector<Instruction *, 8> WorkList;
for (BasicBlock *Pred : predecessors(BB)) {
if (Pred != FC0.ExitBlock) {
WorkList.emplace_back(Pred->getTerminator());
TreeUpdates.emplace_back(
DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
}
}
for (Instruction *CurrentBranch: WorkList) {
BasicBlock *Succ = CurrentBranch->getSuccessor(0);
if (Succ == BB)
Succ = CurrentBranch->getSuccessor(1);
ReplaceInstWithInst(CurrentBranch, BranchInst::Create(Succ));
}
DTU.applyUpdates(TreeUpdates);
DTU.flush();
}
LLVM_DEBUG(
dbgs() << "Sucessfully peeled " << FC0.PP.PeelCount
<< " iterations from the first loop.\n"
"Both Loops have the same number of iterations now.\n");
}
}
bool fuseCandidates() {
bool Fused = false;
LLVM_DEBUG(printFusionCandidates(FusionCandidates));
for (auto &CandidateSet : FusionCandidates) {
if (CandidateSet.size() < 2)
continue;
LLVM_DEBUG(dbgs() << "Attempting fusion on Candidate Set:\n"
<< CandidateSet << "\n");
for (auto FC0 = CandidateSet.begin(); FC0 != CandidateSet.end(); ++FC0) {
assert(!LDT.isRemovedLoop(FC0->L) &&
"Should not have removed loops in CandidateSet!");
auto FC1 = FC0;
for (++FC1; FC1 != CandidateSet.end(); ++FC1) {
assert(!LDT.isRemovedLoop(FC1->L) &&
"Should not have removed loops in CandidateSet!");
LLVM_DEBUG(dbgs() << "Attempting to fuse candidate \n"; FC0->dump();
dbgs() << " with\n"; FC1->dump(); dbgs() << "\n");
FC0->verify();
FC1->verify();
std::pair<bool, Optional<unsigned>> IdenticalTripCountRes =
haveIdenticalTripCounts(*FC0, *FC1);
bool SameTripCount = IdenticalTripCountRes.first;
Optional<unsigned> TCDifference = IdenticalTripCountRes.second;
if (FC0->AbleToPeel && !SameTripCount && TCDifference) {
if (*TCDifference > FusionPeelMaxCount) {
LLVM_DEBUG(dbgs()
<< "Difference in loop trip counts: " << *TCDifference
<< " is greater than maximum peel count specificed: "
<< FusionPeelMaxCount << "\n");
} else {
SameTripCount = true;
}
}
if (!SameTripCount) {
LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical trip "
"counts. Not fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
NonEqualTripCount);
continue;
}
if (!isAdjacent(*FC0, *FC1)) {
LLVM_DEBUG(dbgs()
<< "Fusion candidates are not adjacent. Not fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, NonAdjacent);
continue;
}
if (!FC0->GuardBranch && FC1->GuardBranch) {
LLVM_DEBUG(dbgs() << "The second candidate is guarded while the "
"first one is not. Not fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(
*FC0, *FC1, OnlySecondCandidateIsGuarded);
continue;
}
if (FC0->GuardBranch && FC1->GuardBranch &&
!haveIdenticalGuards(*FC0, *FC1) && !TCDifference) {
LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical "
"guards. Not Fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
NonIdenticalGuards);
continue;
}
if (!isSafeToMoveBefore(*FC1->Preheader,
*FC0->Preheader->getTerminator(), DT, &PDT,
&DI)) {
LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
"instructions in preheader. Not fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
NonEmptyPreheader);
continue;
}
if (FC0->GuardBranch) {
assert(FC1->GuardBranch && "Expecting valid FC1 guard branch");
if (!isSafeToMoveBefore(*FC0->ExitBlock,
*FC1->ExitBlock->getFirstNonPHIOrDbg(), DT,
&PDT, &DI)) {
LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
"instructions in exit block. Not fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
NonEmptyExitBlock);
continue;
}
if (!isSafeToMoveBefore(
*FC1->GuardBranch->getParent(),
*FC0->GuardBranch->getParent()->getTerminator(), DT, &PDT,
&DI)) {
LLVM_DEBUG(dbgs()
<< "Fusion candidate contains unsafe "
"instructions in guard block. Not fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
NonEmptyGuardBlock);
continue;
}
}
if (!dependencesAllowFusion(*FC0, *FC1)) {
LLVM_DEBUG(dbgs() << "Memory dependencies do not allow fusion!\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
InvalidDependencies);
continue;
}
bool BeneficialToFuse = isBeneficialFusion(*FC0, *FC1);
LLVM_DEBUG(dbgs()
<< "\tFusion appears to be "
<< (BeneficialToFuse ? "" : "un") << "profitable!\n");
if (!BeneficialToFuse) {
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
FusionNotBeneficial);
continue;
}
LLVM_DEBUG(dbgs() << "\tFusion is performed: " << *FC0 << " and "
<< *FC1 << "\n");
FusionCandidate FC0Copy = *FC0;
bool Peel = TCDifference && *TCDifference > 0;
if (Peel)
peelFusionCandidate(FC0Copy, *FC1, *TCDifference);
reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : *FC0), *FC1,
FuseCounter);
FusionCandidate FusedCand(
performFusion((Peel ? FC0Copy : *FC0), *FC1), DT, &PDT, ORE,
FC0Copy.PP);
FusedCand.verify();
assert(FusedCand.isEligibleForFusion(SE) &&
"Fused candidate should be eligible for fusion!");
LDT.removeLoop(FC1->L);
CandidateSet.erase(FC0);
CandidateSet.erase(FC1);
auto InsertPos = CandidateSet.insert(FusedCand);
assert(InsertPos.second &&
"Unable to insert TargetCandidate in CandidateSet!");
FC0 = FC1 = InsertPos.first;
LLVM_DEBUG(dbgs() << "Candidate Set (after fusion): " << CandidateSet
<< "\n");
Fused = true;
}
}
}
return Fused;
}
class AddRecLoopReplacer : public SCEVRewriteVisitor<AddRecLoopReplacer> {
public:
AddRecLoopReplacer(ScalarEvolution &SE, const Loop &OldL, const Loop &NewL,
bool UseMax = true)
: SCEVRewriteVisitor(SE), Valid(true), UseMax(UseMax), OldL(OldL),
NewL(NewL) {}
const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
const Loop *ExprL = Expr->getLoop();
SmallVector<const SCEV *, 2> Operands;
if (ExprL == &OldL) {
Operands.append(Expr->op_begin(), Expr->op_end());
return SE.getAddRecExpr(Operands, &NewL, Expr->getNoWrapFlags());
}
if (OldL.contains(ExprL)) {
bool Pos = SE.isKnownPositive(Expr->getStepRecurrence(SE));
if (!UseMax || !Pos || !Expr->isAffine()) {
Valid = false;
return Expr;
}
return visit(Expr->getStart());
}
for (const SCEV *Op : Expr->operands())
Operands.push_back(visit(Op));
return SE.getAddRecExpr(Operands, ExprL, Expr->getNoWrapFlags());
}
bool wasValidSCEV() const { return Valid; }
private:
bool Valid, UseMax;
const Loop &OldL, &NewL;
};
bool accessDiffIsPositive(const Loop &L0, const Loop &L1, Instruction &I0,
Instruction &I1, bool EqualIsInvalid) {
Value *Ptr0 = getLoadStorePointerOperand(&I0);
Value *Ptr1 = getLoadStorePointerOperand(&I1);
if (!Ptr0 || !Ptr1)
return false;
const SCEV *SCEVPtr0 = SE.getSCEVAtScope(Ptr0, &L0);
const SCEV *SCEVPtr1 = SE.getSCEVAtScope(Ptr1, &L1);
#ifndef NDEBUG
if (VerboseFusionDebugging)
LLVM_DEBUG(dbgs() << " Access function check: " << *SCEVPtr0 << " vs "
<< *SCEVPtr1 << "\n");
#endif
AddRecLoopReplacer Rewriter(SE, L0, L1);
SCEVPtr0 = Rewriter.visit(SCEVPtr0);
#ifndef NDEBUG
if (VerboseFusionDebugging)
LLVM_DEBUG(dbgs() << " Access function after rewrite: " << *SCEVPtr0
<< " [Valid: " << Rewriter.wasValidSCEV() << "]\n");
#endif
if (!Rewriter.wasValidSCEV())
return false;
BasicBlock *L0Header = L0.getHeader();
auto HasNonLinearDominanceRelation = [&](const SCEV *S) {
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S);
if (!AddRec)
return false;
return !DT.dominates(L0Header, AddRec->getLoop()->getHeader()) &&
!DT.dominates(AddRec->getLoop()->getHeader(), L0Header);
};
if (SCEVExprContains(SCEVPtr1, HasNonLinearDominanceRelation))
return false;
ICmpInst::Predicate Pred =
EqualIsInvalid ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_SGE;
bool IsAlwaysGE = SE.isKnownPredicate(Pred, SCEVPtr0, SCEVPtr1);
#ifndef NDEBUG
if (VerboseFusionDebugging)
LLVM_DEBUG(dbgs() << " Relation: " << *SCEVPtr0
<< (IsAlwaysGE ? " >= " : " may < ") << *SCEVPtr1
<< "\n");
#endif
return IsAlwaysGE;
}
bool dependencesAllowFusion(const FusionCandidate &FC0,
const FusionCandidate &FC1, Instruction &I0,
Instruction &I1, bool AnyDep,
FusionDependenceAnalysisChoice DepChoice) {
#ifndef NDEBUG
if (VerboseFusionDebugging) {
LLVM_DEBUG(dbgs() << "Check dep: " << I0 << " vs " << I1 << " : "
<< DepChoice << "\n");
}
#endif
switch (DepChoice) {
case FUSION_DEPENDENCE_ANALYSIS_SCEV:
return accessDiffIsPositive(*FC0.L, *FC1.L, I0, I1, AnyDep);
case FUSION_DEPENDENCE_ANALYSIS_DA: {
auto DepResult = DI.depends(&I0, &I1, true);
if (!DepResult)
return true;
#ifndef NDEBUG
if (VerboseFusionDebugging) {
LLVM_DEBUG(dbgs() << "DA res: "; DepResult->dump(dbgs());
dbgs() << " [#l: " << DepResult->getLevels() << "][Ordered: "
<< (DepResult->isOrdered() ? "true" : "false")
<< "]\n");
LLVM_DEBUG(dbgs() << "DepResult Levels: " << DepResult->getLevels()
<< "\n");
}
#endif
if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
LLVM_DEBUG(
dbgs() << "TODO: Implement pred/succ dependence handling!\n");
return false;
}
case FUSION_DEPENDENCE_ANALYSIS_ALL:
return dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
FUSION_DEPENDENCE_ANALYSIS_SCEV) ||
dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
FUSION_DEPENDENCE_ANALYSIS_DA);
}
llvm_unreachable("Unknown fusion dependence analysis choice!");
}
bool dependencesAllowFusion(const FusionCandidate &FC0,
const FusionCandidate &FC1) {
LLVM_DEBUG(dbgs() << "Check if " << FC0 << " can be fused with " << FC1
<< "\n");
assert(FC0.L->getLoopDepth() == FC1.L->getLoopDepth());
assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
for (Instruction *WriteL0 : FC0.MemWrites) {
for (Instruction *WriteL1 : FC1.MemWrites)
if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
false,
FusionDependenceAnalysis)) {
InvalidDependencies++;
return false;
}
for (Instruction *ReadL1 : FC1.MemReads)
if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1,
false,
FusionDependenceAnalysis)) {
InvalidDependencies++;
return false;
}
}
for (Instruction *WriteL1 : FC1.MemWrites) {
for (Instruction *WriteL0 : FC0.MemWrites)
if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
false,
FusionDependenceAnalysis)) {
InvalidDependencies++;
return false;
}
for (Instruction *ReadL0 : FC0.MemReads)
if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1,
false,
FusionDependenceAnalysis)) {
InvalidDependencies++;
return false;
}
}
for (BasicBlock *BB : FC1.L->blocks())
for (Instruction &I : *BB)
for (auto &Op : I.operands())
if (Instruction *Def = dyn_cast<Instruction>(Op))
if (FC0.L->contains(Def->getParent())) {
InvalidDependencies++;
return false;
}
return true;
}
bool isAdjacent(const FusionCandidate &FC0,
const FusionCandidate &FC1) const {
if (FC0.GuardBranch)
return FC0.getNonLoopBlock() == FC1.getEntryBlock();
else
return FC0.ExitBlock == FC1.getEntryBlock();
}
bool haveIdenticalGuards(const FusionCandidate &FC0,
const FusionCandidate &FC1) const {
assert(FC0.GuardBranch && FC1.GuardBranch &&
"Expecting FC0 and FC1 to be guarded loops.");
if (auto FC0CmpInst =
dyn_cast<Instruction>(FC0.GuardBranch->getCondition()))
if (auto FC1CmpInst =
dyn_cast<Instruction>(FC1.GuardBranch->getCondition()))
if (!FC0CmpInst->isIdenticalTo(FC1CmpInst))
return false;
if (FC0.GuardBranch->getSuccessor(0) == FC0.Preheader)
return (FC1.GuardBranch->getSuccessor(0) == FC1.Preheader);
else
return (FC1.GuardBranch->getSuccessor(1) == FC1.Preheader);
}
void simplifyLatchBranch(const FusionCandidate &FC) const {
BranchInst *FCLatchBranch = dyn_cast<BranchInst>(FC.Latch->getTerminator());
if (FCLatchBranch) {
assert(FCLatchBranch->isConditional() &&
FCLatchBranch->getSuccessor(0) == FCLatchBranch->getSuccessor(1) &&
"Expecting the two successors of FCLatchBranch to be the same");
BranchInst *NewBranch =
BranchInst::Create(FCLatchBranch->getSuccessor(0));
ReplaceInstWithInst(FCLatchBranch, NewBranch);
}
}
void mergeLatch(const FusionCandidate &FC0, const FusionCandidate &FC1) {
moveInstructionsToTheBeginning(*FC0.Latch, *FC1.Latch, DT, PDT, DI);
if (BasicBlock *Succ = FC0.Latch->getUniqueSuccessor()) {
MergeBlockIntoPredecessor(Succ, &DTU, &LI);
DTU.flush();
}
}
Loop *performFusion(const FusionCandidate &FC0, const FusionCandidate &FC1) {
assert(FC0.isValid() && FC1.isValid() &&
"Expecting valid fusion candidates");
LLVM_DEBUG(dbgs() << "Fusion Candidate 0: \n"; FC0.dump();
dbgs() << "Fusion Candidate 1: \n"; FC1.dump(););
moveInstructionsToTheEnd(*FC1.Preheader, *FC0.Preheader, DT, PDT, DI);
if (FC0.GuardBranch)
return fuseGuardedLoops(FC0, FC1);
assert(FC1.Preheader ==
(FC0.Peeled ? FC0.ExitBlock->getUniqueSuccessor() : FC0.ExitBlock));
assert(FC1.Preheader->size() == 1 &&
FC1.Preheader->getSingleSuccessor() == FC1.Header);
SmallVector<PHINode *, 8> OriginalFC0PHIs;
if (FC0.ExitingBlock != FC0.Latch)
for (PHINode &PHI : FC0.Header->phis())
OriginalFC0PHIs.push_back(&PHI);
FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
if (!FC0.Peeled) {
FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC1.Preheader,
FC1.Header);
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
} else {
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
FC1.Header);
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
FC0.ExitBlock->getTerminator()->eraseFromParent();
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
}
assert(pred_empty(FC1.Preheader));
FC1.Preheader->getTerminator()->eraseFromParent();
new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Delete, FC1.Preheader, FC1.Header));
while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
if (SE.isSCEVable(PHI->getType()))
SE.forgetValue(PHI);
if (PHI->hasNUsesOrMore(1))
PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
else
PHI->eraseFromParent();
}
Instruction *L1HeaderIP = &FC1.Header->front();
for (PHINode *LCPHI : OriginalFC0PHIs) {
int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
assert(L1LatchBBIdx >= 0 &&
"Expected loop carried value to be rewired at this point!");
Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
PHINode *L1HeaderPHI = PHINode::Create(
LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP);
L1HeaderPHI->addIncoming(LCV, FC0.Latch);
L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()),
FC0.ExitingBlock);
LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
}
FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
simplifyLatchBranch(FC0);
if (FC0.Latch != FC0.ExitingBlock)
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Insert, FC0.Latch, FC1.Header));
TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
FC0.Latch, FC0.Header));
TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
FC1.Latch, FC0.Header));
TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
FC1.Latch, FC1.Header));
DTU.applyUpdates(TreeUpdates);
LI.removeBlock(FC1.Preheader);
DTU.deleteBB(FC1.Preheader);
if (FC0.Peeled) {
LI.removeBlock(FC0.ExitBlock);
DTU.deleteBB(FC0.ExitBlock);
}
DTU.flush();
SE.forgetLoop(FC1.L);
SE.forgetLoop(FC0.L);
mergeLatch(FC0, FC1);
SmallVector<BasicBlock *, 8> Blocks(FC1.L->blocks());
for (BasicBlock *BB : Blocks) {
FC0.L->addBlockEntry(BB);
FC1.L->removeBlockFromLoop(BB);
if (LI.getLoopFor(BB) != FC1.L)
continue;
LI.changeLoopFor(BB, FC0.L);
}
while (!FC1.L->isInnermost()) {
const auto &ChildLoopIt = FC1.L->begin();
Loop *ChildLoop = *ChildLoopIt;
FC1.L->removeChildLoop(ChildLoopIt);
FC0.L->addChildLoop(ChildLoop);
}
LI.erase(FC1.L);
#ifndef NDEBUG
assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
assert(DT.verify(DominatorTree::VerificationLevel::Fast));
assert(PDT.verify());
LI.verify(DT);
SE.verify();
#endif
LLVM_DEBUG(dbgs() << "Fusion done:\n");
return FC0.L;
}
template <typename RemarkKind>
void reportLoopFusion(const FusionCandidate &FC0, const FusionCandidate &FC1,
llvm::Statistic &Stat) {
assert(FC0.Preheader && FC1.Preheader &&
"Expecting valid fusion candidates");
using namespace ore;
#if LLVM_ENABLE_STATS
++Stat;
ORE.emit(RemarkKind(DEBUG_TYPE, Stat.getName(), FC0.L->getStartLoc(),
FC0.Preheader)
<< "[" << FC0.Preheader->getParent()->getName()
<< "]: " << NV("Cand1", StringRef(FC0.Preheader->getName()))
<< " and " << NV("Cand2", StringRef(FC1.Preheader->getName()))
<< ": " << Stat.getDesc());
#endif
}
Loop *fuseGuardedLoops(const FusionCandidate &FC0,
const FusionCandidate &FC1) {
assert(FC0.GuardBranch && FC1.GuardBranch && "Expecting guarded loops");
BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
BasicBlock *FC0ExitBlockSuccessor = FC0.ExitBlock->getUniqueSuccessor();
moveInstructionsToTheBeginning(
(FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
DT, PDT, DI);
moveInstructionsToTheEnd(*FC1GuardBlock, *FC0GuardBlock, DT, PDT, DI);
assert(FC0NonLoopBlock == FC1GuardBlock && "Loops are not adjacent");
SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
FC1NonLoopBlock->replacePhiUsesWith(FC1GuardBlock, FC0GuardBlock);
FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
BBToUpdate->getTerminator()->replaceUsesOfWith(FC1GuardBlock, FC1.Header);
FC1.GuardBranch->eraseFromParent();
new UnreachableInst(FC1GuardBlock->getContext(), FC1GuardBlock);
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
if (FC0.Peeled) {
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
FC0ExitBlockSuccessor->getTerminator()->eraseFromParent();
new UnreachableInst(FC0ExitBlockSuccessor->getContext(),
FC0ExitBlockSuccessor);
}
assert(pred_empty(FC1GuardBlock) &&
"Expecting guard block to have no predecessors");
assert(succ_empty(FC1GuardBlock) &&
"Expecting guard block to have no successors");
SmallVector<PHINode *, 8> OriginalFC0PHIs;
if (FC0.ExitingBlock != FC0.Latch)
for (PHINode &PHI : FC0.Header->phis())
OriginalFC0PHIs.push_back(&PHI);
assert(OriginalFC0PHIs.empty() && "Expecting OriginalFC0PHIs to be empty!");
FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
FC1.Header);
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
assert(pred_empty(FC0.ExitBlock) && "Expecting exit block to be empty");
FC0.ExitBlock->getTerminator()->eraseFromParent();
new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
assert(pred_empty(FC1.Preheader));
FC1.Preheader->getTerminator()->eraseFromParent();
new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Delete, FC1.Preheader, FC1.Header));
while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
if (SE.isSCEVable(PHI->getType()))
SE.forgetValue(PHI);
if (PHI->hasNUsesOrMore(1))
PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
else
PHI->eraseFromParent();
}
Instruction *L1HeaderIP = &FC1.Header->front();
for (PHINode *LCPHI : OriginalFC0PHIs) {
int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
assert(L1LatchBBIdx >= 0 &&
"Expected loop carried value to be rewired at this point!");
Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
PHINode *L1HeaderPHI = PHINode::Create(
LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP);
L1HeaderPHI->addIncoming(LCV, FC0.Latch);
L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()),
FC0.ExitingBlock);
LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
}
FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
simplifyLatchBranch(FC0);
if (FC0.Latch != FC0.ExitingBlock)
TreeUpdates.emplace_back(DominatorTree::UpdateType(
DominatorTree::Insert, FC0.Latch, FC1.Header));
TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
FC0.Latch, FC0.Header));
TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
FC1.Latch, FC0.Header));
TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
FC1.Latch, FC1.Header));
assert(succ_empty(FC1GuardBlock) && "FC1GuardBlock has successors!!");
assert(pred_empty(FC1GuardBlock) && "FC1GuardBlock has predecessors!!");
DTU.applyUpdates(TreeUpdates);
LI.removeBlock(FC1GuardBlock);
LI.removeBlock(FC1.Preheader);
LI.removeBlock(FC0.ExitBlock);
if (FC0.Peeled) {
LI.removeBlock(FC0ExitBlockSuccessor);
DTU.deleteBB(FC0ExitBlockSuccessor);
}
DTU.deleteBB(FC1GuardBlock);
DTU.deleteBB(FC1.Preheader);
DTU.deleteBB(FC0.ExitBlock);
DTU.flush();
SE.forgetLoop(FC1.L);
SE.forgetLoop(FC0.L);
mergeLatch(FC0, FC1);
SmallVector<BasicBlock *, 8> Blocks(FC1.L->blocks());
for (BasicBlock *BB : Blocks) {
FC0.L->addBlockEntry(BB);
FC1.L->removeBlockFromLoop(BB);
if (LI.getLoopFor(BB) != FC1.L)
continue;
LI.changeLoopFor(BB, FC0.L);
}
while (!FC1.L->isInnermost()) {
const auto &ChildLoopIt = FC1.L->begin();
Loop *ChildLoop = *ChildLoopIt;
FC1.L->removeChildLoop(ChildLoopIt);
FC0.L->addChildLoop(ChildLoop);
}
LI.erase(FC1.L);
#ifndef NDEBUG
assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
assert(DT.verify(DominatorTree::VerificationLevel::Fast));
assert(PDT.verify());
LI.verify(DT);
SE.verify();
#endif
LLVM_DEBUG(dbgs() << "Fusion done:\n");
return FC0.L;
}
};
struct LoopFuseLegacy : public FunctionPass {
static char ID;
LoopFuseLegacy() : FunctionPass(ID) {
initializeLoopFuseLegacyPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredID(LoopSimplifyID);
AU.addRequired<ScalarEvolutionWrapperPass>();
AU.addRequired<LoopInfoWrapperPass>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<PostDominatorTreeWrapperPass>();
AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
AU.addRequired<DependenceAnalysisWrapperPass>();
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<TargetTransformInfoWrapperPass>();
AU.addPreserved<ScalarEvolutionWrapperPass>();
AU.addPreserved<LoopInfoWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<PostDominatorTreeWrapperPass>();
}
bool runOnFunction(Function &F) override {
if (skipFunction(F))
return false;
auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI();
auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
const TargetTransformInfo &TTI =
getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
const DataLayout &DL = F.getParent()->getDataLayout();
LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL, AC, TTI);
return LF.fuseLoops(F);
}
};
}
PreservedAnalyses LoopFusePass::run(Function &F, FunctionAnalysisManager &AM) {
auto &LI = AM.getResult<LoopAnalysis>(F);
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &DI = AM.getResult<DependenceAnalysis>(F);
auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
auto &AC = AM.getResult<AssumptionAnalysis>(F);
const TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F);
const DataLayout &DL = F.getParent()->getDataLayout();
LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL, AC, TTI);
bool Changed = LF.fuseLoops(F);
if (!Changed)
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserve<DominatorTreeAnalysis>();
PA.preserve<PostDominatorTreeAnalysis>();
PA.preserve<ScalarEvolutionAnalysis>();
PA.preserve<LoopAnalysis>();
return PA;
}
char LoopFuseLegacy::ID = 0;
INITIALIZE_PASS_BEGIN(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false,
false)
INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_END(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false, false)
FunctionPass *llvm::createLoopFusePass() { return new LoopFuseLegacy(); }