1 //===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the CallGraphSCCPass class, which is used for passes 10 // which are implemented as bottom-up traversals on the call graph. Because 11 // there may be cycles in the call graph, passes of this type operate on the 12 // call-graph in SCC order: that is, they process function bottom-up, except for 13 // recursive functions, which they process all at once. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Analysis/CallGraphSCCPass.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/SCCIterator.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/Analysis/CallGraph.h" 23 #include "llvm/IR/AbstractCallSite.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/Intrinsics.h" 26 #include "llvm/IR/LLVMContext.h" 27 #include "llvm/IR/LegacyPassManagers.h" 28 #include "llvm/IR/Module.h" 29 #include "llvm/IR/PassTimingInfo.h" 30 #include "llvm/IR/PrintPasses.h" 31 #include "llvm/Pass.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/Timer.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include <cassert> 37 #include <string> 38 #include <utility> 39 #include <vector> 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "cgscc-passmgr" 44 45 namespace llvm { 46 cl::opt<unsigned> MaxDevirtIterations("max-devirt-iterations", cl::ReallyHidden, 47 cl::init(4)); 48 } // namespace llvm 49 50 STATISTIC(MaxSCCIterations, "Maximum CGSCCPassMgr iterations on one SCC"); 51 52 //===----------------------------------------------------------------------===// 53 // CGPassManager 54 // 55 /// CGPassManager manages FPPassManagers and CallGraphSCCPasses. 56 57 namespace { 58 59 class CGPassManager : public ModulePass, public PMDataManager { 60 public: 61 static char ID; 62 63 explicit CGPassManager() : ModulePass(ID) {} 64 65 /// Execute all of the passes scheduled for execution. Keep track of 66 /// whether any of the passes modifies the module, and if so, return true. 67 bool runOnModule(Module &M) override; 68 69 using ModulePass::doInitialization; 70 using ModulePass::doFinalization; 71 72 bool doInitialization(CallGraph &CG); 73 bool doFinalization(CallGraph &CG); 74 75 /// Pass Manager itself does not invalidate any analysis info. 76 void getAnalysisUsage(AnalysisUsage &Info) const override { 77 // CGPassManager walks SCC and it needs CallGraph. 78 Info.addRequired<CallGraphWrapperPass>(); 79 Info.setPreservesAll(); 80 } 81 82 StringRef getPassName() const override { return "CallGraph Pass Manager"; } 83 84 PMDataManager *getAsPMDataManager() override { return this; } 85 Pass *getAsPass() override { return this; } 86 87 // Print passes managed by this manager 88 void dumpPassStructure(unsigned Offset) override { 89 errs().indent(Offset*2) << "Call Graph SCC Pass Manager\n"; 90 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { 91 Pass *P = getContainedPass(Index); 92 P->dumpPassStructure(Offset + 1); 93 dumpLastUses(P, Offset+1); 94 } 95 } 96 97 Pass *getContainedPass(unsigned N) { 98 assert(N < PassVector.size() && "Pass number out of range!"); 99 return static_cast<Pass *>(PassVector[N]); 100 } 101 102 PassManagerType getPassManagerType() const override { 103 return PMT_CallGraphPassManager; 104 } 105 106 private: 107 bool RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG, 108 bool &DevirtualizedCall); 109 110 bool RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC, 111 CallGraph &CG, bool &CallGraphUpToDate, 112 bool &DevirtualizedCall); 113 bool RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG, 114 bool IsCheckingMode); 115 }; 116 117 } // end anonymous namespace. 118 119 char CGPassManager::ID = 0; 120 121 bool CGPassManager::RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC, 122 CallGraph &CG, bool &CallGraphUpToDate, 123 bool &DevirtualizedCall) { 124 bool Changed = false; 125 PMDataManager *PM = P->getAsPMDataManager(); 126 Module &M = CG.getModule(); 127 128 if (!PM) { 129 CallGraphSCCPass *CGSP = (CallGraphSCCPass *)P; 130 if (!CallGraphUpToDate) { 131 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false); 132 CallGraphUpToDate = true; 133 } 134 135 { 136 unsigned InstrCount, SCCCount = 0; 137 StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount; 138 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark(); 139 TimeRegion PassTimer(getPassTimer(CGSP)); 140 if (EmitICRemark) 141 InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount); 142 Changed = CGSP->runOnSCC(CurSCC); 143 144 if (EmitICRemark) { 145 // FIXME: Add getInstructionCount to CallGraphSCC. 146 SCCCount = M.getInstructionCount(); 147 // Is there a difference in the number of instructions in the module? 148 if (SCCCount != InstrCount) { 149 // Yep. Emit a remark and update InstrCount. 150 int64_t Delta = 151 static_cast<int64_t>(SCCCount) - static_cast<int64_t>(InstrCount); 152 emitInstrCountChangedRemark(P, M, Delta, InstrCount, 153 FunctionToInstrCount); 154 InstrCount = SCCCount; 155 } 156 } 157 } 158 159 // After the CGSCCPass is done, when assertions are enabled, use 160 // RefreshCallGraph to verify that the callgraph was correctly updated. 161 #ifndef NDEBUG 162 if (Changed) 163 RefreshCallGraph(CurSCC, CG, true); 164 #endif 165 166 return Changed; 167 } 168 169 assert(PM->getPassManagerType() == PMT_FunctionPassManager && 170 "Invalid CGPassManager member"); 171 FPPassManager *FPP = (FPPassManager*)P; 172 173 // Run pass P on all functions in the current SCC. 174 for (CallGraphNode *CGN : CurSCC) { 175 if (Function *F = CGN->getFunction()) { 176 dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName()); 177 { 178 TimeRegion PassTimer(getPassTimer(FPP)); 179 Changed |= FPP->runOnFunction(*F); 180 } 181 F->getContext().yield(); 182 } 183 } 184 185 // The function pass(es) modified the IR, they may have clobbered the 186 // callgraph. 187 if (Changed && CallGraphUpToDate) { 188 LLVM_DEBUG(dbgs() << "CGSCCPASSMGR: Pass Dirtied SCC: " << P->getPassName() 189 << '\n'); 190 CallGraphUpToDate = false; 191 } 192 return Changed; 193 } 194 195 /// Scan the functions in the specified CFG and resync the 196 /// callgraph with the call sites found in it. This is used after 197 /// FunctionPasses have potentially munged the callgraph, and can be used after 198 /// CallGraphSCC passes to verify that they correctly updated the callgraph. 199 /// 200 /// This function returns true if it devirtualized an existing function call, 201 /// meaning it turned an indirect call into a direct call. This happens when 202 /// a function pass like GVN optimizes away stuff feeding the indirect call. 203 /// This never happens in checking mode. 204 bool CGPassManager::RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG, 205 bool CheckingMode) { 206 DenseMap<Value *, CallGraphNode *> Calls; 207 208 LLVM_DEBUG(dbgs() << "CGSCCPASSMGR: Refreshing SCC with " << CurSCC.size() 209 << " nodes:\n"; 210 for (CallGraphNode *CGN 211 : CurSCC) CGN->dump();); 212 213 bool MadeChange = false; 214 bool DevirtualizedCall = false; 215 216 // Scan all functions in the SCC. 217 unsigned FunctionNo = 0; 218 for (CallGraphSCC::iterator SCCIdx = CurSCC.begin(), E = CurSCC.end(); 219 SCCIdx != E; ++SCCIdx, ++FunctionNo) { 220 CallGraphNode *CGN = *SCCIdx; 221 Function *F = CGN->getFunction(); 222 if (!F || F->isDeclaration()) continue; 223 224 // Walk the function body looking for call sites. Sync up the call sites in 225 // CGN with those actually in the function. 226 227 // Keep track of the number of direct and indirect calls that were 228 // invalidated and removed. 229 unsigned NumDirectRemoved = 0, NumIndirectRemoved = 0; 230 231 CallGraphNode::iterator CGNEnd = CGN->end(); 232 233 auto RemoveAndCheckForDone = [&](CallGraphNode::iterator I) { 234 // Just remove the edge from the set of callees, keep track of whether 235 // I points to the last element of the vector. 236 bool WasLast = I + 1 == CGNEnd; 237 CGN->removeCallEdge(I); 238 239 // If I pointed to the last element of the vector, we have to bail out: 240 // iterator checking rejects comparisons of the resultant pointer with 241 // end. 242 if (WasLast) 243 return true; 244 245 CGNEnd = CGN->end(); 246 return false; 247 }; 248 249 // Get the set of call sites currently in the function. 250 for (CallGraphNode::iterator I = CGN->begin(); I != CGNEnd;) { 251 // Delete "reference" call records that do not have call instruction. We 252 // reinsert them as needed later. However, keep them in checking mode. 253 if (!I->first) { 254 if (CheckingMode) { 255 ++I; 256 continue; 257 } 258 if (RemoveAndCheckForDone(I)) 259 break; 260 continue; 261 } 262 263 // If this call site is null, then the function pass deleted the call 264 // entirely and the WeakTrackingVH nulled it out. 265 auto *Call = dyn_cast_or_null<CallBase>(*I->first); 266 if (!Call || 267 // If we've already seen this call site, then the FunctionPass RAUW'd 268 // one call with another, which resulted in two "uses" in the edge 269 // list of the same call. 270 Calls.count(Call)) { 271 assert(!CheckingMode && 272 "CallGraphSCCPass did not update the CallGraph correctly!"); 273 274 // If this was an indirect call site, count it. 275 if (!I->second->getFunction()) 276 ++NumIndirectRemoved; 277 else 278 ++NumDirectRemoved; 279 280 if (RemoveAndCheckForDone(I)) 281 break; 282 continue; 283 } 284 285 assert(!Calls.count(Call) && "Call site occurs in node multiple times"); 286 287 if (Call) { 288 Function *Callee = Call->getCalledFunction(); 289 // Ignore intrinsics because they're not really function calls. 290 if (!Callee || !(Callee->isIntrinsic())) 291 Calls.insert(std::make_pair(Call, I->second)); 292 } 293 ++I; 294 } 295 296 // Loop over all of the instructions in the function, getting the callsites. 297 // Keep track of the number of direct/indirect calls added. 298 unsigned NumDirectAdded = 0, NumIndirectAdded = 0; 299 300 for (BasicBlock &BB : *F) 301 for (Instruction &I : BB) { 302 auto *Call = dyn_cast<CallBase>(&I); 303 if (!Call) 304 continue; 305 Function *Callee = Call->getCalledFunction(); 306 if (Callee && Callee->isIntrinsic()) 307 continue; 308 309 // If we are not in checking mode, insert potential callback calls as 310 // references. This is not a requirement but helps to iterate over the 311 // functions in the right order. 312 if (!CheckingMode) { 313 forEachCallbackFunction(*Call, [&](Function *CB) { 314 CGN->addCalledFunction(nullptr, CG.getOrInsertFunction(CB)); 315 }); 316 } 317 318 // If this call site already existed in the callgraph, just verify it 319 // matches up to expectations and remove it from Calls. 320 DenseMap<Value *, CallGraphNode *>::iterator ExistingIt = 321 Calls.find(Call); 322 if (ExistingIt != Calls.end()) { 323 CallGraphNode *ExistingNode = ExistingIt->second; 324 325 // Remove from Calls since we have now seen it. 326 Calls.erase(ExistingIt); 327 328 // Verify that the callee is right. 329 if (ExistingNode->getFunction() == Call->getCalledFunction()) 330 continue; 331 332 // If we are in checking mode, we are not allowed to actually mutate 333 // the callgraph. If this is a case where we can infer that the 334 // callgraph is less precise than it could be (e.g. an indirect call 335 // site could be turned direct), don't reject it in checking mode, and 336 // don't tweak it to be more precise. 337 if (CheckingMode && Call->getCalledFunction() && 338 ExistingNode->getFunction() == nullptr) 339 continue; 340 341 assert(!CheckingMode && 342 "CallGraphSCCPass did not update the CallGraph correctly!"); 343 344 // If not, we either went from a direct call to indirect, indirect to 345 // direct, or direct to different direct. 346 CallGraphNode *CalleeNode; 347 if (Function *Callee = Call->getCalledFunction()) { 348 CalleeNode = CG.getOrInsertFunction(Callee); 349 // Keep track of whether we turned an indirect call into a direct 350 // one. 351 if (!ExistingNode->getFunction()) { 352 DevirtualizedCall = true; 353 LLVM_DEBUG(dbgs() << " CGSCCPASSMGR: Devirtualized call to '" 354 << Callee->getName() << "'\n"); 355 } 356 } else { 357 CalleeNode = CG.getCallsExternalNode(); 358 } 359 360 // Update the edge target in CGN. 361 CGN->replaceCallEdge(*Call, *Call, CalleeNode); 362 MadeChange = true; 363 continue; 364 } 365 366 assert(!CheckingMode && 367 "CallGraphSCCPass did not update the CallGraph correctly!"); 368 369 // If the call site didn't exist in the CGN yet, add it. 370 CallGraphNode *CalleeNode; 371 if (Function *Callee = Call->getCalledFunction()) { 372 CalleeNode = CG.getOrInsertFunction(Callee); 373 ++NumDirectAdded; 374 } else { 375 CalleeNode = CG.getCallsExternalNode(); 376 ++NumIndirectAdded; 377 } 378 379 CGN->addCalledFunction(Call, CalleeNode); 380 MadeChange = true; 381 } 382 383 // We scanned the old callgraph node, removing invalidated call sites and 384 // then added back newly found call sites. One thing that can happen is 385 // that an old indirect call site was deleted and replaced with a new direct 386 // call. In this case, we have devirtualized a call, and CGSCCPM would like 387 // to iteratively optimize the new code. Unfortunately, we don't really 388 // have a great way to detect when this happens. As an approximation, we 389 // just look at whether the number of indirect calls is reduced and the 390 // number of direct calls is increased. There are tons of ways to fool this 391 // (e.g. DCE'ing an indirect call and duplicating an unrelated block with a 392 // direct call) but this is close enough. 393 if (NumIndirectRemoved > NumIndirectAdded && 394 NumDirectRemoved < NumDirectAdded) 395 DevirtualizedCall = true; 396 397 // After scanning this function, if we still have entries in callsites, then 398 // they are dangling pointers. WeakTrackingVH should save us for this, so 399 // abort if 400 // this happens. 401 assert(Calls.empty() && "Dangling pointers found in call sites map"); 402 403 // Periodically do an explicit clear to remove tombstones when processing 404 // large scc's. 405 if ((FunctionNo & 15) == 15) 406 Calls.clear(); 407 } 408 409 LLVM_DEBUG(if (MadeChange) { 410 dbgs() << "CGSCCPASSMGR: Refreshed SCC is now:\n"; 411 for (CallGraphNode *CGN : CurSCC) 412 CGN->dump(); 413 if (DevirtualizedCall) 414 dbgs() << "CGSCCPASSMGR: Refresh devirtualized a call!\n"; 415 } else { 416 dbgs() << "CGSCCPASSMGR: SCC Refresh didn't change call graph.\n"; 417 }); 418 (void)MadeChange; 419 420 return DevirtualizedCall; 421 } 422 423 /// Execute the body of the entire pass manager on the specified SCC. 424 /// This keeps track of whether a function pass devirtualizes 425 /// any calls and returns it in DevirtualizedCall. 426 bool CGPassManager::RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG, 427 bool &DevirtualizedCall) { 428 bool Changed = false; 429 430 // Keep track of whether the callgraph is known to be up-to-date or not. 431 // The CGSSC pass manager runs two types of passes: 432 // CallGraphSCC Passes and other random function passes. Because other 433 // random function passes are not CallGraph aware, they may clobber the 434 // call graph by introducing new calls or deleting other ones. This flag 435 // is set to false when we run a function pass so that we know to clean up 436 // the callgraph when we need to run a CGSCCPass again. 437 bool CallGraphUpToDate = true; 438 439 // Run all passes on current SCC. 440 for (unsigned PassNo = 0, e = getNumContainedPasses(); 441 PassNo != e; ++PassNo) { 442 Pass *P = getContainedPass(PassNo); 443 444 // If we're in -debug-pass=Executions mode, construct the SCC node list, 445 // otherwise avoid constructing this string as it is expensive. 446 if (isPassDebuggingExecutionsOrMore()) { 447 std::string Functions; 448 #ifndef NDEBUG 449 raw_string_ostream OS(Functions); 450 ListSeparator LS; 451 for (const CallGraphNode *CGN : CurSCC) { 452 OS << LS; 453 CGN->print(OS); 454 } 455 #endif 456 dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, Functions); 457 } 458 dumpRequiredSet(P); 459 460 initializeAnalysisImpl(P); 461 462 #ifdef EXPENSIVE_CHECKS 463 uint64_t RefHash = P->structuralHash(CG.getModule()); 464 #endif 465 466 // Actually run this pass on the current SCC. 467 bool LocalChanged = 468 RunPassOnSCC(P, CurSCC, CG, CallGraphUpToDate, DevirtualizedCall); 469 470 Changed |= LocalChanged; 471 472 #ifdef EXPENSIVE_CHECKS 473 if (!LocalChanged && (RefHash != P->structuralHash(CG.getModule()))) { 474 llvm::errs() << "Pass modifies its input and doesn't report it: " 475 << P->getPassName() << "\n"; 476 llvm_unreachable("Pass modifies its input and doesn't report it"); 477 } 478 #endif 479 if (LocalChanged) 480 dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, ""); 481 dumpPreservedSet(P); 482 483 verifyPreservedAnalysis(P); 484 if (LocalChanged) 485 removeNotPreservedAnalysis(P); 486 recordAvailableAnalysis(P); 487 removeDeadPasses(P, "", ON_CG_MSG); 488 } 489 490 // If the callgraph was left out of date (because the last pass run was a 491 // functionpass), refresh it before we move on to the next SCC. 492 if (!CallGraphUpToDate) 493 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false); 494 return Changed; 495 } 496 497 /// Execute all of the passes scheduled for execution. Keep track of 498 /// whether any of the passes modifies the module, and if so, return true. 499 bool CGPassManager::runOnModule(Module &M) { 500 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 501 bool Changed = doInitialization(CG); 502 503 // Walk the callgraph in bottom-up SCC order. 504 scc_iterator<CallGraph*> CGI = scc_begin(&CG); 505 506 CallGraphSCC CurSCC(CG, &CGI); 507 while (!CGI.isAtEnd()) { 508 // Copy the current SCC and increment past it so that the pass can hack 509 // on the SCC if it wants to without invalidating our iterator. 510 const std::vector<CallGraphNode *> &NodeVec = *CGI; 511 CurSCC.initialize(NodeVec); 512 ++CGI; 513 514 // At the top level, we run all the passes in this pass manager on the 515 // functions in this SCC. However, we support iterative compilation in the 516 // case where a function pass devirtualizes a call to a function. For 517 // example, it is very common for a function pass (often GVN or instcombine) 518 // to eliminate the addressing that feeds into a call. With that improved 519 // information, we would like the call to be an inline candidate, infer 520 // mod-ref information etc. 521 // 522 // Because of this, we allow iteration up to a specified iteration count. 523 // This only happens in the case of a devirtualized call, so we only burn 524 // compile time in the case that we're making progress. We also have a hard 525 // iteration count limit in case there is crazy code. 526 unsigned Iteration = 0; 527 bool DevirtualizedCall = false; 528 do { 529 LLVM_DEBUG(if (Iteration) dbgs() 530 << " SCCPASSMGR: Re-visiting SCC, iteration #" << Iteration 531 << '\n'); 532 DevirtualizedCall = false; 533 Changed |= RunAllPassesOnSCC(CurSCC, CG, DevirtualizedCall); 534 } while (Iteration++ < MaxDevirtIterations && DevirtualizedCall); 535 536 if (DevirtualizedCall) 537 LLVM_DEBUG(dbgs() << " CGSCCPASSMGR: Stopped iteration after " 538 << Iteration 539 << " times, due to -max-devirt-iterations\n"); 540 541 MaxSCCIterations.updateMax(Iteration); 542 } 543 Changed |= doFinalization(CG); 544 return Changed; 545 } 546 547 /// Initialize CG 548 bool CGPassManager::doInitialization(CallGraph &CG) { 549 bool Changed = false; 550 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) { 551 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) { 552 assert(PM->getPassManagerType() == PMT_FunctionPassManager && 553 "Invalid CGPassManager member"); 554 Changed |= ((FPPassManager*)PM)->doInitialization(CG.getModule()); 555 } else { 556 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doInitialization(CG); 557 } 558 } 559 return Changed; 560 } 561 562 /// Finalize CG 563 bool CGPassManager::doFinalization(CallGraph &CG) { 564 bool Changed = false; 565 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) { 566 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) { 567 assert(PM->getPassManagerType() == PMT_FunctionPassManager && 568 "Invalid CGPassManager member"); 569 Changed |= ((FPPassManager*)PM)->doFinalization(CG.getModule()); 570 } else { 571 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doFinalization(CG); 572 } 573 } 574 return Changed; 575 } 576 577 //===----------------------------------------------------------------------===// 578 // CallGraphSCC Implementation 579 //===----------------------------------------------------------------------===// 580 581 /// This informs the SCC and the pass manager that the specified 582 /// Old node has been deleted, and New is to be used in its place. 583 void CallGraphSCC::ReplaceNode(CallGraphNode *Old, CallGraphNode *New) { 584 assert(Old != New && "Should not replace node with self"); 585 for (unsigned i = 0; ; ++i) { 586 assert(i != Nodes.size() && "Node not in SCC"); 587 if (Nodes[i] != Old) continue; 588 if (New) 589 Nodes[i] = New; 590 else 591 Nodes.erase(Nodes.begin() + i); 592 break; 593 } 594 595 // Update the active scc_iterator so that it doesn't contain dangling 596 // pointers to the old CallGraphNode. 597 scc_iterator<CallGraph*> *CGI = (scc_iterator<CallGraph*>*)Context; 598 CGI->ReplaceNode(Old, New); 599 } 600 601 void CallGraphSCC::DeleteNode(CallGraphNode *Old) { 602 ReplaceNode(Old, /*New=*/nullptr); 603 } 604 605 //===----------------------------------------------------------------------===// 606 // CallGraphSCCPass Implementation 607 //===----------------------------------------------------------------------===// 608 609 /// Assign pass manager to manage this pass. 610 void CallGraphSCCPass::assignPassManager(PMStack &PMS, 611 PassManagerType PreferredType) { 612 // Find CGPassManager 613 while (!PMS.empty() && 614 PMS.top()->getPassManagerType() > PMT_CallGraphPassManager) 615 PMS.pop(); 616 617 assert(!PMS.empty() && "Unable to handle Call Graph Pass"); 618 CGPassManager *CGP; 619 620 if (PMS.top()->getPassManagerType() == PMT_CallGraphPassManager) 621 CGP = (CGPassManager*)PMS.top(); 622 else { 623 // Create new Call Graph SCC Pass Manager if it does not exist. 624 assert(!PMS.empty() && "Unable to create Call Graph Pass Manager"); 625 PMDataManager *PMD = PMS.top(); 626 627 // [1] Create new Call Graph Pass Manager 628 CGP = new CGPassManager(); 629 630 // [2] Set up new manager's top level manager 631 PMTopLevelManager *TPM = PMD->getTopLevelManager(); 632 TPM->addIndirectPassManager(CGP); 633 634 // [3] Assign manager to manage this new manager. This may create 635 // and push new managers into PMS 636 Pass *P = CGP; 637 TPM->schedulePass(P); 638 639 // [4] Push new manager into PMS 640 PMS.push(CGP); 641 } 642 643 CGP->add(this); 644 } 645 646 /// For this class, we declare that we require and preserve the call graph. 647 /// If the derived class implements this method, it should 648 /// always explicitly call the implementation here. 649 void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const { 650 AU.addRequired<CallGraphWrapperPass>(); 651 AU.addPreserved<CallGraphWrapperPass>(); 652 } 653 654 //===----------------------------------------------------------------------===// 655 // PrintCallGraphPass Implementation 656 //===----------------------------------------------------------------------===// 657 658 namespace { 659 660 /// PrintCallGraphPass - Print a Module corresponding to a call graph. 661 /// 662 class PrintCallGraphPass : public CallGraphSCCPass { 663 std::string Banner; 664 raw_ostream &OS; // raw_ostream to print on. 665 666 public: 667 static char ID; 668 669 PrintCallGraphPass(const std::string &B, raw_ostream &OS) 670 : CallGraphSCCPass(ID), Banner(B), OS(OS) {} 671 672 void getAnalysisUsage(AnalysisUsage &AU) const override { 673 AU.setPreservesAll(); 674 } 675 676 bool runOnSCC(CallGraphSCC &SCC) override { 677 bool BannerPrinted = false; 678 auto PrintBannerOnce = [&]() { 679 if (BannerPrinted) 680 return; 681 OS << Banner; 682 BannerPrinted = true; 683 }; 684 685 bool NeedModule = llvm::forcePrintModuleIR(); 686 if (isFunctionInPrintList("*") && NeedModule) { 687 PrintBannerOnce(); 688 OS << "\n"; 689 SCC.getCallGraph().getModule().print(OS, nullptr); 690 return false; 691 } 692 bool FoundFunction = false; 693 for (CallGraphNode *CGN : SCC) { 694 if (Function *F = CGN->getFunction()) { 695 if (!F->isDeclaration() && isFunctionInPrintList(F->getName())) { 696 FoundFunction = true; 697 if (!NeedModule) { 698 PrintBannerOnce(); 699 F->print(OS); 700 } 701 } 702 } else if (isFunctionInPrintList("*")) { 703 PrintBannerOnce(); 704 OS << "\nPrinting <null> Function\n"; 705 } 706 } 707 if (NeedModule && FoundFunction) { 708 PrintBannerOnce(); 709 OS << "\n"; 710 SCC.getCallGraph().getModule().print(OS, nullptr); 711 } 712 return false; 713 } 714 715 StringRef getPassName() const override { return "Print CallGraph IR"; } 716 }; 717 718 } // end anonymous namespace. 719 720 char PrintCallGraphPass::ID = 0; 721 722 Pass *CallGraphSCCPass::createPrinterPass(raw_ostream &OS, 723 const std::string &Banner) const { 724 return new PrintCallGraphPass(Banner, OS); 725 } 726 727 char DummyCGSCCPass::ID = 0; 728 729 INITIALIZE_PASS(DummyCGSCCPass, "DummyCGSCCPass", "DummyCGSCCPass", false, 730 false) 731