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