1 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
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 // This file implements the legacy LLVM Pass Manager infrastructure.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/IR/IRPrintingPasses.h"
17 #include "llvm/IR/LegacyPassManager.h"
18 #include "llvm/IR/LegacyPassManagers.h"
19 #include "llvm/IR/LegacyPassNameParser.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Support/TimeValue.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm>
30 #include <map>
31 #include <unordered_set>
32 using namespace llvm;
33 using namespace llvm::legacy;
34 
35 // See PassManagers.h for Pass Manager infrastructure overview.
36 
37 //===----------------------------------------------------------------------===//
38 // Pass debugging information.  Often it is useful to find out what pass is
39 // running when a crash occurs in a utility.  When this library is compiled with
40 // debugging on, a command line option (--debug-pass) is enabled that causes the
41 // pass name to be printed before it executes.
42 //
43 
44 namespace {
45 // Different debug levels that can be enabled...
46 enum PassDebugLevel {
47   Disabled, Arguments, Structure, Executions, Details
48 };
49 }
50 
51 static cl::opt<enum PassDebugLevel>
52 PassDebugging("debug-pass", cl::Hidden,
53                   cl::desc("Print PassManager debugging information"),
54                   cl::values(
55   clEnumVal(Disabled  , "disable debug output"),
56   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
57   clEnumVal(Structure , "print pass structure before run()"),
58   clEnumVal(Executions, "print pass name before it is executed"),
59   clEnumVal(Details   , "print pass details when it is executed")));
60 
61 namespace {
62 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
63 PassOptionList;
64 }
65 
66 // Print IR out before/after specified passes.
67 static PassOptionList
68 PrintBefore("print-before",
69             llvm::cl::desc("Print IR before specified passes"),
70             cl::Hidden);
71 
72 static PassOptionList
73 PrintAfter("print-after",
74            llvm::cl::desc("Print IR after specified passes"),
75            cl::Hidden);
76 
77 static cl::opt<bool>
78 PrintBeforeAll("print-before-all",
79                llvm::cl::desc("Print IR before each pass"),
80                cl::init(false));
81 static cl::opt<bool>
82 PrintAfterAll("print-after-all",
83               llvm::cl::desc("Print IR after each pass"),
84               cl::init(false));
85 
86 static cl::list<std::string>
87     PrintFuncsList("filter-print-funcs", cl::value_desc("function names"),
88                    cl::desc("Only print IR for functions whose name "
89                             "match this for all print-[before|after][-all] "
90                             "options"),
91                    cl::CommaSeparated);
92 
93 /// This is a helper to determine whether to print IR before or
94 /// after a pass.
95 
96 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
97                                          PassOptionList &PassesToPrint) {
98   for (auto *PassInf : PassesToPrint) {
99     if (PassInf)
100       if (PassInf->getPassArgument() == PI->getPassArgument()) {
101         return true;
102       }
103   }
104   return false;
105 }
106 
107 /// This is a utility to check whether a pass should have IR dumped
108 /// before it.
109 static bool ShouldPrintBeforePass(const PassInfo *PI) {
110   return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
111 }
112 
113 /// This is a utility to check whether a pass should have IR dumped
114 /// after it.
115 static bool ShouldPrintAfterPass(const PassInfo *PI) {
116   return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
117 }
118 
119 bool llvm::isFunctionInPrintList(StringRef FunctionName) {
120   static std::unordered_set<std::string> PrintFuncNames(PrintFuncsList.begin(),
121                                                         PrintFuncsList.end());
122   return PrintFuncNames.empty() || PrintFuncNames.count(FunctionName);
123 }
124 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
125 /// or higher is specified.
126 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
127   return PassDebugging >= Executions;
128 }
129 
130 
131 
132 
133 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
134   if (!V && !M)
135     OS << "Releasing pass '";
136   else
137     OS << "Running pass '";
138 
139   OS << P->getPassName() << "'";
140 
141   if (M) {
142     OS << " on module '" << M->getModuleIdentifier() << "'.\n";
143     return;
144   }
145   if (!V) {
146     OS << '\n';
147     return;
148   }
149 
150   OS << " on ";
151   if (isa<Function>(V))
152     OS << "function";
153   else if (isa<BasicBlock>(V))
154     OS << "basic block";
155   else
156     OS << "value";
157 
158   OS << " '";
159   V->printAsOperand(OS, /*PrintTy=*/false, M);
160   OS << "'\n";
161 }
162 
163 
164 namespace {
165 //===----------------------------------------------------------------------===//
166 // BBPassManager
167 //
168 /// BBPassManager manages BasicBlockPass. It batches all the
169 /// pass together and sequence them to process one basic block before
170 /// processing next basic block.
171 class BBPassManager : public PMDataManager, public FunctionPass {
172 
173 public:
174   static char ID;
175   explicit BBPassManager()
176     : PMDataManager(), FunctionPass(ID) {}
177 
178   /// Execute all of the passes scheduled for execution.  Keep track of
179   /// whether any of the passes modifies the function, and if so, return true.
180   bool runOnFunction(Function &F) override;
181 
182   /// Pass Manager itself does not invalidate any analysis info.
183   void getAnalysisUsage(AnalysisUsage &Info) const override {
184     Info.setPreservesAll();
185   }
186 
187   bool doInitialization(Module &M) override;
188   bool doInitialization(Function &F);
189   bool doFinalization(Module &M) override;
190   bool doFinalization(Function &F);
191 
192   PMDataManager *getAsPMDataManager() override { return this; }
193   Pass *getAsPass() override { return this; }
194 
195   StringRef getPassName() const override { return "BasicBlock Pass Manager"; }
196 
197   // Print passes managed by this manager
198   void dumpPassStructure(unsigned Offset) override {
199     dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
200     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
201       BasicBlockPass *BP = getContainedPass(Index);
202       BP->dumpPassStructure(Offset + 1);
203       dumpLastUses(BP, Offset+1);
204     }
205   }
206 
207   BasicBlockPass *getContainedPass(unsigned N) {
208     assert(N < PassVector.size() && "Pass number out of range!");
209     BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
210     return BP;
211   }
212 
213   PassManagerType getPassManagerType() const override {
214     return PMT_BasicBlockPassManager;
215   }
216 };
217 
218 char BBPassManager::ID = 0;
219 } // End anonymous namespace
220 
221 namespace llvm {
222 namespace legacy {
223 //===----------------------------------------------------------------------===//
224 // FunctionPassManagerImpl
225 //
226 /// FunctionPassManagerImpl manages FPPassManagers
227 class FunctionPassManagerImpl : public Pass,
228                                 public PMDataManager,
229                                 public PMTopLevelManager {
230   virtual void anchor();
231 private:
232   bool wasRun;
233 public:
234   static char ID;
235   explicit FunctionPassManagerImpl() :
236     Pass(PT_PassManager, ID), PMDataManager(),
237     PMTopLevelManager(new FPPassManager()), wasRun(false) {}
238 
239   /// \copydoc FunctionPassManager::add()
240   void add(Pass *P) {
241     schedulePass(P);
242   }
243 
244   /// createPrinterPass - Get a function printer pass.
245   Pass *createPrinterPass(raw_ostream &O,
246                           const std::string &Banner) const override {
247     return createPrintFunctionPass(O, Banner);
248   }
249 
250   // Prepare for running an on the fly pass, freeing memory if needed
251   // from a previous run.
252   void releaseMemoryOnTheFly();
253 
254   /// run - Execute all of the passes scheduled for execution.  Keep track of
255   /// whether any of the passes modifies the module, and if so, return true.
256   bool run(Function &F);
257 
258   /// doInitialization - Run all of the initializers for the function passes.
259   ///
260   bool doInitialization(Module &M) override;
261 
262   /// doFinalization - Run all of the finalizers for the function passes.
263   ///
264   bool doFinalization(Module &M) override;
265 
266 
267   PMDataManager *getAsPMDataManager() override { return this; }
268   Pass *getAsPass() override { return this; }
269   PassManagerType getTopLevelPassManagerType() override {
270     return PMT_FunctionPassManager;
271   }
272 
273   /// Pass Manager itself does not invalidate any analysis info.
274   void getAnalysisUsage(AnalysisUsage &Info) const override {
275     Info.setPreservesAll();
276   }
277 
278   FPPassManager *getContainedManager(unsigned N) {
279     assert(N < PassManagers.size() && "Pass number out of range!");
280     FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
281     return FP;
282   }
283 };
284 
285 void FunctionPassManagerImpl::anchor() {}
286 
287 char FunctionPassManagerImpl::ID = 0;
288 } // End of legacy namespace
289 } // End of llvm namespace
290 
291 namespace {
292 //===----------------------------------------------------------------------===//
293 // MPPassManager
294 //
295 /// MPPassManager manages ModulePasses and function pass managers.
296 /// It batches all Module passes and function pass managers together and
297 /// sequences them to process one module.
298 class MPPassManager : public Pass, public PMDataManager {
299 public:
300   static char ID;
301   explicit MPPassManager() :
302     Pass(PT_PassManager, ID), PMDataManager() { }
303 
304   // Delete on the fly managers.
305   ~MPPassManager() override {
306     for (auto &OnTheFlyManager : OnTheFlyManagers) {
307       FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
308       delete FPP;
309     }
310   }
311 
312   /// createPrinterPass - Get a module printer pass.
313   Pass *createPrinterPass(raw_ostream &O,
314                           const std::string &Banner) const override {
315     return createPrintModulePass(O, Banner);
316   }
317 
318   /// run - Execute all of the passes scheduled for execution.  Keep track of
319   /// whether any of the passes modifies the module, and if so, return true.
320   bool runOnModule(Module &M);
321 
322   using llvm::Pass::doInitialization;
323   using llvm::Pass::doFinalization;
324 
325   /// Pass Manager itself does not invalidate any analysis info.
326   void getAnalysisUsage(AnalysisUsage &Info) const override {
327     Info.setPreservesAll();
328   }
329 
330   /// Add RequiredPass into list of lower level passes required by pass P.
331   /// RequiredPass is run on the fly by Pass Manager when P requests it
332   /// through getAnalysis interface.
333   void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
334 
335   /// Return function pass corresponding to PassInfo PI, that is
336   /// required by module pass MP. Instantiate analysis pass, by using
337   /// its runOnFunction() for function F.
338   Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
339 
340   StringRef getPassName() const override { return "Module Pass Manager"; }
341 
342   PMDataManager *getAsPMDataManager() override { return this; }
343   Pass *getAsPass() override { return this; }
344 
345   // Print passes managed by this manager
346   void dumpPassStructure(unsigned Offset) override {
347     dbgs().indent(Offset*2) << "ModulePass Manager\n";
348     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
349       ModulePass *MP = getContainedPass(Index);
350       MP->dumpPassStructure(Offset + 1);
351       std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
352         OnTheFlyManagers.find(MP);
353       if (I != OnTheFlyManagers.end())
354         I->second->dumpPassStructure(Offset + 2);
355       dumpLastUses(MP, Offset+1);
356     }
357   }
358 
359   ModulePass *getContainedPass(unsigned N) {
360     assert(N < PassVector.size() && "Pass number out of range!");
361     return static_cast<ModulePass *>(PassVector[N]);
362   }
363 
364   PassManagerType getPassManagerType() const override {
365     return PMT_ModulePassManager;
366   }
367 
368  private:
369   /// Collection of on the fly FPPassManagers. These managers manage
370   /// function passes that are required by module passes.
371   std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
372 };
373 
374 char MPPassManager::ID = 0;
375 } // End anonymous namespace
376 
377 namespace llvm {
378 namespace legacy {
379 //===----------------------------------------------------------------------===//
380 // PassManagerImpl
381 //
382 
383 /// PassManagerImpl manages MPPassManagers
384 class PassManagerImpl : public Pass,
385                         public PMDataManager,
386                         public PMTopLevelManager {
387   virtual void anchor();
388 
389 public:
390   static char ID;
391   explicit PassManagerImpl() :
392     Pass(PT_PassManager, ID), PMDataManager(),
393                               PMTopLevelManager(new MPPassManager()) {}
394 
395   /// \copydoc PassManager::add()
396   void add(Pass *P) {
397     schedulePass(P);
398   }
399 
400   /// createPrinterPass - Get a module printer pass.
401   Pass *createPrinterPass(raw_ostream &O,
402                           const std::string &Banner) const override {
403     return createPrintModulePass(O, Banner);
404   }
405 
406   /// run - Execute all of the passes scheduled for execution.  Keep track of
407   /// whether any of the passes modifies the module, and if so, return true.
408   bool run(Module &M);
409 
410   using llvm::Pass::doInitialization;
411   using llvm::Pass::doFinalization;
412 
413   /// Pass Manager itself does not invalidate any analysis info.
414   void getAnalysisUsage(AnalysisUsage &Info) const override {
415     Info.setPreservesAll();
416   }
417 
418   PMDataManager *getAsPMDataManager() override { return this; }
419   Pass *getAsPass() override { return this; }
420   PassManagerType getTopLevelPassManagerType() override {
421     return PMT_ModulePassManager;
422   }
423 
424   MPPassManager *getContainedManager(unsigned N) {
425     assert(N < PassManagers.size() && "Pass number out of range!");
426     MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
427     return MP;
428   }
429 };
430 
431 void PassManagerImpl::anchor() {}
432 
433 char PassManagerImpl::ID = 0;
434 } // End of legacy namespace
435 } // End of llvm namespace
436 
437 namespace {
438 
439 //===----------------------------------------------------------------------===//
440 /// TimingInfo Class - This class is used to calculate information about the
441 /// amount of time each pass takes to execute.  This only happens when
442 /// -time-passes is enabled on the command line.
443 ///
444 
445 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
446 
447 class TimingInfo {
448   DenseMap<Pass*, Timer*> TimingData;
449   TimerGroup TG;
450 public:
451   // Use 'create' member to get this.
452   TimingInfo() : TG("... Pass execution timing report ...") {}
453 
454   // TimingDtor - Print out information about timing information
455   ~TimingInfo() {
456     // Delete all of the timers, which accumulate their info into the
457     // TimerGroup.
458     for (auto &I : TimingData)
459       delete I.second;
460     // TimerGroup is deleted next, printing the report.
461   }
462 
463   // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
464   // to a non-null value (if the -time-passes option is enabled) or it leaves it
465   // null.  It may be called multiple times.
466   static void createTheTimeInfo();
467 
468   /// getPassTimer - Return the timer for the specified pass if it exists.
469   Timer *getPassTimer(Pass *P) {
470     if (P->getAsPMDataManager())
471       return nullptr;
472 
473     sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
474     Timer *&T = TimingData[P];
475     if (!T)
476       T = new Timer(P->getPassName(), TG);
477     return T;
478   }
479 };
480 
481 } // End of anon namespace
482 
483 static TimingInfo *TheTimeInfo;
484 
485 //===----------------------------------------------------------------------===//
486 // PMTopLevelManager implementation
487 
488 /// Initialize top level manager. Create first pass manager.
489 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
490   PMDM->setTopLevelManager(this);
491   addPassManager(PMDM);
492   activeStack.push(PMDM);
493 }
494 
495 /// Set pass P as the last user of the given analysis passes.
496 void
497 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
498   unsigned PDepth = 0;
499   if (P->getResolver())
500     PDepth = P->getResolver()->getPMDataManager().getDepth();
501 
502   for (Pass *AP : AnalysisPasses) {
503     LastUser[AP] = P;
504 
505     if (P == AP)
506       continue;
507 
508     // Update the last users of passes that are required transitive by AP.
509     AnalysisUsage *AnUsage = findAnalysisUsage(AP);
510     const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
511     SmallVector<Pass *, 12> LastUses;
512     SmallVector<Pass *, 12> LastPMUses;
513     for (AnalysisID ID : IDs) {
514       Pass *AnalysisPass = findAnalysisPass(ID);
515       assert(AnalysisPass && "Expected analysis pass to exist.");
516       AnalysisResolver *AR = AnalysisPass->getResolver();
517       assert(AR && "Expected analysis resolver to exist.");
518       unsigned APDepth = AR->getPMDataManager().getDepth();
519 
520       if (PDepth == APDepth)
521         LastUses.push_back(AnalysisPass);
522       else if (PDepth > APDepth)
523         LastPMUses.push_back(AnalysisPass);
524     }
525 
526     setLastUser(LastUses, P);
527 
528     // If this pass has a corresponding pass manager, push higher level
529     // analysis to this pass manager.
530     if (P->getResolver())
531       setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
532 
533 
534     // If AP is the last user of other passes then make P last user of
535     // such passes.
536     for (auto LU : LastUser) {
537       if (LU.second == AP)
538         // DenseMap iterator is not invalidated here because
539         // this is just updating existing entries.
540         LastUser[LU.first] = P;
541     }
542   }
543 }
544 
545 /// Collect passes whose last user is P
546 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
547                                         Pass *P) {
548   DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
549     InversedLastUser.find(P);
550   if (DMI == InversedLastUser.end())
551     return;
552 
553   SmallPtrSet<Pass *, 8> &LU = DMI->second;
554   for (Pass *LUP : LU) {
555     LastUses.push_back(LUP);
556   }
557 
558 }
559 
560 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
561   AnalysisUsage *AnUsage = nullptr;
562   auto DMI = AnUsageMap.find(P);
563   if (DMI != AnUsageMap.end())
564     AnUsage = DMI->second;
565   else {
566     // Look up the analysis usage from the pass instance (different instances
567     // of the same pass can produce different results), but unique the
568     // resulting object to reduce memory usage.  This helps to greatly reduce
569     // memory usage when we have many instances of only a few pass types
570     // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
571     // of dependencies.
572     AnalysisUsage AU;
573     P->getAnalysisUsage(AU);
574 
575     AUFoldingSetNode* Node = nullptr;
576     FoldingSetNodeID ID;
577     AUFoldingSetNode::Profile(ID, AU);
578     void *IP = nullptr;
579     if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
580       Node = N;
581     else {
582       Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
583       UniqueAnalysisUsages.InsertNode(Node, IP);
584     }
585     assert(Node && "cached analysis usage must be non null");
586 
587     AnUsageMap[P] = &Node->AU;
588     AnUsage = &Node->AU;;
589   }
590   return AnUsage;
591 }
592 
593 /// Schedule pass P for execution. Make sure that passes required by
594 /// P are run before P is run. Update analysis info maintained by
595 /// the manager. Remove dead passes. This is a recursive function.
596 void PMTopLevelManager::schedulePass(Pass *P) {
597 
598   // TODO : Allocate function manager for this pass, other wise required set
599   // may be inserted into previous function manager
600 
601   // Give pass a chance to prepare the stage.
602   P->preparePassManager(activeStack);
603 
604   // If P is an analysis pass and it is available then do not
605   // generate the analysis again. Stale analysis info should not be
606   // available at this point.
607   const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
608   if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
609     delete P;
610     return;
611   }
612 
613   AnalysisUsage *AnUsage = findAnalysisUsage(P);
614 
615   bool checkAnalysis = true;
616   while (checkAnalysis) {
617     checkAnalysis = false;
618 
619     const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
620     for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
621            E = RequiredSet.end(); I != E; ++I) {
622 
623       Pass *AnalysisPass = findAnalysisPass(*I);
624       if (!AnalysisPass) {
625         const PassInfo *PI = findAnalysisPassInfo(*I);
626 
627         if (!PI) {
628           // Pass P is not in the global PassRegistry
629           dbgs() << "Pass '"  << P->getPassName() << "' is not initialized." << "\n";
630           dbgs() << "Verify if there is a pass dependency cycle." << "\n";
631           dbgs() << "Required Passes:" << "\n";
632           for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
633                  E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
634             Pass *AnalysisPass2 = findAnalysisPass(*I2);
635             if (AnalysisPass2) {
636               dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
637             } else {
638               dbgs() << "\t"   << "Error: Required pass not found! Possible causes:"  << "\n";
639               dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)"    << "\n";
640               dbgs() << "\t\t" << "- Corruption of the global PassRegistry"           << "\n";
641             }
642           }
643         }
644 
645         assert(PI && "Expected required passes to be initialized");
646         AnalysisPass = PI->createPass();
647         if (P->getPotentialPassManagerType () ==
648             AnalysisPass->getPotentialPassManagerType())
649           // Schedule analysis pass that is managed by the same pass manager.
650           schedulePass(AnalysisPass);
651         else if (P->getPotentialPassManagerType () >
652                  AnalysisPass->getPotentialPassManagerType()) {
653           // Schedule analysis pass that is managed by a new manager.
654           schedulePass(AnalysisPass);
655           // Recheck analysis passes to ensure that required analyses that
656           // are already checked are still available.
657           checkAnalysis = true;
658         } else
659           // Do not schedule this analysis. Lower level analysis
660           // passes are run on the fly.
661           delete AnalysisPass;
662       }
663     }
664   }
665 
666   // Now all required passes are available.
667   if (ImmutablePass *IP = P->getAsImmutablePass()) {
668     // P is a immutable pass and it will be managed by this
669     // top level manager. Set up analysis resolver to connect them.
670     PMDataManager *DM = getAsPMDataManager();
671     AnalysisResolver *AR = new AnalysisResolver(*DM);
672     P->setResolver(AR);
673     DM->initializeAnalysisImpl(P);
674     addImmutablePass(IP);
675     DM->recordAvailableAnalysis(IP);
676     return;
677   }
678 
679   if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
680     Pass *PP = P->createPrinterPass(
681         dbgs(), ("*** IR Dump Before " + P->getPassName() + " ***").str());
682     PP->assignPassManager(activeStack, getTopLevelPassManagerType());
683   }
684 
685   // Add the requested pass to the best available pass manager.
686   P->assignPassManager(activeStack, getTopLevelPassManagerType());
687 
688   if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
689     Pass *PP = P->createPrinterPass(
690         dbgs(), ("*** IR Dump After " + P->getPassName() + " ***").str());
691     PP->assignPassManager(activeStack, getTopLevelPassManagerType());
692   }
693 }
694 
695 /// Find the pass that implements Analysis AID. Search immutable
696 /// passes and all pass managers. If desired pass is not found
697 /// then return NULL.
698 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
699   // For immutable passes we have a direct mapping from ID to pass, so check
700   // that first.
701   if (Pass *P = ImmutablePassMap.lookup(AID))
702     return P;
703 
704   // Check pass managers
705   for (PMDataManager *PassManager : PassManagers)
706     if (Pass *P = PassManager->findAnalysisPass(AID, false))
707       return P;
708 
709   // Check other pass managers
710   for (PMDataManager *IndirectPassManager : IndirectPassManagers)
711     if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
712       return P;
713 
714   return nullptr;
715 }
716 
717 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
718   const PassInfo *&PI = AnalysisPassInfos[AID];
719   if (!PI)
720     PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
721   else
722     assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
723            "The pass info pointer changed for an analysis ID!");
724 
725   return PI;
726 }
727 
728 void PMTopLevelManager::addImmutablePass(ImmutablePass *P) {
729   P->initializePass();
730   ImmutablePasses.push_back(P);
731 
732   // Add this pass to the map from its analysis ID. We clobber any prior runs
733   // of the pass in the map so that the last one added is the one found when
734   // doing lookups.
735   AnalysisID AID = P->getPassID();
736   ImmutablePassMap[AID] = P;
737 
738   // Also add any interfaces implemented by the immutable pass to the map for
739   // fast lookup.
740   const PassInfo *PassInf = findAnalysisPassInfo(AID);
741   assert(PassInf && "Expected all immutable passes to be initialized");
742   for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
743     ImmutablePassMap[ImmPI->getTypeInfo()] = P;
744 }
745 
746 // Print passes managed by this top level manager.
747 void PMTopLevelManager::dumpPasses() const {
748 
749   if (PassDebugging < Structure)
750     return;
751 
752   // Print out the immutable passes
753   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
754     ImmutablePasses[i]->dumpPassStructure(0);
755   }
756 
757   // Every class that derives from PMDataManager also derives from Pass
758   // (sometimes indirectly), but there's no inheritance relationship
759   // between PMDataManager and Pass, so we have to getAsPass to get
760   // from a PMDataManager* to a Pass*.
761   for (PMDataManager *Manager : PassManagers)
762     Manager->getAsPass()->dumpPassStructure(1);
763 }
764 
765 void PMTopLevelManager::dumpArguments() const {
766 
767   if (PassDebugging < Arguments)
768     return;
769 
770   dbgs() << "Pass Arguments: ";
771   for (ImmutablePass *P : ImmutablePasses)
772     if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {
773       assert(PI && "Expected all immutable passes to be initialized");
774       if (!PI->isAnalysisGroup())
775         dbgs() << " -" << PI->getPassArgument();
776     }
777   for (PMDataManager *PM : PassManagers)
778     PM->dumpPassArguments();
779   dbgs() << "\n";
780 }
781 
782 void PMTopLevelManager::initializeAllAnalysisInfo() {
783   for (PMDataManager *PM : PassManagers)
784     PM->initializeAnalysisInfo();
785 
786   // Initailize other pass managers
787   for (PMDataManager *IPM : IndirectPassManagers)
788     IPM->initializeAnalysisInfo();
789 
790   for (auto LU : LastUser) {
791     SmallPtrSet<Pass *, 8> &L = InversedLastUser[LU.second];
792     L.insert(LU.first);
793   }
794 }
795 
796 /// Destructor
797 PMTopLevelManager::~PMTopLevelManager() {
798   for (PMDataManager *PM : PassManagers)
799     delete PM;
800 
801   for (ImmutablePass *P : ImmutablePasses)
802     delete P;
803 }
804 
805 //===----------------------------------------------------------------------===//
806 // PMDataManager implementation
807 
808 /// Augement AvailableAnalysis by adding analysis made available by pass P.
809 void PMDataManager::recordAvailableAnalysis(Pass *P) {
810   AnalysisID PI = P->getPassID();
811 
812   AvailableAnalysis[PI] = P;
813 
814   assert(!AvailableAnalysis.empty());
815 
816   // This pass is the current implementation of all of the interfaces it
817   // implements as well.
818   const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
819   if (!PInf) return;
820   const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
821   for (unsigned i = 0, e = II.size(); i != e; ++i)
822     AvailableAnalysis[II[i]->getTypeInfo()] = P;
823 }
824 
825 // Return true if P preserves high level analysis used by other
826 // passes managed by this manager
827 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
828   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
829   if (AnUsage->getPreservesAll())
830     return true;
831 
832   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
833   for (Pass *P1 : HigherLevelAnalysis) {
834     if (P1->getAsImmutablePass() == nullptr &&
835         !is_contained(PreservedSet, P1->getPassID()))
836       return false;
837   }
838 
839   return true;
840 }
841 
842 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
843 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
844   // Don't do this unless assertions are enabled.
845 #ifdef NDEBUG
846   return;
847 #endif
848   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
849   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
850 
851   // Verify preserved analysis
852   for (AnalysisID AID : PreservedSet) {
853     if (Pass *AP = findAnalysisPass(AID, true)) {
854       TimeRegion PassTimer(getPassTimer(AP));
855       AP->verifyAnalysis();
856     }
857   }
858 }
859 
860 /// Remove Analysis not preserved by Pass P
861 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
862   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
863   if (AnUsage->getPreservesAll())
864     return;
865 
866   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
867   for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
868          E = AvailableAnalysis.end(); I != E; ) {
869     DenseMap<AnalysisID, Pass*>::iterator Info = I++;
870     if (Info->second->getAsImmutablePass() == nullptr &&
871         !is_contained(PreservedSet, Info->first)) {
872       // Remove this analysis
873       if (PassDebugging >= Details) {
874         Pass *S = Info->second;
875         dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
876         dbgs() << S->getPassName() << "'\n";
877       }
878       AvailableAnalysis.erase(Info);
879     }
880   }
881 
882   // Check inherited analysis also. If P is not preserving analysis
883   // provided by parent manager then remove it here.
884   for (unsigned Index = 0; Index < PMT_Last; ++Index) {
885 
886     if (!InheritedAnalysis[Index])
887       continue;
888 
889     for (DenseMap<AnalysisID, Pass*>::iterator
890            I = InheritedAnalysis[Index]->begin(),
891            E = InheritedAnalysis[Index]->end(); I != E; ) {
892       DenseMap<AnalysisID, Pass *>::iterator Info = I++;
893       if (Info->second->getAsImmutablePass() == nullptr &&
894           !is_contained(PreservedSet, Info->first)) {
895         // Remove this analysis
896         if (PassDebugging >= Details) {
897           Pass *S = Info->second;
898           dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
899           dbgs() << S->getPassName() << "'\n";
900         }
901         InheritedAnalysis[Index]->erase(Info);
902       }
903     }
904   }
905 }
906 
907 /// Remove analysis passes that are not used any longer
908 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
909                                      enum PassDebuggingString DBG_STR) {
910 
911   SmallVector<Pass *, 12> DeadPasses;
912 
913   // If this is a on the fly manager then it does not have TPM.
914   if (!TPM)
915     return;
916 
917   TPM->collectLastUses(DeadPasses, P);
918 
919   if (PassDebugging >= Details && !DeadPasses.empty()) {
920     dbgs() << " -*- '" <<  P->getPassName();
921     dbgs() << "' is the last user of following pass instances.";
922     dbgs() << " Free these instances\n";
923   }
924 
925   for (Pass *P : DeadPasses)
926     freePass(P, Msg, DBG_STR);
927 }
928 
929 void PMDataManager::freePass(Pass *P, StringRef Msg,
930                              enum PassDebuggingString DBG_STR) {
931   dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
932 
933   {
934     // If the pass crashes releasing memory, remember this.
935     PassManagerPrettyStackEntry X(P);
936     TimeRegion PassTimer(getPassTimer(P));
937 
938     P->releaseMemory();
939   }
940 
941   AnalysisID PI = P->getPassID();
942   if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
943     // Remove the pass itself (if it is not already removed).
944     AvailableAnalysis.erase(PI);
945 
946     // Remove all interfaces this pass implements, for which it is also
947     // listed as the available implementation.
948     const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
949     for (unsigned i = 0, e = II.size(); i != e; ++i) {
950       DenseMap<AnalysisID, Pass*>::iterator Pos =
951         AvailableAnalysis.find(II[i]->getTypeInfo());
952       if (Pos != AvailableAnalysis.end() && Pos->second == P)
953         AvailableAnalysis.erase(Pos);
954     }
955   }
956 }
957 
958 /// Add pass P into the PassVector. Update
959 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
960 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
961   // This manager is going to manage pass P. Set up analysis resolver
962   // to connect them.
963   AnalysisResolver *AR = new AnalysisResolver(*this);
964   P->setResolver(AR);
965 
966   // If a FunctionPass F is the last user of ModulePass info M
967   // then the F's manager, not F, records itself as a last user of M.
968   SmallVector<Pass *, 12> TransferLastUses;
969 
970   if (!ProcessAnalysis) {
971     // Add pass
972     PassVector.push_back(P);
973     return;
974   }
975 
976   // At the moment, this pass is the last user of all required passes.
977   SmallVector<Pass *, 12> LastUses;
978   SmallVector<Pass *, 8> UsedPasses;
979   SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
980 
981   unsigned PDepth = this->getDepth();
982 
983   collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
984   for (Pass *PUsed : UsedPasses) {
985     unsigned RDepth = 0;
986 
987     assert(PUsed->getResolver() && "Analysis Resolver is not set");
988     PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
989     RDepth = DM.getDepth();
990 
991     if (PDepth == RDepth)
992       LastUses.push_back(PUsed);
993     else if (PDepth > RDepth) {
994       // Let the parent claim responsibility of last use
995       TransferLastUses.push_back(PUsed);
996       // Keep track of higher level analysis used by this manager.
997       HigherLevelAnalysis.push_back(PUsed);
998     } else
999       llvm_unreachable("Unable to accommodate Used Pass");
1000   }
1001 
1002   // Set P as P's last user until someone starts using P.
1003   // However, if P is a Pass Manager then it does not need
1004   // to record its last user.
1005   if (!P->getAsPMDataManager())
1006     LastUses.push_back(P);
1007   TPM->setLastUser(LastUses, P);
1008 
1009   if (!TransferLastUses.empty()) {
1010     Pass *My_PM = getAsPass();
1011     TPM->setLastUser(TransferLastUses, My_PM);
1012     TransferLastUses.clear();
1013   }
1014 
1015   // Now, take care of required analyses that are not available.
1016   for (AnalysisID ID : ReqAnalysisNotAvailable) {
1017     const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1018     Pass *AnalysisPass = PI->createPass();
1019     this->addLowerLevelRequiredPass(P, AnalysisPass);
1020   }
1021 
1022   // Take a note of analysis required and made available by this pass.
1023   // Remove the analysis not preserved by this pass
1024   removeNotPreservedAnalysis(P);
1025   recordAvailableAnalysis(P);
1026 
1027   // Add pass
1028   PassVector.push_back(P);
1029 }
1030 
1031 
1032 /// Populate UP with analysis pass that are used or required by
1033 /// pass P and are available. Populate RP_NotAvail with analysis
1034 /// pass that are required by pass P but are not available.
1035 void PMDataManager::collectRequiredAndUsedAnalyses(
1036     SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail,
1037     Pass *P) {
1038   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1039 
1040   for (const auto &UsedID : AnUsage->getUsedSet())
1041     if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1042       UP.push_back(AnalysisPass);
1043 
1044   for (const auto &RequiredID : AnUsage->getRequiredSet())
1045     if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1046       UP.push_back(AnalysisPass);
1047     else
1048       RP_NotAvail.push_back(RequiredID);
1049 
1050   for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet())
1051     if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1052       UP.push_back(AnalysisPass);
1053     else
1054       RP_NotAvail.push_back(RequiredID);
1055 }
1056 
1057 // All Required analyses should be available to the pass as it runs!  Here
1058 // we fill in the AnalysisImpls member of the pass so that it can
1059 // successfully use the getAnalysis() method to retrieve the
1060 // implementations it needs.
1061 //
1062 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1063   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1064 
1065   for (AnalysisUsage::VectorType::const_iterator
1066          I = AnUsage->getRequiredSet().begin(),
1067          E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1068     Pass *Impl = findAnalysisPass(*I, true);
1069     if (!Impl)
1070       // This may be analysis pass that is initialized on the fly.
1071       // If that is not the case then it will raise an assert when it is used.
1072       continue;
1073     AnalysisResolver *AR = P->getResolver();
1074     assert(AR && "Analysis Resolver is not set");
1075     AR->addAnalysisImplsPair(*I, Impl);
1076   }
1077 }
1078 
1079 /// Find the pass that implements Analysis AID. If desired pass is not found
1080 /// then return NULL.
1081 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1082 
1083   // Check if AvailableAnalysis map has one entry.
1084   DenseMap<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
1085 
1086   if (I != AvailableAnalysis.end())
1087     return I->second;
1088 
1089   // Search Parents through TopLevelManager
1090   if (SearchParent)
1091     return TPM->findAnalysisPass(AID);
1092 
1093   return nullptr;
1094 }
1095 
1096 // Print list of passes that are last used by P.
1097 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1098 
1099   SmallVector<Pass *, 12> LUses;
1100 
1101   // If this is a on the fly manager then it does not have TPM.
1102   if (!TPM)
1103     return;
1104 
1105   TPM->collectLastUses(LUses, P);
1106 
1107   for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1108          E = LUses.end(); I != E; ++I) {
1109     dbgs() << "--" << std::string(Offset*2, ' ');
1110     (*I)->dumpPassStructure(0);
1111   }
1112 }
1113 
1114 void PMDataManager::dumpPassArguments() const {
1115   for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1116         E = PassVector.end(); I != E; ++I) {
1117     if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1118       PMD->dumpPassArguments();
1119     else
1120       if (const PassInfo *PI =
1121             TPM->findAnalysisPassInfo((*I)->getPassID()))
1122         if (!PI->isAnalysisGroup())
1123           dbgs() << " -" << PI->getPassArgument();
1124   }
1125 }
1126 
1127 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1128                                  enum PassDebuggingString S2,
1129                                  StringRef Msg) {
1130   if (PassDebugging < Executions)
1131     return;
1132   dbgs() << "[" << sys::TimeValue::now().str() << "] " << (void *)this
1133          << std::string(getDepth() * 2 + 1, ' ');
1134   switch (S1) {
1135   case EXECUTION_MSG:
1136     dbgs() << "Executing Pass '" << P->getPassName();
1137     break;
1138   case MODIFICATION_MSG:
1139     dbgs() << "Made Modification '" << P->getPassName();
1140     break;
1141   case FREEING_MSG:
1142     dbgs() << " Freeing Pass '" << P->getPassName();
1143     break;
1144   default:
1145     break;
1146   }
1147   switch (S2) {
1148   case ON_BASICBLOCK_MSG:
1149     dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1150     break;
1151   case ON_FUNCTION_MSG:
1152     dbgs() << "' on Function '" << Msg << "'...\n";
1153     break;
1154   case ON_MODULE_MSG:
1155     dbgs() << "' on Module '"  << Msg << "'...\n";
1156     break;
1157   case ON_REGION_MSG:
1158     dbgs() << "' on Region '"  << Msg << "'...\n";
1159     break;
1160   case ON_LOOP_MSG:
1161     dbgs() << "' on Loop '" << Msg << "'...\n";
1162     break;
1163   case ON_CG_MSG:
1164     dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1165     break;
1166   default:
1167     break;
1168   }
1169 }
1170 
1171 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1172   if (PassDebugging < Details)
1173     return;
1174 
1175   AnalysisUsage analysisUsage;
1176   P->getAnalysisUsage(analysisUsage);
1177   dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1178 }
1179 
1180 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1181   if (PassDebugging < Details)
1182     return;
1183 
1184   AnalysisUsage analysisUsage;
1185   P->getAnalysisUsage(analysisUsage);
1186   dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1187 }
1188 
1189 void PMDataManager::dumpUsedSet(const Pass *P) const {
1190   if (PassDebugging < Details)
1191     return;
1192 
1193   AnalysisUsage analysisUsage;
1194   P->getAnalysisUsage(analysisUsage);
1195   dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1196 }
1197 
1198 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1199                                    const AnalysisUsage::VectorType &Set) const {
1200   assert(PassDebugging >= Details);
1201   if (Set.empty())
1202     return;
1203   dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1204   for (unsigned i = 0; i != Set.size(); ++i) {
1205     if (i) dbgs() << ',';
1206     const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1207     if (!PInf) {
1208       // Some preserved passes, such as AliasAnalysis, may not be initialized by
1209       // all drivers.
1210       dbgs() << " Uninitialized Pass";
1211       continue;
1212     }
1213     dbgs() << ' ' << PInf->getPassName();
1214   }
1215   dbgs() << '\n';
1216 }
1217 
1218 /// Add RequiredPass into list of lower level passes required by pass P.
1219 /// RequiredPass is run on the fly by Pass Manager when P requests it
1220 /// through getAnalysis interface.
1221 /// This should be handled by specific pass manager.
1222 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1223   if (TPM) {
1224     TPM->dumpArguments();
1225     TPM->dumpPasses();
1226   }
1227 
1228   // Module Level pass may required Function Level analysis info
1229   // (e.g. dominator info). Pass manager uses on the fly function pass manager
1230   // to provide this on demand. In that case, in Pass manager terminology,
1231   // module level pass is requiring lower level analysis info managed by
1232   // lower level pass manager.
1233 
1234   // When Pass manager is not able to order required analysis info, Pass manager
1235   // checks whether any lower level manager will be able to provide this
1236   // analysis info on demand or not.
1237 #ifndef NDEBUG
1238   dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1239   dbgs() << "' required by '" << P->getPassName() << "'\n";
1240 #endif
1241   llvm_unreachable("Unable to schedule pass");
1242 }
1243 
1244 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1245   llvm_unreachable("Unable to find on the fly pass");
1246 }
1247 
1248 // Destructor
1249 PMDataManager::~PMDataManager() {
1250   for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1251          E = PassVector.end(); I != E; ++I)
1252     delete *I;
1253 }
1254 
1255 //===----------------------------------------------------------------------===//
1256 // NOTE: Is this the right place to define this method ?
1257 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1258 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1259   return PM.findAnalysisPass(ID, dir);
1260 }
1261 
1262 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1263                                      Function &F) {
1264   return PM.getOnTheFlyPass(P, AnalysisPI, F);
1265 }
1266 
1267 //===----------------------------------------------------------------------===//
1268 // BBPassManager implementation
1269 
1270 /// Execute all of the passes scheduled for execution by invoking
1271 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies
1272 /// the function, and if so, return true.
1273 bool BBPassManager::runOnFunction(Function &F) {
1274   if (F.isDeclaration())
1275     return false;
1276 
1277   bool Changed = doInitialization(F);
1278 
1279   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1280     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1281       BasicBlockPass *BP = getContainedPass(Index);
1282       bool LocalChanged = false;
1283 
1284       dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1285       dumpRequiredSet(BP);
1286 
1287       initializeAnalysisImpl(BP);
1288 
1289       {
1290         // If the pass crashes, remember this.
1291         PassManagerPrettyStackEntry X(BP, *I);
1292         TimeRegion PassTimer(getPassTimer(BP));
1293 
1294         LocalChanged |= BP->runOnBasicBlock(*I);
1295       }
1296 
1297       Changed |= LocalChanged;
1298       if (LocalChanged)
1299         dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1300                      I->getName());
1301       dumpPreservedSet(BP);
1302       dumpUsedSet(BP);
1303 
1304       verifyPreservedAnalysis(BP);
1305       removeNotPreservedAnalysis(BP);
1306       recordAvailableAnalysis(BP);
1307       removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1308     }
1309 
1310   return doFinalization(F) || Changed;
1311 }
1312 
1313 // Implement doInitialization and doFinalization
1314 bool BBPassManager::doInitialization(Module &M) {
1315   bool Changed = false;
1316 
1317   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1318     Changed |= getContainedPass(Index)->doInitialization(M);
1319 
1320   return Changed;
1321 }
1322 
1323 bool BBPassManager::doFinalization(Module &M) {
1324   bool Changed = false;
1325 
1326   for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1327     Changed |= getContainedPass(Index)->doFinalization(M);
1328 
1329   return Changed;
1330 }
1331 
1332 bool BBPassManager::doInitialization(Function &F) {
1333   bool Changed = false;
1334 
1335   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1336     BasicBlockPass *BP = getContainedPass(Index);
1337     Changed |= BP->doInitialization(F);
1338   }
1339 
1340   return Changed;
1341 }
1342 
1343 bool BBPassManager::doFinalization(Function &F) {
1344   bool Changed = false;
1345 
1346   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1347     BasicBlockPass *BP = getContainedPass(Index);
1348     Changed |= BP->doFinalization(F);
1349   }
1350 
1351   return Changed;
1352 }
1353 
1354 
1355 //===----------------------------------------------------------------------===//
1356 // FunctionPassManager implementation
1357 
1358 /// Create new Function pass manager
1359 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1360   FPM = new FunctionPassManagerImpl();
1361   // FPM is the top level manager.
1362   FPM->setTopLevelManager(FPM);
1363 
1364   AnalysisResolver *AR = new AnalysisResolver(*FPM);
1365   FPM->setResolver(AR);
1366 }
1367 
1368 FunctionPassManager::~FunctionPassManager() {
1369   delete FPM;
1370 }
1371 
1372 void FunctionPassManager::add(Pass *P) {
1373   FPM->add(P);
1374 }
1375 
1376 /// run - Execute all of the passes scheduled for execution.  Keep
1377 /// track of whether any of the passes modifies the function, and if
1378 /// so, return true.
1379 ///
1380 bool FunctionPassManager::run(Function &F) {
1381   if (std::error_code EC = F.materialize())
1382     report_fatal_error("Error reading bitcode file: " + EC.message());
1383   return FPM->run(F);
1384 }
1385 
1386 
1387 /// doInitialization - Run all of the initializers for the function passes.
1388 ///
1389 bool FunctionPassManager::doInitialization() {
1390   return FPM->doInitialization(*M);
1391 }
1392 
1393 /// doFinalization - Run all of the finalizers for the function passes.
1394 ///
1395 bool FunctionPassManager::doFinalization() {
1396   return FPM->doFinalization(*M);
1397 }
1398 
1399 //===----------------------------------------------------------------------===//
1400 // FunctionPassManagerImpl implementation
1401 //
1402 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1403   bool Changed = false;
1404 
1405   dumpArguments();
1406   dumpPasses();
1407 
1408   for (ImmutablePass *ImPass : getImmutablePasses())
1409     Changed |= ImPass->doInitialization(M);
1410 
1411   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1412     Changed |= getContainedManager(Index)->doInitialization(M);
1413 
1414   return Changed;
1415 }
1416 
1417 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1418   bool Changed = false;
1419 
1420   for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1421     Changed |= getContainedManager(Index)->doFinalization(M);
1422 
1423   for (ImmutablePass *ImPass : getImmutablePasses())
1424     Changed |= ImPass->doFinalization(M);
1425 
1426   return Changed;
1427 }
1428 
1429 /// cleanup - After running all passes, clean up pass manager cache.
1430 void FPPassManager::cleanup() {
1431  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1432     FunctionPass *FP = getContainedPass(Index);
1433     AnalysisResolver *AR = FP->getResolver();
1434     assert(AR && "Analysis Resolver is not set");
1435     AR->clearAnalysisImpls();
1436  }
1437 }
1438 
1439 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1440   if (!wasRun)
1441     return;
1442   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1443     FPPassManager *FPPM = getContainedManager(Index);
1444     for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1445       FPPM->getContainedPass(Index)->releaseMemory();
1446     }
1447   }
1448   wasRun = false;
1449 }
1450 
1451 // Execute all the passes managed by this top level manager.
1452 // Return true if any function is modified by a pass.
1453 bool FunctionPassManagerImpl::run(Function &F) {
1454   bool Changed = false;
1455   TimingInfo::createTheTimeInfo();
1456 
1457   initializeAllAnalysisInfo();
1458   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1459     Changed |= getContainedManager(Index)->runOnFunction(F);
1460     F.getContext().yield();
1461   }
1462 
1463   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1464     getContainedManager(Index)->cleanup();
1465 
1466   wasRun = true;
1467   return Changed;
1468 }
1469 
1470 //===----------------------------------------------------------------------===//
1471 // FPPassManager implementation
1472 
1473 char FPPassManager::ID = 0;
1474 /// Print passes managed by this manager
1475 void FPPassManager::dumpPassStructure(unsigned Offset) {
1476   dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1477   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1478     FunctionPass *FP = getContainedPass(Index);
1479     FP->dumpPassStructure(Offset + 1);
1480     dumpLastUses(FP, Offset+1);
1481   }
1482 }
1483 
1484 
1485 /// Execute all of the passes scheduled for execution by invoking
1486 /// runOnFunction method.  Keep track of whether any of the passes modifies
1487 /// the function, and if so, return true.
1488 bool FPPassManager::runOnFunction(Function &F) {
1489   if (F.isDeclaration())
1490     return false;
1491 
1492   bool Changed = false;
1493 
1494   // Collect inherited analysis from Module level pass manager.
1495   populateInheritedAnalysis(TPM->activeStack);
1496 
1497   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1498     FunctionPass *FP = getContainedPass(Index);
1499     bool LocalChanged = false;
1500 
1501     dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1502     dumpRequiredSet(FP);
1503 
1504     initializeAnalysisImpl(FP);
1505 
1506     {
1507       PassManagerPrettyStackEntry X(FP, F);
1508       TimeRegion PassTimer(getPassTimer(FP));
1509 
1510       LocalChanged |= FP->runOnFunction(F);
1511     }
1512 
1513     Changed |= LocalChanged;
1514     if (LocalChanged)
1515       dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1516     dumpPreservedSet(FP);
1517     dumpUsedSet(FP);
1518 
1519     verifyPreservedAnalysis(FP);
1520     removeNotPreservedAnalysis(FP);
1521     recordAvailableAnalysis(FP);
1522     removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1523   }
1524   return Changed;
1525 }
1526 
1527 bool FPPassManager::runOnModule(Module &M) {
1528   bool Changed = false;
1529 
1530   for (Function &F : M)
1531     Changed |= runOnFunction(F);
1532 
1533   return Changed;
1534 }
1535 
1536 bool FPPassManager::doInitialization(Module &M) {
1537   bool Changed = false;
1538 
1539   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1540     Changed |= getContainedPass(Index)->doInitialization(M);
1541 
1542   return Changed;
1543 }
1544 
1545 bool FPPassManager::doFinalization(Module &M) {
1546   bool Changed = false;
1547 
1548   for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1549     Changed |= getContainedPass(Index)->doFinalization(M);
1550 
1551   return Changed;
1552 }
1553 
1554 //===----------------------------------------------------------------------===//
1555 // MPPassManager implementation
1556 
1557 /// Execute all of the passes scheduled for execution by invoking
1558 /// runOnModule method.  Keep track of whether any of the passes modifies
1559 /// the module, and if so, return true.
1560 bool
1561 MPPassManager::runOnModule(Module &M) {
1562   bool Changed = false;
1563 
1564   // Initialize on-the-fly passes
1565   for (auto &OnTheFlyManager : OnTheFlyManagers) {
1566     FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1567     Changed |= FPP->doInitialization(M);
1568   }
1569 
1570   // Initialize module passes
1571   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1572     Changed |= getContainedPass(Index)->doInitialization(M);
1573 
1574   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1575     ModulePass *MP = getContainedPass(Index);
1576     bool LocalChanged = false;
1577 
1578     dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1579     dumpRequiredSet(MP);
1580 
1581     initializeAnalysisImpl(MP);
1582 
1583     {
1584       PassManagerPrettyStackEntry X(MP, M);
1585       TimeRegion PassTimer(getPassTimer(MP));
1586 
1587       LocalChanged |= MP->runOnModule(M);
1588     }
1589 
1590     Changed |= LocalChanged;
1591     if (LocalChanged)
1592       dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1593                    M.getModuleIdentifier());
1594     dumpPreservedSet(MP);
1595     dumpUsedSet(MP);
1596 
1597     verifyPreservedAnalysis(MP);
1598     removeNotPreservedAnalysis(MP);
1599     recordAvailableAnalysis(MP);
1600     removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1601   }
1602 
1603   // Finalize module passes
1604   for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1605     Changed |= getContainedPass(Index)->doFinalization(M);
1606 
1607   // Finalize on-the-fly passes
1608   for (auto &OnTheFlyManager : OnTheFlyManagers) {
1609     FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1610     // We don't know when is the last time an on-the-fly pass is run,
1611     // so we need to releaseMemory / finalize here
1612     FPP->releaseMemoryOnTheFly();
1613     Changed |= FPP->doFinalization(M);
1614   }
1615 
1616   return Changed;
1617 }
1618 
1619 /// Add RequiredPass into list of lower level passes required by pass P.
1620 /// RequiredPass is run on the fly by Pass Manager when P requests it
1621 /// through getAnalysis interface.
1622 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1623   assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1624          "Unable to handle Pass that requires lower level Analysis pass");
1625   assert((P->getPotentialPassManagerType() <
1626           RequiredPass->getPotentialPassManagerType()) &&
1627          "Unable to handle Pass that requires lower level Analysis pass");
1628   if (!RequiredPass)
1629     return;
1630 
1631   FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1632   if (!FPP) {
1633     FPP = new FunctionPassManagerImpl();
1634     // FPP is the top level manager.
1635     FPP->setTopLevelManager(FPP);
1636 
1637     OnTheFlyManagers[P] = FPP;
1638   }
1639   const PassInfo *RequiredPassPI =
1640       TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1641 
1642   Pass *FoundPass = nullptr;
1643   if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1644     FoundPass =
1645       ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1646   }
1647   if (!FoundPass) {
1648     FoundPass = RequiredPass;
1649     // This should be guaranteed to add RequiredPass to the passmanager given
1650     // that we checked for an available analysis above.
1651     FPP->add(RequiredPass);
1652   }
1653   // Register P as the last user of FoundPass or RequiredPass.
1654   SmallVector<Pass *, 1> LU;
1655   LU.push_back(FoundPass);
1656   FPP->setLastUser(LU,  P);
1657 }
1658 
1659 /// Return function pass corresponding to PassInfo PI, that is
1660 /// required by module pass MP. Instantiate analysis pass, by using
1661 /// its runOnFunction() for function F.
1662 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1663   FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1664   assert(FPP && "Unable to find on the fly pass");
1665 
1666   FPP->releaseMemoryOnTheFly();
1667   FPP->run(F);
1668   return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1669 }
1670 
1671 
1672 //===----------------------------------------------------------------------===//
1673 // PassManagerImpl implementation
1674 
1675 //
1676 /// run - Execute all of the passes scheduled for execution.  Keep track of
1677 /// whether any of the passes modifies the module, and if so, return true.
1678 bool PassManagerImpl::run(Module &M) {
1679   bool Changed = false;
1680   TimingInfo::createTheTimeInfo();
1681 
1682   dumpArguments();
1683   dumpPasses();
1684 
1685   for (ImmutablePass *ImPass : getImmutablePasses())
1686     Changed |= ImPass->doInitialization(M);
1687 
1688   initializeAllAnalysisInfo();
1689   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1690     Changed |= getContainedManager(Index)->runOnModule(M);
1691     M.getContext().yield();
1692   }
1693 
1694   for (ImmutablePass *ImPass : getImmutablePasses())
1695     Changed |= ImPass->doFinalization(M);
1696 
1697   return Changed;
1698 }
1699 
1700 //===----------------------------------------------------------------------===//
1701 // PassManager implementation
1702 
1703 /// Create new pass manager
1704 PassManager::PassManager() {
1705   PM = new PassManagerImpl();
1706   // PM is the top level manager
1707   PM->setTopLevelManager(PM);
1708 }
1709 
1710 PassManager::~PassManager() {
1711   delete PM;
1712 }
1713 
1714 void PassManager::add(Pass *P) {
1715   PM->add(P);
1716 }
1717 
1718 /// run - Execute all of the passes scheduled for execution.  Keep track of
1719 /// whether any of the passes modifies the module, and if so, return true.
1720 bool PassManager::run(Module &M) {
1721   return PM->run(M);
1722 }
1723 
1724 //===----------------------------------------------------------------------===//
1725 // TimingInfo implementation
1726 
1727 bool llvm::TimePassesIsEnabled = false;
1728 static cl::opt<bool,true>
1729 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1730             cl::desc("Time each pass, printing elapsed time for each on exit"));
1731 
1732 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1733 // a non-null value (if the -time-passes option is enabled) or it leaves it
1734 // null.  It may be called multiple times.
1735 void TimingInfo::createTheTimeInfo() {
1736   if (!TimePassesIsEnabled || TheTimeInfo) return;
1737 
1738   // Constructed the first time this is called, iff -time-passes is enabled.
1739   // This guarantees that the object will be constructed before static globals,
1740   // thus it will be destroyed before them.
1741   static ManagedStatic<TimingInfo> TTI;
1742   TheTimeInfo = &*TTI;
1743 }
1744 
1745 /// If TimingInfo is enabled then start pass timer.
1746 Timer *llvm::getPassTimer(Pass *P) {
1747   if (TheTimeInfo)
1748     return TheTimeInfo->getPassTimer(P);
1749   return nullptr;
1750 }
1751 
1752 //===----------------------------------------------------------------------===//
1753 // PMStack implementation
1754 //
1755 
1756 // Pop Pass Manager from the stack and clear its analysis info.
1757 void PMStack::pop() {
1758 
1759   PMDataManager *Top = this->top();
1760   Top->initializeAnalysisInfo();
1761 
1762   S.pop_back();
1763 }
1764 
1765 // Push PM on the stack and set its top level manager.
1766 void PMStack::push(PMDataManager *PM) {
1767   assert(PM && "Unable to push. Pass Manager expected");
1768   assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1769 
1770   if (!this->empty()) {
1771     assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1772            && "pushing bad pass manager to PMStack");
1773     PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1774 
1775     assert(TPM && "Unable to find top level manager");
1776     TPM->addIndirectPassManager(PM);
1777     PM->setTopLevelManager(TPM);
1778     PM->setDepth(this->top()->getDepth()+1);
1779   } else {
1780     assert((PM->getPassManagerType() == PMT_ModulePassManager
1781            || PM->getPassManagerType() == PMT_FunctionPassManager)
1782            && "pushing bad pass manager to PMStack");
1783     PM->setDepth(1);
1784   }
1785 
1786   S.push_back(PM);
1787 }
1788 
1789 // Dump content of the pass manager stack.
1790 LLVM_DUMP_METHOD void PMStack::dump() const {
1791   for (PMDataManager *Manager : S)
1792     dbgs() << Manager->getAsPass()->getPassName() << ' ';
1793 
1794   if (!S.empty())
1795     dbgs() << '\n';
1796 }
1797 
1798 /// Find appropriate Module Pass Manager in the PM Stack and
1799 /// add self into that manager.
1800 void ModulePass::assignPassManager(PMStack &PMS,
1801                                    PassManagerType PreferredType) {
1802   // Find Module Pass Manager
1803   while (!PMS.empty()) {
1804     PassManagerType TopPMType = PMS.top()->getPassManagerType();
1805     if (TopPMType == PreferredType)
1806       break; // We found desired pass manager
1807     else if (TopPMType > PMT_ModulePassManager)
1808       PMS.pop();    // Pop children pass managers
1809     else
1810       break;
1811   }
1812   assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1813   PMS.top()->add(this);
1814 }
1815 
1816 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1817 /// in the PM Stack and add self into that manager.
1818 void FunctionPass::assignPassManager(PMStack &PMS,
1819                                      PassManagerType PreferredType) {
1820 
1821   // Find Function Pass Manager
1822   while (!PMS.empty()) {
1823     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1824       PMS.pop();
1825     else
1826       break;
1827   }
1828 
1829   // Create new Function Pass Manager if needed.
1830   FPPassManager *FPP;
1831   if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1832     FPP = (FPPassManager *)PMS.top();
1833   } else {
1834     assert(!PMS.empty() && "Unable to create Function Pass Manager");
1835     PMDataManager *PMD = PMS.top();
1836 
1837     // [1] Create new Function Pass Manager
1838     FPP = new FPPassManager();
1839     FPP->populateInheritedAnalysis(PMS);
1840 
1841     // [2] Set up new manager's top level manager
1842     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1843     TPM->addIndirectPassManager(FPP);
1844 
1845     // [3] Assign manager to manage this new manager. This may create
1846     // and push new managers into PMS
1847     FPP->assignPassManager(PMS, PMD->getPassManagerType());
1848 
1849     // [4] Push new manager into PMS
1850     PMS.push(FPP);
1851   }
1852 
1853   // Assign FPP as the manager of this pass.
1854   FPP->add(this);
1855 }
1856 
1857 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1858 /// in the PM Stack and add self into that manager.
1859 void BasicBlockPass::assignPassManager(PMStack &PMS,
1860                                        PassManagerType PreferredType) {
1861   BBPassManager *BBP;
1862 
1863   // Basic Pass Manager is a leaf pass manager. It does not handle
1864   // any other pass manager.
1865   if (!PMS.empty() &&
1866       PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1867     BBP = (BBPassManager *)PMS.top();
1868   } else {
1869     // If leaf manager is not Basic Block Pass manager then create new
1870     // basic Block Pass manager.
1871     assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1872     PMDataManager *PMD = PMS.top();
1873 
1874     // [1] Create new Basic Block Manager
1875     BBP = new BBPassManager();
1876 
1877     // [2] Set up new manager's top level manager
1878     // Basic Block Pass Manager does not live by itself
1879     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1880     TPM->addIndirectPassManager(BBP);
1881 
1882     // [3] Assign manager to manage this new manager. This may create
1883     // and push new managers into PMS
1884     BBP->assignPassManager(PMS, PreferredType);
1885 
1886     // [4] Push new manager into PMS
1887     PMS.push(BBP);
1888   }
1889 
1890   // Assign BBP as the manager of this pass.
1891   BBP->add(this);
1892 }
1893 
1894 PassManagerBase::~PassManagerBase() {}
1895