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