1bf71a34eSChandler Carruth //===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
2bf71a34eSChandler Carruth //
3bf71a34eSChandler Carruth //                     The LLVM Compiler Infrastructure
4bf71a34eSChandler Carruth //
5bf71a34eSChandler Carruth // This file is distributed under the University of Illinois Open Source
6bf71a34eSChandler Carruth // License. See LICENSE.TXT for details.
7bf71a34eSChandler Carruth //
8bf71a34eSChandler Carruth //===----------------------------------------------------------------------===//
9bf71a34eSChandler Carruth 
10bf71a34eSChandler Carruth #include "llvm/Analysis/LazyCallGraph.h"
1118eadd92SChandler Carruth #include "llvm/ADT/STLExtras.h"
12219b89b9SChandler Carruth #include "llvm/IR/CallSite.h"
137da14f1aSChandler Carruth #include "llvm/IR/InstVisitor.h"
14bf71a34eSChandler Carruth #include "llvm/IR/Instructions.h"
15bf71a34eSChandler Carruth #include "llvm/IR/PassManager.h"
1699b756dbSChandler Carruth #include "llvm/Support/Debug.h"
17bf71a34eSChandler Carruth #include "llvm/Support/raw_ostream.h"
18bf71a34eSChandler Carruth 
19bf71a34eSChandler Carruth using namespace llvm;
20bf71a34eSChandler Carruth 
21f1221bd0SChandler Carruth #define DEBUG_TYPE "lcg"
22f1221bd0SChandler Carruth 
23bf71a34eSChandler Carruth static void findCallees(
24bf71a34eSChandler Carruth     SmallVectorImpl<Constant *> &Worklist, SmallPtrSetImpl<Constant *> &Visited,
25bf71a34eSChandler Carruth     SmallVectorImpl<PointerUnion<Function *, LazyCallGraph::Node *>> &Callees,
260b623baeSChandler Carruth     DenseMap<Function *, size_t> &CalleeIndexMap) {
27bf71a34eSChandler Carruth   while (!Worklist.empty()) {
28bf71a34eSChandler Carruth     Constant *C = Worklist.pop_back_val();
29bf71a34eSChandler Carruth 
30bf71a34eSChandler Carruth     if (Function *F = dyn_cast<Function>(C)) {
31bf71a34eSChandler Carruth       // Note that we consider *any* function with a definition to be a viable
32bf71a34eSChandler Carruth       // edge. Even if the function's definition is subject to replacement by
33bf71a34eSChandler Carruth       // some other module (say, a weak definition) there may still be
34bf71a34eSChandler Carruth       // optimizations which essentially speculate based on the definition and
35bf71a34eSChandler Carruth       // a way to check that the specific definition is in fact the one being
36bf71a34eSChandler Carruth       // used. For example, this could be done by moving the weak definition to
37bf71a34eSChandler Carruth       // a strong (internal) definition and making the weak definition be an
38bf71a34eSChandler Carruth       // alias. Then a test of the address of the weak function against the new
39bf71a34eSChandler Carruth       // strong definition's address would be an effective way to determine the
40bf71a34eSChandler Carruth       // safety of optimizing a direct call edge.
410b623baeSChandler Carruth       if (!F->isDeclaration() &&
420b623baeSChandler Carruth           CalleeIndexMap.insert(std::make_pair(F, Callees.size())).second) {
4399b756dbSChandler Carruth         DEBUG(dbgs() << "    Added callable function: " << F->getName()
4499b756dbSChandler Carruth                      << "\n");
45bf71a34eSChandler Carruth         Callees.push_back(F);
4699b756dbSChandler Carruth       }
47bf71a34eSChandler Carruth       continue;
48bf71a34eSChandler Carruth     }
49bf71a34eSChandler Carruth 
501583e99cSChandler Carruth     for (Value *Op : C->operand_values())
511583e99cSChandler Carruth       if (Visited.insert(cast<Constant>(Op)))
521583e99cSChandler Carruth         Worklist.push_back(cast<Constant>(Op));
53bf71a34eSChandler Carruth   }
54bf71a34eSChandler Carruth }
55bf71a34eSChandler Carruth 
5618eadd92SChandler Carruth LazyCallGraph::Node::Node(LazyCallGraph &G, Function &F)
5718eadd92SChandler Carruth     : G(&G), F(F), DFSNumber(0), LowLink(0) {
5899b756dbSChandler Carruth   DEBUG(dbgs() << "  Adding functions called by '" << F.getName()
5999b756dbSChandler Carruth                << "' to the graph.\n");
6099b756dbSChandler Carruth 
61bf71a34eSChandler Carruth   SmallVector<Constant *, 16> Worklist;
62bf71a34eSChandler Carruth   SmallPtrSet<Constant *, 16> Visited;
63bf71a34eSChandler Carruth   // Find all the potential callees in this function. First walk the
64bf71a34eSChandler Carruth   // instructions and add every operand which is a constant to the worklist.
65b9e2f8c4SChandler Carruth   for (BasicBlock &BB : F)
66b9e2f8c4SChandler Carruth     for (Instruction &I : BB)
67b9e2f8c4SChandler Carruth       for (Value *Op : I.operand_values())
681583e99cSChandler Carruth         if (Constant *C = dyn_cast<Constant>(Op))
69bf71a34eSChandler Carruth           if (Visited.insert(C))
70bf71a34eSChandler Carruth             Worklist.push_back(C);
71bf71a34eSChandler Carruth 
72bf71a34eSChandler Carruth   // We've collected all the constant (and thus potentially function or
73bf71a34eSChandler Carruth   // function containing) operands to all of the instructions in the function.
74bf71a34eSChandler Carruth   // Process them (recursively) collecting every function found.
750b623baeSChandler Carruth   findCallees(Worklist, Visited, Callees, CalleeIndexMap);
76bf71a34eSChandler Carruth }
77bf71a34eSChandler Carruth 
78*c00a7ff4SChandler Carruth void LazyCallGraph::Node::insertEdgeInternal(Function &Callee) {
79*c00a7ff4SChandler Carruth   CalleeIndexMap.insert(std::make_pair(&Callee, Callees.size()));
80*c00a7ff4SChandler Carruth   if (Node *N = G->lookup(Callee))
81*c00a7ff4SChandler Carruth     Callees.push_back(N);
82*c00a7ff4SChandler Carruth   else
83*c00a7ff4SChandler Carruth     Callees.push_back(&Callee);
84*c00a7ff4SChandler Carruth }
85*c00a7ff4SChandler Carruth 
86aa839b22SChandler Carruth void LazyCallGraph::Node::removeEdgeInternal(Function &Callee) {
87aa839b22SChandler Carruth   auto IndexMapI = CalleeIndexMap.find(&Callee);
88aa839b22SChandler Carruth   assert(IndexMapI != CalleeIndexMap.end() &&
89aa839b22SChandler Carruth          "Callee not in the callee set for this caller?");
90aa839b22SChandler Carruth 
91aa839b22SChandler Carruth   Callees.erase(Callees.begin() + IndexMapI->second);
92aa839b22SChandler Carruth   CalleeIndexMap.erase(IndexMapI);
93aa839b22SChandler Carruth }
94aa839b22SChandler Carruth 
952174f44fSChandler Carruth LazyCallGraph::LazyCallGraph(Module &M) : NextDFSNumber(0) {
9699b756dbSChandler Carruth   DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
9799b756dbSChandler Carruth                << "\n");
98b9e2f8c4SChandler Carruth   for (Function &F : M)
99b9e2f8c4SChandler Carruth     if (!F.isDeclaration() && !F.hasLocalLinkage())
1000b623baeSChandler Carruth       if (EntryIndexMap.insert(std::make_pair(&F, EntryNodes.size())).second) {
10199b756dbSChandler Carruth         DEBUG(dbgs() << "  Adding '" << F.getName()
10299b756dbSChandler Carruth                      << "' to entry set of the graph.\n");
103b9e2f8c4SChandler Carruth         EntryNodes.push_back(&F);
10499b756dbSChandler Carruth       }
105bf71a34eSChandler Carruth 
106bf71a34eSChandler Carruth   // Now add entry nodes for functions reachable via initializers to globals.
107bf71a34eSChandler Carruth   SmallVector<Constant *, 16> Worklist;
108bf71a34eSChandler Carruth   SmallPtrSet<Constant *, 16> Visited;
109b9e2f8c4SChandler Carruth   for (GlobalVariable &GV : M.globals())
110b9e2f8c4SChandler Carruth     if (GV.hasInitializer())
111b9e2f8c4SChandler Carruth       if (Visited.insert(GV.getInitializer()))
112b9e2f8c4SChandler Carruth         Worklist.push_back(GV.getInitializer());
113bf71a34eSChandler Carruth 
11499b756dbSChandler Carruth   DEBUG(dbgs() << "  Adding functions referenced by global initializers to the "
11599b756dbSChandler Carruth                   "entry set.\n");
1160b623baeSChandler Carruth   findCallees(Worklist, Visited, EntryNodes, EntryIndexMap);
11718eadd92SChandler Carruth 
11818eadd92SChandler Carruth   for (auto &Entry : EntryNodes)
11918eadd92SChandler Carruth     if (Function *F = Entry.dyn_cast<Function *>())
12090821c2aSChandler Carruth       SCCEntryNodes.push_back(F);
12118eadd92SChandler Carruth     else
12290821c2aSChandler Carruth       SCCEntryNodes.push_back(&Entry.get<Node *>()->getFunction());
123bf71a34eSChandler Carruth }
124bf71a34eSChandler Carruth 
125bf71a34eSChandler Carruth LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
1262174f44fSChandler Carruth     : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
1272174f44fSChandler Carruth       EntryNodes(std::move(G.EntryNodes)),
1280b623baeSChandler Carruth       EntryIndexMap(std::move(G.EntryIndexMap)), SCCBPA(std::move(G.SCCBPA)),
12918eadd92SChandler Carruth       SCCMap(std::move(G.SCCMap)), LeafSCCs(std::move(G.LeafSCCs)),
13018eadd92SChandler Carruth       DFSStack(std::move(G.DFSStack)),
1312174f44fSChandler Carruth       SCCEntryNodes(std::move(G.SCCEntryNodes)),
1322174f44fSChandler Carruth       NextDFSNumber(G.NextDFSNumber) {
133d8d865e2SChandler Carruth   updateGraphPtrs();
134d8d865e2SChandler Carruth }
135d8d865e2SChandler Carruth 
136d8d865e2SChandler Carruth LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
137d8d865e2SChandler Carruth   BPA = std::move(G.BPA);
1382174f44fSChandler Carruth   NodeMap = std::move(G.NodeMap);
139d8d865e2SChandler Carruth   EntryNodes = std::move(G.EntryNodes);
1400b623baeSChandler Carruth   EntryIndexMap = std::move(G.EntryIndexMap);
141d8d865e2SChandler Carruth   SCCBPA = std::move(G.SCCBPA);
142d8d865e2SChandler Carruth   SCCMap = std::move(G.SCCMap);
143d8d865e2SChandler Carruth   LeafSCCs = std::move(G.LeafSCCs);
144d8d865e2SChandler Carruth   DFSStack = std::move(G.DFSStack);
145d8d865e2SChandler Carruth   SCCEntryNodes = std::move(G.SCCEntryNodes);
1462174f44fSChandler Carruth   NextDFSNumber = G.NextDFSNumber;
147d8d865e2SChandler Carruth   updateGraphPtrs();
148d8d865e2SChandler Carruth   return *this;
149d8d865e2SChandler Carruth }
150d8d865e2SChandler Carruth 
151aa839b22SChandler Carruth void LazyCallGraph::SCC::insert(Node &N) {
1528f92d6dbSChandler Carruth   N.DFSNumber = N.LowLink = -1;
1538f92d6dbSChandler Carruth   Nodes.push_back(&N);
154aa839b22SChandler Carruth   G->SCCMap[&N] = this;
1558f92d6dbSChandler Carruth }
1568f92d6dbSChandler Carruth 
157aa839b22SChandler Carruth void LazyCallGraph::SCC::removeInterSCCEdge(Node &CallerN, Node &CalleeN) {
158aa839b22SChandler Carruth   // First remove it from the node.
159aa839b22SChandler Carruth   CallerN.removeEdgeInternal(CalleeN.getFunction());
160aa839b22SChandler Carruth 
161aa839b22SChandler Carruth   assert(G->SCCMap.lookup(&CallerN) == this &&
162aa839b22SChandler Carruth          "The caller must be a member of this SCC.");
163aa839b22SChandler Carruth 
164aa839b22SChandler Carruth   SCC &CalleeC = *G->SCCMap.lookup(&CalleeN);
165aa839b22SChandler Carruth   assert(&CalleeC != this &&
166aa839b22SChandler Carruth          "This API only supports the rmoval of inter-SCC edges.");
167aa839b22SChandler Carruth 
168aa839b22SChandler Carruth   assert(std::find(G->LeafSCCs.begin(), G->LeafSCCs.end(), this) ==
169aa839b22SChandler Carruth              G->LeafSCCs.end() &&
1709302fbf0SChandler Carruth          "Cannot have a leaf SCC caller with a different SCC callee.");
1719302fbf0SChandler Carruth 
1729302fbf0SChandler Carruth   bool HasOtherCallToCalleeC = false;
1739302fbf0SChandler Carruth   bool HasOtherCallOutsideSCC = false;
1749302fbf0SChandler Carruth   for (Node *N : *this) {
175aa839b22SChandler Carruth     for (Node &OtherCalleeN : *N) {
176aa839b22SChandler Carruth       SCC &OtherCalleeC = *G->SCCMap.lookup(&OtherCalleeN);
177bd5d3082SChandler Carruth       if (&OtherCalleeC == &CalleeC) {
1789302fbf0SChandler Carruth         HasOtherCallToCalleeC = true;
1799302fbf0SChandler Carruth         break;
1809302fbf0SChandler Carruth       }
181bd5d3082SChandler Carruth       if (&OtherCalleeC != this)
1829302fbf0SChandler Carruth         HasOtherCallOutsideSCC = true;
1839302fbf0SChandler Carruth     }
1849302fbf0SChandler Carruth     if (HasOtherCallToCalleeC)
1859302fbf0SChandler Carruth       break;
1869302fbf0SChandler Carruth   }
1879302fbf0SChandler Carruth   // Because the SCCs form a DAG, deleting such an edge cannot change the set
1889302fbf0SChandler Carruth   // of SCCs in the graph. However, it may cut an edge of the SCC DAG, making
1899302fbf0SChandler Carruth   // the caller no longer a parent of the callee. Walk the other call edges
1909302fbf0SChandler Carruth   // in the caller to tell.
1919302fbf0SChandler Carruth   if (!HasOtherCallToCalleeC) {
192493e0a6aSChandler Carruth     bool Removed = CalleeC.ParentSCCs.erase(this);
1939302fbf0SChandler Carruth     (void)Removed;
1949302fbf0SChandler Carruth     assert(Removed &&
1959302fbf0SChandler Carruth            "Did not find the caller SCC in the callee SCC's parent list!");
1969302fbf0SChandler Carruth 
1979302fbf0SChandler Carruth     // It may orphan an SCC if it is the last edge reaching it, but that does
1989302fbf0SChandler Carruth     // not violate any invariants of the graph.
1999302fbf0SChandler Carruth     if (CalleeC.ParentSCCs.empty())
200aa839b22SChandler Carruth       DEBUG(dbgs() << "LCG: Update removing " << CallerN.getFunction().getName()
201aa839b22SChandler Carruth                    << " -> " << CalleeN.getFunction().getName()
202aa839b22SChandler Carruth                    << " edge orphaned the callee's SCC!\n");
2039302fbf0SChandler Carruth   }
2049302fbf0SChandler Carruth 
2059302fbf0SChandler Carruth   // It may make the Caller SCC a leaf SCC.
2069302fbf0SChandler Carruth   if (!HasOtherCallOutsideSCC)
207aa839b22SChandler Carruth     G->LeafSCCs.push_back(this);
2089302fbf0SChandler Carruth }
2099302fbf0SChandler Carruth 
210aca48d04SChandler Carruth void LazyCallGraph::SCC::internalDFS(
211aca48d04SChandler Carruth     SmallVectorImpl<std::pair<Node *, Node::iterator>> &DFSStack,
212aca48d04SChandler Carruth     SmallVectorImpl<Node *> &PendingSCCStack, Node *N,
213aca48d04SChandler Carruth     SmallVectorImpl<SCC *> &ResultSCCs) {
214aca48d04SChandler Carruth   Node::iterator I = N->begin();
215aca48d04SChandler Carruth   N->LowLink = N->DFSNumber = 1;
216aca48d04SChandler Carruth   int NextDFSNumber = 2;
217aca48d04SChandler Carruth   for (;;) {
218aca48d04SChandler Carruth     assert(N->DFSNumber != 0 && "We should always assign a DFS number "
219aca48d04SChandler Carruth                                 "before processing a node.");
220aca48d04SChandler Carruth 
221aca48d04SChandler Carruth     // We simulate recursion by popping out of the nested loop and continuing.
222aca48d04SChandler Carruth     Node::iterator E = N->end();
223aca48d04SChandler Carruth     while (I != E) {
224aca48d04SChandler Carruth       Node &ChildN = *I;
225aa839b22SChandler Carruth       if (SCC *ChildSCC = G->SCCMap.lookup(&ChildN)) {
226aca48d04SChandler Carruth         // Check if we have reached a node in the new (known connected) set of
227aca48d04SChandler Carruth         // this SCC. If so, the entire stack is necessarily in that set and we
228aca48d04SChandler Carruth         // can re-start.
229aca48d04SChandler Carruth         if (ChildSCC == this) {
230aa839b22SChandler Carruth           insert(*N);
231aca48d04SChandler Carruth           while (!PendingSCCStack.empty())
232aa839b22SChandler Carruth             insert(*PendingSCCStack.pop_back_val());
233aca48d04SChandler Carruth           while (!DFSStack.empty())
234aa839b22SChandler Carruth             insert(*DFSStack.pop_back_val().first);
235aca48d04SChandler Carruth           return;
236aca48d04SChandler Carruth         }
237aca48d04SChandler Carruth 
238aca48d04SChandler Carruth         // If this child isn't currently in this SCC, no need to process it.
239aca48d04SChandler Carruth         // However, we do need to remove this SCC from its SCC's parent set.
240aca48d04SChandler Carruth         ChildSCC->ParentSCCs.erase(this);
241aca48d04SChandler Carruth         ++I;
242aca48d04SChandler Carruth         continue;
243aca48d04SChandler Carruth       }
244aca48d04SChandler Carruth 
245aca48d04SChandler Carruth       if (ChildN.DFSNumber == 0) {
246aca48d04SChandler Carruth         // Mark that we should start at this child when next this node is the
247aca48d04SChandler Carruth         // top of the stack. We don't start at the next child to ensure this
248aca48d04SChandler Carruth         // child's lowlink is reflected.
249aca48d04SChandler Carruth         DFSStack.push_back(std::make_pair(N, I));
250aca48d04SChandler Carruth 
251aca48d04SChandler Carruth         // Continue, resetting to the child node.
252aca48d04SChandler Carruth         ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
253aca48d04SChandler Carruth         N = &ChildN;
254aca48d04SChandler Carruth         I = ChildN.begin();
255aca48d04SChandler Carruth         E = ChildN.end();
256aca48d04SChandler Carruth         continue;
257aca48d04SChandler Carruth       }
258aca48d04SChandler Carruth 
259aca48d04SChandler Carruth       // Track the lowest link of the childen, if any are still in the stack.
260aca48d04SChandler Carruth       // Any child not on the stack will have a LowLink of -1.
261aca48d04SChandler Carruth       assert(ChildN.LowLink != 0 &&
262aca48d04SChandler Carruth              "Low-link must not be zero with a non-zero DFS number.");
263aca48d04SChandler Carruth       if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
264aca48d04SChandler Carruth         N->LowLink = ChildN.LowLink;
265aca48d04SChandler Carruth       ++I;
266aca48d04SChandler Carruth     }
267aca48d04SChandler Carruth 
268aca48d04SChandler Carruth     if (N->LowLink == N->DFSNumber) {
269aa839b22SChandler Carruth       ResultSCCs.push_back(G->formSCC(N, PendingSCCStack));
270aca48d04SChandler Carruth       if (DFSStack.empty())
271aca48d04SChandler Carruth         return;
272aca48d04SChandler Carruth     } else {
273aca48d04SChandler Carruth       // At this point we know that N cannot ever be an SCC root. Its low-link
274aca48d04SChandler Carruth       // is not its dfs-number, and we've processed all of its children. It is
275aca48d04SChandler Carruth       // just sitting here waiting until some node further down the stack gets
276aca48d04SChandler Carruth       // low-link == dfs-number and pops it off as well. Move it to the pending
277aca48d04SChandler Carruth       // stack which is pulled into the next SCC to be formed.
278aca48d04SChandler Carruth       PendingSCCStack.push_back(N);
279aca48d04SChandler Carruth 
280aca48d04SChandler Carruth       assert(!DFSStack.empty() && "We shouldn't have an empty stack!");
281aca48d04SChandler Carruth     }
282aca48d04SChandler Carruth 
283aca48d04SChandler Carruth     N = DFSStack.back().first;
284aca48d04SChandler Carruth     I = DFSStack.back().second;
285aca48d04SChandler Carruth     DFSStack.pop_back();
286aca48d04SChandler Carruth   }
287aca48d04SChandler Carruth }
288aca48d04SChandler Carruth 
2899302fbf0SChandler Carruth SmallVector<LazyCallGraph::SCC *, 1>
290aa839b22SChandler Carruth LazyCallGraph::SCC::removeIntraSCCEdge(Node &CallerN,
291aa839b22SChandler Carruth                                        Node &CalleeN) {
292aa839b22SChandler Carruth   // First remove it from the node.
293aa839b22SChandler Carruth   CallerN.removeEdgeInternal(CalleeN.getFunction());
294aa839b22SChandler Carruth 
2953f5f5fe1SChandler Carruth   // We return a list of the resulting *new* SCCs in postorder.
2969302fbf0SChandler Carruth   SmallVector<SCC *, 1> ResultSCCs;
2979302fbf0SChandler Carruth 
298a7205b61SChandler Carruth   // Direct recursion doesn't impact the SCC graph at all.
299aa839b22SChandler Carruth   if (&CallerN == &CalleeN)
300a7205b61SChandler Carruth     return ResultSCCs;
301a7205b61SChandler Carruth 
302770060ddSChandler Carruth   // The worklist is every node in the original SCC.
303770060ddSChandler Carruth   SmallVector<Node *, 1> Worklist;
304770060ddSChandler Carruth   Worklist.swap(Nodes);
305770060ddSChandler Carruth   for (Node *N : Worklist) {
3062e6ef0e8SChandler Carruth     // The nodes formerly in this SCC are no longer in any SCC.
3079302fbf0SChandler Carruth     N->DFSNumber = 0;
3089302fbf0SChandler Carruth     N->LowLink = 0;
309aa839b22SChandler Carruth     G->SCCMap.erase(N);
3109302fbf0SChandler Carruth   }
311a7205b61SChandler Carruth   assert(Worklist.size() > 1 && "We have to have at least two nodes to have an "
312a7205b61SChandler Carruth                                 "edge between them that is within the SCC.");
3139302fbf0SChandler Carruth 
3149302fbf0SChandler Carruth   // The callee can already reach every node in this SCC (by definition). It is
3159302fbf0SChandler Carruth   // the only node we know will stay inside this SCC. Everything which
3169302fbf0SChandler Carruth   // transitively reaches Callee will also remain in the SCC. To model this we
3179302fbf0SChandler Carruth   // incrementally add any chain of nodes which reaches something in the new
3189302fbf0SChandler Carruth   // node set to the new node set. This short circuits one side of the Tarjan's
3199302fbf0SChandler Carruth   // walk.
320aa839b22SChandler Carruth   insert(CalleeN);
3219302fbf0SChandler Carruth 
322aca48d04SChandler Carruth   // We're going to do a full mini-Tarjan's walk using a local stack here.
323aca48d04SChandler Carruth   SmallVector<std::pair<Node *, Node::iterator>, 4> DFSStack;
324aca48d04SChandler Carruth   SmallVector<Node *, 4> PendingSCCStack;
325aca48d04SChandler Carruth   do {
326aca48d04SChandler Carruth     Node *N = Worklist.pop_back_val();
327aca48d04SChandler Carruth     if (N->DFSNumber == 0)
328aa839b22SChandler Carruth       internalDFS(DFSStack, PendingSCCStack, N, ResultSCCs);
3299302fbf0SChandler Carruth 
330aca48d04SChandler Carruth     assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
331aca48d04SChandler Carruth     assert(PendingSCCStack.empty() && "Didn't flush all pending SCC nodes!");
332aca48d04SChandler Carruth   } while (!Worklist.empty());
3339302fbf0SChandler Carruth 
3349302fbf0SChandler Carruth   // Now we need to reconnect the current SCC to the graph.
3359302fbf0SChandler Carruth   bool IsLeafSCC = true;
3369ba7762dSChandler Carruth   for (Node *N : Nodes) {
337bd5d3082SChandler Carruth     for (Node &ChildN : *N) {
338aa839b22SChandler Carruth       SCC &ChildSCC = *G->SCCMap.lookup(&ChildN);
3399ba7762dSChandler Carruth       if (&ChildSCC == this)
3409ba7762dSChandler Carruth         continue;
341bd5d3082SChandler Carruth       ChildSCC.ParentSCCs.insert(this);
3429302fbf0SChandler Carruth       IsLeafSCC = false;
3439302fbf0SChandler Carruth     }
3449302fbf0SChandler Carruth   }
3459302fbf0SChandler Carruth #ifndef NDEBUG
3463f5f5fe1SChandler Carruth   if (!ResultSCCs.empty())
3479302fbf0SChandler Carruth     assert(!IsLeafSCC && "This SCC cannot be a leaf as we have split out new "
3489302fbf0SChandler Carruth                          "SCCs by removing this edge.");
349aa839b22SChandler Carruth   if (!std::any_of(G->LeafSCCs.begin(), G->LeafSCCs.end(),
3509302fbf0SChandler Carruth                    [&](SCC *C) { return C == this; }))
3519302fbf0SChandler Carruth     assert(!IsLeafSCC && "This SCC cannot be a leaf as it already had child "
3529302fbf0SChandler Carruth                          "SCCs before we removed this edge.");
3539302fbf0SChandler Carruth #endif
3549302fbf0SChandler Carruth   // If this SCC stopped being a leaf through this edge removal, remove it from
3559302fbf0SChandler Carruth   // the leaf SCC list.
3563f5f5fe1SChandler Carruth   if (!IsLeafSCC && !ResultSCCs.empty())
357aa839b22SChandler Carruth     G->LeafSCCs.erase(std::remove(G->LeafSCCs.begin(), G->LeafSCCs.end(), this),
358aa839b22SChandler Carruth                      G->LeafSCCs.end());
3599302fbf0SChandler Carruth 
3609302fbf0SChandler Carruth   // Return the new list of SCCs.
3619302fbf0SChandler Carruth   return ResultSCCs;
3629302fbf0SChandler Carruth }
3639302fbf0SChandler Carruth 
364*c00a7ff4SChandler Carruth void LazyCallGraph::insertEdge(Node &CallerN, Function &Callee) {
365*c00a7ff4SChandler Carruth   assert(SCCMap.empty() && DFSStack.empty() &&
366*c00a7ff4SChandler Carruth          "This method cannot be called after SCCs have been formed!");
367*c00a7ff4SChandler Carruth 
368*c00a7ff4SChandler Carruth   return CallerN.insertEdgeInternal(Callee);
369*c00a7ff4SChandler Carruth }
370*c00a7ff4SChandler Carruth 
3719302fbf0SChandler Carruth void LazyCallGraph::removeEdge(Node &CallerN, Function &Callee) {
372aa839b22SChandler Carruth   assert(SCCMap.empty() && DFSStack.empty() &&
373aa839b22SChandler Carruth          "This method cannot be called after SCCs have been formed!");
3749302fbf0SChandler Carruth 
375aa839b22SChandler Carruth   return CallerN.removeEdgeInternal(Callee);
3769302fbf0SChandler Carruth }
3779302fbf0SChandler Carruth 
3782a898e0dSChandler Carruth LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
3792a898e0dSChandler Carruth   return *new (MappedN = BPA.Allocate()) Node(*this, F);
380d8d865e2SChandler Carruth }
381d8d865e2SChandler Carruth 
382d8d865e2SChandler Carruth void LazyCallGraph::updateGraphPtrs() {
383b60cb315SChandler Carruth   // Process all nodes updating the graph pointers.
384aa839b22SChandler Carruth   {
385b60cb315SChandler Carruth     SmallVector<Node *, 16> Worklist;
386b9e2f8c4SChandler Carruth     for (auto &Entry : EntryNodes)
387b9e2f8c4SChandler Carruth       if (Node *EntryN = Entry.dyn_cast<Node *>())
388b60cb315SChandler Carruth         Worklist.push_back(EntryN);
389b60cb315SChandler Carruth 
390b60cb315SChandler Carruth     while (!Worklist.empty()) {
391b60cb315SChandler Carruth       Node *N = Worklist.pop_back_val();
392b60cb315SChandler Carruth       N->G = this;
393b60cb315SChandler Carruth       for (auto &Callee : N->Callees)
394b60cb315SChandler Carruth         if (Node *CalleeN = Callee.dyn_cast<Node *>())
395b60cb315SChandler Carruth           Worklist.push_back(CalleeN);
396b60cb315SChandler Carruth     }
397bf71a34eSChandler Carruth   }
398bf71a34eSChandler Carruth 
399aa839b22SChandler Carruth   // Process all SCCs updating the graph pointers.
400aa839b22SChandler Carruth   {
401aa839b22SChandler Carruth     SmallVector<SCC *, 16> Worklist(LeafSCCs.begin(), LeafSCCs.end());
402aa839b22SChandler Carruth 
403aa839b22SChandler Carruth     while (!Worklist.empty()) {
404aa839b22SChandler Carruth       SCC *C = Worklist.pop_back_val();
405aa839b22SChandler Carruth       C->G = this;
406aa839b22SChandler Carruth       Worklist.insert(Worklist.end(), C->ParentSCCs.begin(),
407aa839b22SChandler Carruth                       C->ParentSCCs.end());
408aa839b22SChandler Carruth     }
409aa839b22SChandler Carruth   }
410aa839b22SChandler Carruth }
411aa839b22SChandler Carruth 
41224553934SChandler Carruth LazyCallGraph::SCC *LazyCallGraph::formSCC(Node *RootN,
41324553934SChandler Carruth                                            SmallVectorImpl<Node *> &NodeStack) {
4143f9869a8SChandler Carruth   // The tail of the stack is the new SCC. Allocate the SCC and pop the stack
4153f9869a8SChandler Carruth   // into it.
416aa839b22SChandler Carruth   SCC *NewSCC = new (SCCBPA.Allocate()) SCC(*this);
4173f9869a8SChandler Carruth 
41824553934SChandler Carruth   while (!NodeStack.empty() && NodeStack.back()->DFSNumber > RootN->DFSNumber) {
4198f92d6dbSChandler Carruth     assert(NodeStack.back()->LowLink >= RootN->LowLink &&
420cace6623SChandler Carruth            "We cannot have a low link in an SCC lower than its root on the "
421cace6623SChandler Carruth            "stack!");
422aa839b22SChandler Carruth     NewSCC->insert(*NodeStack.pop_back_val());
423cace6623SChandler Carruth   }
424aa839b22SChandler Carruth   NewSCC->insert(*RootN);
4253f9869a8SChandler Carruth 
4263f9869a8SChandler Carruth   // A final pass over all edges in the SCC (this remains linear as we only
4273f9869a8SChandler Carruth   // do this once when we build the SCC) to connect it to the parent sets of
4283f9869a8SChandler Carruth   // its children.
4293f9869a8SChandler Carruth   bool IsLeafSCC = true;
4303f9869a8SChandler Carruth   for (Node *SCCN : NewSCC->Nodes)
431bd5d3082SChandler Carruth     for (Node &SCCChildN : *SCCN) {
432d52f8e0eSChandler Carruth       if (SCCMap.lookup(&SCCChildN) == NewSCC)
4333f9869a8SChandler Carruth         continue;
434bd5d3082SChandler Carruth       SCC &ChildSCC = *SCCMap.lookup(&SCCChildN);
435bd5d3082SChandler Carruth       ChildSCC.ParentSCCs.insert(NewSCC);
4363f9869a8SChandler Carruth       IsLeafSCC = false;
4373f9869a8SChandler Carruth     }
4383f9869a8SChandler Carruth 
4393f9869a8SChandler Carruth   // For the SCCs where we fine no child SCCs, add them to the leaf list.
4403f9869a8SChandler Carruth   if (IsLeafSCC)
4413f9869a8SChandler Carruth     LeafSCCs.push_back(NewSCC);
4423f9869a8SChandler Carruth 
4433f9869a8SChandler Carruth   return NewSCC;
4443f9869a8SChandler Carruth }
4453f9869a8SChandler Carruth 
44618eadd92SChandler Carruth LazyCallGraph::SCC *LazyCallGraph::getNextSCCInPostOrder() {
4475e2d70b9SChandler Carruth   Node *N;
4485e2d70b9SChandler Carruth   Node::iterator I;
4495e2d70b9SChandler Carruth   if (!DFSStack.empty()) {
4505e2d70b9SChandler Carruth     N = DFSStack.back().first;
4515e2d70b9SChandler Carruth     I = DFSStack.back().second;
4525e2d70b9SChandler Carruth     DFSStack.pop_back();
4535e2d70b9SChandler Carruth   } else {
45418eadd92SChandler Carruth     // If we've handled all candidate entry nodes to the SCC forest, we're done.
45590821c2aSChandler Carruth     do {
45618eadd92SChandler Carruth       if (SCCEntryNodes.empty())
45718eadd92SChandler Carruth         return nullptr;
45818eadd92SChandler Carruth 
4595e2d70b9SChandler Carruth       N = &get(*SCCEntryNodes.pop_back_val());
46090821c2aSChandler Carruth     } while (N->DFSNumber != 0);
4615e2d70b9SChandler Carruth     I = N->begin();
4625e2d70b9SChandler Carruth     N->LowLink = N->DFSNumber = 1;
46309751bf1SChandler Carruth     NextDFSNumber = 2;
46418eadd92SChandler Carruth   }
46518eadd92SChandler Carruth 
46691dcf0f9SChandler Carruth   for (;;) {
46724553934SChandler Carruth     assert(N->DFSNumber != 0 && "We should always assign a DFS number "
46809751bf1SChandler Carruth                                 "before placing a node onto the stack.");
46918eadd92SChandler Carruth 
4705e2d70b9SChandler Carruth     Node::iterator E = N->end();
4715e2d70b9SChandler Carruth     while (I != E) {
472bd5d3082SChandler Carruth       Node &ChildN = *I;
473bd5d3082SChandler Carruth       if (ChildN.DFSNumber == 0) {
47418eadd92SChandler Carruth         // Mark that we should start at this child when next this node is the
47518eadd92SChandler Carruth         // top of the stack. We don't start at the next child to ensure this
47618eadd92SChandler Carruth         // child's lowlink is reflected.
4775e2d70b9SChandler Carruth         DFSStack.push_back(std::make_pair(N, N->begin()));
47818eadd92SChandler Carruth 
47918eadd92SChandler Carruth         // Recurse onto this node via a tail call.
48009751bf1SChandler Carruth         assert(!SCCMap.count(&ChildN) &&
48109751bf1SChandler Carruth                "Found a node with 0 DFS number but already in an SCC!");
48209751bf1SChandler Carruth         ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
4835e2d70b9SChandler Carruth         N = &ChildN;
4845e2d70b9SChandler Carruth         I = ChildN.begin();
4855e2d70b9SChandler Carruth         E = ChildN.end();
4865e2d70b9SChandler Carruth         continue;
48718eadd92SChandler Carruth       }
48818eadd92SChandler Carruth 
48918eadd92SChandler Carruth       // Track the lowest link of the childen, if any are still in the stack.
490bd5d3082SChandler Carruth       assert(ChildN.LowLink != 0 &&
491b4a04da0SChandler Carruth              "Low-link must not be zero with a non-zero DFS number.");
492bd5d3082SChandler Carruth       if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
493bd5d3082SChandler Carruth         N->LowLink = ChildN.LowLink;
4945e2d70b9SChandler Carruth       ++I;
49518eadd92SChandler Carruth     }
49618eadd92SChandler Carruth 
497cace6623SChandler Carruth     if (N->LowLink == N->DFSNumber)
4983f9869a8SChandler Carruth       // Form the new SCC out of the top of the DFS stack.
49924553934SChandler Carruth       return formSCC(N, PendingSCCStack);
500cace6623SChandler Carruth 
50124553934SChandler Carruth     // At this point we know that N cannot ever be an SCC root. Its low-link
50224553934SChandler Carruth     // is not its dfs-number, and we've processed all of its children. It is
50324553934SChandler Carruth     // just sitting here waiting until some node further down the stack gets
50424553934SChandler Carruth     // low-link == dfs-number and pops it off as well. Move it to the pending
50524553934SChandler Carruth     // stack which is pulled into the next SCC to be formed.
50624553934SChandler Carruth     PendingSCCStack.push_back(N);
5075e2d70b9SChandler Carruth 
5085e2d70b9SChandler Carruth     assert(!DFSStack.empty() && "We never found a viable root!");
5095e2d70b9SChandler Carruth     N = DFSStack.back().first;
5105e2d70b9SChandler Carruth     I = DFSStack.back().second;
5115e2d70b9SChandler Carruth     DFSStack.pop_back();
51291dcf0f9SChandler Carruth   }
51318eadd92SChandler Carruth }
51418eadd92SChandler Carruth 
515bf71a34eSChandler Carruth char LazyCallGraphAnalysis::PassID;
516bf71a34eSChandler Carruth 
517bf71a34eSChandler Carruth LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
518bf71a34eSChandler Carruth 
519bf71a34eSChandler Carruth static void printNodes(raw_ostream &OS, LazyCallGraph::Node &N,
520bf71a34eSChandler Carruth                        SmallPtrSetImpl<LazyCallGraph::Node *> &Printed) {
521bf71a34eSChandler Carruth   // Recurse depth first through the nodes.
522bd5d3082SChandler Carruth   for (LazyCallGraph::Node &ChildN : N)
523bd5d3082SChandler Carruth     if (Printed.insert(&ChildN))
524bd5d3082SChandler Carruth       printNodes(OS, ChildN, Printed);
525bf71a34eSChandler Carruth 
526bf71a34eSChandler Carruth   OS << "  Call edges in function: " << N.getFunction().getName() << "\n";
527bf71a34eSChandler Carruth   for (LazyCallGraph::iterator I = N.begin(), E = N.end(); I != E; ++I)
528bf71a34eSChandler Carruth     OS << "    -> " << I->getFunction().getName() << "\n";
529bf71a34eSChandler Carruth 
530bf71a34eSChandler Carruth   OS << "\n";
531bf71a34eSChandler Carruth }
532bf71a34eSChandler Carruth 
53318eadd92SChandler Carruth static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &SCC) {
53418eadd92SChandler Carruth   ptrdiff_t SCCSize = std::distance(SCC.begin(), SCC.end());
53518eadd92SChandler Carruth   OS << "  SCC with " << SCCSize << " functions:\n";
53618eadd92SChandler Carruth 
53718eadd92SChandler Carruth   for (LazyCallGraph::Node *N : SCC)
53818eadd92SChandler Carruth     OS << "    " << N->getFunction().getName() << "\n";
53918eadd92SChandler Carruth 
54018eadd92SChandler Carruth   OS << "\n";
54118eadd92SChandler Carruth }
54218eadd92SChandler Carruth 
543e9b50617SChandler Carruth PreservedAnalyses LazyCallGraphPrinterPass::run(Module *M,
544e9b50617SChandler Carruth                                                 ModuleAnalysisManager *AM) {
545bf71a34eSChandler Carruth   LazyCallGraph &G = AM->getResult<LazyCallGraphAnalysis>(M);
546bf71a34eSChandler Carruth 
547e9b50617SChandler Carruth   OS << "Printing the call graph for module: " << M->getModuleIdentifier()
548e9b50617SChandler Carruth      << "\n\n";
549bf71a34eSChandler Carruth 
550bf71a34eSChandler Carruth   SmallPtrSet<LazyCallGraph::Node *, 16> Printed;
551bd5d3082SChandler Carruth   for (LazyCallGraph::Node &N : G)
552bd5d3082SChandler Carruth     if (Printed.insert(&N))
553bd5d3082SChandler Carruth       printNodes(OS, N, Printed);
554bf71a34eSChandler Carruth 
5556a4fee87SChandler Carruth   for (LazyCallGraph::SCC &SCC : G.postorder_sccs())
5566a4fee87SChandler Carruth     printSCC(OS, SCC);
55718eadd92SChandler Carruth 
558bf71a34eSChandler Carruth   return PreservedAnalyses::all();
55918eadd92SChandler Carruth 
560bf71a34eSChandler Carruth }
561