#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/DependenceAnalysis.h"
#include "llvm/Analysis/DomTreeUpdater.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/LoopIterator.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/LoopPassManager.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
using namespace llvm;
#define DEBUG_TYPE "loop-simplifycfg"
static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",
cl::init(true));
STATISTIC(NumTerminatorsFolded,
"Number of terminators folded to unconditional branches");
STATISTIC(NumLoopBlocksDeleted,
"Number of loop blocks deleted");
STATISTIC(NumLoopExitsDeleted,
"Number of loop exiting edges deleted");
static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) {
Instruction *TI = BB->getTerminator();
if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
if (BI->isUnconditional())
return nullptr;
if (BI->getSuccessor(0) == BI->getSuccessor(1))
return BI->getSuccessor(0);
ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
if (!Cond)
return nullptr;
return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
}
if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
if (!CI)
return nullptr;
for (auto Case : SI->cases())
if (Case.getCaseValue() == CI)
return Case.getCaseSuccessor();
return SI->getDefaultDest();
}
return nullptr;
}
static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop,
Loop *LastLoop = nullptr) {
assert((!LastLoop || LastLoop->contains(FirstLoop->getHeader())) &&
"First loop is supposed to be inside of last loop!");
assert(FirstLoop->contains(BB) && "Must be a loop block!");
for (Loop *Current = FirstLoop; Current != LastLoop;
Current = Current->getParentLoop())
Current->removeBlockFromLoop(BB);
}
static Loop *getInnermostLoopFor(SmallPtrSetImpl<BasicBlock *> &BBs,
Loop &L, LoopInfo &LI) {
Loop *Innermost = nullptr;
for (BasicBlock *BB : BBs) {
Loop *BBL = LI.getLoopFor(BB);
while (BBL && !BBL->contains(L.getHeader()))
BBL = BBL->getParentLoop();
if (BBL == &L)
BBL = BBL->getParentLoop();
if (!BBL)
continue;
if (!Innermost || BBL->getLoopDepth() > Innermost->getLoopDepth())
Innermost = BBL;
}
return Innermost;
}
namespace {
class ConstantTerminatorFoldingImpl {
private:
Loop &L;
LoopInfo &LI;
DominatorTree &DT;
ScalarEvolution &SE;
MemorySSAUpdater *MSSAU;
LoopBlocksDFS DFS;
DomTreeUpdater DTU;
SmallVector<DominatorTree::UpdateType, 16> DTUpdates;
bool HasIrreducibleCFG = false;
bool DeleteCurrentLoop = false;
SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
SmallVector<BasicBlock *, 8> DeadLoopBlocks;
SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
SmallVector<BasicBlock *, 8> DeadExitBlocks;
SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
SmallVector<BasicBlock *, 8> FoldCandidates;
void dump() const {
dbgs() << "Constant terminator folding for loop " << L << "\n";
dbgs() << "After terminator constant-folding, the loop will";
if (!DeleteCurrentLoop)
dbgs() << " not";
dbgs() << " be destroyed\n";
auto PrintOutVector = [&](const char *Message,
const SmallVectorImpl<BasicBlock *> &S) {
dbgs() << Message << "\n";
for (const BasicBlock *BB : S)
dbgs() << "\t" << BB->getName() << "\n";
};
auto PrintOutSet = [&](const char *Message,
const SmallPtrSetImpl<BasicBlock *> &S) {
dbgs() << Message << "\n";
for (const BasicBlock *BB : S)
dbgs() << "\t" << BB->getName() << "\n";
};
PrintOutVector("Blocks in which we can constant-fold terminator:",
FoldCandidates);
PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
PrintOutSet("Live exit blocks:", LiveExitBlocks);
PrintOutVector("Dead exit blocks:", DeadExitBlocks);
if (!DeleteCurrentLoop)
PrintOutSet("The following blocks will still be part of the loop:",
BlocksInLoopAfterFolding);
}
bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
assert(DFS.isComplete() && "DFS is expected to be finished");
DenseMap<const BasicBlock *, unsigned> RPO;
unsigned Current = 0;
for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
RPO[*I] = Current++;
for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
BasicBlock *BB = *I;
for (auto *Succ : successors(BB))
if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
return true;
}
return false;
}
void analyze() {
DFS.perform(&LI);
assert(DFS.isComplete() && "DFS is expected to be finished");
if (hasIrreducibleCFG(DFS)) {
HasIrreducibleCFG = true;
return;
}
LiveLoopBlocks.insert(L.getHeader());
for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
BasicBlock *BB = *I;
if (!LiveLoopBlocks.count(BB)) {
DeadLoopBlocks.push_back(BB);
continue;
}
BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;
if (TakeFoldCandidate)
FoldCandidates.push_back(BB);
for (BasicBlock *Succ : successors(BB))
if (!TakeFoldCandidate || TheOnlySucc == Succ) {
if (L.contains(Succ))
LiveLoopBlocks.insert(Succ);
else
LiveExitBlocks.insert(Succ);
}
}
assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
"Malformed block sets?");
SmallVector<BasicBlock *, 8> ExitBlocks;
L.getExitBlocks(ExitBlocks);
SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;
for (auto *ExitBlock : ExitBlocks)
if (!LiveExitBlocks.count(ExitBlock) &&
UniqueDeadExits.insert(ExitBlock).second &&
all_of(predecessors(ExitBlock),
[this](BasicBlock *Pred) { return L.contains(Pred); }))
DeadExitBlocks.push_back(ExitBlock);
auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
if (!LiveLoopBlocks.count(From))
return false;
BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;
};
DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
if (DeleteCurrentLoop)
return;
BlocksInLoopAfterFolding.insert(L.getLoopLatch());
auto BlockIsInLoop = [&](BasicBlock *BB) {
return any_of(successors(BB), [&](BasicBlock *Succ) {
return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
});
};
for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
BasicBlock *BB = *I;
if (BlockIsInLoop(BB))
BlocksInLoopAfterFolding.insert(BB);
}
assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
"Header not in loop?");
assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
"All blocks that stay in loop should be live!");
}
void handleDeadExits() {
if (DeadExitBlocks.empty())
return;
BasicBlock *Preheader = L.getLoopPreheader();
BasicBlock *NewPreheader = llvm::SplitBlock(
Preheader, Preheader->getTerminator(), &DT, &LI, MSSAU);
IRBuilder<> Builder(Preheader->getTerminator());
SwitchInst *DummySwitch =
Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
Preheader->getTerminator()->eraseFromParent();
unsigned DummyIdx = 1;
for (BasicBlock *BB : DeadExitBlocks) {
SmallVector<Instruction *, 4> DeadInstructions;
for (auto &PN : BB->phis())
DeadInstructions.push_back(&PN);
if (auto *LandingPad = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()))
DeadInstructions.emplace_back(LandingPad);
for (Instruction *I : DeadInstructions) {
I->replaceAllUsesWith(PoisonValue::get(I->getType()));
I->eraseFromParent();
}
assert(DummyIdx != 0 && "Too many dead exits!");
DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});
++NumLoopExitsDeleted;
}
assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");
if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {
Loop *StillReachable = getInnermostLoopFor(LiveExitBlocks, L, LI);
if (StillReachable != OuterLoop) {
LI.changeLoopFor(NewPreheader, StillReachable);
removeBlockFromLoops(NewPreheader, OuterLoop, StillReachable);
for (auto *BB : L.blocks())
removeBlockFromLoops(BB, OuterLoop, StillReachable);
OuterLoop->removeChildLoop(&L);
if (StillReachable)
StillReachable->addChildLoop(&L);
else
LI.addTopLevelLoop(&L);
Loop *FixLCSSALoop = OuterLoop;
while (FixLCSSALoop->getParentLoop() != StillReachable)
FixLCSSALoop = FixLCSSALoop->getParentLoop();
assert(FixLCSSALoop && "Should be a loop!");
if (MSSAU)
MSSAU->applyUpdates(DTUpdates, DT, true);
else
DTU.applyUpdates(DTUpdates);
DTUpdates.clear();
formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
}
}
if (MSSAU) {
MSSAU->applyUpdates(DTUpdates, DT, true);
DTUpdates.clear();
if (VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
}
}
void deleteDeadLoopBlocks() {
if (MSSAU) {
SmallSetVector<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
DeadLoopBlocks.end());
MSSAU->removeBlocks(DeadLoopBlocksSet);
}
for (auto *BB : DeadLoopBlocks)
if (LI.isLoopHeader(BB)) {
assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
Loop *DL = LI.getLoopFor(BB);
if (!DL->isOutermost()) {
for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())
for (auto *BB : DL->getBlocks())
PL->removeBlockFromLoop(BB);
DL->getParentLoop()->removeChildLoop(DL);
LI.addTopLevelLoop(DL);
}
LI.erase(DL);
}
for (auto *BB : DeadLoopBlocks) {
assert(BB != L.getHeader() &&
"Header of the current loop cannot be dead!");
LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
<< "\n");
LI.removeBlock(BB);
}
detachDeadBlocks(DeadLoopBlocks, &DTUpdates, true);
DTU.applyUpdates(DTUpdates);
DTUpdates.clear();
for (auto *BB : DeadLoopBlocks)
DTU.deleteBB(BB);
NumLoopBlocksDeleted += DeadLoopBlocks.size();
}
void foldTerminators() {
for (BasicBlock *BB : FoldCandidates) {
assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
assert(TheOnlySucc && "Should have one live successor!");
LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
<< " with an unconditional branch to the block "
<< TheOnlySucc->getName() << "\n");
SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
unsigned TheOnlySuccDuplicates = 0;
for (auto *Succ : successors(BB))
if (Succ != TheOnlySucc) {
DeadSuccessors.insert(Succ);
bool PreserveLCSSAPhi = !L.contains(Succ);
Succ->removePredecessor(BB, PreserveLCSSAPhi);
if (MSSAU)
MSSAU->removeEdge(BB, Succ);
} else
++TheOnlySuccDuplicates;
assert(TheOnlySuccDuplicates > 0 && "Should be!");
bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
if (MSSAU && TheOnlySuccDuplicates > 1)
MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
IRBuilder<> Builder(BB->getContext());
Instruction *Term = BB->getTerminator();
Builder.SetInsertPoint(Term);
Builder.CreateBr(TheOnlySucc);
Term->eraseFromParent();
for (auto *DeadSucc : DeadSuccessors)
DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});
++NumTerminatorsFolded;
}
}
public:
ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
ScalarEvolution &SE,
MemorySSAUpdater *MSSAU)
: L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU), DFS(&L),
DTU(DT, DomTreeUpdater::UpdateStrategy::Eager) {}
bool run() {
assert(L.getLoopLatch() && "Should be single latch!");
analyze();
BasicBlock *Header = L.getHeader();
(void)Header;
LLVM_DEBUG(dbgs() << "In function " << Header->getParent()->getName()
<< ": ");
if (HasIrreducibleCFG) {
LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
return false;
}
if (FoldCandidates.empty()) {
LLVM_DEBUG(
dbgs() << "No constant terminator folding candidates found in loop "
<< Header->getName() << "\n");
return false;
}
if (DeleteCurrentLoop) {
LLVM_DEBUG(
dbgs()
<< "Give up constant terminator folding in loop " << Header->getName()
<< ": we don't currently support deletion of the current loop.\n");
return false;
}
if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
L.getNumBlocks()) {
LLVM_DEBUG(
dbgs() << "Give up constant terminator folding in loop "
<< Header->getName() << ": we don't currently"
" support blocks that are not dead, but will stop "
"being a part of the loop after constant-folding.\n");
return false;
}
if (!DeadExitBlocks.empty() && !L.isLCSSAForm(DT, false)) {
assert(L.isLCSSAForm(DT, true) &&
"LCSSA broken not by tokens?");
LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop "
<< Header->getName()
<< ": tokens uses potentially break LCSSA form.\n");
return false;
}
SE.forgetTopmostLoop(&L);
LLVM_DEBUG(dump());
LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
<< " terminators in loop " << Header->getName() << "\n");
handleDeadExits();
foldTerminators();
if (!DeadLoopBlocks.empty()) {
LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
<< " dead blocks in loop " << Header->getName() << "\n");
deleteDeadLoopBlocks();
} else {
DTU.applyUpdates(DTUpdates);
DTUpdates.clear();
}
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
#ifndef NDEBUG
#if defined(EXPENSIVE_CHECKS)
assert(DT.verify(DominatorTree::VerificationLevel::Full) &&
"DT broken after transform!");
#else
assert(DT.verify(DominatorTree::VerificationLevel::Fast) &&
"DT broken after transform!");
#endif
assert(DT.isReachableFromEntry(Header));
LI.verify(DT);
#endif
return true;
}
bool foldingBreaksCurrentLoop() const {
return DeleteCurrentLoop;
}
};
}
static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
ScalarEvolution &SE,
MemorySSAUpdater *MSSAU,
bool &IsLoopDeleted) {
if (!EnableTermFolding)
return false;
if (!L.getLoopLatch())
return false;
ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
bool Changed = BranchFolder.run();
IsLoopDeleted = Changed && BranchFolder.foldingBreaksCurrentLoop();
return Changed;
}
static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
LoopInfo &LI, MemorySSAUpdater *MSSAU) {
bool Changed = false;
DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
for (auto &Block : Blocks) {
BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
if (!Succ)
continue;
BasicBlock *Pred = Succ->getSinglePredecessor();
if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
continue;
MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
if (MSSAU && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
Changed = true;
}
return Changed;
}
static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
ScalarEvolution &SE, MemorySSAUpdater *MSSAU,
bool &IsLoopDeleted) {
bool Changed = false;
Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU, IsLoopDeleted);
if (IsLoopDeleted)
return true;
Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
if (Changed)
SE.forgetTopmostLoop(&L);
return Changed;
}
PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
LoopStandardAnalysisResults &AR,
LPMUpdater &LPMU) {
Optional<MemorySSAUpdater> MSSAU;
if (AR.MSSA)
MSSAU = MemorySSAUpdater(AR.MSSA);
bool DeleteCurrentLoop = false;
if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
MSSAU ? MSSAU.getPointer() : nullptr, DeleteCurrentLoop))
return PreservedAnalyses::all();
if (DeleteCurrentLoop)
LPMU.markLoopAsDeleted(L, "loop-simplifycfg");
auto PA = getLoopPassPreservedAnalyses();
if (AR.MSSA)
PA.preserve<MemorySSAAnalysis>();
return PA;
}
namespace {
class LoopSimplifyCFGLegacyPass : public LoopPass {
public:
static char ID; LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnLoop(Loop *L, LPPassManager &LPM) override {
if (skipLoop(L))
return false;
DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
auto *MSSAA = getAnalysisIfAvailable<MemorySSAWrapperPass>();
Optional<MemorySSAUpdater> MSSAU;
if (MSSAA)
MSSAU = MemorySSAUpdater(&MSSAA->getMSSA());
if (MSSAA && VerifyMemorySSA)
MSSAU->getMemorySSA()->verifyMemorySSA();
bool DeleteCurrentLoop = false;
bool Changed =
simplifyLoopCFG(*L, DT, LI, SE, MSSAU ? MSSAU.getPointer() : nullptr,
DeleteCurrentLoop);
if (DeleteCurrentLoop)
LPM.markLoopAsDeleted(*L);
return Changed;
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addPreserved<MemorySSAWrapperPass>();
AU.addPreserved<DependenceAnalysisWrapperPass>();
getLoopAnalysisUsage(AU);
}
};
}
char LoopSimplifyCFGLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
"Simplify loop CFG", false, false)
INITIALIZE_PASS_DEPENDENCY(LoopPass)
INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
"Simplify loop CFG", false, false)
Pass *llvm::createLoopSimplifyCFGPass() {
return new LoopSimplifyCFGLegacyPass();
}