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