LLVM API Documentation

LoopExtractor.cpp

Go to the documentation of this file.
00001 //===- LoopExtractor.cpp - Extract each loop into a new function ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // A pass wrapper around the ExtractLoop() scalar transformation to extract each
00011 // top-level loop into its own new function. If the loop is the ONLY loop in a
00012 // given function, it is not touched. This is a pass most useful for debugging
00013 // via bugpoint.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #define DEBUG_TYPE "loop-extract"
00018 #include "llvm/Transforms/IPO.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Module.h"
00021 #include "llvm/Pass.h"
00022 #include "llvm/Analysis/Dominators.h"
00023 #include "llvm/Analysis/LoopInfo.h"
00024 #include "llvm/Support/CommandLine.h"
00025 #include "llvm/Support/Compiler.h"
00026 #include "llvm/Transforms/Scalar.h"
00027 #include "llvm/Transforms/Utils/FunctionUtils.h"
00028 #include "llvm/ADT/Statistic.h"
00029 #include <fstream>
00030 #include <set>
00031 using namespace llvm;
00032 
00033 STATISTIC(NumExtracted, "Number of loops extracted");
00034 
00035 namespace {
00036   // FIXME: This is not a function pass, but the PassManager doesn't allow
00037   // Module passes to require FunctionPasses, so we can't get loop info if we're
00038   // not a function pass.
00039   struct VISIBILITY_HIDDEN LoopExtractor : public FunctionPass {
00040     static char ID; // Pass identification, replacement for typeid
00041     unsigned NumLoops;
00042 
00043     explicit LoopExtractor(unsigned numLoops = ~0) 
00044       : FunctionPass(&ID), NumLoops(numLoops) {}
00045 
00046     virtual bool runOnFunction(Function &F);
00047 
00048     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00049       AU.addRequiredID(BreakCriticalEdgesID);
00050       AU.addRequiredID(LoopSimplifyID);
00051       AU.addRequired<DominatorTree>();
00052       AU.addRequired<LoopInfo>();
00053     }
00054   };
00055 }
00056 
00057 char LoopExtractor::ID = 0;
00058 static RegisterPass<LoopExtractor>
00059 X("loop-extract", "Extract loops into new functions");
00060 
00061 namespace {
00062   /// SingleLoopExtractor - For bugpoint.
00063   struct SingleLoopExtractor : public LoopExtractor {
00064     static char ID; // Pass identification, replacement for typeid
00065     SingleLoopExtractor() : LoopExtractor(1) {}
00066   };
00067 } // End anonymous namespace
00068 
00069 char SingleLoopExtractor::ID = 0;
00070 static RegisterPass<SingleLoopExtractor>
00071 Y("loop-extract-single", "Extract at most one loop into a new function");
00072 
00073 // createLoopExtractorPass - This pass extracts all natural loops from the
00074 // program into a function if it can.
00075 //
00076 FunctionPass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
00077 
00078 bool LoopExtractor::runOnFunction(Function &F) {
00079   LoopInfo &LI = getAnalysis<LoopInfo>();
00080 
00081   // If this function has no loops, there is nothing to do.
00082   if (LI.empty())
00083     return false;
00084 
00085   DominatorTree &DT = getAnalysis<DominatorTree>();
00086 
00087   // If there is more than one top-level loop in this function, extract all of
00088   // the loops.
00089   bool Changed = false;
00090   if (LI.end()-LI.begin() > 1) {
00091     for (LoopInfo::iterator i = LI.begin(), e = LI.end(); i != e; ++i) {
00092       if (NumLoops == 0) return Changed;
00093       --NumLoops;
00094       Changed |= ExtractLoop(DT, *i) != 0;
00095       ++NumExtracted;
00096     }
00097   } else {
00098     // Otherwise there is exactly one top-level loop.  If this function is more
00099     // than a minimal wrapper around the loop, extract the loop.
00100     Loop *TLL = *LI.begin();
00101     bool ShouldExtractLoop = false;
00102 
00103     // Extract the loop if the entry block doesn't branch to the loop header.
00104     TerminatorInst *EntryTI = F.getEntryBlock().getTerminator();
00105     if (!isa<BranchInst>(EntryTI) ||
00106         !cast<BranchInst>(EntryTI)->isUnconditional() ||
00107         EntryTI->getSuccessor(0) != TLL->getHeader())
00108       ShouldExtractLoop = true;
00109     else {
00110       // Check to see if any exits from the loop are more than just return
00111       // blocks.
00112       SmallVector<BasicBlock*, 8> ExitBlocks;
00113       TLL->getExitBlocks(ExitBlocks);
00114       for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
00115         if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) {
00116           ShouldExtractLoop = true;
00117           break;
00118         }
00119     }
00120 
00121     if (ShouldExtractLoop) {
00122       if (NumLoops == 0) return Changed;
00123       --NumLoops;
00124       Changed |= ExtractLoop(DT, TLL) != 0;
00125       ++NumExtracted;
00126     } else {
00127       // Okay, this function is a minimal container around the specified loop.
00128       // If we extract the loop, we will continue to just keep extracting it
00129       // infinitely... so don't extract it.  However, if the loop contains any
00130       // subloops, extract them.
00131       for (Loop::iterator i = TLL->begin(), e = TLL->end(); i != e; ++i) {
00132         if (NumLoops == 0) return Changed;
00133         --NumLoops;
00134         Changed |= ExtractLoop(DT, *i) != 0;
00135         ++NumExtracted;
00136       }
00137     }
00138   }
00139 
00140   return Changed;
00141 }
00142 
00143 // createSingleLoopExtractorPass - This pass extracts one natural loop from the
00144 // program into a function if it can.  This is used by bugpoint.
00145 //
00146 FunctionPass *llvm::createSingleLoopExtractorPass() {
00147   return new SingleLoopExtractor();
00148 }
00149 
00150 
00151 // BlockFile - A file which contains a list of blocks that should not be
00152 // extracted.
00153 static cl::opt<std::string>
00154 BlockFile("extract-blocks-file", cl::value_desc("filename"),
00155           cl::desc("A file containing list of basic blocks to not extract"),
00156           cl::Hidden);
00157 
00158 namespace {
00159   /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
00160   /// from the module into their own functions except for those specified by the
00161   /// BlocksToNotExtract list.
00162   class BlockExtractorPass : public ModulePass {
00163     void LoadFile(const char *Filename);
00164 
00165     std::vector<BasicBlock*> BlocksToNotExtract;
00166     std::vector<std::pair<std::string, std::string> > BlocksToNotExtractByName;
00167   public:
00168     static char ID; // Pass identification, replacement for typeid
00169     explicit BlockExtractorPass(const std::vector<BasicBlock*> &B) 
00170       : ModulePass(&ID), BlocksToNotExtract(B) {
00171       if (!BlockFile.empty())
00172         LoadFile(BlockFile.c_str());
00173     }
00174     BlockExtractorPass() : ModulePass(&ID) {}
00175 
00176     bool runOnModule(Module &M);
00177   };
00178 }
00179 
00180 char BlockExtractorPass::ID = 0;
00181 static RegisterPass<BlockExtractorPass>
00182 XX("extract-blocks", "Extract Basic Blocks From Module (for bugpoint use)");
00183 
00184 // createBlockExtractorPass - This pass extracts all blocks (except those
00185 // specified in the argument list) from the functions in the module.
00186 //
00187 ModulePass *llvm::createBlockExtractorPass(const std::vector<BasicBlock*> &BTNE)
00188 {
00189   return new BlockExtractorPass(BTNE);
00190 }
00191 
00192 void BlockExtractorPass::LoadFile(const char *Filename) {
00193   // Load the BlockFile...
00194   std::ifstream In(Filename);
00195   if (!In.good()) {
00196     cerr << "WARNING: BlockExtractor couldn't load file '" << Filename
00197          << "'!\n";
00198     return;
00199   }
00200   while (In) {
00201     std::string FunctionName, BlockName;
00202     In >> FunctionName;
00203     In >> BlockName;
00204     if (!BlockName.empty())
00205       BlocksToNotExtractByName.push_back(
00206           std::make_pair(FunctionName, BlockName));
00207   }
00208 }
00209 
00210 bool BlockExtractorPass::runOnModule(Module &M) {
00211   std::set<BasicBlock*> TranslatedBlocksToNotExtract;
00212   for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
00213     BasicBlock *BB = BlocksToNotExtract[i];
00214     Function *F = BB->getParent();
00215 
00216     // Map the corresponding function in this module.
00217     Function *MF = M.getFunction(F->getName());
00218     assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
00219 
00220     // Figure out which index the basic block is in its function.
00221     Function::iterator BBI = MF->begin();
00222     std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
00223     TranslatedBlocksToNotExtract.insert(BBI);
00224   }
00225 
00226   while (!BlocksToNotExtractByName.empty()) {
00227     // There's no way to find BBs by name without looking at every BB inside
00228     // every Function. Fortunately, this is always empty except when used by
00229     // bugpoint in which case correctness is more important than performance.
00230 
00231     std::string &FuncName  = BlocksToNotExtractByName.back().first;
00232     std::string &BlockName = BlocksToNotExtractByName.back().second;
00233 
00234     for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
00235       Function &F = *FI;
00236       if (F.getName() != FuncName) continue;
00237 
00238       for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
00239         BasicBlock &BB = *BI;
00240         if (BB.getName() != BlockName) continue;
00241 
00242         TranslatedBlocksToNotExtract.insert(BI);
00243       }
00244     }
00245 
00246     BlocksToNotExtractByName.pop_back();
00247   }
00248 
00249   // Now that we know which blocks to not extract, figure out which ones we WANT
00250   // to extract.
00251   std::vector<BasicBlock*> BlocksToExtract;
00252   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
00253     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00254       if (!TranslatedBlocksToNotExtract.count(BB))
00255         BlocksToExtract.push_back(BB);
00256 
00257   for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i)
00258     ExtractBasicBlock(BlocksToExtract[i]);
00259 
00260   return !BlocksToExtract.empty();
00261 }