1 //===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Analysis/CallGraphSCCPass.h"
19 #include "llvm/ADT/SCCIterator.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/CallGraph.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/LegacyPassManagers.h"
26 #include "llvm/IR/OptBisect.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Timer.h"
30 #include "llvm/Support/raw_ostream.h"
33 #define DEBUG_TYPE "cgscc-passmgr"
35 static cl::opt<unsigned>
36 MaxIterations("max-cg-scc-iterations", cl::ReallyHidden, cl::init(4));
38 STATISTIC(MaxSCCIterations, "Maximum CGSCCPassMgr iterations on one SCC");
40 //===----------------------------------------------------------------------===//
43 /// CGPassManager manages FPPassManagers and CallGraphSCCPasses.
47 class CGPassManager : public ModulePass, public PMDataManager {
50 explicit CGPassManager()
51 : ModulePass(ID), PMDataManager() { }
53 /// Execute all of the passes scheduled for execution. Keep track of
54 /// whether any of the passes modifies the module, and if so, return true.
55 bool runOnModule(Module &M) override;
57 using ModulePass::doInitialization;
58 using ModulePass::doFinalization;
60 bool doInitialization(CallGraph &CG);
61 bool doFinalization(CallGraph &CG);
63 /// Pass Manager itself does not invalidate any analysis info.
64 void getAnalysisUsage(AnalysisUsage &Info) const override {
65 // CGPassManager walks SCC and it needs CallGraph.
66 Info.addRequired<CallGraphWrapperPass>();
67 Info.setPreservesAll();
70 StringRef getPassName() const override { return "CallGraph Pass Manager"; }
72 PMDataManager *getAsPMDataManager() override { return this; }
73 Pass *getAsPass() override { return this; }
75 // Print passes managed by this manager
76 void dumpPassStructure(unsigned Offset) override {
77 errs().indent(Offset*2) << "Call Graph SCC Pass Manager\n";
78 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
79 Pass *P = getContainedPass(Index);
80 P->dumpPassStructure(Offset + 1);
81 dumpLastUses(P, Offset+1);
85 Pass *getContainedPass(unsigned N) {
86 assert(N < PassVector.size() && "Pass number out of range!");
87 return static_cast<Pass *>(PassVector[N]);
90 PassManagerType getPassManagerType() const override {
91 return PMT_CallGraphPassManager;
95 bool RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
96 bool &DevirtualizedCall);
98 bool RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
99 CallGraph &CG, bool &CallGraphUpToDate,
100 bool &DevirtualizedCall);
101 bool RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG,
102 bool IsCheckingMode);
105 } // end anonymous namespace.
107 char CGPassManager::ID = 0;
110 bool CGPassManager::RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
111 CallGraph &CG, bool &CallGraphUpToDate,
112 bool &DevirtualizedCall) {
113 bool Changed = false;
114 PMDataManager *PM = P->getAsPMDataManager();
117 CallGraphSCCPass *CGSP = (CallGraphSCCPass*)P;
118 if (!CallGraphUpToDate) {
119 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
120 CallGraphUpToDate = true;
124 TimeRegion PassTimer(getPassTimer(CGSP));
125 Changed = CGSP->runOnSCC(CurSCC);
128 // After the CGSCCPass is done, when assertions are enabled, use
129 // RefreshCallGraph to verify that the callgraph was correctly updated.
132 RefreshCallGraph(CurSCC, CG, true);
139 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
140 "Invalid CGPassManager member");
141 FPPassManager *FPP = (FPPassManager*)P;
143 // Run pass P on all functions in the current SCC.
144 for (CallGraphNode *CGN : CurSCC) {
145 if (Function *F = CGN->getFunction()) {
146 dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName());
148 TimeRegion PassTimer(getPassTimer(FPP));
149 Changed |= FPP->runOnFunction(*F);
151 F->getContext().yield();
155 // The function pass(es) modified the IR, they may have clobbered the
157 if (Changed && CallGraphUpToDate) {
158 DEBUG(dbgs() << "CGSCCPASSMGR: Pass Dirtied SCC: "
159 << P->getPassName() << '\n');
160 CallGraphUpToDate = false;
166 /// Scan the functions in the specified CFG and resync the
167 /// callgraph with the call sites found in it. This is used after
168 /// FunctionPasses have potentially munged the callgraph, and can be used after
169 /// CallGraphSCC passes to verify that they correctly updated the callgraph.
171 /// This function returns true if it devirtualized an existing function call,
172 /// meaning it turned an indirect call into a direct call. This happens when
173 /// a function pass like GVN optimizes away stuff feeding the indirect call.
174 /// This never happens in checking mode.
176 bool CGPassManager::RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG,
178 DenseMap<Value*, CallGraphNode*> CallSites;
180 DEBUG(dbgs() << "CGSCCPASSMGR: Refreshing SCC with " << CurSCC.size()
182 for (CallGraphNode *CGN : CurSCC)
186 bool MadeChange = false;
187 bool DevirtualizedCall = false;
189 // Scan all functions in the SCC.
190 unsigned FunctionNo = 0;
191 for (CallGraphSCC::iterator SCCIdx = CurSCC.begin(), E = CurSCC.end();
192 SCCIdx != E; ++SCCIdx, ++FunctionNo) {
193 CallGraphNode *CGN = *SCCIdx;
194 Function *F = CGN->getFunction();
195 if (!F || F->isDeclaration()) continue;
197 // Walk the function body looking for call sites. Sync up the call sites in
198 // CGN with those actually in the function.
200 // Keep track of the number of direct and indirect calls that were
201 // invalidated and removed.
202 unsigned NumDirectRemoved = 0, NumIndirectRemoved = 0;
204 // Get the set of call sites currently in the function.
205 for (CallGraphNode::iterator I = CGN->begin(), E = CGN->end(); I != E; ) {
206 // If this call site is null, then the function pass deleted the call
207 // entirely and the WeakVH nulled it out.
209 // If we've already seen this call site, then the FunctionPass RAUW'd
210 // one call with another, which resulted in two "uses" in the edge
211 // list of the same call.
212 CallSites.count(I->first) ||
214 // If the call edge is not from a call or invoke, or it is a
215 // instrinsic call, then the function pass RAUW'd a call with
216 // another value. This can happen when constant folding happens
217 // of well known functions etc.
218 !CallSite(I->first) ||
219 (CallSite(I->first).getCalledFunction() &&
220 CallSite(I->first).getCalledFunction()->isIntrinsic() &&
222 CallSite(I->first).getCalledFunction()->getIntrinsicID()))) {
223 assert(!CheckingMode &&
224 "CallGraphSCCPass did not update the CallGraph correctly!");
226 // If this was an indirect call site, count it.
227 if (!I->second->getFunction())
228 ++NumIndirectRemoved;
232 // Just remove the edge from the set of callees, keep track of whether
233 // I points to the last element of the vector.
234 bool WasLast = I + 1 == E;
235 CGN->removeCallEdge(I);
237 // If I pointed to the last element of the vector, we have to bail out:
238 // iterator checking rejects comparisons of the resultant pointer with
246 assert(!CallSites.count(I->first) &&
247 "Call site occurs in node multiple times");
249 CallSite CS(I->first);
251 Function *Callee = CS.getCalledFunction();
252 // Ignore intrinsics because they're not really function calls.
253 if (!Callee || !(Callee->isIntrinsic()))
254 CallSites.insert(std::make_pair(I->first, I->second));
259 // Loop over all of the instructions in the function, getting the callsites.
260 // Keep track of the number of direct/indirect calls added.
261 unsigned NumDirectAdded = 0, NumIndirectAdded = 0;
263 for (BasicBlock &BB : *F)
264 for (Instruction &I : BB) {
267 Function *Callee = CS.getCalledFunction();
268 if (Callee && Callee->isIntrinsic()) continue;
270 // If this call site already existed in the callgraph, just verify it
271 // matches up to expectations and remove it from CallSites.
272 DenseMap<Value*, CallGraphNode*>::iterator ExistingIt =
273 CallSites.find(CS.getInstruction());
274 if (ExistingIt != CallSites.end()) {
275 CallGraphNode *ExistingNode = ExistingIt->second;
277 // Remove from CallSites since we have now seen it.
278 CallSites.erase(ExistingIt);
280 // Verify that the callee is right.
281 if (ExistingNode->getFunction() == CS.getCalledFunction())
284 // If we are in checking mode, we are not allowed to actually mutate
285 // the callgraph. If this is a case where we can infer that the
286 // callgraph is less precise than it could be (e.g. an indirect call
287 // site could be turned direct), don't reject it in checking mode, and
288 // don't tweak it to be more precise.
289 if (CheckingMode && CS.getCalledFunction() &&
290 ExistingNode->getFunction() == nullptr)
293 assert(!CheckingMode &&
294 "CallGraphSCCPass did not update the CallGraph correctly!");
296 // If not, we either went from a direct call to indirect, indirect to
297 // direct, or direct to different direct.
298 CallGraphNode *CalleeNode;
299 if (Function *Callee = CS.getCalledFunction()) {
300 CalleeNode = CG.getOrInsertFunction(Callee);
301 // Keep track of whether we turned an indirect call into a direct
303 if (!ExistingNode->getFunction()) {
304 DevirtualizedCall = true;
305 DEBUG(dbgs() << " CGSCCPASSMGR: Devirtualized call to '"
306 << Callee->getName() << "'\n");
309 CalleeNode = CG.getCallsExternalNode();
312 // Update the edge target in CGN.
313 CGN->replaceCallEdge(CS, CS, CalleeNode);
318 assert(!CheckingMode &&
319 "CallGraphSCCPass did not update the CallGraph correctly!");
321 // If the call site didn't exist in the CGN yet, add it.
322 CallGraphNode *CalleeNode;
323 if (Function *Callee = CS.getCalledFunction()) {
324 CalleeNode = CG.getOrInsertFunction(Callee);
327 CalleeNode = CG.getCallsExternalNode();
331 CGN->addCalledFunction(CS, CalleeNode);
335 // We scanned the old callgraph node, removing invalidated call sites and
336 // then added back newly found call sites. One thing that can happen is
337 // that an old indirect call site was deleted and replaced with a new direct
338 // call. In this case, we have devirtualized a call, and CGSCCPM would like
339 // to iteratively optimize the new code. Unfortunately, we don't really
340 // have a great way to detect when this happens. As an approximation, we
341 // just look at whether the number of indirect calls is reduced and the
342 // number of direct calls is increased. There are tons of ways to fool this
343 // (e.g. DCE'ing an indirect call and duplicating an unrelated block with a
344 // direct call) but this is close enough.
345 if (NumIndirectRemoved > NumIndirectAdded &&
346 NumDirectRemoved < NumDirectAdded)
347 DevirtualizedCall = true;
349 // After scanning this function, if we still have entries in callsites, then
350 // they are dangling pointers. WeakVH should save us for this, so abort if
352 assert(CallSites.empty() && "Dangling pointers found in call sites map");
354 // Periodically do an explicit clear to remove tombstones when processing
356 if ((FunctionNo & 15) == 15)
360 DEBUG(if (MadeChange) {
361 dbgs() << "CGSCCPASSMGR: Refreshed SCC is now:\n";
362 for (CallGraphNode *CGN : CurSCC)
364 if (DevirtualizedCall)
365 dbgs() << "CGSCCPASSMGR: Refresh devirtualized a call!\n";
368 dbgs() << "CGSCCPASSMGR: SCC Refresh didn't change call graph.\n";
373 return DevirtualizedCall;
376 /// Execute the body of the entire pass manager on the specified SCC.
377 /// This keeps track of whether a function pass devirtualizes
378 /// any calls and returns it in DevirtualizedCall.
379 bool CGPassManager::RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
380 bool &DevirtualizedCall) {
381 bool Changed = false;
383 // Keep track of whether the callgraph is known to be up-to-date or not.
384 // The CGSSC pass manager runs two types of passes:
385 // CallGraphSCC Passes and other random function passes. Because other
386 // random function passes are not CallGraph aware, they may clobber the
387 // call graph by introducing new calls or deleting other ones. This flag
388 // is set to false when we run a function pass so that we know to clean up
389 // the callgraph when we need to run a CGSCCPass again.
390 bool CallGraphUpToDate = true;
392 // Run all passes on current SCC.
393 for (unsigned PassNo = 0, e = getNumContainedPasses();
394 PassNo != e; ++PassNo) {
395 Pass *P = getContainedPass(PassNo);
397 // If we're in -debug-pass=Executions mode, construct the SCC node list,
398 // otherwise avoid constructing this string as it is expensive.
399 if (isPassDebuggingExecutionsOrMore()) {
400 std::string Functions;
402 raw_string_ostream OS(Functions);
403 for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
405 if (I != CurSCC.begin()) OS << ", ";
410 dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, Functions);
414 initializeAnalysisImpl(P);
416 // Actually run this pass on the current SCC.
417 Changed |= RunPassOnSCC(P, CurSCC, CG,
418 CallGraphUpToDate, DevirtualizedCall);
421 dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, "");
424 verifyPreservedAnalysis(P);
425 removeNotPreservedAnalysis(P);
426 recordAvailableAnalysis(P);
427 removeDeadPasses(P, "", ON_CG_MSG);
430 // If the callgraph was left out of date (because the last pass run was a
431 // functionpass), refresh it before we move on to the next SCC.
432 if (!CallGraphUpToDate)
433 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
437 /// Execute all of the passes scheduled for execution. Keep track of
438 /// whether any of the passes modifies the module, and if so, return true.
439 bool CGPassManager::runOnModule(Module &M) {
440 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
441 bool Changed = doInitialization(CG);
443 // Walk the callgraph in bottom-up SCC order.
444 scc_iterator<CallGraph*> CGI = scc_begin(&CG);
446 CallGraphSCC CurSCC(CG, &CGI);
447 while (!CGI.isAtEnd()) {
448 // Copy the current SCC and increment past it so that the pass can hack
449 // on the SCC if it wants to without invalidating our iterator.
450 const std::vector<CallGraphNode *> &NodeVec = *CGI;
451 CurSCC.initialize(NodeVec);
454 // At the top level, we run all the passes in this pass manager on the
455 // functions in this SCC. However, we support iterative compilation in the
456 // case where a function pass devirtualizes a call to a function. For
457 // example, it is very common for a function pass (often GVN or instcombine)
458 // to eliminate the addressing that feeds into a call. With that improved
459 // information, we would like the call to be an inline candidate, infer
460 // mod-ref information etc.
462 // Because of this, we allow iteration up to a specified iteration count.
463 // This only happens in the case of a devirtualized call, so we only burn
464 // compile time in the case that we're making progress. We also have a hard
465 // iteration count limit in case there is crazy code.
466 unsigned Iteration = 0;
467 bool DevirtualizedCall = false;
470 dbgs() << " SCCPASSMGR: Re-visiting SCC, iteration #"
471 << Iteration << '\n');
472 DevirtualizedCall = false;
473 Changed |= RunAllPassesOnSCC(CurSCC, CG, DevirtualizedCall);
474 } while (Iteration++ < MaxIterations && DevirtualizedCall);
476 if (DevirtualizedCall)
477 DEBUG(dbgs() << " CGSCCPASSMGR: Stopped iteration after " << Iteration
478 << " times, due to -max-cg-scc-iterations\n");
480 if (Iteration > MaxSCCIterations)
481 MaxSCCIterations = Iteration;
484 Changed |= doFinalization(CG);
490 bool CGPassManager::doInitialization(CallGraph &CG) {
491 bool Changed = false;
492 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
493 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
494 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
495 "Invalid CGPassManager member");
496 Changed |= ((FPPassManager*)PM)->doInitialization(CG.getModule());
498 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doInitialization(CG);
505 bool CGPassManager::doFinalization(CallGraph &CG) {
506 bool Changed = false;
507 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
508 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
509 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
510 "Invalid CGPassManager member");
511 Changed |= ((FPPassManager*)PM)->doFinalization(CG.getModule());
513 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doFinalization(CG);
519 //===----------------------------------------------------------------------===//
520 // CallGraphSCC Implementation
521 //===----------------------------------------------------------------------===//
523 /// This informs the SCC and the pass manager that the specified
524 /// Old node has been deleted, and New is to be used in its place.
525 void CallGraphSCC::ReplaceNode(CallGraphNode *Old, CallGraphNode *New) {
526 assert(Old != New && "Should not replace node with self");
527 for (unsigned i = 0; ; ++i) {
528 assert(i != Nodes.size() && "Node not in SCC");
529 if (Nodes[i] != Old) continue;
534 // Update the active scc_iterator so that it doesn't contain dangling
535 // pointers to the old CallGraphNode.
536 scc_iterator<CallGraph*> *CGI = (scc_iterator<CallGraph*>*)Context;
537 CGI->ReplaceNode(Old, New);
541 //===----------------------------------------------------------------------===//
542 // CallGraphSCCPass Implementation
543 //===----------------------------------------------------------------------===//
545 /// Assign pass manager to manage this pass.
546 void CallGraphSCCPass::assignPassManager(PMStack &PMS,
547 PassManagerType PreferredType) {
548 // Find CGPassManager
549 while (!PMS.empty() &&
550 PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)
553 assert(!PMS.empty() && "Unable to handle Call Graph Pass");
556 if (PMS.top()->getPassManagerType() == PMT_CallGraphPassManager)
557 CGP = (CGPassManager*)PMS.top();
559 // Create new Call Graph SCC Pass Manager if it does not exist.
560 assert(!PMS.empty() && "Unable to create Call Graph Pass Manager");
561 PMDataManager *PMD = PMS.top();
563 // [1] Create new Call Graph Pass Manager
564 CGP = new CGPassManager();
566 // [2] Set up new manager's top level manager
567 PMTopLevelManager *TPM = PMD->getTopLevelManager();
568 TPM->addIndirectPassManager(CGP);
570 // [3] Assign manager to manage this new manager. This may create
571 // and push new managers into PMS
573 TPM->schedulePass(P);
575 // [4] Push new manager into PMS
582 /// For this class, we declare that we require and preserve the call graph.
583 /// If the derived class implements this method, it should
584 /// always explicitly call the implementation here.
585 void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {
586 AU.addRequired<CallGraphWrapperPass>();
587 AU.addPreserved<CallGraphWrapperPass>();
591 //===----------------------------------------------------------------------===//
592 // PrintCallGraphPass Implementation
593 //===----------------------------------------------------------------------===//
596 /// PrintCallGraphPass - Print a Module corresponding to a call graph.
598 class PrintCallGraphPass : public CallGraphSCCPass {
600 raw_ostream &Out; // raw_ostream to print on.
604 PrintCallGraphPass(const std::string &B, raw_ostream &o)
605 : CallGraphSCCPass(ID), Banner(B), Out(o) {}
607 void getAnalysisUsage(AnalysisUsage &AU) const override {
608 AU.setPreservesAll();
611 bool runOnSCC(CallGraphSCC &SCC) override {
613 for (CallGraphNode *CGN : SCC) {
614 if (CGN->getFunction()) {
615 if (isFunctionInPrintList(CGN->getFunction()->getName()))
616 CGN->getFunction()->print(Out);
618 Out << "\nPrinting <null> Function\n";
624 } // end anonymous namespace.
626 char PrintCallGraphPass::ID = 0;
628 Pass *CallGraphSCCPass::createPrinterPass(raw_ostream &O,
629 const std::string &Banner) const {
630 return new PrintCallGraphPass(Banner, O);
633 bool CallGraphSCCPass::skipSCC(CallGraphSCC &SCC) const {
634 return !SCC.getCallGraph().getModule()
637 .shouldRunPass(this, SCC);
640 char DummyCGSCCPass::ID = 0;
641 INITIALIZE_PASS(DummyCGSCCPass, "DummyCGSCCPass", "DummyCGSCCPass", false,