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