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