blob: 8e4ad642ddd50b340aaaa3841282edf0dbb6a948 [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 Lattner78a996a2004-03-14 02:37:16 +000017#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/LoopPass.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000020#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Instructions.h"
22#include "llvm/IR/Module.h"
Misha Brukman03a11342004-02-28 03:33:01 +000023#include "llvm/Pass.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"
Chandler Carruth0fde0012012-05-04 10:18:49 +000027#include "llvm/Transforms/Utils/CodeExtractor.h"
Nick Lewyckyc6243022007-11-14 06:47:06 +000028#include <fstream>
29#include <set>
Misha Brukman03a11342004-02-28 03:33:01 +000030using namespace llvm;
31
Chandler Carruth964daaa2014-04-22 02:55:47 +000032#define DEBUG_TYPE "loop-extract"
33
Chris Lattner1631bcb2006-12-19 22:09:18 +000034STATISTIC(NumExtracted, "Number of loops extracted");
Misha Brukmanb1c93172005-04-21 23:48:37 +000035
Chris Lattner1631bcb2006-12-19 22:09:18 +000036namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000037 struct LoopExtractor : public LoopPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000038 static char ID; // Pass identification, replacement for typeid
Chris Lattnera1672c12004-03-14 20:01:36 +000039 unsigned NumLoops;
40
Dan Gohman34d442f2007-08-01 15:32:29 +000041 explicit LoopExtractor(unsigned numLoops = ~0)
Owen Anderson6c18d1a2010-10-19 17:21:58 +000042 : LoopPass(ID), NumLoops(numLoops) {
43 initializeLoopExtractorPass(*PassRegistry::getPassRegistry());
44 }
Chris Lattnera1672c12004-03-14 20:01:36 +000045
Justin Bogner883a3ea2015-12-16 18:40:20 +000046 bool runOnLoop(Loop *L, LPPassManager &) override;
Misha Brukmanb1c93172005-04-21 23:48:37 +000047
Craig Topper3e4c6972014-03-05 09:10:37 +000048 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattner5bce0c82004-03-18 05:43:18 +000049 AU.addRequiredID(BreakCriticalEdgesID);
50 AU.addRequiredID(LoopSimplifyID);
Chandler Carruth73523022014-01-13 13:07:17 +000051 AU.addRequired<DominatorTreeWrapperPass>();
Justin Bogner883a3ea2015-12-16 18:40:20 +000052 AU.addRequired<LoopInfoWrapperPass>();
Chris Lattner692a47a2004-03-14 02:34:07 +000053 }
54 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000055}
Misha Brukman03a11342004-02-28 03:33:01 +000056
Dan Gohmand78c4002008-05-13 00:00:25 +000057char LoopExtractor::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000058INITIALIZE_PASS_BEGIN(LoopExtractor, "loop-extract",
Bill Wendlingc1da6ea2011-09-20 19:10:24 +000059 "Extract loops into new functions", false, false)
Owen Anderson8ac477f2010-10-12 19:48:12 +000060INITIALIZE_PASS_DEPENDENCY(BreakCriticalEdges)
61INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Chandler Carruth73523022014-01-13 13:07:17 +000062INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +000063INITIALIZE_PASS_END(LoopExtractor, "loop-extract",
Bill Wendlingc1da6ea2011-09-20 19:10:24 +000064 "Extract loops into new functions", false, false)
Chris Lattnera1672c12004-03-14 20:01:36 +000065
Dan Gohmand78c4002008-05-13 00:00:25 +000066namespace {
Chris Lattnera1672c12004-03-14 20:01:36 +000067 /// SingleLoopExtractor - For bugpoint.
68 struct SingleLoopExtractor : public LoopExtractor {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000069 static char ID; // Pass identification, replacement for typeid
Chris Lattnera1672c12004-03-14 20:01:36 +000070 SingleLoopExtractor() : LoopExtractor(1) {}
71 };
Misha Brukmanb1c93172005-04-21 23:48:37 +000072} // End anonymous namespace
Misha Brukman03a11342004-02-28 03:33:01 +000073
Dan Gohmand78c4002008-05-13 00:00:25 +000074char SingleLoopExtractor::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +000075INITIALIZE_PASS(SingleLoopExtractor, "loop-extract-single",
Owen Andersondf7a4f22010-10-07 22:25:06 +000076 "Extract at most one loop into a new function", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000077
Jeff Cohen677babc2005-01-08 17:21:40 +000078// createLoopExtractorPass - This pass extracts all natural loops from the
79// program into a function if it can.
80//
Dan Gohman9a7320c2009-09-28 14:37:51 +000081Pass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
Jeff Cohen677babc2005-01-08 17:21:40 +000082
Justin Bogner883a3ea2015-12-16 18:40:20 +000083bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +000084 if (skipOptnoneFunction(L))
85 return false;
86
Dan Gohman9a7320c2009-09-28 14:37:51 +000087 // Only visit top-level loops.
88 if (L->getParentLoop())
Misha Brukman03a11342004-02-28 03:33:01 +000089 return false;
90
Dan Gohmana83ac2d2009-11-05 21:11:53 +000091 // If LoopSimplify form is not available, stay out of trouble.
92 if (!L->isLoopSimplifyForm())
93 return false;
94
Chandler Carruth73523022014-01-13 13:07:17 +000095 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Justin Bogner883a3ea2015-12-16 18:40:20 +000096 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Dan Gohman9a7320c2009-09-28 14:37:51 +000097 bool Changed = false;
Chris Lattnere9235d22004-03-18 03:48:06 +000098
Chris Lattner2f155d82004-03-15 00:02:02 +000099 // If there is more than one top-level loop in this function, extract all of
Dan Gohman9a7320c2009-09-28 14:37:51 +0000100 // the loops. Otherwise there is exactly one top-level loop; in this case if
101 // this function is more than a minimal wrapper around the loop, extract
102 // the loop.
103 bool ShouldExtractLoop = false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000104
Dan Gohman9a7320c2009-09-28 14:37:51 +0000105 // Extract the loop if the entry block doesn't branch to the loop header.
106 TerminatorInst *EntryTI =
107 L->getHeader()->getParent()->getEntryBlock().getTerminator();
108 if (!isa<BranchInst>(EntryTI) ||
109 !cast<BranchInst>(EntryTI)->isUnconditional() ||
Bill Wendling00585202011-09-20 22:23:09 +0000110 EntryTI->getSuccessor(0) != L->getHeader()) {
Dan Gohman9a7320c2009-09-28 14:37:51 +0000111 ShouldExtractLoop = true;
Bill Wendling00585202011-09-20 22:23:09 +0000112 } else {
Dan Gohman9a7320c2009-09-28 14:37:51 +0000113 // Check to see if any exits from the loop are more than just return
Bill Wendling04289fc2011-09-20 22:27:16 +0000114 // blocks.
115 SmallVector<BasicBlock*, 8> ExitBlocks;
116 L->getExitBlocks(ExitBlocks);
117 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
118 if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) {
119 ShouldExtractLoop = true;
120 break;
121 }
122 }
123
124 if (ShouldExtractLoop) {
David Majnemereb518bd2015-08-04 08:21:40 +0000125 // We must omit EH pads. EH pads must accompany the invoke
Bill Wendling04289fc2011-09-20 22:27:16 +0000126 // instruction. But this would result in a loop in the extracted
Bill Wendling00585202011-09-20 22:23:09 +0000127 // function. An infinite cycle occurs when it tries to extract that loop as
128 // well.
Dan Gohman9a7320c2009-09-28 14:37:51 +0000129 SmallVector<BasicBlock*, 8> ExitBlocks;
130 L->getExitBlocks(ExitBlocks);
Bill Wendling04289fc2011-09-20 22:27:16 +0000131 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
David Majnemereb518bd2015-08-04 08:21:40 +0000132 if (ExitBlocks[i]->isEHPad()) {
Bill Wendling00585202011-09-20 22:23:09 +0000133 ShouldExtractLoop = false;
Dan Gohman9a7320c2009-09-28 14:37:51 +0000134 break;
Chris Lattner2f155d82004-03-15 00:02:02 +0000135 }
Dan Gohman9a7320c2009-09-28 14:37:51 +0000136 }
Bill Wendling04289fc2011-09-20 22:27:16 +0000137
Dan Gohman9a7320c2009-09-28 14:37:51 +0000138 if (ShouldExtractLoop) {
139 if (NumLoops == 0) return Changed;
140 --NumLoops;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000141 CodeExtractor Extractor(DT, *L);
Craig Topperf40110f2014-04-25 05:29:35 +0000142 if (Extractor.extractCodeRegion() != nullptr) {
Dan Gohman9a7320c2009-09-28 14:37:51 +0000143 Changed = true;
144 // After extraction, the loop is replaced by a function call, so
145 // we shouldn't try to run any more loop passes on it.
Justin Bogner883a3ea2015-12-16 18:40:20 +0000146 LI.updateUnloop(L);
Chris Lattner2f155d82004-03-15 00:02:02 +0000147 }
Dan Gohman9a7320c2009-09-28 14:37:51 +0000148 ++NumExtracted;
Chris Lattnera1672c12004-03-14 20:01:36 +0000149 }
Misha Brukman03a11342004-02-28 03:33:01 +0000150
151 return Changed;
152}
153
Chris Lattnera1672c12004-03-14 20:01:36 +0000154// createSingleLoopExtractorPass - This pass extracts one natural loop from the
155// program into a function if it can. This is used by bugpoint.
156//
Dan Gohman9a7320c2009-09-28 14:37:51 +0000157Pass *llvm::createSingleLoopExtractorPass() {
Chris Lattnera1672c12004-03-14 20:01:36 +0000158 return new SingleLoopExtractor();
Misha Brukman03a11342004-02-28 03:33:01 +0000159}
Chris Lattner7386e632004-08-13 03:05:17 +0000160
161
Dan Gohmand78c4002008-05-13 00:00:25 +0000162// BlockFile - A file which contains a list of blocks that should not be
163// extracted.
164static cl::opt<std::string>
165BlockFile("extract-blocks-file", cl::value_desc("filename"),
166 cl::desc("A file containing list of basic blocks to not extract"),
167 cl::Hidden);
Nick Lewyckyc6243022007-11-14 06:47:06 +0000168
Dan Gohmand78c4002008-05-13 00:00:25 +0000169namespace {
Chris Lattner7386e632004-08-13 03:05:17 +0000170 /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
171 /// from the module into their own functions except for those specified by the
172 /// BlocksToNotExtract list.
Chris Lattner4f2cf032004-09-20 04:48:05 +0000173 class BlockExtractorPass : public ModulePass {
Nick Lewyckyc6243022007-11-14 06:47:06 +0000174 void LoadFile(const char *Filename);
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000175 void SplitLandingPadPreds(Function *F);
Nick Lewyckyc6243022007-11-14 06:47:06 +0000176
Chris Lattner7386e632004-08-13 03:05:17 +0000177 std::vector<BasicBlock*> BlocksToNotExtract;
Nick Lewyckyc6243022007-11-14 06:47:06 +0000178 std::vector<std::pair<std::string, std::string> > BlocksToNotExtractByName;
Chris Lattner7386e632004-08-13 03:05:17 +0000179 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000180 static char ID; // Pass identification, replacement for typeid
Owen Andersona7aed182010-08-06 18:33:48 +0000181 BlockExtractorPass() : ModulePass(ID) {
Nick Lewyckyc6243022007-11-14 06:47:06 +0000182 if (!BlockFile.empty())
183 LoadFile(BlockFile.c_str());
184 }
Chris Lattner7386e632004-08-13 03:05:17 +0000185
Craig Topper3e4c6972014-03-05 09:10:37 +0000186 bool runOnModule(Module &M) override;
Chris Lattner7386e632004-08-13 03:05:17 +0000187 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000188}
Chris Lattner7386e632004-08-13 03:05:17 +0000189
Dan Gohmand78c4002008-05-13 00:00:25 +0000190char BlockExtractorPass::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +0000191INITIALIZE_PASS(BlockExtractorPass, "extract-blocks",
192 "Extract Basic Blocks From Module (for bugpoint use)",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000193 false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000194
Chris Lattner7386e632004-08-13 03:05:17 +0000195// createBlockExtractorPass - This pass extracts all blocks (except those
196// specified in the argument list) from the functions in the module.
197//
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000198ModulePass *llvm::createBlockExtractorPass() {
Rafael Espindola40f18832010-07-31 00:32:17 +0000199 return new BlockExtractorPass();
Chris Lattner7386e632004-08-13 03:05:17 +0000200}
201
Nick Lewyckyc6243022007-11-14 06:47:06 +0000202void BlockExtractorPass::LoadFile(const char *Filename) {
203 // Load the BlockFile...
204 std::ifstream In(Filename);
205 if (!In.good()) {
Chris Lattner4883d902009-08-23 07:19:13 +0000206 errs() << "WARNING: BlockExtractor couldn't load file '" << Filename
207 << "'!\n";
Nick Lewyckyc6243022007-11-14 06:47:06 +0000208 return;
209 }
210 while (In) {
211 std::string FunctionName, BlockName;
212 In >> FunctionName;
213 In >> BlockName;
214 if (!BlockName.empty())
215 BlocksToNotExtractByName.push_back(
216 std::make_pair(FunctionName, BlockName));
217 }
218}
219
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000220/// SplitLandingPadPreds - The landing pad needs to be extracted with the invoke
221/// instruction. The critical edge breaker will refuse to break critical edges
222/// to a landing pad. So do them here. After this method runs, all landing pads
223/// should have only one predecessor.
224void BlockExtractorPass::SplitLandingPadPreds(Function *F) {
225 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
226 InvokeInst *II = dyn_cast<InvokeInst>(I);
227 if (!II) continue;
228 BasicBlock *Parent = II->getParent();
229 BasicBlock *LPad = II->getUnwindDest();
230
231 // Look through the landing pad's predecessors. If one of them ends in an
232 // 'invoke', then we want to split the landing pad.
233 bool Split = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000234 for (pred_iterator
235 PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ++PI) {
236 BasicBlock *BB = *PI;
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000237 if (BB->isLandingPad() && BB != Parent &&
238 isa<InvokeInst>(Parent->getTerminator())) {
239 Split = true;
240 break;
241 }
242 }
243
244 if (!Split) continue;
245
246 SmallVector<BasicBlock*, 2> NewBBs;
Chandler Carruth0eae1122015-01-19 03:03:39 +0000247 SplitLandingPadPredecessors(LPad, Parent, ".1", ".2", NewBBs);
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000248 }
249}
250
Chris Lattner4f2cf032004-09-20 04:48:05 +0000251bool BlockExtractorPass::runOnModule(Module &M) {
Chris Lattner7386e632004-08-13 03:05:17 +0000252 std::set<BasicBlock*> TranslatedBlocksToNotExtract;
253 for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
254 BasicBlock *BB = BlocksToNotExtract[i];
255 Function *F = BB->getParent();
256
257 // Map the corresponding function in this module.
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000258 Function *MF = M.getFunction(F->getName());
259 assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
Chris Lattner7386e632004-08-13 03:05:17 +0000260
261 // Figure out which index the basic block is in its function.
262 Function::iterator BBI = MF->begin();
263 std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000264 TranslatedBlocksToNotExtract.insert(&*BBI);
Chris Lattner7386e632004-08-13 03:05:17 +0000265 }
266
Nick Lewyckyc6243022007-11-14 06:47:06 +0000267 while (!BlocksToNotExtractByName.empty()) {
268 // There's no way to find BBs by name without looking at every BB inside
269 // every Function. Fortunately, this is always empty except when used by
270 // bugpoint in which case correctness is more important than performance.
271
272 std::string &FuncName = BlocksToNotExtractByName.back().first;
273 std::string &BlockName = BlocksToNotExtractByName.back().second;
274
275 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
276 Function &F = *FI;
277 if (F.getName() != FuncName) continue;
278
279 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
280 BasicBlock &BB = *BI;
281 if (BB.getName() != BlockName) continue;
282
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000283 TranslatedBlocksToNotExtract.insert(&*BI);
Nick Lewyckyc6243022007-11-14 06:47:06 +0000284 }
285 }
286
287 BlocksToNotExtractByName.pop_back();
288 }
289
Chris Lattner7386e632004-08-13 03:05:17 +0000290 // Now that we know which blocks to not extract, figure out which ones we WANT
291 // to extract.
292 std::vector<BasicBlock*> BlocksToExtract;
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000293 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
294 SplitLandingPadPreds(&*F);
Chris Lattner7386e632004-08-13 03:05:17 +0000295 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000296 if (!TranslatedBlocksToNotExtract.count(&*BB))
297 BlocksToExtract.push_back(&*BB);
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000298 }
Chris Lattner7386e632004-08-13 03:05:17 +0000299
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000300 for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i) {
301 SmallVector<BasicBlock*, 2> BlocksToExtractVec;
302 BlocksToExtractVec.push_back(BlocksToExtract[i]);
Bill Wendling3d48f592011-09-20 20:20:50 +0000303 if (const InvokeInst *II =
304 dyn_cast<InvokeInst>(BlocksToExtract[i]->getTerminator()))
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000305 BlocksToExtractVec.push_back(II->getUnwindDest());
Chandler Carruth0fde0012012-05-04 10:18:49 +0000306 CodeExtractor(BlocksToExtractVec).extractCodeRegion();
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000307 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000308
Chris Lattner7386e632004-08-13 03:05:17 +0000309 return !BlocksToExtract.empty();
310}