LoopExtractor.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. #define DEBUG_TYPE "loop-extract"
  17. #include "llvm/Transforms/IPO.h"
  18. #include "llvm/Instructions.h"
  19. #include "llvm/Module.h"
  20. #include "llvm/Pass.h"
  21. #include "llvm/Analysis/Dominators.h"
  22. #include "llvm/Analysis/LoopInfo.h"
  23. #include "llvm/Support/CommandLine.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. #include <fstream>
  29. #include <set>
  30. using namespace llvm;
  31. STATISTIC(NumExtracted, "Number of loops extracted");
  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. static char ID; // Pass identification, replacement for typeid
  38. unsigned NumLoops;
  39. explicit LoopExtractor(unsigned numLoops = ~0)
  40. : FunctionPass(&ID), NumLoops(numLoops) {}
  41. virtual bool runOnFunction(Function &F);
  42. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  43. AU.addRequiredID(BreakCriticalEdgesID);
  44. AU.addRequiredID(LoopSimplifyID);
  45. AU.addRequired<DominatorTree>();
  46. AU.addRequired<LoopInfo>();
  47. }
  48. };
  49. }
  50. char LoopExtractor::ID = 0;
  51. static RegisterPass<LoopExtractor>
  52. X("loop-extract", "Extract loops into new functions");
  53. namespace {
  54. /// SingleLoopExtractor - For bugpoint.
  55. struct SingleLoopExtractor : public LoopExtractor {
  56. static char ID; // Pass identification, replacement for typeid
  57. SingleLoopExtractor() : LoopExtractor(1) {}
  58. };
  59. } // End anonymous namespace
  60. char SingleLoopExtractor::ID = 0;
  61. static RegisterPass<SingleLoopExtractor>
  62. Y("loop-extract-single", "Extract at most one loop into a new function");
  63. // createLoopExtractorPass - This pass extracts all natural loops from the
  64. // program into a function if it can.
  65. //
  66. FunctionPass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
  67. bool LoopExtractor::runOnFunction(Function &F) {
  68. LoopInfo &LI = getAnalysis<LoopInfo>();
  69. // If this function has no loops, there is nothing to do.
  70. if (LI.empty())
  71. return false;
  72. DominatorTree &DT = getAnalysis<DominatorTree>();
  73. // If there is more than one top-level loop in this function, extract all of
  74. // the loops.
  75. bool Changed = false;
  76. if (LI.end()-LI.begin() > 1) {
  77. for (LoopInfo::iterator i = LI.begin(), e = LI.end(); i != e; ++i) {
  78. if (NumLoops == 0) return Changed;
  79. --NumLoops;
  80. Changed |= ExtractLoop(DT, *i) != 0;
  81. ++NumExtracted;
  82. }
  83. } else {
  84. // Otherwise there is exactly one top-level loop. If this function is more
  85. // than a minimal wrapper around the loop, extract the loop.
  86. Loop *TLL = *LI.begin();
  87. bool ShouldExtractLoop = false;
  88. // Extract the loop if the entry block doesn't branch to the loop header.
  89. TerminatorInst *EntryTI = F.getEntryBlock().getTerminator();
  90. if (!isa<BranchInst>(EntryTI) ||
  91. !cast<BranchInst>(EntryTI)->isUnconditional() ||
  92. EntryTI->getSuccessor(0) != TLL->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. TLL->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. Changed |= ExtractLoop(DT, TLL) != 0;
  109. ++NumExtracted;
  110. } else {
  111. // Okay, this function is a minimal container around the specified loop.
  112. // If we extract the loop, we will continue to just keep extracting it
  113. // infinitely... so don't extract it. However, if the loop contains any
  114. // subloops, extract them.
  115. for (Loop::iterator i = TLL->begin(), e = TLL->end(); i != e; ++i) {
  116. if (NumLoops == 0) return Changed;
  117. --NumLoops;
  118. Changed |= ExtractLoop(DT, *i) != 0;
  119. ++NumExtracted;
  120. }
  121. }
  122. }
  123. return Changed;
  124. }
  125. // createSingleLoopExtractorPass - This pass extracts one natural loop from the
  126. // program into a function if it can. This is used by bugpoint.
  127. //
  128. FunctionPass *llvm::createSingleLoopExtractorPass() {
  129. return new SingleLoopExtractor();
  130. }
  131. // BlockFile - A file which contains a list of blocks that should not be
  132. // extracted.
  133. static cl::opt<std::string>
  134. BlockFile("extract-blocks-file", cl::value_desc("filename"),
  135. cl::desc("A file containing list of basic blocks to not extract"),
  136. cl::Hidden);
  137. namespace {
  138. /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
  139. /// from the module into their own functions except for those specified by the
  140. /// BlocksToNotExtract list.
  141. class BlockExtractorPass : public ModulePass {
  142. void LoadFile(const char *Filename);
  143. std::vector<BasicBlock*> BlocksToNotExtract;
  144. std::vector<std::pair<std::string, std::string> > BlocksToNotExtractByName;
  145. public:
  146. static char ID; // Pass identification, replacement for typeid
  147. explicit BlockExtractorPass(const std::vector<BasicBlock*> &B)
  148. : ModulePass(&ID), BlocksToNotExtract(B) {
  149. if (!BlockFile.empty())
  150. LoadFile(BlockFile.c_str());
  151. }
  152. BlockExtractorPass() : ModulePass(&ID) {}
  153. bool runOnModule(Module &M);
  154. };
  155. }
  156. char BlockExtractorPass::ID = 0;
  157. static RegisterPass<BlockExtractorPass>
  158. XX("extract-blocks", "Extract Basic Blocks From Module (for bugpoint use)");
  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(const std::vector<BasicBlock*> &BTNE)
  163. {
  164. return new BlockExtractorPass(BTNE);
  165. }
  166. void BlockExtractorPass::LoadFile(const char *Filename) {
  167. // Load the BlockFile...
  168. std::ifstream In(Filename);
  169. if (!In.good()) {
  170. cerr << "WARNING: BlockExtractor couldn't load file '" << Filename
  171. << "'!\n";
  172. return;
  173. }
  174. while (In) {
  175. std::string FunctionName, BlockName;
  176. In >> FunctionName;
  177. In >> BlockName;
  178. if (!BlockName.empty())
  179. BlocksToNotExtractByName.push_back(
  180. std::make_pair(FunctionName, BlockName));
  181. }
  182. }
  183. bool BlockExtractorPass::runOnModule(Module &M) {
  184. std::set<BasicBlock*> TranslatedBlocksToNotExtract;
  185. for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
  186. BasicBlock *BB = BlocksToNotExtract[i];
  187. Function *F = BB->getParent();
  188. // Map the corresponding function in this module.
  189. Function *MF = M.getFunction(F->getName());
  190. assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
  191. // Figure out which index the basic block is in its function.
  192. Function::iterator BBI = MF->begin();
  193. std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
  194. TranslatedBlocksToNotExtract.insert(BBI);
  195. }
  196. while (!BlocksToNotExtractByName.empty()) {
  197. // There's no way to find BBs by name without looking at every BB inside
  198. // every Function. Fortunately, this is always empty except when used by
  199. // bugpoint in which case correctness is more important than performance.
  200. std::string &FuncName = BlocksToNotExtractByName.back().first;
  201. std::string &BlockName = BlocksToNotExtractByName.back().second;
  202. for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
  203. Function &F = *FI;
  204. if (F.getName() != FuncName) continue;
  205. for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
  206. BasicBlock &BB = *BI;
  207. if (BB.getName() != BlockName) continue;
  208. TranslatedBlocksToNotExtract.insert(BI);
  209. }
  210. }
  211. BlocksToNotExtractByName.pop_back();
  212. }
  213. // Now that we know which blocks to not extract, figure out which ones we WANT
  214. // to extract.
  215. std::vector<BasicBlock*> BlocksToExtract;
  216. for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
  217. for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
  218. if (!TranslatedBlocksToNotExtract.count(BB))
  219. BlocksToExtract.push_back(BB);
  220. for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i)
  221. ExtractBasicBlock(BlocksToExtract[i]);
  222. return !BlocksToExtract.empty();
  223. }