blob: 714282b2b5eb11f8eb24c7a0c6aea2cdf0a60710 [file] [log] [blame]
Misha Brukman03a11342004-02-28 03:33:01 +00001//===- LoopExtractor.cpp - Extract each loop into a new function ----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner692a47a2004-03-14 02:34:07 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner692a47a2004-03-14 02:34:07 +00008//===----------------------------------------------------------------------===//
Misha Brukman03a11342004-02-28 03:33:01 +00009//
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
Misha Brukmanf272f9b2004-03-02 00:19:09 +000012// given function, it is not touched. This is a pass most useful for debugging
13// via bugpoint.
Misha Brukman03a11342004-02-28 03:33:01 +000014//
15//===----------------------------------------------------------------------===//
16
Chris Lattner1631bcb2006-12-19 22:09:18 +000017#define DEBUG_TYPE "loop-extract"
Chris Lattner78a996a2004-03-14 02:37:16 +000018#include "llvm/Transforms/IPO.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000019#include "llvm/Instructions.h"
Misha Brukman03a11342004-02-28 03:33:01 +000020#include "llvm/Module.h"
21#include "llvm/Pass.h"
Chris Lattnere9235d22004-03-18 03:48:06 +000022#include "llvm/Analysis/Dominators.h"
Dan Gohman9a7320c2009-09-28 14:37:51 +000023#include "llvm/Analysis/LoopPass.h"
Nick Lewyckyc6243022007-11-14 06:47:06 +000024#include "llvm/Support/CommandLine.h"
Chris Lattner6c3e8c72004-03-14 04:01:06 +000025#include "llvm/Transforms/Scalar.h"
Bill Wendlingc1da6ea2011-09-20 19:10:24 +000026#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Misha Brukman03a11342004-02-28 03:33:01 +000027#include "llvm/Transforms/Utils/FunctionUtils.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/ADT/Statistic.h"
Nick Lewyckyc6243022007-11-14 06:47:06 +000029#include <fstream>
30#include <set>
Misha Brukman03a11342004-02-28 03:33:01 +000031using namespace llvm;
32
Chris Lattner1631bcb2006-12-19 22:09:18 +000033STATISTIC(NumExtracted, "Number of loops extracted");
Misha Brukmanb1c93172005-04-21 23:48:37 +000034
Chris Lattner1631bcb2006-12-19 22:09:18 +000035namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000036 struct LoopExtractor : public LoopPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000037 static char ID; // Pass identification, replacement for typeid
Chris Lattnera1672c12004-03-14 20:01:36 +000038 unsigned NumLoops;
39
Dan Gohman34d442f2007-08-01 15:32:29 +000040 explicit LoopExtractor(unsigned numLoops = ~0)
Owen Anderson6c18d1a2010-10-19 17:21:58 +000041 : LoopPass(ID), NumLoops(numLoops) {
42 initializeLoopExtractorPass(*PassRegistry::getPassRegistry());
43 }
Chris Lattnera1672c12004-03-14 20:01:36 +000044
Dan Gohman9a7320c2009-09-28 14:37:51 +000045 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +000046
Chris Lattner692a47a2004-03-14 02:34:07 +000047 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner5bce0c82004-03-18 05:43:18 +000048 AU.addRequiredID(BreakCriticalEdgesID);
49 AU.addRequiredID(LoopSimplifyID);
Owen Andersonf095bf32007-04-07 05:31:27 +000050 AU.addRequired<DominatorTree>();
Chris Lattner692a47a2004-03-14 02:34:07 +000051 }
52 };
Dan Gohmand78c4002008-05-13 00:00:25 +000053}
Misha Brukman03a11342004-02-28 03:33:01 +000054
Dan Gohmand78c4002008-05-13 00:00:25 +000055char LoopExtractor::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000056INITIALIZE_PASS_BEGIN(LoopExtractor, "loop-extract",
Bill Wendlingc1da6ea2011-09-20 19:10:24 +000057 "Extract loops into new functions", false, false)
Owen Anderson8ac477f2010-10-12 19:48:12 +000058INITIALIZE_PASS_DEPENDENCY(BreakCriticalEdges)
59INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
60INITIALIZE_PASS_DEPENDENCY(DominatorTree)
61INITIALIZE_PASS_END(LoopExtractor, "loop-extract",
Bill Wendlingc1da6ea2011-09-20 19:10:24 +000062 "Extract loops into new functions", false, false)
Chris Lattnera1672c12004-03-14 20:01:36 +000063
Dan Gohmand78c4002008-05-13 00:00:25 +000064namespace {
Chris Lattnera1672c12004-03-14 20:01:36 +000065 /// SingleLoopExtractor - For bugpoint.
66 struct SingleLoopExtractor : public LoopExtractor {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Chris Lattnera1672c12004-03-14 20:01:36 +000068 SingleLoopExtractor() : LoopExtractor(1) {}
69 };
Misha Brukmanb1c93172005-04-21 23:48:37 +000070} // End anonymous namespace
Misha Brukman03a11342004-02-28 03:33:01 +000071
Dan Gohmand78c4002008-05-13 00:00:25 +000072char SingleLoopExtractor::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +000073INITIALIZE_PASS(SingleLoopExtractor, "loop-extract-single",
Owen Andersondf7a4f22010-10-07 22:25:06 +000074 "Extract at most one loop into a new function", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000075
Jeff Cohen677babc2005-01-08 17:21:40 +000076// createLoopExtractorPass - This pass extracts all natural loops from the
77// program into a function if it can.
78//
Dan Gohman9a7320c2009-09-28 14:37:51 +000079Pass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
Jeff Cohen677babc2005-01-08 17:21:40 +000080
Dan Gohman9a7320c2009-09-28 14:37:51 +000081bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &LPM) {
82 // Only visit top-level loops.
83 if (L->getParentLoop())
Misha Brukman03a11342004-02-28 03:33:01 +000084 return false;
85
Dan Gohmana83ac2d2009-11-05 21:11:53 +000086 // If LoopSimplify form is not available, stay out of trouble.
87 if (!L->isLoopSimplifyForm())
88 return false;
89
Owen Andersonf095bf32007-04-07 05:31:27 +000090 DominatorTree &DT = getAnalysis<DominatorTree>();
Dan Gohman9a7320c2009-09-28 14:37:51 +000091 bool Changed = false;
Chris Lattnere9235d22004-03-18 03:48:06 +000092
Chris Lattner2f155d82004-03-15 00:02:02 +000093 // If there is more than one top-level loop in this function, extract all of
Dan Gohman9a7320c2009-09-28 14:37:51 +000094 // the loops. Otherwise there is exactly one top-level loop; in this case if
95 // this function is more than a minimal wrapper around the loop, extract
96 // the loop.
97 bool ShouldExtractLoop = false;
Misha Brukmanb1c93172005-04-21 23:48:37 +000098
Dan Gohman9a7320c2009-09-28 14:37:51 +000099 // Extract the loop if the entry block doesn't branch to the loop header.
100 TerminatorInst *EntryTI =
101 L->getHeader()->getParent()->getEntryBlock().getTerminator();
102 if (!isa<BranchInst>(EntryTI) ||
103 !cast<BranchInst>(EntryTI)->isUnconditional() ||
104 EntryTI->getSuccessor(0) != L->getHeader())
105 ShouldExtractLoop = true;
106 else {
107 // Check to see if any exits from the loop are more than just return
108 // blocks.
109 SmallVector<BasicBlock*, 8> ExitBlocks;
110 L->getExitBlocks(ExitBlocks);
111 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
112 if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) {
113 ShouldExtractLoop = true;
114 break;
Chris Lattner2f155d82004-03-15 00:02:02 +0000115 }
Dan Gohman9a7320c2009-09-28 14:37:51 +0000116 }
117 if (ShouldExtractLoop) {
118 if (NumLoops == 0) return Changed;
119 --NumLoops;
120 if (ExtractLoop(DT, L) != 0) {
121 Changed = true;
122 // After extraction, the loop is replaced by a function call, so
123 // we shouldn't try to run any more loop passes on it.
124 LPM.deleteLoopFromQueue(L);
Chris Lattner2f155d82004-03-15 00:02:02 +0000125 }
Dan Gohman9a7320c2009-09-28 14:37:51 +0000126 ++NumExtracted;
Chris Lattnera1672c12004-03-14 20:01:36 +0000127 }
Misha Brukman03a11342004-02-28 03:33:01 +0000128
129 return Changed;
130}
131
Chris Lattnera1672c12004-03-14 20:01:36 +0000132// createSingleLoopExtractorPass - This pass extracts one natural loop from the
133// program into a function if it can. This is used by bugpoint.
134//
Dan Gohman9a7320c2009-09-28 14:37:51 +0000135Pass *llvm::createSingleLoopExtractorPass() {
Chris Lattnera1672c12004-03-14 20:01:36 +0000136 return new SingleLoopExtractor();
Misha Brukman03a11342004-02-28 03:33:01 +0000137}
Chris Lattner7386e632004-08-13 03:05:17 +0000138
139
Dan Gohmand78c4002008-05-13 00:00:25 +0000140// BlockFile - A file which contains a list of blocks that should not be
141// extracted.
142static cl::opt<std::string>
143BlockFile("extract-blocks-file", cl::value_desc("filename"),
144 cl::desc("A file containing list of basic blocks to not extract"),
145 cl::Hidden);
Nick Lewyckyc6243022007-11-14 06:47:06 +0000146
Dan Gohmand78c4002008-05-13 00:00:25 +0000147namespace {
Chris Lattner7386e632004-08-13 03:05:17 +0000148 /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
149 /// from the module into their own functions except for those specified by the
150 /// BlocksToNotExtract list.
Chris Lattner4f2cf032004-09-20 04:48:05 +0000151 class BlockExtractorPass : public ModulePass {
Nick Lewyckyc6243022007-11-14 06:47:06 +0000152 void LoadFile(const char *Filename);
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000153 void SplitLandingPadPreds(Function *F);
Nick Lewyckyc6243022007-11-14 06:47:06 +0000154
Chris Lattner7386e632004-08-13 03:05:17 +0000155 std::vector<BasicBlock*> BlocksToNotExtract;
Nick Lewyckyc6243022007-11-14 06:47:06 +0000156 std::vector<std::pair<std::string, std::string> > BlocksToNotExtractByName;
Chris Lattner7386e632004-08-13 03:05:17 +0000157 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000158 static char ID; // Pass identification, replacement for typeid
Owen Andersona7aed182010-08-06 18:33:48 +0000159 BlockExtractorPass() : ModulePass(ID) {
Nick Lewyckyc6243022007-11-14 06:47:06 +0000160 if (!BlockFile.empty())
161 LoadFile(BlockFile.c_str());
162 }
Chris Lattner7386e632004-08-13 03:05:17 +0000163
Chris Lattner4f2cf032004-09-20 04:48:05 +0000164 bool runOnModule(Module &M);
Chris Lattner7386e632004-08-13 03:05:17 +0000165 };
Chris Lattner7386e632004-08-13 03:05:17 +0000166}
167
Dan Gohmand78c4002008-05-13 00:00:25 +0000168char BlockExtractorPass::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +0000169INITIALIZE_PASS(BlockExtractorPass, "extract-blocks",
170 "Extract Basic Blocks From Module (for bugpoint use)",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000171 false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000172
Chris Lattner7386e632004-08-13 03:05:17 +0000173// createBlockExtractorPass - This pass extracts all blocks (except those
174// specified in the argument list) from the functions in the module.
175//
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000176ModulePass *llvm::createBlockExtractorPass() {
Rafael Espindola40f18832010-07-31 00:32:17 +0000177 return new BlockExtractorPass();
Chris Lattner7386e632004-08-13 03:05:17 +0000178}
179
Nick Lewyckyc6243022007-11-14 06:47:06 +0000180void BlockExtractorPass::LoadFile(const char *Filename) {
181 // Load the BlockFile...
182 std::ifstream In(Filename);
183 if (!In.good()) {
Chris Lattner4883d902009-08-23 07:19:13 +0000184 errs() << "WARNING: BlockExtractor couldn't load file '" << Filename
185 << "'!\n";
Nick Lewyckyc6243022007-11-14 06:47:06 +0000186 return;
187 }
188 while (In) {
189 std::string FunctionName, BlockName;
190 In >> FunctionName;
191 In >> BlockName;
192 if (!BlockName.empty())
193 BlocksToNotExtractByName.push_back(
194 std::make_pair(FunctionName, BlockName));
195 }
196}
197
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000198/// SplitLandingPadPreds - The landing pad needs to be extracted with the invoke
199/// instruction. The critical edge breaker will refuse to break critical edges
200/// to a landing pad. So do them here. After this method runs, all landing pads
201/// should have only one predecessor.
202void BlockExtractorPass::SplitLandingPadPreds(Function *F) {
203 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
204 InvokeInst *II = dyn_cast<InvokeInst>(I);
205 if (!II) continue;
206 BasicBlock *Parent = II->getParent();
207 BasicBlock *LPad = II->getUnwindDest();
208
209 // Look through the landing pad's predecessors. If one of them ends in an
210 // 'invoke', then we want to split the landing pad.
211 bool Split = false;
212 for (pred_iterator
213 PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ++PI) {
214 BasicBlock *BB = *PI;
215 if (BB->isLandingPad() && BB != Parent &&
216 isa<InvokeInst>(Parent->getTerminator())) {
217 Split = true;
218 break;
219 }
220 }
221
222 if (!Split) continue;
223
224 SmallVector<BasicBlock*, 2> NewBBs;
225 SplitLandingPadPredecessors(LPad, Parent, ".1", ".2", 0, NewBBs);
226 }
227}
228
Chris Lattner4f2cf032004-09-20 04:48:05 +0000229bool BlockExtractorPass::runOnModule(Module &M) {
Chris Lattner7386e632004-08-13 03:05:17 +0000230 std::set<BasicBlock*> TranslatedBlocksToNotExtract;
231 for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
232 BasicBlock *BB = BlocksToNotExtract[i];
233 Function *F = BB->getParent();
234
235 // Map the corresponding function in this module.
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000236 Function *MF = M.getFunction(F->getName());
237 assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
Chris Lattner7386e632004-08-13 03:05:17 +0000238
239 // Figure out which index the basic block is in its function.
240 Function::iterator BBI = MF->begin();
241 std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
242 TranslatedBlocksToNotExtract.insert(BBI);
243 }
244
Nick Lewyckyc6243022007-11-14 06:47:06 +0000245 while (!BlocksToNotExtractByName.empty()) {
246 // There's no way to find BBs by name without looking at every BB inside
247 // every Function. Fortunately, this is always empty except when used by
248 // bugpoint in which case correctness is more important than performance.
249
250 std::string &FuncName = BlocksToNotExtractByName.back().first;
251 std::string &BlockName = BlocksToNotExtractByName.back().second;
252
253 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
254 Function &F = *FI;
255 if (F.getName() != FuncName) continue;
256
257 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
258 BasicBlock &BB = *BI;
259 if (BB.getName() != BlockName) continue;
260
261 TranslatedBlocksToNotExtract.insert(BI);
262 }
263 }
264
265 BlocksToNotExtractByName.pop_back();
266 }
267
Chris Lattner7386e632004-08-13 03:05:17 +0000268 // Now that we know which blocks to not extract, figure out which ones we WANT
269 // to extract.
270 std::vector<BasicBlock*> BlocksToExtract;
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000271 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
272 SplitLandingPadPreds(&*F);
Chris Lattner7386e632004-08-13 03:05:17 +0000273 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
274 if (!TranslatedBlocksToNotExtract.count(BB))
275 BlocksToExtract.push_back(BB);
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000276 }
Chris Lattner7386e632004-08-13 03:05:17 +0000277
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000278 for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i) {
279 SmallVector<BasicBlock*, 2> BlocksToExtractVec;
280 BlocksToExtractVec.push_back(BlocksToExtract[i]);
Bill Wendling3d48f592011-09-20 20:20:50 +0000281 if (const InvokeInst *II =
282 dyn_cast<InvokeInst>(BlocksToExtract[i]->getTerminator()))
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000283 BlocksToExtractVec.push_back(II->getUnwindDest());
284 ExtractBasicBlock(BlocksToExtractVec);
285 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000286
Chris Lattner7386e632004-08-13 03:05:17 +0000287 return !BlocksToExtract.empty();
288}