LoopExtractor.cpp revision f5a86f45e75ec744c203270ffa03659eb0a220c1
1//===- LoopExtractor.cpp - Extract each loop into a new function ----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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/LoopPass.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Transforms/Scalar.h"
26#include "llvm/Transforms/Utils/FunctionUtils.h"
27#include "llvm/ADT/Statistic.h"
28#include <fstream>
29#include <set>
30using namespace llvm;
31
32STATISTIC(NumExtracted, "Number of loops extracted");
33
34namespace {
35  struct LoopExtractor : public LoopPass {
36    static char ID; // Pass identification, replacement for typeid
37    unsigned NumLoops;
38
39    explicit LoopExtractor(unsigned numLoops = ~0)
40      : LoopPass(&ID), NumLoops(numLoops) {}
41
42    virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
43
44    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
45      AU.addRequiredID(BreakCriticalEdgesID);
46      AU.addRequiredID(LoopSimplifyID);
47      AU.addRequired<DominatorTree>();
48    }
49  };
50}
51
52char LoopExtractor::ID = 0;
53static RegisterPass<LoopExtractor>
54X("loop-extract", "Extract loops into new functions");
55
56namespace {
57  /// SingleLoopExtractor - For bugpoint.
58  struct SingleLoopExtractor : public LoopExtractor {
59    static char ID; // Pass identification, replacement for typeid
60    SingleLoopExtractor() : LoopExtractor(1) {}
61  };
62} // End anonymous namespace
63
64char SingleLoopExtractor::ID = 0;
65static RegisterPass<SingleLoopExtractor>
66Y("loop-extract-single", "Extract at most one loop into a new function");
67
68// createLoopExtractorPass - This pass extracts all natural loops from the
69// program into a function if it can.
70//
71Pass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
72
73bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &LPM) {
74  // Only visit top-level loops.
75  if (L->getParentLoop())
76    return false;
77
78  DominatorTree &DT = getAnalysis<DominatorTree>();
79  bool Changed = false;
80
81  // If there is more than one top-level loop in this function, extract all of
82  // the loops. Otherwise there is exactly one top-level loop; in this case if
83  // this function is more than a minimal wrapper around the loop, extract
84  // the loop.
85  bool ShouldExtractLoop = false;
86
87  // Extract the loop if the entry block doesn't branch to the loop header.
88  TerminatorInst *EntryTI =
89    L->getHeader()->getParent()->getEntryBlock().getTerminator();
90  if (!isa<BranchInst>(EntryTI) ||
91      !cast<BranchInst>(EntryTI)->isUnconditional() ||
92      EntryTI->getSuccessor(0) != L->getHeader())
93    ShouldExtractLoop = true;
94  else {
95    // Check to see if any exits from the loop are more than just return
96    // blocks.
97    SmallVector<BasicBlock*, 8> ExitBlocks;
98    L->getExitBlocks(ExitBlocks);
99    for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
100      if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) {
101        ShouldExtractLoop = true;
102        break;
103      }
104  }
105  if (ShouldExtractLoop) {
106    if (NumLoops == 0) return Changed;
107    --NumLoops;
108    if (ExtractLoop(DT, L) != 0) {
109      Changed = true;
110      // After extraction, the loop is replaced by a function call, so
111      // we shouldn't try to run any more loop passes on it.
112      LPM.deleteLoopFromQueue(L);
113    }
114    ++NumExtracted;
115  }
116
117  return Changed;
118}
119
120// createSingleLoopExtractorPass - This pass extracts one natural loop from the
121// program into a function if it can.  This is used by bugpoint.
122//
123Pass *llvm::createSingleLoopExtractorPass() {
124  return new SingleLoopExtractor();
125}
126
127
128// BlockFile - A file which contains a list of blocks that should not be
129// extracted.
130static cl::opt<std::string>
131BlockFile("extract-blocks-file", cl::value_desc("filename"),
132          cl::desc("A file containing list of basic blocks to not extract"),
133          cl::Hidden);
134
135namespace {
136  /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
137  /// from the module into their own functions except for those specified by the
138  /// BlocksToNotExtract list.
139  class BlockExtractorPass : public ModulePass {
140    void LoadFile(const char *Filename);
141
142    std::vector<BasicBlock*> BlocksToNotExtract;
143    std::vector<std::pair<std::string, std::string> > BlocksToNotExtractByName;
144  public:
145    static char ID; // Pass identification, replacement for typeid
146    explicit BlockExtractorPass(const std::vector<BasicBlock*> &B)
147      : ModulePass(&ID), BlocksToNotExtract(B) {
148      if (!BlockFile.empty())
149        LoadFile(BlockFile.c_str());
150    }
151    BlockExtractorPass() : ModulePass(&ID) {}
152
153    bool runOnModule(Module &M);
154  };
155}
156
157char BlockExtractorPass::ID = 0;
158static RegisterPass<BlockExtractorPass>
159XX("extract-blocks", "Extract Basic Blocks From Module (for bugpoint use)");
160
161// createBlockExtractorPass - This pass extracts all blocks (except those
162// specified in the argument list) from the functions in the module.
163//
164ModulePass *llvm::createBlockExtractorPass(const std::vector<BasicBlock*> &BTNE)
165{
166  return new BlockExtractorPass(BTNE);
167}
168
169void BlockExtractorPass::LoadFile(const char *Filename) {
170  // Load the BlockFile...
171  std::ifstream In(Filename);
172  if (!In.good()) {
173    errs() << "WARNING: BlockExtractor couldn't load file '" << Filename
174           << "'!\n";
175    return;
176  }
177  while (In) {
178    std::string FunctionName, BlockName;
179    In >> FunctionName;
180    In >> BlockName;
181    if (!BlockName.empty())
182      BlocksToNotExtractByName.push_back(
183          std::make_pair(FunctionName, BlockName));
184  }
185}
186
187bool BlockExtractorPass::runOnModule(Module &M) {
188  std::set<BasicBlock*> TranslatedBlocksToNotExtract;
189  for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
190    BasicBlock *BB = BlocksToNotExtract[i];
191    Function *F = BB->getParent();
192
193    // Map the corresponding function in this module.
194    Function *MF = M.getFunction(F->getName());
195    assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
196
197    // Figure out which index the basic block is in its function.
198    Function::iterator BBI = MF->begin();
199    std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
200    TranslatedBlocksToNotExtract.insert(BBI);
201  }
202
203  while (!BlocksToNotExtractByName.empty()) {
204    // There's no way to find BBs by name without looking at every BB inside
205    // every Function. Fortunately, this is always empty except when used by
206    // bugpoint in which case correctness is more important than performance.
207
208    std::string &FuncName  = BlocksToNotExtractByName.back().first;
209    std::string &BlockName = BlocksToNotExtractByName.back().second;
210
211    for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
212      Function &F = *FI;
213      if (F.getName() != FuncName) continue;
214
215      for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
216        BasicBlock &BB = *BI;
217        if (BB.getName() != BlockName) continue;
218
219        TranslatedBlocksToNotExtract.insert(BI);
220      }
221    }
222
223    BlocksToNotExtractByName.pop_back();
224  }
225
226  // Now that we know which blocks to not extract, figure out which ones we WANT
227  // to extract.
228  std::vector<BasicBlock*> BlocksToExtract;
229  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
230    for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
231      if (!TranslatedBlocksToNotExtract.count(BB))
232        BlocksToExtract.push_back(BB);
233
234  for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i)
235    ExtractBasicBlock(BlocksToExtract[i]);
236
237  return !BlocksToExtract.empty();
238}
239