CallGraphSCCPass.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. //===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===//
  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 CallGraphSCCPass class, which is used for passes
  11. // which are implemented as bottom-up traversals on the call graph. Because
  12. // there may be cycles in the call graph, passes of this type operate on the
  13. // call-graph in SCC order: that is, they process function bottom-up, except for
  14. // recursive functions, which they process all at once.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Analysis/CallGraphSCCPass.h"
  18. #include "llvm/ADT/SCCIterator.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/CallGraph.h"
  21. #include "llvm/IR/Function.h"
  22. #include "llvm/IR/IntrinsicInst.h"
  23. #include "llvm/IR/LLVMContext.h"
  24. #include "llvm/IR/LegacyPassManagers.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "llvm/Support/Timer.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. using namespace llvm;
  30. #define DEBUG_TYPE "cgscc-passmgr"
  31. #if 0 // HLSL Change Starts - option pending
  32. static cl::opt<unsigned>
  33. MaxIterations("max-cg-scc-iterations", cl::ReallyHidden, cl::init(4));
  34. #else
  35. static const unsigned MaxIterations = 4;
  36. #endif
  37. STATISTIC(MaxSCCIterations, "Maximum CGSCCPassMgr iterations on one SCC");
  38. //===----------------------------------------------------------------------===//
  39. // CGPassManager
  40. //
  41. /// CGPassManager manages FPPassManagers and CallGraphSCCPasses.
  42. namespace {
  43. class CGPassManager : public ModulePass, public PMDataManager {
  44. public:
  45. static char ID;
  46. explicit CGPassManager()
  47. : ModulePass(ID), PMDataManager() { }
  48. /// Execute all of the passes scheduled for execution. Keep track of
  49. /// whether any of the passes modifies the module, and if so, return true.
  50. bool runOnModule(Module &M) override;
  51. using ModulePass::doInitialization;
  52. using ModulePass::doFinalization;
  53. bool doInitialization(CallGraph &CG);
  54. bool doFinalization(CallGraph &CG);
  55. /// Pass Manager itself does not invalidate any analysis info.
  56. void getAnalysisUsage(AnalysisUsage &Info) const override {
  57. // CGPassManager walks SCC and it needs CallGraph.
  58. Info.addRequired<CallGraphWrapperPass>();
  59. Info.setPreservesAll();
  60. }
  61. const char *getPassName() const override {
  62. return "CallGraph Pass Manager";
  63. }
  64. PMDataManager *getAsPMDataManager() override { return this; }
  65. Pass *getAsPass() override { return this; }
  66. // Print passes managed by this manager
  67. void dumpPassStructure(unsigned Offset) override {
  68. errs().indent(Offset*2) << "Call Graph SCC Pass Manager\n";
  69. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
  70. Pass *P = getContainedPass(Index);
  71. P->dumpPassStructure(Offset + 1);
  72. dumpLastUses(P, Offset+1);
  73. }
  74. }
  75. Pass *getContainedPass(unsigned N) {
  76. assert(N < PassVector.size() && "Pass number out of range!");
  77. return static_cast<Pass *>(PassVector[N]);
  78. }
  79. PassManagerType getPassManagerType() const override {
  80. return PMT_CallGraphPassManager;
  81. }
  82. private:
  83. bool RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
  84. bool &DevirtualizedCall);
  85. bool RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
  86. CallGraph &CG, bool &CallGraphUpToDate,
  87. bool &DevirtualizedCall);
  88. bool RefreshCallGraph(CallGraphSCC &CurSCC, CallGraph &CG,
  89. bool IsCheckingMode);
  90. };
  91. } // end anonymous namespace.
  92. char CGPassManager::ID = 0;
  93. bool CGPassManager::RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
  94. CallGraph &CG, bool &CallGraphUpToDate,
  95. bool &DevirtualizedCall) {
  96. bool Changed = false;
  97. PMDataManager *PM = P->getAsPMDataManager();
  98. if (!PM) {
  99. CallGraphSCCPass *CGSP = (CallGraphSCCPass*)P;
  100. if (!CallGraphUpToDate) {
  101. DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
  102. CallGraphUpToDate = true;
  103. }
  104. {
  105. TimeRegion PassTimer(getPassTimer(CGSP));
  106. Changed = CGSP->runOnSCC(CurSCC);
  107. }
  108. // After the CGSCCPass is done, when assertions are enabled, use
  109. // RefreshCallGraph to verify that the callgraph was correctly updated.
  110. #ifndef NDEBUG
  111. if (Changed)
  112. RefreshCallGraph(CurSCC, CG, true);
  113. #endif
  114. return Changed;
  115. }
  116. assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
  117. "Invalid CGPassManager member");
  118. FPPassManager *FPP = (FPPassManager*)P;
  119. // Run pass P on all functions in the current SCC.
  120. for (CallGraphNode *CGN : CurSCC) {
  121. if (Function *F = CGN->getFunction()) {
  122. dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName());
  123. {
  124. TimeRegion PassTimer(getPassTimer(FPP));
  125. Changed |= FPP->runOnFunction(*F);
  126. }
  127. F->getContext().yield();
  128. }
  129. }
  130. // The function pass(es) modified the IR, they may have clobbered the
  131. // callgraph.
  132. if (Changed && CallGraphUpToDate) {
  133. DEBUG(dbgs() << "CGSCCPASSMGR: Pass Dirtied SCC: "
  134. << P->getPassName() << '\n');
  135. CallGraphUpToDate = false;
  136. }
  137. return Changed;
  138. }
  139. /// Scan the functions in the specified CFG and resync the
  140. /// callgraph with the call sites found in it. This is used after
  141. /// FunctionPasses have potentially munged the callgraph, and can be used after
  142. /// CallGraphSCC passes to verify that they correctly updated the callgraph.
  143. ///
  144. /// This function returns true if it devirtualized an existing function call,
  145. /// meaning it turned an indirect call into a direct call. This happens when
  146. /// a function pass like GVN optimizes away stuff feeding the indirect call.
  147. /// This never happens in checking mode.
  148. ///
  149. bool CGPassManager::RefreshCallGraph(CallGraphSCC &CurSCC,
  150. CallGraph &CG, bool CheckingMode) {
  151. DenseMap<Value*, CallGraphNode*> CallSites;
  152. DEBUG(dbgs() << "CGSCCPASSMGR: Refreshing SCC with " << CurSCC.size()
  153. << " nodes:\n";
  154. for (CallGraphNode *CGN : CurSCC)
  155. CGN->dump();
  156. );
  157. bool MadeChange = false;
  158. bool DevirtualizedCall = false;
  159. // Scan all functions in the SCC.
  160. unsigned FunctionNo = 0;
  161. for (CallGraphSCC::iterator SCCIdx = CurSCC.begin(), E = CurSCC.end();
  162. SCCIdx != E; ++SCCIdx, ++FunctionNo) {
  163. CallGraphNode *CGN = *SCCIdx;
  164. Function *F = CGN->getFunction();
  165. if (!F || F->isDeclaration()) continue;
  166. // Walk the function body looking for call sites. Sync up the call sites in
  167. // CGN with those actually in the function.
  168. // Keep track of the number of direct and indirect calls that were
  169. // invalidated and removed.
  170. unsigned NumDirectRemoved = 0, NumIndirectRemoved = 0;
  171. // Get the set of call sites currently in the function.
  172. for (CallGraphNode::iterator I = CGN->begin(), E = CGN->end(); I != E; ) {
  173. // If this call site is null, then the function pass deleted the call
  174. // entirely and the WeakVH nulled it out.
  175. if (!I->first ||
  176. // If we've already seen this call site, then the FunctionPass RAUW'd
  177. // one call with another, which resulted in two "uses" in the edge
  178. // list of the same call.
  179. CallSites.count(I->first) ||
  180. // If the call edge is not from a call or invoke, or it is a
  181. // instrinsic call, then the function pass RAUW'd a call with
  182. // another value. This can happen when constant folding happens
  183. // of well known functions etc.
  184. !CallSite(I->first) ||
  185. (CallSite(I->first).getCalledFunction() &&
  186. CallSite(I->first).getCalledFunction()->isIntrinsic() &&
  187. Intrinsic::isLeaf(
  188. CallSite(I->first).getCalledFunction()->getIntrinsicID()))) {
  189. assert(!CheckingMode &&
  190. "CallGraphSCCPass did not update the CallGraph correctly!");
  191. // If this was an indirect call site, count it.
  192. if (!I->second->getFunction())
  193. ++NumIndirectRemoved;
  194. else
  195. ++NumDirectRemoved;
  196. // Just remove the edge from the set of callees, keep track of whether
  197. // I points to the last element of the vector.
  198. bool WasLast = I + 1 == E;
  199. CGN->removeCallEdge(I);
  200. // If I pointed to the last element of the vector, we have to bail out:
  201. // iterator checking rejects comparisons of the resultant pointer with
  202. // end.
  203. if (WasLast)
  204. break;
  205. E = CGN->end();
  206. continue;
  207. }
  208. assert(!CallSites.count(I->first) &&
  209. "Call site occurs in node multiple times");
  210. CallSite CS(I->first);
  211. if (CS) {
  212. Function *Callee = CS.getCalledFunction();
  213. // Ignore intrinsics because they're not really function calls.
  214. if (!Callee || !(Callee->isIntrinsic()))
  215. CallSites.insert(std::make_pair(I->first, I->second));
  216. }
  217. ++I;
  218. }
  219. // Loop over all of the instructions in the function, getting the callsites.
  220. // Keep track of the number of direct/indirect calls added.
  221. unsigned NumDirectAdded = 0, NumIndirectAdded = 0;
  222. for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
  223. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  224. CallSite CS(cast<Value>(I));
  225. if (!CS) continue;
  226. Function *Callee = CS.getCalledFunction();
  227. if (Callee && Callee->isIntrinsic()) continue;
  228. // If this call site already existed in the callgraph, just verify it
  229. // matches up to expectations and remove it from CallSites.
  230. DenseMap<Value*, CallGraphNode*>::iterator ExistingIt =
  231. CallSites.find(CS.getInstruction());
  232. if (ExistingIt != CallSites.end()) {
  233. CallGraphNode *ExistingNode = ExistingIt->second;
  234. // Remove from CallSites since we have now seen it.
  235. CallSites.erase(ExistingIt);
  236. // Verify that the callee is right.
  237. if (ExistingNode->getFunction() == CS.getCalledFunction())
  238. continue;
  239. // If we are in checking mode, we are not allowed to actually mutate
  240. // the callgraph. If this is a case where we can infer that the
  241. // callgraph is less precise than it could be (e.g. an indirect call
  242. // site could be turned direct), don't reject it in checking mode, and
  243. // don't tweak it to be more precise.
  244. if (CheckingMode && CS.getCalledFunction() &&
  245. ExistingNode->getFunction() == nullptr)
  246. continue;
  247. assert(!CheckingMode &&
  248. "CallGraphSCCPass did not update the CallGraph correctly!");
  249. // If not, we either went from a direct call to indirect, indirect to
  250. // direct, or direct to different direct.
  251. CallGraphNode *CalleeNode;
  252. if (Function *Callee = CS.getCalledFunction()) {
  253. CalleeNode = CG.getOrInsertFunction(Callee);
  254. // Keep track of whether we turned an indirect call into a direct
  255. // one.
  256. if (!ExistingNode->getFunction()) {
  257. DevirtualizedCall = true;
  258. DEBUG(dbgs() << " CGSCCPASSMGR: Devirtualized call to '"
  259. << Callee->getName() << "'\n");
  260. }
  261. } else {
  262. CalleeNode = CG.getCallsExternalNode();
  263. }
  264. // Update the edge target in CGN.
  265. CGN->replaceCallEdge(CS, CS, CalleeNode);
  266. MadeChange = true;
  267. continue;
  268. }
  269. assert(!CheckingMode &&
  270. "CallGraphSCCPass did not update the CallGraph correctly!");
  271. // If the call site didn't exist in the CGN yet, add it.
  272. CallGraphNode *CalleeNode;
  273. if (Function *Callee = CS.getCalledFunction()) {
  274. CalleeNode = CG.getOrInsertFunction(Callee);
  275. ++NumDirectAdded;
  276. } else {
  277. CalleeNode = CG.getCallsExternalNode();
  278. ++NumIndirectAdded;
  279. }
  280. CGN->addCalledFunction(CS, CalleeNode);
  281. MadeChange = true;
  282. }
  283. // We scanned the old callgraph node, removing invalidated call sites and
  284. // then added back newly found call sites. One thing that can happen is
  285. // that an old indirect call site was deleted and replaced with a new direct
  286. // call. In this case, we have devirtualized a call, and CGSCCPM would like
  287. // to iteratively optimize the new code. Unfortunately, we don't really
  288. // have a great way to detect when this happens. As an approximation, we
  289. // just look at whether the number of indirect calls is reduced and the
  290. // number of direct calls is increased. There are tons of ways to fool this
  291. // (e.g. DCE'ing an indirect call and duplicating an unrelated block with a
  292. // direct call) but this is close enough.
  293. if (NumIndirectRemoved > NumIndirectAdded &&
  294. NumDirectRemoved < NumDirectAdded)
  295. DevirtualizedCall = true;
  296. // After scanning this function, if we still have entries in callsites, then
  297. // they are dangling pointers. WeakVH should save us for this, so abort if
  298. // this happens.
  299. assert(CallSites.empty() && "Dangling pointers found in call sites map");
  300. // Periodically do an explicit clear to remove tombstones when processing
  301. // large scc's.
  302. if ((FunctionNo & 15) == 15)
  303. CallSites.clear();
  304. }
  305. DEBUG(if (MadeChange) {
  306. dbgs() << "CGSCCPASSMGR: Refreshed SCC is now:\n";
  307. for (CallGraphNode *CGN : CurSCC)
  308. CGN->dump();
  309. if (DevirtualizedCall)
  310. dbgs() << "CGSCCPASSMGR: Refresh devirtualized a call!\n";
  311. } else {
  312. dbgs() << "CGSCCPASSMGR: SCC Refresh didn't change call graph.\n";
  313. }
  314. );
  315. (void)MadeChange;
  316. return DevirtualizedCall;
  317. }
  318. /// Execute the body of the entire pass manager on the specified SCC.
  319. /// This keeps track of whether a function pass devirtualizes
  320. /// any calls and returns it in DevirtualizedCall.
  321. bool CGPassManager::RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
  322. bool &DevirtualizedCall) {
  323. bool Changed = false;
  324. // Keep track of whether the callgraph is known to be up-to-date or not.
  325. // The CGSSC pass manager runs two types of passes:
  326. // CallGraphSCC Passes and other random function passes. Because other
  327. // random function passes are not CallGraph aware, they may clobber the
  328. // call graph by introducing new calls or deleting other ones. This flag
  329. // is set to false when we run a function pass so that we know to clean up
  330. // the callgraph when we need to run a CGSCCPass again.
  331. bool CallGraphUpToDate = true;
  332. // Run all passes on current SCC.
  333. for (unsigned PassNo = 0, e = getNumContainedPasses();
  334. PassNo != e; ++PassNo) {
  335. Pass *P = getContainedPass(PassNo);
  336. // If we're in -debug-pass=Executions mode, construct the SCC node list,
  337. // otherwise avoid constructing this string as it is expensive.
  338. if (isPassDebuggingExecutionsOrMore()) {
  339. std::string Functions;
  340. #ifndef NDEBUG
  341. raw_string_ostream OS(Functions);
  342. for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
  343. I != E; ++I) {
  344. if (I != CurSCC.begin()) OS << ", ";
  345. (*I)->print(OS);
  346. }
  347. OS.flush();
  348. #endif
  349. dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, Functions);
  350. }
  351. dumpRequiredSet(P);
  352. initializeAnalysisImpl(P);
  353. // Actually run this pass on the current SCC.
  354. Changed |= RunPassOnSCC(P, CurSCC, CG,
  355. CallGraphUpToDate, DevirtualizedCall);
  356. if (Changed)
  357. dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, "");
  358. dumpPreservedSet(P);
  359. verifyPreservedAnalysis(P);
  360. removeNotPreservedAnalysis(P);
  361. recordAvailableAnalysis(P);
  362. removeDeadPasses(P, "", ON_CG_MSG);
  363. }
  364. // If the callgraph was left out of date (because the last pass run was a
  365. // functionpass), refresh it before we move on to the next SCC.
  366. if (!CallGraphUpToDate)
  367. DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
  368. return Changed;
  369. }
  370. /// Execute all of the passes scheduled for execution. Keep track of
  371. /// whether any of the passes modifies the module, and if so, return true.
  372. bool CGPassManager::runOnModule(Module &M) {
  373. CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
  374. bool Changed = doInitialization(CG);
  375. // Walk the callgraph in bottom-up SCC order.
  376. scc_iterator<CallGraph*> CGI = scc_begin(&CG);
  377. CallGraphSCC CurSCC(&CGI);
  378. while (!CGI.isAtEnd()) {
  379. // Copy the current SCC and increment past it so that the pass can hack
  380. // on the SCC if it wants to without invalidating our iterator.
  381. const std::vector<CallGraphNode *> &NodeVec = *CGI;
  382. CurSCC.initialize(NodeVec.data(), NodeVec.data() + NodeVec.size());
  383. ++CGI;
  384. // At the top level, we run all the passes in this pass manager on the
  385. // functions in this SCC. However, we support iterative compilation in the
  386. // case where a function pass devirtualizes a call to a function. For
  387. // example, it is very common for a function pass (often GVN or instcombine)
  388. // to eliminate the addressing that feeds into a call. With that improved
  389. // information, we would like the call to be an inline candidate, infer
  390. // mod-ref information etc.
  391. //
  392. // Because of this, we allow iteration up to a specified iteration count.
  393. // This only happens in the case of a devirtualized call, so we only burn
  394. // compile time in the case that we're making progress. We also have a hard
  395. // iteration count limit in case there is crazy code.
  396. unsigned Iteration = 0;
  397. bool DevirtualizedCall = false;
  398. do {
  399. DEBUG(if (Iteration)
  400. dbgs() << " SCCPASSMGR: Re-visiting SCC, iteration #"
  401. << Iteration << '\n');
  402. DevirtualizedCall = false;
  403. Changed |= RunAllPassesOnSCC(CurSCC, CG, DevirtualizedCall);
  404. } while (Iteration++ < MaxIterations && DevirtualizedCall);
  405. if (DevirtualizedCall)
  406. DEBUG(dbgs() << " CGSCCPASSMGR: Stopped iteration after " << Iteration
  407. << " times, due to -max-cg-scc-iterations\n");
  408. if (Iteration > MaxSCCIterations)
  409. MaxSCCIterations = Iteration;
  410. }
  411. Changed |= doFinalization(CG);
  412. return Changed;
  413. }
  414. /// Initialize CG
  415. bool CGPassManager::doInitialization(CallGraph &CG) {
  416. bool Changed = false;
  417. for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
  418. if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
  419. assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
  420. "Invalid CGPassManager member");
  421. Changed |= ((FPPassManager*)PM)->doInitialization(CG.getModule());
  422. } else {
  423. Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doInitialization(CG);
  424. }
  425. }
  426. return Changed;
  427. }
  428. /// Finalize CG
  429. bool CGPassManager::doFinalization(CallGraph &CG) {
  430. bool Changed = false;
  431. for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
  432. if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
  433. assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
  434. "Invalid CGPassManager member");
  435. Changed |= ((FPPassManager*)PM)->doFinalization(CG.getModule());
  436. } else {
  437. Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doFinalization(CG);
  438. }
  439. }
  440. return Changed;
  441. }
  442. //===----------------------------------------------------------------------===//
  443. // CallGraphSCC Implementation
  444. //===----------------------------------------------------------------------===//
  445. /// This informs the SCC and the pass manager that the specified
  446. /// Old node has been deleted, and New is to be used in its place.
  447. void CallGraphSCC::ReplaceNode(CallGraphNode *Old, CallGraphNode *New) {
  448. assert(Old != New && "Should not replace node with self");
  449. for (unsigned i = 0; ; ++i) {
  450. assert(i != Nodes.size() && "Node not in SCC");
  451. if (Nodes[i] != Old) continue;
  452. Nodes[i] = New;
  453. break;
  454. }
  455. // Update the active scc_iterator so that it doesn't contain dangling
  456. // pointers to the old CallGraphNode.
  457. scc_iterator<CallGraph*> *CGI = (scc_iterator<CallGraph*>*)Context;
  458. CGI->ReplaceNode(Old, New);
  459. }
  460. //===----------------------------------------------------------------------===//
  461. // CallGraphSCCPass Implementation
  462. //===----------------------------------------------------------------------===//
  463. /// Assign pass manager to manage this pass.
  464. void CallGraphSCCPass::assignPassManager(PMStack &PMS,
  465. PassManagerType PreferredType) {
  466. std::unique_ptr<CallGraphSCCPass> thisPtr(this); // HLSL Change
  467. // Find CGPassManager
  468. while (!PMS.empty() &&
  469. PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)
  470. PMS.pop();
  471. assert(!PMS.empty() && "Unable to handle Call Graph Pass");
  472. CGPassManager *CGP;
  473. if (PMS.top()->getPassManagerType() == PMT_CallGraphPassManager)
  474. CGP = (CGPassManager*)PMS.top();
  475. else {
  476. // Create new Call Graph SCC Pass Manager if it does not exist.
  477. assert(!PMS.empty() && "Unable to create Call Graph Pass Manager");
  478. PMDataManager *PMD = PMS.top();
  479. // [1] Create new Call Graph Pass Manager
  480. CGP = new CGPassManager();
  481. // [2] Set up new manager's top level manager
  482. PMTopLevelManager *TPM = PMD->getTopLevelManager();
  483. TPM->addIndirectPassManager(CGP);
  484. // [3] Assign manager to manage this new manager. This may create
  485. // and push new managers into PMS
  486. Pass *P = CGP;
  487. TPM->schedulePass(P);
  488. // [4] Push new manager into PMS
  489. PMS.push(CGP);
  490. }
  491. thisPtr.release();
  492. CGP->add(this);
  493. }
  494. /// For this class, we declare that we require and preserve the call graph.
  495. /// If the derived class implements this method, it should
  496. /// always explicitly call the implementation here.
  497. void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {
  498. AU.addRequired<CallGraphWrapperPass>();
  499. AU.addPreserved<CallGraphWrapperPass>();
  500. }
  501. //===----------------------------------------------------------------------===//
  502. // PrintCallGraphPass Implementation
  503. //===----------------------------------------------------------------------===//
  504. namespace {
  505. /// PrintCallGraphPass - Print a Module corresponding to a call graph.
  506. ///
  507. class PrintCallGraphPass : public CallGraphSCCPass {
  508. std::string Banner;
  509. raw_ostream &Out; // raw_ostream to print on.
  510. public:
  511. static char ID;
  512. PrintCallGraphPass(const std::string &B, raw_ostream &o)
  513. : CallGraphSCCPass(ID), Banner(B), Out(o) {}
  514. void getAnalysisUsage(AnalysisUsage &AU) const override {
  515. AU.setPreservesAll();
  516. }
  517. bool runOnSCC(CallGraphSCC &SCC) override {
  518. Out << Banner;
  519. for (CallGraphNode *CGN : SCC) {
  520. if (CGN->getFunction())
  521. CGN->getFunction()->print(Out);
  522. else
  523. Out << "\nPrinting <null> Function\n";
  524. }
  525. return false;
  526. }
  527. };
  528. } // end anonymous namespace.
  529. char PrintCallGraphPass::ID = 0;
  530. Pass *CallGraphSCCPass::createPrinterPass(raw_ostream &O,
  531. const std::string &Banner) const {
  532. return new PrintCallGraphPass(Banner, O);
  533. }