LoopExtractor.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. #include "llvm/Transforms/IPO.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/LoopPass.h"
  19. #include "llvm/IR/Dominators.h"
  20. #include "llvm/IR/Instructions.h"
  21. #include "llvm/IR/Module.h"
  22. #include "llvm/Pass.h"
  23. #include "llvm/Support/CommandLine.h"
  24. #include "llvm/Transforms/Scalar.h"
  25. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  26. #include "llvm/Transforms/Utils/CodeExtractor.h"
  27. #include <fstream>
  28. #include <set>
  29. using namespace llvm;
  30. #define DEBUG_TYPE "loop-extract"
  31. STATISTIC(NumExtracted, "Number of loops extracted");
  32. namespace {
  33. struct LoopExtractor : public LoopPass {
  34. static char ID; // Pass identification, replacement for typeid
  35. unsigned NumLoops;
  36. explicit LoopExtractor(unsigned numLoops = ~0)
  37. : LoopPass(ID), NumLoops(numLoops) {
  38. initializeLoopExtractorPass(*PassRegistry::getPassRegistry());
  39. }
  40. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  41. void getAnalysisUsage(AnalysisUsage &AU) const override {
  42. AU.addRequiredID(BreakCriticalEdgesID);
  43. AU.addRequiredID(LoopSimplifyID);
  44. AU.addRequired<DominatorTreeWrapperPass>();
  45. }
  46. };
  47. }
  48. char LoopExtractor::ID = 0;
  49. INITIALIZE_PASS_BEGIN(LoopExtractor, "loop-extract",
  50. "Extract loops into new functions", false, false)
  51. INITIALIZE_PASS_DEPENDENCY(BreakCriticalEdges)
  52. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  53. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  54. INITIALIZE_PASS_END(LoopExtractor, "loop-extract",
  55. "Extract loops into new functions", false, false)
  56. namespace {
  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. char SingleLoopExtractor::ID = 0;
  64. INITIALIZE_PASS(SingleLoopExtractor, "loop-extract-single",
  65. "Extract at most one loop into a new function", false, false)
  66. // createLoopExtractorPass - This pass extracts all natural loops from the
  67. // program into a function if it can.
  68. //
  69. Pass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
  70. bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &LPM) {
  71. if (skipOptnoneFunction(L))
  72. return false;
  73. // Only visit top-level loops.
  74. if (L->getParentLoop())
  75. return false;
  76. // If LoopSimplify form is not available, stay out of trouble.
  77. if (!L->isLoopSimplifyForm())
  78. return false;
  79. DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  80. bool Changed = false;
  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. // Extract the loop if the entry block doesn't branch to the loop header.
  87. TerminatorInst *EntryTI =
  88. L->getHeader()->getParent()->getEntryBlock().getTerminator();
  89. if (!isa<BranchInst>(EntryTI) ||
  90. !cast<BranchInst>(EntryTI)->isUnconditional() ||
  91. EntryTI->getSuccessor(0) != L->getHeader()) {
  92. ShouldExtractLoop = true;
  93. } else {
  94. // Check to see if any exits from the loop are more than just return
  95. // blocks.
  96. SmallVector<BasicBlock*, 8> ExitBlocks;
  97. L->getExitBlocks(ExitBlocks);
  98. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
  99. if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) {
  100. ShouldExtractLoop = true;
  101. break;
  102. }
  103. }
  104. if (ShouldExtractLoop) {
  105. // We must omit landing pads. Landing pads must accompany the invoke
  106. // instruction. But this would result in a loop in the extracted
  107. // function. An infinite cycle occurs when it tries to extract that loop as
  108. // well.
  109. SmallVector<BasicBlock*, 8> ExitBlocks;
  110. L->getExitBlocks(ExitBlocks);
  111. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
  112. if (ExitBlocks[i]->isLandingPad()) {
  113. ShouldExtractLoop = false;
  114. break;
  115. }
  116. }
  117. if (ShouldExtractLoop) {
  118. if (NumLoops == 0) return Changed;
  119. --NumLoops;
  120. CodeExtractor Extractor(DT, *L);
  121. if (Extractor.extractCodeRegion() != nullptr) {
  122. Changed = true;
  123. // After extraction, the loop is replaced by a function call, so
  124. // we shouldn't try to run any more loop passes on it.
  125. LPM.deleteLoopFromQueue(L);
  126. }
  127. ++NumExtracted;
  128. }
  129. return Changed;
  130. }
  131. // createSingleLoopExtractorPass - This pass extracts one natural loop from the
  132. // program into a function if it can. This is used by bugpoint.
  133. //
  134. Pass *llvm::createSingleLoopExtractorPass() {
  135. return new SingleLoopExtractor();
  136. }
  137. // BlockFile - A file which contains a list of blocks that should not be
  138. // extracted.
  139. static cl::opt<std::string>
  140. BlockFile("extract-blocks-file", cl::value_desc("filename"),
  141. cl::desc("A file containing list of basic blocks to not extract"),
  142. cl::Hidden);
  143. namespace {
  144. /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
  145. /// from the module into their own functions except for those specified by the
  146. /// BlocksToNotExtract list.
  147. class BlockExtractorPass : public ModulePass {
  148. void LoadFile(const char *Filename);
  149. void SplitLandingPadPreds(Function *F);
  150. std::vector<BasicBlock*> BlocksToNotExtract;
  151. std::vector<std::pair<std::string, std::string> > BlocksToNotExtractByName;
  152. public:
  153. static char ID; // Pass identification, replacement for typeid
  154. BlockExtractorPass() : ModulePass(ID) {
  155. if (!BlockFile.empty())
  156. LoadFile(BlockFile.c_str());
  157. }
  158. bool runOnModule(Module &M) override;
  159. };
  160. }
  161. char BlockExtractorPass::ID = 0;
  162. INITIALIZE_PASS(BlockExtractorPass, "extract-blocks",
  163. "Extract Basic Blocks From Module (for bugpoint use)",
  164. false, false)
  165. // createBlockExtractorPass - This pass extracts all blocks (except those
  166. // specified in the argument list) from the functions in the module.
  167. //
  168. ModulePass *llvm::createBlockExtractorPass() {
  169. return new BlockExtractorPass();
  170. }
  171. void BlockExtractorPass::LoadFile(const char *Filename) {
  172. // Load the BlockFile...
  173. std::ifstream In(Filename);
  174. if (!In.good()) {
  175. errs() << "WARNING: BlockExtractor couldn't load file '" << Filename
  176. << "'!\n";
  177. return;
  178. }
  179. while (In) {
  180. std::string FunctionName, BlockName;
  181. In >> FunctionName;
  182. In >> BlockName;
  183. if (!BlockName.empty())
  184. BlocksToNotExtractByName.push_back(
  185. std::make_pair(FunctionName, BlockName));
  186. }
  187. }
  188. /// SplitLandingPadPreds - The landing pad needs to be extracted with the invoke
  189. /// instruction. The critical edge breaker will refuse to break critical edges
  190. /// to a landing pad. So do them here. After this method runs, all landing pads
  191. /// should have only one predecessor.
  192. void BlockExtractorPass::SplitLandingPadPreds(Function *F) {
  193. for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
  194. InvokeInst *II = dyn_cast<InvokeInst>(I);
  195. if (!II) continue;
  196. BasicBlock *Parent = II->getParent();
  197. BasicBlock *LPad = II->getUnwindDest();
  198. // Look through the landing pad's predecessors. If one of them ends in an
  199. // 'invoke', then we want to split the landing pad.
  200. bool Split = false;
  201. for (pred_iterator
  202. PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ++PI) {
  203. BasicBlock *BB = *PI;
  204. if (BB->isLandingPad() && BB != Parent &&
  205. isa<InvokeInst>(Parent->getTerminator())) {
  206. Split = true;
  207. break;
  208. }
  209. }
  210. if (!Split) continue;
  211. SmallVector<BasicBlock*, 2> NewBBs;
  212. SplitLandingPadPredecessors(LPad, Parent, ".1", ".2", NewBBs);
  213. }
  214. }
  215. bool BlockExtractorPass::runOnModule(Module &M) {
  216. std::set<BasicBlock*> TranslatedBlocksToNotExtract;
  217. for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
  218. BasicBlock *BB = BlocksToNotExtract[i];
  219. Function *F = BB->getParent();
  220. // Map the corresponding function in this module.
  221. Function *MF = M.getFunction(F->getName());
  222. assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
  223. // Figure out which index the basic block is in its function.
  224. Function::iterator BBI = MF->begin();
  225. std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
  226. TranslatedBlocksToNotExtract.insert(BBI);
  227. }
  228. while (!BlocksToNotExtractByName.empty()) {
  229. // There's no way to find BBs by name without looking at every BB inside
  230. // every Function. Fortunately, this is always empty except when used by
  231. // bugpoint in which case correctness is more important than performance.
  232. std::string &FuncName = BlocksToNotExtractByName.back().first;
  233. std::string &BlockName = BlocksToNotExtractByName.back().second;
  234. for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
  235. Function &F = *FI;
  236. if (F.getName() != FuncName) continue;
  237. for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
  238. BasicBlock &BB = *BI;
  239. if (BB.getName() != BlockName) continue;
  240. TranslatedBlocksToNotExtract.insert(BI);
  241. }
  242. }
  243. BlocksToNotExtractByName.pop_back();
  244. }
  245. // Now that we know which blocks to not extract, figure out which ones we WANT
  246. // to extract.
  247. std::vector<BasicBlock*> BlocksToExtract;
  248. for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
  249. SplitLandingPadPreds(&*F);
  250. for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
  251. if (!TranslatedBlocksToNotExtract.count(BB))
  252. BlocksToExtract.push_back(BB);
  253. }
  254. for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i) {
  255. SmallVector<BasicBlock*, 2> BlocksToExtractVec;
  256. BlocksToExtractVec.push_back(BlocksToExtract[i]);
  257. if (const InvokeInst *II =
  258. dyn_cast<InvokeInst>(BlocksToExtract[i]->getTerminator()))
  259. BlocksToExtractVec.push_back(II->getUnwindDest());
  260. CodeExtractor(BlocksToExtractVec).extractCodeRegion();
  261. }
  262. return !BlocksToExtract.empty();
  263. }