LLVM API Documentation

LoopPass.cpp
Go to the documentation of this file.
00001 //===- LoopPass.cpp - Loop Pass and Loop Pass Manager ---------------------===//
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 // This file implements LoopPass and LPPassManager. All loop optimization
00011 // and transformation passes are derived from LoopPass. LPPassManager is
00012 // responsible for managing LoopPasses.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Analysis/LoopPass.h"
00017 #include "llvm/IR/IRPrintingPasses.h"
00018 #include "llvm/IR/LLVMContext.h"
00019 #include "llvm/Support/Debug.h"
00020 #include "llvm/Support/Timer.h"
00021 using namespace llvm;
00022 
00023 #define DEBUG_TYPE "loop-pass-manager"
00024 
00025 namespace {
00026 
00027 /// PrintLoopPass - Print a Function corresponding to a Loop.
00028 ///
00029 class PrintLoopPass : public LoopPass {
00030 private:
00031   std::string Banner;
00032   raw_ostream &Out;       // raw_ostream to print on.
00033 
00034 public:
00035   static char ID;
00036   PrintLoopPass(const std::string &B, raw_ostream &o)
00037       : LoopPass(ID), Banner(B), Out(o) {}
00038 
00039   void getAnalysisUsage(AnalysisUsage &AU) const override {
00040     AU.setPreservesAll();
00041   }
00042 
00043   bool runOnLoop(Loop *L, LPPassManager &) override {
00044     Out << Banner;
00045     for (Loop::block_iterator b = L->block_begin(), be = L->block_end();
00046          b != be;
00047          ++b) {
00048       if (*b)
00049         (*b)->print(Out);
00050       else
00051         Out << "Printing <null> block";
00052     }
00053     return false;
00054   }
00055 };
00056 
00057 char PrintLoopPass::ID = 0;
00058 }
00059 
00060 //===----------------------------------------------------------------------===//
00061 // LPPassManager
00062 //
00063 
00064 char LPPassManager::ID = 0;
00065 
00066 LPPassManager::LPPassManager()
00067   : FunctionPass(ID), PMDataManager() {
00068   skipThisLoop = false;
00069   redoThisLoop = false;
00070   LI = nullptr;
00071   CurrentLoop = nullptr;
00072 }
00073 
00074 /// Delete loop from the loop queue and loop hierarchy (LoopInfo).
00075 void LPPassManager::deleteLoopFromQueue(Loop *L) {
00076 
00077   LI->updateUnloop(L);
00078 
00079   // Notify passes that the loop is being deleted.
00080   deleteSimpleAnalysisLoop(L);
00081 
00082   // If L is current loop then skip rest of the passes and let
00083   // runOnFunction remove L from LQ. Otherwise, remove L from LQ now
00084   // and continue applying other passes on CurrentLoop.
00085   if (CurrentLoop == L)
00086     skipThisLoop = true;
00087 
00088   delete L;
00089 
00090   if (skipThisLoop)
00091     return;
00092 
00093   for (std::deque<Loop *>::iterator I = LQ.begin(),
00094          E = LQ.end(); I != E; ++I) {
00095     if (*I == L) {
00096       LQ.erase(I);
00097       break;
00098     }
00099   }
00100 }
00101 
00102 // Inset loop into loop nest (LoopInfo) and loop queue (LQ).
00103 void LPPassManager::insertLoop(Loop *L, Loop *ParentLoop) {
00104 
00105   assert (CurrentLoop != L && "Cannot insert CurrentLoop");
00106 
00107   // Insert into loop nest
00108   if (ParentLoop)
00109     ParentLoop->addChildLoop(L);
00110   else
00111     LI->addTopLevelLoop(L);
00112 
00113   insertLoopIntoQueue(L);
00114 }
00115 
00116 void LPPassManager::insertLoopIntoQueue(Loop *L) {
00117   // Insert L into loop queue
00118   if (L == CurrentLoop)
00119     redoLoop(L);
00120   else if (!L->getParentLoop())
00121     // This is top level loop.
00122     LQ.push_front(L);
00123   else {
00124     // Insert L after the parent loop.
00125     for (std::deque<Loop *>::iterator I = LQ.begin(),
00126            E = LQ.end(); I != E; ++I) {
00127       if (*I == L->getParentLoop()) {
00128         // deque does not support insert after.
00129         ++I;
00130         LQ.insert(I, 1, L);
00131         break;
00132       }
00133     }
00134   }
00135 }
00136 
00137 // Reoptimize this loop. LPPassManager will re-insert this loop into the
00138 // queue. This allows LoopPass to change loop nest for the loop. This
00139 // utility may send LPPassManager into infinite loops so use caution.
00140 void LPPassManager::redoLoop(Loop *L) {
00141   assert (CurrentLoop == L && "Can redo only CurrentLoop");
00142   redoThisLoop = true;
00143 }
00144 
00145 /// cloneBasicBlockSimpleAnalysis - Invoke cloneBasicBlockAnalysis hook for
00146 /// all loop passes.
00147 void LPPassManager::cloneBasicBlockSimpleAnalysis(BasicBlock *From,
00148                                                   BasicBlock *To, Loop *L) {
00149   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00150     LoopPass *LP = getContainedPass(Index);
00151     LP->cloneBasicBlockAnalysis(From, To, L);
00152   }
00153 }
00154 
00155 /// deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes.
00156 void LPPassManager::deleteSimpleAnalysisValue(Value *V, Loop *L) {
00157   if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
00158     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;
00159          ++BI) {
00160       Instruction &I = *BI;
00161       deleteSimpleAnalysisValue(&I, L);
00162     }
00163   }
00164   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00165     LoopPass *LP = getContainedPass(Index);
00166     LP->deleteAnalysisValue(V, L);
00167   }
00168 }
00169 
00170 /// Invoke deleteAnalysisLoop hook for all passes.
00171 void LPPassManager::deleteSimpleAnalysisLoop(Loop *L) {
00172   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00173     LoopPass *LP = getContainedPass(Index);
00174     LP->deleteAnalysisLoop(L);
00175   }
00176 }
00177 
00178 
00179 // Recurse through all subloops and all loops  into LQ.
00180 static void addLoopIntoQueue(Loop *L, std::deque<Loop *> &LQ) {
00181   LQ.push_back(L);
00182   for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I)
00183     addLoopIntoQueue(*I, LQ);
00184 }
00185 
00186 /// Pass Manager itself does not invalidate any analysis info.
00187 void LPPassManager::getAnalysisUsage(AnalysisUsage &Info) const {
00188   // LPPassManager needs LoopInfo. In the long term LoopInfo class will
00189   // become part of LPPassManager.
00190   Info.addRequired<LoopInfo>();
00191   Info.setPreservesAll();
00192 }
00193 
00194 /// run - Execute all of the passes scheduled for execution.  Keep track of
00195 /// whether any of the passes modifies the function, and if so, return true.
00196 bool LPPassManager::runOnFunction(Function &F) {
00197   LI = &getAnalysis<LoopInfo>();
00198   bool Changed = false;
00199 
00200   // Collect inherited analysis from Module level pass manager.
00201   populateInheritedAnalysis(TPM->activeStack);
00202 
00203   // Populate the loop queue in reverse program order. There is no clear need to
00204   // process sibling loops in either forward or reverse order. There may be some
00205   // advantage in deleting uses in a later loop before optimizing the
00206   // definitions in an earlier loop. If we find a clear reason to process in
00207   // forward order, then a forward variant of LoopPassManager should be created.
00208   //
00209   // Note that LoopInfo::iterator visits loops in reverse program
00210   // order. Here, reverse_iterator gives us a forward order, and the LoopQueue
00211   // reverses the order a third time by popping from the back.
00212   for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
00213     addLoopIntoQueue(*I, LQ);
00214 
00215   if (LQ.empty()) // No loops, skip calling finalizers
00216     return false;
00217 
00218   // Initialization
00219   for (std::deque<Loop *>::const_iterator I = LQ.begin(), E = LQ.end();
00220        I != E; ++I) {
00221     Loop *L = *I;
00222     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00223       LoopPass *P = getContainedPass(Index);
00224       Changed |= P->doInitialization(L, *this);
00225     }
00226   }
00227 
00228   // Walk Loops
00229   while (!LQ.empty()) {
00230 
00231     CurrentLoop  = LQ.back();
00232     skipThisLoop = false;
00233     redoThisLoop = false;
00234 
00235     // Run all passes on the current Loop.
00236     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00237       LoopPass *P = getContainedPass(Index);
00238 
00239       dumpPassInfo(P, EXECUTION_MSG, ON_LOOP_MSG,
00240                    CurrentLoop->getHeader()->getName());
00241       dumpRequiredSet(P);
00242 
00243       initializeAnalysisImpl(P);
00244 
00245       {
00246         PassManagerPrettyStackEntry X(P, *CurrentLoop->getHeader());
00247         TimeRegion PassTimer(getPassTimer(P));
00248 
00249         Changed |= P->runOnLoop(CurrentLoop, *this);
00250       }
00251 
00252       if (Changed)
00253         dumpPassInfo(P, MODIFICATION_MSG, ON_LOOP_MSG,
00254                      skipThisLoop ? "<deleted>" :
00255                                     CurrentLoop->getHeader()->getName());
00256       dumpPreservedSet(P);
00257 
00258       if (!skipThisLoop) {
00259         // Manually check that this loop is still healthy. This is done
00260         // instead of relying on LoopInfo::verifyLoop since LoopInfo
00261         // is a function pass and it's really expensive to verify every
00262         // loop in the function every time. That level of checking can be
00263         // enabled with the -verify-loop-info option.
00264         {
00265           TimeRegion PassTimer(getPassTimer(LI));
00266           CurrentLoop->verifyLoop();
00267         }
00268 
00269         // Then call the regular verifyAnalysis functions.
00270         verifyPreservedAnalysis(P);
00271 
00272         F.getContext().yield();
00273       }
00274 
00275       removeNotPreservedAnalysis(P);
00276       recordAvailableAnalysis(P);
00277       removeDeadPasses(P,
00278                        skipThisLoop ? "<deleted>" :
00279                                       CurrentLoop->getHeader()->getName(),
00280                        ON_LOOP_MSG);
00281 
00282       if (skipThisLoop)
00283         // Do not run other passes on this loop.
00284         break;
00285     }
00286 
00287     // If the loop was deleted, release all the loop passes. This frees up
00288     // some memory, and avoids trouble with the pass manager trying to call
00289     // verifyAnalysis on them.
00290     if (skipThisLoop)
00291       for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00292         Pass *P = getContainedPass(Index);
00293         freePass(P, "<deleted>", ON_LOOP_MSG);
00294       }
00295 
00296     // Pop the loop from queue after running all passes.
00297     LQ.pop_back();
00298 
00299     if (redoThisLoop)
00300       LQ.push_back(CurrentLoop);
00301   }
00302 
00303   // Finalization
00304   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00305     LoopPass *P = getContainedPass(Index);
00306     Changed |= P->doFinalization();
00307   }
00308 
00309   return Changed;
00310 }
00311 
00312 /// Print passes managed by this manager
00313 void LPPassManager::dumpPassStructure(unsigned Offset) {
00314   errs().indent(Offset*2) << "Loop Pass Manager\n";
00315   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00316     Pass *P = getContainedPass(Index);
00317     P->dumpPassStructure(Offset + 1);
00318     dumpLastUses(P, Offset+1);
00319   }
00320 }
00321 
00322 
00323 //===----------------------------------------------------------------------===//
00324 // LoopPass
00325 
00326 Pass *LoopPass::createPrinterPass(raw_ostream &O,
00327                                   const std::string &Banner) const {
00328   return new PrintLoopPass(Banner, O);
00329 }
00330 
00331 // Check if this pass is suitable for the current LPPassManager, if
00332 // available. This pass P is not suitable for a LPPassManager if P
00333 // is not preserving higher level analysis info used by other
00334 // LPPassManager passes. In such case, pop LPPassManager from the
00335 // stack. This will force assignPassManager() to create new
00336 // LPPassManger as expected.
00337 void LoopPass::preparePassManager(PMStack &PMS) {
00338 
00339   // Find LPPassManager
00340   while (!PMS.empty() &&
00341          PMS.top()->getPassManagerType() > PMT_LoopPassManager)
00342     PMS.pop();
00343 
00344   // If this pass is destroying high level information that is used
00345   // by other passes that are managed by LPM then do not insert
00346   // this pass in current LPM. Use new LPPassManager.
00347   if (PMS.top()->getPassManagerType() == PMT_LoopPassManager &&
00348       !PMS.top()->preserveHigherLevelAnalysis(this))
00349     PMS.pop();
00350 }
00351 
00352 /// Assign pass manager to manage this pass.
00353 void LoopPass::assignPassManager(PMStack &PMS,
00354                                  PassManagerType PreferredType) {
00355   // Find LPPassManager
00356   while (!PMS.empty() &&
00357          PMS.top()->getPassManagerType() > PMT_LoopPassManager)
00358     PMS.pop();
00359 
00360   LPPassManager *LPPM;
00361   if (PMS.top()->getPassManagerType() == PMT_LoopPassManager)
00362     LPPM = (LPPassManager*)PMS.top();
00363   else {
00364     // Create new Loop Pass Manager if it does not exist.
00365     assert (!PMS.empty() && "Unable to create Loop Pass Manager");
00366     PMDataManager *PMD = PMS.top();
00367 
00368     // [1] Create new Loop Pass Manager
00369     LPPM = new LPPassManager();
00370     LPPM->populateInheritedAnalysis(PMS);
00371 
00372     // [2] Set up new manager's top level manager
00373     PMTopLevelManager *TPM = PMD->getTopLevelManager();
00374     TPM->addIndirectPassManager(LPPM);
00375 
00376     // [3] Assign manager to manage this new manager. This may create
00377     // and push new managers into PMS
00378     Pass *P = LPPM->getAsPass();
00379     TPM->schedulePass(P);
00380 
00381     // [4] Push new manager into PMS
00382     PMS.push(LPPM);
00383   }
00384 
00385   LPPM->add(this);
00386 }
00387 
00388 // Containing function has Attribute::OptimizeNone and transformation
00389 // passes should skip it.
00390 bool LoopPass::skipOptnoneFunction(const Loop *L) const {
00391   const Function *F = L->getHeader()->getParent();
00392   if (F && F->hasFnAttribute(Attribute::OptimizeNone)) {
00393     // FIXME: Report this to dbgs() only once per function.
00394     DEBUG(dbgs() << "Skipping pass '" << getPassName()
00395           << "' in function " << F->getName() << "\n");
00396     // FIXME: Delete loop from pass manager's queue?
00397     return true;
00398   }
00399   return false;
00400 }