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