Convert LoopSimplify and LoopExtractor from FunctionPass to LoopPass.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@82990 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Dan Gohman 2009-09-28 14:37:51 +00:00
parent 522ce97532
commit d84db11333
4 changed files with 91 additions and 149 deletions

View File

@ -19,7 +19,6 @@
namespace llvm { namespace llvm {
class FunctionPass;
class ModulePass; class ModulePass;
class Pass; class Pass;
class Function; class Function;
@ -174,12 +173,12 @@ ModulePass *createIPSCCPPass();
/// createLoopExtractorPass - This pass extracts all natural loops from the /// createLoopExtractorPass - This pass extracts all natural loops from the
/// program into a function if it can. /// program into a function if it can.
/// ///
FunctionPass *createLoopExtractorPass(); Pass *createLoopExtractorPass();
/// createSingleLoopExtractorPass - This pass extracts one natural loop from the /// createSingleLoopExtractorPass - This pass extracts one natural loop from the
/// program into a function if it can. This is used by bugpoint. /// program into a function if it can. This is used by bugpoint.
/// ///
FunctionPass *createSingleLoopExtractorPass(); Pass *createSingleLoopExtractorPass();
/// createBlockExtractorPass - This pass extracts all blocks (except those /// createBlockExtractorPass - This pass extracts all blocks (except those
/// specified in the argument list) from the functions in the module. /// specified in the argument list) from the functions in the module.

View File

@ -220,7 +220,7 @@ extern const PassInfo *const BreakCriticalEdgesID;
// //
// AU.addRequiredID(LoopSimplifyID); // AU.addRequiredID(LoopSimplifyID);
// //
FunctionPass *createLoopSimplifyPass(); Pass *createLoopSimplifyPass();
extern const PassInfo *const LoopSimplifyID; extern const PassInfo *const LoopSimplifyID;
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//

View File

@ -20,7 +20,7 @@
#include "llvm/Module.h" #include "llvm/Module.h"
#include "llvm/Pass.h" #include "llvm/Pass.h"
#include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopPass.h"
#include "llvm/Support/CommandLine.h" #include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h" #include "llvm/Support/Compiler.h"
#include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Scalar.h"
@ -33,23 +33,19 @@ using namespace llvm;
STATISTIC(NumExtracted, "Number of loops extracted"); STATISTIC(NumExtracted, "Number of loops extracted");
namespace { namespace {
// FIXME: This is not a function pass, but the PassManager doesn't allow struct VISIBILITY_HIDDEN LoopExtractor : public LoopPass {
// Module passes to require FunctionPasses, so we can't get loop info if we're
// not a function pass.
struct VISIBILITY_HIDDEN LoopExtractor : public FunctionPass {
static char ID; // Pass identification, replacement for typeid static char ID; // Pass identification, replacement for typeid
unsigned NumLoops; unsigned NumLoops;
explicit LoopExtractor(unsigned numLoops = ~0) explicit LoopExtractor(unsigned numLoops = ~0)
: FunctionPass(&ID), NumLoops(numLoops) {} : LoopPass(&ID), NumLoops(numLoops) {}
virtual bool runOnFunction(Function &F); virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
virtual void getAnalysisUsage(AnalysisUsage &AU) const { virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequiredID(BreakCriticalEdgesID); AU.addRequiredID(BreakCriticalEdgesID);
AU.addRequiredID(LoopSimplifyID); AU.addRequiredID(LoopSimplifyID);
AU.addRequired<DominatorTree>(); AU.addRequired<DominatorTree>();
AU.addRequired<LoopInfo>();
} }
}; };
} }
@ -73,68 +69,50 @@ Y("loop-extract-single", "Extract at most one loop into a new function");
// createLoopExtractorPass - This pass extracts all natural loops from the // createLoopExtractorPass - This pass extracts all natural loops from the
// program into a function if it can. // program into a function if it can.
// //
FunctionPass *llvm::createLoopExtractorPass() { return new LoopExtractor(); } Pass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
bool LoopExtractor::runOnFunction(Function &F) { bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &LPM) {
LoopInfo &LI = getAnalysis<LoopInfo>(); // Only visit top-level loops.
if (L->getParentLoop())
// If this function has no loops, there is nothing to do.
if (LI.empty())
return false; return false;
DominatorTree &DT = getAnalysis<DominatorTree>(); DominatorTree &DT = getAnalysis<DominatorTree>();
bool Changed = false;
// If there is more than one top-level loop in this function, extract all of // If there is more than one top-level loop in this function, extract all of
// the loops. // the loops. Otherwise there is exactly one top-level loop; in this case if
bool Changed = false; // this function is more than a minimal wrapper around the loop, extract
if (LI.end()-LI.begin() > 1) { // the loop.
for (LoopInfo::iterator i = LI.begin(), e = LI.end(); i != e; ++i) { bool ShouldExtractLoop = false;
if (NumLoops == 0) return Changed;
--NumLoops;
Changed |= ExtractLoop(DT, *i) != 0;
++NumExtracted;
}
} else {
// Otherwise there is exactly one top-level loop. If this function is more
// than a minimal wrapper around the loop, extract the loop.
Loop *TLL = *LI.begin();
bool ShouldExtractLoop = false;
// Extract the loop if the entry block doesn't branch to the loop header. // Extract the loop if the entry block doesn't branch to the loop header.
TerminatorInst *EntryTI = F.getEntryBlock().getTerminator(); TerminatorInst *EntryTI =
if (!isa<BranchInst>(EntryTI) || L->getHeader()->getParent()->getEntryBlock().getTerminator();
!cast<BranchInst>(EntryTI)->isUnconditional() || if (!isa<BranchInst>(EntryTI) ||
EntryTI->getSuccessor(0) != TLL->getHeader()) !cast<BranchInst>(EntryTI)->isUnconditional() ||
ShouldExtractLoop = true; EntryTI->getSuccessor(0) != L->getHeader())
else { ShouldExtractLoop = true;
// Check to see if any exits from the loop are more than just return else {
// blocks. // Check to see if any exits from the loop are more than just return
SmallVector<BasicBlock*, 8> ExitBlocks; // blocks.
TLL->getExitBlocks(ExitBlocks); SmallVector<BasicBlock*, 8> ExitBlocks;
for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) L->getExitBlocks(ExitBlocks);
if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) { for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
ShouldExtractLoop = true; if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) {
break; ShouldExtractLoop = true;
} break;
}
if (ShouldExtractLoop) {
if (NumLoops == 0) return Changed;
--NumLoops;
Changed |= ExtractLoop(DT, TLL) != 0;
++NumExtracted;
} else {
// Okay, this function is a minimal container around the specified loop.
// If we extract the loop, we will continue to just keep extracting it
// infinitely... so don't extract it. However, if the loop contains any
// subloops, extract them.
for (Loop::iterator i = TLL->begin(), e = TLL->end(); i != e; ++i) {
if (NumLoops == 0) return Changed;
--NumLoops;
Changed |= ExtractLoop(DT, *i) != 0;
++NumExtracted;
} }
}
if (ShouldExtractLoop) {
if (NumLoops == 0) return Changed;
--NumLoops;
if (ExtractLoop(DT, L) != 0) {
Changed = true;
// After extraction, the loop is replaced by a function call, so
// we shouldn't try to run any more loop passes on it.
LPM.deleteLoopFromQueue(L);
} }
++NumExtracted;
} }
return Changed; return Changed;
@ -143,7 +121,7 @@ bool LoopExtractor::runOnFunction(Function &F) {
// createSingleLoopExtractorPass - This pass extracts one natural loop from the // createSingleLoopExtractorPass - This pass extracts one natural loop from the
// program into a function if it can. This is used by bugpoint. // program into a function if it can. This is used by bugpoint.
// //
FunctionPass *llvm::createSingleLoopExtractorPass() { Pass *llvm::createSingleLoopExtractorPass() {
return new SingleLoopExtractor(); return new SingleLoopExtractor();
} }

View File

@ -41,7 +41,8 @@
#include "llvm/Type.h" #include "llvm/Type.h"
#include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h" #include "llvm/Transforms/Utils/Local.h"
#include "llvm/Support/CFG.h" #include "llvm/Support/CFG.h"
@ -56,16 +57,17 @@ STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
STATISTIC(NumNested , "Number of nested loops split out"); STATISTIC(NumNested , "Number of nested loops split out");
namespace { namespace {
struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass { struct VISIBILITY_HIDDEN LoopSimplify : public LoopPass {
static char ID; // Pass identification, replacement for typeid static char ID; // Pass identification, replacement for typeid
LoopSimplify() : FunctionPass(&ID) {} LoopSimplify() : LoopPass(&ID) {}
// AA - If we have an alias analysis object to update, this is it, otherwise // AA - If we have an alias analysis object to update, this is it, otherwise
// this is null. // this is null.
AliasAnalysis *AA; AliasAnalysis *AA;
LoopInfo *LI; LoopInfo *LI;
DominatorTree *DT; DominatorTree *DT;
virtual bool runOnFunction(Function &F); Loop *L;
virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
virtual void getAnalysisUsage(AnalysisUsage &AU) const { virtual void getAnalysisUsage(AnalysisUsage &AU) const {
// We need loop information to identify the loops... // We need loop information to identify the loops...
@ -76,25 +78,20 @@ namespace {
AU.addPreserved<DominatorTree>(); AU.addPreserved<DominatorTree>();
AU.addPreserved<DominanceFrontier>(); AU.addPreserved<DominanceFrontier>();
AU.addPreserved<AliasAnalysis>(); AU.addPreserved<AliasAnalysis>();
AU.addPreserved<ScalarEvolution>();
AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added. AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
} }
/// verifyAnalysis() - Verify loop nest. /// verifyAnalysis() - Verify loop nest.
void verifyAnalysis() const { void verifyAnalysis() const {
#ifndef NDEBUG assert(L->isLoopSimplifyForm() && "LoopSimplify form not preserved!");
LoopInfo *NLI = &getAnalysis<LoopInfo>();
for (LoopInfo::iterator I = NLI->begin(), E = NLI->end(); I != E; ++I) {
// Check the special guarantees that LoopSimplify makes.
assert((*I)->isLoopSimplifyForm());
}
#endif
} }
private: private:
bool ProcessLoop(Loop *L); bool ProcessLoop(Loop *L, LPPassManager &LPM);
BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit); BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
BasicBlock *InsertPreheaderForLoop(Loop *L); BasicBlock *InsertPreheaderForLoop(Loop *L);
Loop *SeparateNestedLoop(Loop *L); Loop *SeparateNestedLoop(Loop *L, LPPassManager &LPM);
void InsertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader); void InsertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader);
void PlaceSplitBlockCarefully(BasicBlock *NewBB, void PlaceSplitBlockCarefully(BasicBlock *NewBB,
SmallVectorImpl<BasicBlock*> &SplitPreds, SmallVectorImpl<BasicBlock*> &SplitPreds,
@ -108,73 +105,19 @@ X("loopsimplify", "Canonicalize natural loops", true);
// Publically exposed interface to pass... // Publically exposed interface to pass...
const PassInfo *const llvm::LoopSimplifyID = &X; const PassInfo *const llvm::LoopSimplifyID = &X;
FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); } Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
/// runOnFunction - Run down all loops in the CFG (recursively, but we could do /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
/// it in any convenient order) inserting preheaders... /// it in any convenient order) inserting preheaders...
/// ///
bool LoopSimplify::runOnFunction(Function &F) { bool LoopSimplify::runOnLoop(Loop *l, LPPassManager &LPM) {
L = l;
bool Changed = false; bool Changed = false;
LI = &getAnalysis<LoopInfo>(); LI = &getAnalysis<LoopInfo>();
AA = getAnalysisIfAvailable<AliasAnalysis>(); AA = getAnalysisIfAvailable<AliasAnalysis>();
DT = &getAnalysis<DominatorTree>(); DT = &getAnalysis<DominatorTree>();
// Check to see that no blocks (other than the header) in loops have Changed |= ProcessLoop(L, LPM);
// predecessors that are not in loops. This is not valid for natural loops,
// but can occur if the blocks are unreachable. Since they are unreachable we
// can just shamelessly destroy their terminators to make them not branch into
// the loop!
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
// This case can only occur for unreachable blocks. Blocks that are
// unreachable can't be in loops, so filter those blocks out.
if (LI->getLoopFor(BB)) continue;
bool BlockUnreachable = false;
TerminatorInst *TI = BB->getTerminator();
// Check to see if any successors of this block are non-loop-header loops
// that are not the header.
for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
// If this successor is not in a loop, BB is clearly ok.
Loop *L = LI->getLoopFor(TI->getSuccessor(i));
if (!L) continue;
// If the succ is the loop header, and if L is a top-level loop, then this
// is an entrance into a loop through the header, which is also ok.
if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
continue;
// Otherwise, this is an entrance into a loop from some place invalid.
// Either the loop structure is invalid and this is not a natural loop (in
// which case the compiler is buggy somewhere else) or BB is unreachable.
BlockUnreachable = true;
break;
}
// If this block is ok, check the next one.
if (!BlockUnreachable) continue;
// Otherwise, this block is dead. To clean up the CFG and to allow later
// loop transformations to ignore this case, we delete the edges into the
// loop by replacing the terminator.
// Remove PHI entries from the successors.
for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
TI->getSuccessor(i)->removePredecessor(BB);
// Add a new unreachable instruction before the old terminator.
new UnreachableInst(TI->getContext(), TI);
// Delete the dead terminator.
if (AA) AA->deleteValue(TI);
if (!TI->use_empty())
TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
TI->eraseFromParent();
Changed |= true;
}
for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Changed |= ProcessLoop(*I);
return Changed; return Changed;
} }
@ -182,17 +125,37 @@ bool LoopSimplify::runOnFunction(Function &F) {
/// ProcessLoop - Walk the loop structure in depth first order, ensuring that /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
/// all loops have preheaders. /// all loops have preheaders.
/// ///
bool LoopSimplify::ProcessLoop(Loop *L) { bool LoopSimplify::ProcessLoop(Loop *L, LPPassManager &LPM) {
bool Changed = false; bool Changed = false;
ReprocessLoop: ReprocessLoop:
// Canonicalize inner loops before outer loops. Inner loop canonicalization // Check to see that no blocks (other than the header) in this loop that has
// can provide work for the outer loop to canonicalize. // predecessors that are not in the loop. This is not valid for natural
for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) // loops, but can occur if the blocks are unreachable. Since they are
Changed |= ProcessLoop(*I); // unreachable we can just shamelessly delete those CFG edges!
for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
assert(L->getBlocks()[0] == L->getHeader() && BB != E; ++BB) {
"Header isn't first block in loop?"); if (*BB == L->getHeader()) continue;
SmallPtrSet<BasicBlock *, 4> BadPreds;
for (pred_iterator PI = pred_begin(*BB), PE = pred_end(*BB); PI != PE; ++PI)
if (!L->contains(*PI))
BadPreds.insert(*PI);
// Delete each unique out-of-loop (and thus dead) predecessor.
for (SmallPtrSet<BasicBlock *, 4>::iterator I = BadPreds.begin(),
E = BadPreds.end(); I != E; ++I) {
// Inform each successor of each dead pred.
for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
(*SI)->removePredecessor(*I);
// Zap the dead pred's terminator and replace it with unreachable.
TerminatorInst *TI = (*I)->getTerminator();
TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
(*I)->getTerminator()->eraseFromParent();
new UnreachableInst((*I)->getContext(), *I);
Changed = true;
}
}
// Does the loop already have a preheader? If so, don't insert one. // Does the loop already have a preheader? If so, don't insert one.
BasicBlock *Preheader = L->getLoopPreheader(); BasicBlock *Preheader = L->getLoopPreheader();
@ -233,10 +196,9 @@ ReprocessLoop:
// this for loops with a giant number of backedges, just factor them into a // this for loops with a giant number of backedges, just factor them into a
// common backedge instead. // common backedge instead.
if (NumBackedges < 8) { if (NumBackedges < 8) {
if (Loop *NL = SeparateNestedLoop(L)) { if (SeparateNestedLoop(L, LPM)) {
++NumNested; ++NumNested;
// This is a big restructuring change, reprocess the whole loop. // This is a big restructuring change, reprocess the whole loop.
ProcessLoop(NL);
Changed = true; Changed = true;
// GCC doesn't tail recursion eliminate this. // GCC doesn't tail recursion eliminate this.
goto ReprocessLoop; goto ReprocessLoop;
@ -472,7 +434,7 @@ void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
/// If we are able to separate out a loop, return the new outer loop that was /// If we are able to separate out a loop, return the new outer loop that was
/// created. /// created.
/// ///
Loop *LoopSimplify::SeparateNestedLoop(Loop *L) { Loop *LoopSimplify::SeparateNestedLoop(Loop *L, LPPassManager &LPM) {
PHINode *PN = FindPHIToPartitionLoops(L, DT, AA); PHINode *PN = FindPHIToPartitionLoops(L, DT, AA);
if (PN == 0) return 0; // No known way to partition. if (PN == 0) return 0; // No known way to partition.
@ -506,6 +468,9 @@ Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
// L is now a subloop of our outer loop. // L is now a subloop of our outer loop.
NewOuter->addChildLoop(L); NewOuter->addChildLoop(L);
// Add the new loop to the pass manager queue.
LPM.insertLoopIntoQueue(NewOuter);
for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
I != E; ++I) I != E; ++I)
NewOuter->addBlockEntry(*I); NewOuter->addBlockEntry(*I);