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