blob: 36b6bdba2cd0248371b6b46646f7626c41ca0402 [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
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/Analysis/LoopPass.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000019#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Module.h"
Misha Brukman03a11342004-02-28 03:33:01 +000022#include "llvm/Pass.h"
Nick Lewyckyc6243022007-11-14 06:47:06 +000023#include "llvm/Support/CommandLine.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "llvm/Transforms/IPO.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
Justin Bognere9fb228d2016-01-08 19:08:53 +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
Sanjoy Dasdef17292017-09-28 02:45:42 +000083bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kayloraa641a52016-04-22 22:06:11 +000084 if (skipLoop(L))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +000085 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.
Sanjoy Dasdef17292017-09-28 02:45:42 +0000146 LPM.markLoopAsDeleted(*L);
Sanjoy Das388b0122017-09-22 01:47:41 +0000147 LI.erase(L);
Chris Lattner2f155d82004-03-15 00:02:02 +0000148 }
Dan Gohman9a7320c2009-09-28 14:37:51 +0000149 ++NumExtracted;
Chris Lattnera1672c12004-03-14 20:01:36 +0000150 }
Misha Brukman03a11342004-02-28 03:33:01 +0000151
152 return Changed;
153}
154
Chris Lattnera1672c12004-03-14 20:01:36 +0000155// createSingleLoopExtractorPass - This pass extracts one natural loop from the
156// program into a function if it can. This is used by bugpoint.
157//
Dan Gohman9a7320c2009-09-28 14:37:51 +0000158Pass *llvm::createSingleLoopExtractorPass() {
Chris Lattnera1672c12004-03-14 20:01:36 +0000159 return new SingleLoopExtractor();
Misha Brukman03a11342004-02-28 03:33:01 +0000160}
Chris Lattner7386e632004-08-13 03:05:17 +0000161
162
Dan Gohmand78c4002008-05-13 00:00:25 +0000163// BlockFile - A file which contains a list of blocks that should not be
164// extracted.
165static cl::opt<std::string>
166BlockFile("extract-blocks-file", cl::value_desc("filename"),
167 cl::desc("A file containing list of basic blocks to not extract"),
168 cl::Hidden);
Nick Lewyckyc6243022007-11-14 06:47:06 +0000169
Dan Gohmand78c4002008-05-13 00:00:25 +0000170namespace {
Chris Lattner7386e632004-08-13 03:05:17 +0000171 /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
172 /// from the module into their own functions except for those specified by the
173 /// BlocksToNotExtract list.
Chris Lattner4f2cf032004-09-20 04:48:05 +0000174 class BlockExtractorPass : public ModulePass {
Nick Lewyckyc6243022007-11-14 06:47:06 +0000175 void LoadFile(const char *Filename);
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000176 void SplitLandingPadPreds(Function *F);
Nick Lewyckyc6243022007-11-14 06:47:06 +0000177
Chris Lattner7386e632004-08-13 03:05:17 +0000178 std::vector<BasicBlock*> BlocksToNotExtract;
Nick Lewyckyc6243022007-11-14 06:47:06 +0000179 std::vector<std::pair<std::string, std::string> > BlocksToNotExtractByName;
Chris Lattner7386e632004-08-13 03:05:17 +0000180 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000181 static char ID; // Pass identification, replacement for typeid
Owen Andersona7aed182010-08-06 18:33:48 +0000182 BlockExtractorPass() : ModulePass(ID) {
Nick Lewyckyc6243022007-11-14 06:47:06 +0000183 if (!BlockFile.empty())
184 LoadFile(BlockFile.c_str());
185 }
Chris Lattner7386e632004-08-13 03:05:17 +0000186
Craig Topper3e4c6972014-03-05 09:10:37 +0000187 bool runOnModule(Module &M) override;
Chris Lattner7386e632004-08-13 03:05:17 +0000188 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000189}
Chris Lattner7386e632004-08-13 03:05:17 +0000190
Dan Gohmand78c4002008-05-13 00:00:25 +0000191char BlockExtractorPass::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +0000192INITIALIZE_PASS(BlockExtractorPass, "extract-blocks",
193 "Extract Basic Blocks From Module (for bugpoint use)",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000194 false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000195
Chris Lattner7386e632004-08-13 03:05:17 +0000196// createBlockExtractorPass - This pass extracts all blocks (except those
197// specified in the argument list) from the functions in the module.
198//
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000199ModulePass *llvm::createBlockExtractorPass() {
Rafael Espindola40f18832010-07-31 00:32:17 +0000200 return new BlockExtractorPass();
Chris Lattner7386e632004-08-13 03:05:17 +0000201}
202
Nick Lewyckyc6243022007-11-14 06:47:06 +0000203void BlockExtractorPass::LoadFile(const char *Filename) {
204 // Load the BlockFile...
205 std::ifstream In(Filename);
206 if (!In.good()) {
Chris Lattner4883d902009-08-23 07:19:13 +0000207 errs() << "WARNING: BlockExtractor couldn't load file '" << Filename
208 << "'!\n";
Nick Lewyckyc6243022007-11-14 06:47:06 +0000209 return;
210 }
211 while (In) {
212 std::string FunctionName, BlockName;
213 In >> FunctionName;
214 In >> BlockName;
215 if (!BlockName.empty())
216 BlocksToNotExtractByName.push_back(
217 std::make_pair(FunctionName, BlockName));
218 }
219}
220
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000221/// SplitLandingPadPreds - The landing pad needs to be extracted with the invoke
222/// instruction. The critical edge breaker will refuse to break critical edges
223/// to a landing pad. So do them here. After this method runs, all landing pads
224/// should have only one predecessor.
225void BlockExtractorPass::SplitLandingPadPreds(Function *F) {
226 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
227 InvokeInst *II = dyn_cast<InvokeInst>(I);
228 if (!II) continue;
229 BasicBlock *Parent = II->getParent();
230 BasicBlock *LPad = II->getUnwindDest();
231
232 // Look through the landing pad's predecessors. If one of them ends in an
233 // 'invoke', then we want to split the landing pad.
234 bool Split = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000235 for (pred_iterator
236 PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ++PI) {
237 BasicBlock *BB = *PI;
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000238 if (BB->isLandingPad() && BB != Parent &&
239 isa<InvokeInst>(Parent->getTerminator())) {
240 Split = true;
241 break;
242 }
243 }
244
245 if (!Split) continue;
246
247 SmallVector<BasicBlock*, 2> NewBBs;
Chandler Carruth0eae1122015-01-19 03:03:39 +0000248 SplitLandingPadPredecessors(LPad, Parent, ".1", ".2", NewBBs);
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000249 }
250}
251
Chris Lattner4f2cf032004-09-20 04:48:05 +0000252bool BlockExtractorPass::runOnModule(Module &M) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000253 if (skipModule(M))
254 return false;
255
Chris Lattner7386e632004-08-13 03:05:17 +0000256 std::set<BasicBlock*> TranslatedBlocksToNotExtract;
257 for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
258 BasicBlock *BB = BlocksToNotExtract[i];
259 Function *F = BB->getParent();
260
261 // Map the corresponding function in this module.
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000262 Function *MF = M.getFunction(F->getName());
263 assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
Chris Lattner7386e632004-08-13 03:05:17 +0000264
265 // Figure out which index the basic block is in its function.
266 Function::iterator BBI = MF->begin();
267 std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000268 TranslatedBlocksToNotExtract.insert(&*BBI);
Chris Lattner7386e632004-08-13 03:05:17 +0000269 }
270
Nick Lewyckyc6243022007-11-14 06:47:06 +0000271 while (!BlocksToNotExtractByName.empty()) {
272 // There's no way to find BBs by name without looking at every BB inside
273 // every Function. Fortunately, this is always empty except when used by
274 // bugpoint in which case correctness is more important than performance.
275
276 std::string &FuncName = BlocksToNotExtractByName.back().first;
277 std::string &BlockName = BlocksToNotExtractByName.back().second;
278
Benjamin Kramer135f7352016-06-26 12:28:59 +0000279 for (Function &F : M) {
Nick Lewyckyc6243022007-11-14 06:47:06 +0000280 if (F.getName() != FuncName) continue;
281
Benjamin Kramer135f7352016-06-26 12:28:59 +0000282 for (BasicBlock &BB : F) {
Nick Lewyckyc6243022007-11-14 06:47:06 +0000283 if (BB.getName() != BlockName) continue;
284
Benjamin Kramer135f7352016-06-26 12:28:59 +0000285 TranslatedBlocksToNotExtract.insert(&BB);
Nick Lewyckyc6243022007-11-14 06:47:06 +0000286 }
287 }
288
289 BlocksToNotExtractByName.pop_back();
290 }
291
Chris Lattner7386e632004-08-13 03:05:17 +0000292 // Now that we know which blocks to not extract, figure out which ones we WANT
293 // to extract.
294 std::vector<BasicBlock*> BlocksToExtract;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000295 for (Function &F : M) {
296 SplitLandingPadPreds(&F);
297 for (BasicBlock &BB : F)
298 if (!TranslatedBlocksToNotExtract.count(&BB))
299 BlocksToExtract.push_back(&BB);
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000300 }
Chris Lattner7386e632004-08-13 03:05:17 +0000301
Benjamin Kramer135f7352016-06-26 12:28:59 +0000302 for (BasicBlock *BlockToExtract : BlocksToExtract) {
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000303 SmallVector<BasicBlock*, 2> BlocksToExtractVec;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000304 BlocksToExtractVec.push_back(BlockToExtract);
Bill Wendling3d48f592011-09-20 20:20:50 +0000305 if (const InvokeInst *II =
Benjamin Kramer135f7352016-06-26 12:28:59 +0000306 dyn_cast<InvokeInst>(BlockToExtract->getTerminator()))
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000307 BlocksToExtractVec.push_back(II->getUnwindDest());
Chandler Carruth0fde0012012-05-04 10:18:49 +0000308 CodeExtractor(BlocksToExtractVec).extractCodeRegion();
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000309 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000310
Chris Lattner7386e632004-08-13 03:05:17 +0000311 return !BlocksToExtract.empty();
312}