blob: 229e2c93adea83b32cad4b56a1270a559cb0f6e7 [file] [log] [blame]
Chandler Carruthbf71a342014-02-06 04:37:03 +00001//===- LazyCallGraph.cpp - Analysis of a Module's 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#include "llvm/Analysis/LazyCallGraph.h"
Chandler Carruth18eadd922014-04-18 10:50:32 +000011#include "llvm/ADT/STLExtras.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000012#include "llvm/IR/CallSite.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000013#include "llvm/IR/InstVisitor.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000014#include "llvm/IR/Instructions.h"
15#include "llvm/IR/PassManager.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000016#include "llvm/Support/raw_ostream.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000017
18using namespace llvm;
19
20static void findCallees(
21 SmallVectorImpl<Constant *> &Worklist, SmallPtrSetImpl<Constant *> &Visited,
Chandler Carruthe9b50612014-03-10 02:14:14 +000022 SmallVectorImpl<PointerUnion<Function *, LazyCallGraph::Node *>> &Callees,
Chandler Carruthbf71a342014-02-06 04:37:03 +000023 SmallPtrSetImpl<Function *> &CalleeSet) {
24 while (!Worklist.empty()) {
25 Constant *C = Worklist.pop_back_val();
26
27 if (Function *F = dyn_cast<Function>(C)) {
28 // Note that we consider *any* function with a definition to be a viable
29 // edge. Even if the function's definition is subject to replacement by
30 // some other module (say, a weak definition) there may still be
31 // optimizations which essentially speculate based on the definition and
32 // a way to check that the specific definition is in fact the one being
33 // used. For example, this could be done by moving the weak definition to
34 // a strong (internal) definition and making the weak definition be an
35 // alias. Then a test of the address of the weak function against the new
36 // strong definition's address would be an effective way to determine the
37 // safety of optimizing a direct call edge.
38 if (!F->isDeclaration() && CalleeSet.insert(F))
Chandler Carruthe9b50612014-03-10 02:14:14 +000039 Callees.push_back(F);
Chandler Carruthbf71a342014-02-06 04:37:03 +000040 continue;
41 }
42
Chandler Carruth1583e992014-03-03 10:42:58 +000043 for (Value *Op : C->operand_values())
44 if (Visited.insert(cast<Constant>(Op)))
45 Worklist.push_back(cast<Constant>(Op));
Chandler Carruthbf71a342014-02-06 04:37:03 +000046 }
47}
48
Chandler Carruth18eadd922014-04-18 10:50:32 +000049LazyCallGraph::Node::Node(LazyCallGraph &G, Function &F)
50 : G(&G), F(F), DFSNumber(0), LowLink(0) {
Chandler Carruthbf71a342014-02-06 04:37:03 +000051 SmallVector<Constant *, 16> Worklist;
52 SmallPtrSet<Constant *, 16> Visited;
53 // Find all the potential callees in this function. First walk the
54 // instructions and add every operand which is a constant to the worklist.
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000055 for (BasicBlock &BB : F)
56 for (Instruction &I : BB)
57 for (Value *Op : I.operand_values())
Chandler Carruth1583e992014-03-03 10:42:58 +000058 if (Constant *C = dyn_cast<Constant>(Op))
Chandler Carruthbf71a342014-02-06 04:37:03 +000059 if (Visited.insert(C))
60 Worklist.push_back(C);
61
62 // We've collected all the constant (and thus potentially function or
63 // function containing) operands to all of the instructions in the function.
64 // Process them (recursively) collecting every function found.
65 findCallees(Worklist, Visited, Callees, CalleeSet);
66}
67
Chandler Carruth81f497d2014-04-17 07:22:19 +000068LazyCallGraph::LazyCallGraph(Module &M) {
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000069 for (Function &F : M)
70 if (!F.isDeclaration() && !F.hasLocalLinkage())
71 if (EntryNodeSet.insert(&F))
72 EntryNodes.push_back(&F);
Chandler Carruthbf71a342014-02-06 04:37:03 +000073
74 // Now add entry nodes for functions reachable via initializers to globals.
75 SmallVector<Constant *, 16> Worklist;
76 SmallPtrSet<Constant *, 16> Visited;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000077 for (GlobalVariable &GV : M.globals())
78 if (GV.hasInitializer())
79 if (Visited.insert(GV.getInitializer()))
80 Worklist.push_back(GV.getInitializer());
Chandler Carruthbf71a342014-02-06 04:37:03 +000081
82 findCallees(Worklist, Visited, EntryNodes, EntryNodeSet);
Chandler Carruth18eadd922014-04-18 10:50:32 +000083
84 for (auto &Entry : EntryNodes)
85 if (Function *F = Entry.dyn_cast<Function *>())
86 SCCEntryNodes.insert(F);
87 else
88 SCCEntryNodes.insert(&Entry.get<Node *>()->getFunction());
Chandler Carruthbf71a342014-02-06 04:37:03 +000089}
90
Chandler Carruthbf71a342014-02-06 04:37:03 +000091LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
Chandler Carruthb60cb312014-04-17 07:25:59 +000092 : BPA(std::move(G.BPA)), EntryNodes(std::move(G.EntryNodes)),
Chandler Carruth18eadd922014-04-18 10:50:32 +000093 EntryNodeSet(std::move(G.EntryNodeSet)), SCCBPA(std::move(G.SCCBPA)),
94 SCCMap(std::move(G.SCCMap)), LeafSCCs(std::move(G.LeafSCCs)),
95 DFSStack(std::move(G.DFSStack)),
96 SCCEntryNodes(std::move(G.SCCEntryNodes)) {
Chandler Carruthd8d865e2014-04-18 11:02:33 +000097 updateGraphPtrs();
98}
99
100LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
101 BPA = std::move(G.BPA);
102 EntryNodes = std::move(G.EntryNodes);
103 EntryNodeSet = std::move(G.EntryNodeSet);
104 SCCBPA = std::move(G.SCCBPA);
105 SCCMap = std::move(G.SCCMap);
106 LeafSCCs = std::move(G.LeafSCCs);
107 DFSStack = std::move(G.DFSStack);
108 SCCEntryNodes = std::move(G.SCCEntryNodes);
109 updateGraphPtrs();
110 return *this;
111}
112
113LazyCallGraph::Node *LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
114 return new (MappedN = BPA.Allocate()) Node(*this, F);
115}
116
117void LazyCallGraph::updateGraphPtrs() {
Chandler Carruthb60cb312014-04-17 07:25:59 +0000118 // Process all nodes updating the graph pointers.
119 SmallVector<Node *, 16> Worklist;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000120 for (auto &Entry : EntryNodes)
121 if (Node *EntryN = Entry.dyn_cast<Node *>())
Chandler Carruthb60cb312014-04-17 07:25:59 +0000122 Worklist.push_back(EntryN);
123
124 while (!Worklist.empty()) {
125 Node *N = Worklist.pop_back_val();
126 N->G = this;
127 for (auto &Callee : N->Callees)
128 if (Node *CalleeN = Callee.dyn_cast<Node *>())
129 Worklist.push_back(CalleeN);
130 }
Chandler Carruthbf71a342014-02-06 04:37:03 +0000131}
Chandler Carruthbf71a342014-02-06 04:37:03 +0000132
Chandler Carruth18eadd922014-04-18 10:50:32 +0000133LazyCallGraph::SCC *LazyCallGraph::getNextSCCInPostOrder() {
134 // When the stack is empty, there are no more SCCs to walk in this graph.
135 if (DFSStack.empty()) {
136 // If we've handled all candidate entry nodes to the SCC forest, we're done.
137 if (SCCEntryNodes.empty())
138 return nullptr;
139
140 Node *N = get(*SCCEntryNodes.pop_back_val());
141 DFSStack.push_back(std::make_pair(N, N->begin()));
142 }
143
144 Node *N = DFSStack.back().first;
145 if (N->DFSNumber == 0) {
146 // This node hasn't been visited before, assign it a DFS number and remove
147 // it from the entry set.
148 N->LowLink = N->DFSNumber = NextDFSNumber++;
149 SCCEntryNodes.remove(&N->getFunction());
150 }
151
152 for (auto I = DFSStack.back().second, E = N->end(); I != E; ++I) {
153 Node *ChildN = *I;
154 if (ChildN->DFSNumber == 0) {
155 // Mark that we should start at this child when next this node is the
156 // top of the stack. We don't start at the next child to ensure this
157 // child's lowlink is reflected.
158 // FIXME: I don't actually think this is required, and we could start
159 // at the next child.
160 DFSStack.back().second = I;
161
162 // Recurse onto this node via a tail call.
163 DFSStack.push_back(std::make_pair(ChildN, ChildN->begin()));
164 return LazyCallGraph::getNextSCCInPostOrder();
165 }
166
167 // Track the lowest link of the childen, if any are still in the stack.
168 if (ChildN->LowLink < N->LowLink && !SCCMap.count(&ChildN->getFunction()))
169 N->LowLink = ChildN->LowLink;
170 }
171
172 // The tail of the stack is the new SCC. Allocate the SCC and pop the stack
173 // into it.
174 SCC *NewSCC = new (SCCBPA.Allocate()) SCC();
175
176 // Because we don't follow the strict Tarjan recursive formulation, walk
177 // from the top of the stack down, propagating the lowest link and stopping
178 // when the DFS number is the lowest link.
179 int LowestLink = N->LowLink;
180 do {
181 Node *SCCN = DFSStack.pop_back_val().first;
182 SCCMap.insert(std::make_pair(&SCCN->getFunction(), NewSCC));
183 NewSCC->Nodes.push_back(SCCN);
184 LowestLink = std::min(LowestLink, SCCN->LowLink);
185 bool Inserted =
186 NewSCC->NodeSet.insert(&SCCN->getFunction());
187 (void)Inserted;
188 assert(Inserted && "Cannot have duplicates in the DFSStack!");
189 } while (!DFSStack.empty() && LowestLink <= DFSStack.back().first->DFSNumber);
190 assert(LowestLink == NewSCC->Nodes.back()->DFSNumber &&
191 "Cannot stop with a DFS number greater than the lowest link!");
192
193 // A final pass over all edges in the SCC (this remains linear as we only
194 // do this once when we build the SCC) to connect it to the parent sets of
195 // its children.
196 bool IsLeafSCC = true;
197 for (Node *SCCN : NewSCC->Nodes)
198 for (Node *SCCChildN : *SCCN) {
199 if (NewSCC->NodeSet.count(&SCCChildN->getFunction()))
200 continue;
201 SCC *ChildSCC = SCCMap.lookup(&SCCChildN->getFunction());
202 assert(ChildSCC &&
203 "Must have all child SCCs processed when building a new SCC!");
204 ChildSCC->ParentSCCs.insert(NewSCC);
205 IsLeafSCC = false;
206 }
207
208 // For the SCCs where we fine no child SCCs, add them to the leaf list.
209 if (IsLeafSCC)
210 LeafSCCs.push_back(NewSCC);
211
212 return NewSCC;
213}
214
Chandler Carruthbf71a342014-02-06 04:37:03 +0000215char LazyCallGraphAnalysis::PassID;
216
217LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
218
219static void printNodes(raw_ostream &OS, LazyCallGraph::Node &N,
220 SmallPtrSetImpl<LazyCallGraph::Node *> &Printed) {
221 // Recurse depth first through the nodes.
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000222 for (LazyCallGraph::Node *ChildN : N)
223 if (Printed.insert(ChildN))
224 printNodes(OS, *ChildN, Printed);
Chandler Carruthbf71a342014-02-06 04:37:03 +0000225
226 OS << " Call edges in function: " << N.getFunction().getName() << "\n";
227 for (LazyCallGraph::iterator I = N.begin(), E = N.end(); I != E; ++I)
228 OS << " -> " << I->getFunction().getName() << "\n";
229
230 OS << "\n";
231}
232
Chandler Carruth18eadd922014-04-18 10:50:32 +0000233static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &SCC) {
234 ptrdiff_t SCCSize = std::distance(SCC.begin(), SCC.end());
235 OS << " SCC with " << SCCSize << " functions:\n";
236
237 for (LazyCallGraph::Node *N : SCC)
238 OS << " " << N->getFunction().getName() << "\n";
239
240 OS << "\n";
241}
242
Chandler Carruthe9b50612014-03-10 02:14:14 +0000243PreservedAnalyses LazyCallGraphPrinterPass::run(Module *M,
244 ModuleAnalysisManager *AM) {
Chandler Carruthbf71a342014-02-06 04:37:03 +0000245 LazyCallGraph &G = AM->getResult<LazyCallGraphAnalysis>(M);
246
Chandler Carruthe9b50612014-03-10 02:14:14 +0000247 OS << "Printing the call graph for module: " << M->getModuleIdentifier()
248 << "\n\n";
Chandler Carruthbf71a342014-02-06 04:37:03 +0000249
250 SmallPtrSet<LazyCallGraph::Node *, 16> Printed;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000251 for (LazyCallGraph::Node *N : G)
252 if (Printed.insert(N))
253 printNodes(OS, *N, Printed);
Chandler Carruthbf71a342014-02-06 04:37:03 +0000254
Chandler Carruth18eadd922014-04-18 10:50:32 +0000255 for (LazyCallGraph::SCC *SCC : G.postorder_sccs())
256 printSCC(OS, *SCC);
257
Chandler Carruthbf71a342014-02-06 04:37:03 +0000258 return PreservedAnalyses::all();
Chandler Carruth18eadd922014-04-18 10:50:32 +0000259
Chandler Carruthbf71a342014-02-06 04:37:03 +0000260}