avoid iterator invalidation.
[oota-llvm.git] / lib / Transforms / IPO / LoopExtractor.cpp
1 //===- LoopExtractor.cpp - Extract each loop into a new function ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // A pass wrapper around the ExtractLoop() scalar transformation to extract each
11 // top-level loop into its own new function. If the loop is the ONLY loop in a
12 // given function, it is not touched. This is a pass most useful for debugging
13 // via bugpoint.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "loop-extract"
18 #include "llvm/Transforms/IPO.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/Transforms/Utils/FunctionUtils.h"
27 #include "llvm/ADT/Statistic.h"
28 using namespace llvm;
29
30 STATISTIC(NumExtracted, "Number of loops extracted");
31
32 namespace {
33   // FIXME: This is not a function pass, but the PassManager doesn't allow
34   // Module passes to require FunctionPasses, so we can't get loop info if we're
35   // not a function pass.
36   struct VISIBILITY_HIDDEN LoopExtractor : public FunctionPass {
37     unsigned NumLoops;
38
39     LoopExtractor(unsigned numLoops = ~0) : NumLoops(numLoops) {}
40
41     virtual bool runOnFunction(Function &F);
42
43     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
44       AU.addRequiredID(BreakCriticalEdgesID);
45       AU.addRequiredID(LoopSimplifyID);
46       AU.addRequired<ETForest>();
47       AU.addRequired<DominatorTree>();
48       AU.addRequired<LoopInfo>();
49     }
50   };
51
52   RegisterPass<LoopExtractor>
53   X("loop-extract", "Extract loops into new functions");
54
55   /// SingleLoopExtractor - For bugpoint.
56   struct SingleLoopExtractor : public LoopExtractor {
57     SingleLoopExtractor() : LoopExtractor(1) {}
58   };
59
60   RegisterPass<SingleLoopExtractor>
61   Y("loop-extract-single", "Extract at most one loop into a new function");
62 } // End anonymous namespace
63
64 // createLoopExtractorPass - This pass extracts all natural loops from the
65 // program into a function if it can.
66 //
67 FunctionPass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
68
69 bool LoopExtractor::runOnFunction(Function &F) {
70   LoopInfo &LI = getAnalysis<LoopInfo>();
71
72   // If this function has no loops, there is nothing to do.
73   if (LI.begin() == LI.end())
74     return false;
75
76   ETForest &EF = getAnalysis<ETForest>();
77   DominatorTree &DT = getAnalysis<DominatorTree>();
78
79   // If there is more than one top-level loop in this function, extract all of
80   // the loops.
81   bool Changed = false;
82   if (LI.end()-LI.begin() > 1) {
83     for (LoopInfo::iterator i = LI.begin(), e = LI.end(); i != e; ++i) {
84       if (NumLoops == 0) return Changed;
85       --NumLoops;
86       Changed |= ExtractLoop(EF, DT, *i) != 0;
87       ++NumExtracted;
88     }
89   } else {
90     // Otherwise there is exactly one top-level loop.  If this function is more
91     // than a minimal wrapper around the loop, extract the loop.
92     Loop *TLL = *LI.begin();
93     bool ShouldExtractLoop = false;
94
95     // Extract the loop if the entry block doesn't branch to the loop header.
96     TerminatorInst *EntryTI = F.getEntryBlock().getTerminator();
97     if (!isa<BranchInst>(EntryTI) ||
98         !cast<BranchInst>(EntryTI)->isUnconditional() ||
99         EntryTI->getSuccessor(0) != TLL->getHeader())
100       ShouldExtractLoop = true;
101     else {
102       // Check to see if any exits from the loop are more than just return
103       // blocks.
104       std::vector<BasicBlock*> ExitBlocks;
105       TLL->getExitBlocks(ExitBlocks);
106       for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
107         if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) {
108           ShouldExtractLoop = true;
109           break;
110         }
111     }
112
113     if (ShouldExtractLoop) {
114       if (NumLoops == 0) return Changed;
115       --NumLoops;
116       Changed |= ExtractLoop(EF, DT, TLL) != 0;
117       ++NumExtracted;
118     } else {
119       // Okay, this function is a minimal container around the specified loop.
120       // If we extract the loop, we will continue to just keep extracting it
121       // infinitely... so don't extract it.  However, if the loop contains any
122       // subloops, extract them.
123       for (Loop::iterator i = TLL->begin(), e = TLL->end(); i != e; ++i) {
124         if (NumLoops == 0) return Changed;
125         --NumLoops;
126         Changed |= ExtractLoop(EF, DT, *i) != 0;
127         ++NumExtracted;
128       }
129     }
130   }
131
132   return Changed;
133 }
134
135 // createSingleLoopExtractorPass - This pass extracts one natural loop from the
136 // program into a function if it can.  This is used by bugpoint.
137 //
138 FunctionPass *llvm::createSingleLoopExtractorPass() {
139   return new SingleLoopExtractor();
140 }
141
142
143 namespace {
144   /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
145   /// from the module into their own functions except for those specified by the
146   /// BlocksToNotExtract list.
147   class BlockExtractorPass : public ModulePass {
148     std::vector<BasicBlock*> BlocksToNotExtract;
149   public:
150     BlockExtractorPass(std::vector<BasicBlock*> &B) : BlocksToNotExtract(B) {}
151     BlockExtractorPass() {}
152
153     bool runOnModule(Module &M);
154   };
155   RegisterPass<BlockExtractorPass>
156   XX("extract-blocks", "Extract Basic Blocks From Module (for bugpoint use)");
157 }
158
159 // createBlockExtractorPass - This pass extracts all blocks (except those
160 // specified in the argument list) from the functions in the module.
161 //
162 ModulePass *llvm::createBlockExtractorPass(std::vector<BasicBlock*> &BTNE) {
163   return new BlockExtractorPass(BTNE);
164 }
165
166 bool BlockExtractorPass::runOnModule(Module &M) {
167   std::set<BasicBlock*> TranslatedBlocksToNotExtract;
168   for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
169     BasicBlock *BB = BlocksToNotExtract[i];
170     Function *F = BB->getParent();
171
172     // Map the corresponding function in this module.
173     Function *MF = M.getFunction(F->getName());
174     assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
175
176     // Figure out which index the basic block is in its function.
177     Function::iterator BBI = MF->begin();
178     std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
179     TranslatedBlocksToNotExtract.insert(BBI);
180   }
181
182   // Now that we know which blocks to not extract, figure out which ones we WANT
183   // to extract.
184   std::vector<BasicBlock*> BlocksToExtract;
185   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
186     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
187       if (!TranslatedBlocksToNotExtract.count(BB))
188         BlocksToExtract.push_back(BB);
189
190   for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i)
191     ExtractBasicBlock(BlocksToExtract[i]);
192
193   return !BlocksToExtract.empty();
194 }