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