blob: eaa0d0181afa7b9a82bf1627ac17ab95466e8466 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- CallGraph.cpp - Build a Module's call graph ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the CallGraph class and provides the BasicCallGraph
11// default implementation.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/CallGraph.h"
16#include "llvm/Module.h"
17#include "llvm/Instructions.h"
18#include "llvm/Support/CallSite.h"
19#include "llvm/Support/Compiler.h"
20#include "llvm/Support/Streams.h"
21#include <ostream>
22using namespace llvm;
23
24/// isOnlyADirectCall - Return true if this callsite is *just* a direct call to
25/// the specified function. Specifically return false if the callsite also
26/// takes the address of the function.
27static bool isOnlyADirectCall(Function *F, CallSite CS) {
28 if (!CS.getInstruction()) return false;
29 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
30 if (*I == F) return false;
31 return true;
32}
33
34namespace {
35
36//===----------------------------------------------------------------------===//
37// BasicCallGraph class definition
38//
39class VISIBILITY_HIDDEN BasicCallGraph : public CallGraph, public ModulePass {
40 // Root is root of the call graph, or the external node if a 'main' function
41 // couldn't be found.
42 //
43 CallGraphNode *Root;
44
45 // ExternalCallingNode - This node has edges to all external functions and
46 // those internal functions that have their address taken.
47 CallGraphNode *ExternalCallingNode;
48
49 // CallsExternalNode - This node has edges to it from all functions making
50 // indirect calls or calling an external function.
51 CallGraphNode *CallsExternalNode;
52
53public:
54 static char ID; // Class identification, replacement for typeinfo
55 BasicCallGraph() : ModulePass((intptr_t)&ID), Root(0),
56 ExternalCallingNode(0), CallsExternalNode(0) {}
57
58 // runOnModule - Compute the call graph for the specified module.
59 virtual bool runOnModule(Module &M) {
60 CallGraph::initialize(M);
61
62 ExternalCallingNode = getOrInsertFunction(0);
63 CallsExternalNode = new CallGraphNode(0);
64 Root = 0;
65
66 // Add every function to the call graph...
67 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
68 addToCallGraph(I);
69
70 // If we didn't find a main function, use the external call graph node
71 if (Root == 0) Root = ExternalCallingNode;
72
73 return false;
74 }
75
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.setPreservesAll();
78 }
79
80 void print(std::ostream *o, const Module *M) const {
81 if (o) print(*o, M);
82 }
83
84 virtual void print(std::ostream &o, const Module *M) const {
85 o << "CallGraph Root is: ";
86 if (Function *F = getRoot()->getFunction())
87 o << F->getName() << "\n";
88 else
89 o << "<<null function: 0x" << getRoot() << ">>\n";
90
91 CallGraph::print(o, M);
92 }
93
94 virtual void releaseMemory() {
95 destroy();
96 }
97
98 /// dump - Print out this call graph.
99 ///
100 inline void dump() const {
101 print(cerr, Mod);
102 }
103
104 CallGraphNode* getExternalCallingNode() const { return ExternalCallingNode; }
105 CallGraphNode* getCallsExternalNode() const { return CallsExternalNode; }
106
107 // getRoot - Return the root of the call graph, which is either main, or if
108 // main cannot be found, the external node.
109 //
110 CallGraphNode *getRoot() { return Root; }
111 const CallGraphNode *getRoot() const { return Root; }
112
113private:
114 //===---------------------------------------------------------------------
115 // Implementation of CallGraph construction
116 //
117
118 // addToCallGraph - Add a function to the call graph, and link the node to all
119 // of the functions that it calls.
120 //
121 void addToCallGraph(Function *F) {
122 CallGraphNode *Node = getOrInsertFunction(F);
123
124 // If this function has external linkage, anything could call it.
125 if (!F->hasInternalLinkage()) {
126 ExternalCallingNode->addCalledFunction(CallSite(), Node);
127
128 // Found the entry point?
129 if (F->getName() == "main") {
130 if (Root) // Found multiple external mains? Don't pick one.
131 Root = ExternalCallingNode;
132 else
133 Root = Node; // Found a main, keep track of it!
134 }
135 }
136
137 // If this function is not defined in this translation unit, it could call
138 // anything.
Duncan Sands79d28872007-12-03 20:06:50 +0000139 if (F->isDeclaration() && !F->isIntrinsic())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140 Node->addCalledFunction(CallSite(), CallsExternalNode);
141
142 // Loop over all of the users of the function... looking for callers...
143 //
144 bool isUsedExternally = false;
145 for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I){
146 if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
147 CallSite CS = CallSite::get(Inst);
148 if (isOnlyADirectCall(F, CS))
149 getOrInsertFunction(Inst->getParent()->getParent())
150 ->addCalledFunction(CS, Node);
151 else
152 isUsedExternally = true;
153 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(*I)) {
154 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end();
155 I != E; ++I)
156 if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
157 CallSite CS = CallSite::get(Inst);
158 if (isOnlyADirectCall(F, CS))
159 getOrInsertFunction(Inst->getParent()->getParent())
160 ->addCalledFunction(CS, Node);
161 else
162 isUsedExternally = true;
163 } else {
164 isUsedExternally = true;
165 }
166 } else { // Can't classify the user!
167 isUsedExternally = true;
168 }
169 }
170 if (isUsedExternally)
171 ExternalCallingNode->addCalledFunction(CallSite(), Node);
172
173 // Look for an indirect function call.
174 for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
175 for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
176 II != IE; ++II) {
177 CallSite CS = CallSite::get(II);
178 if (CS.getInstruction() && !CS.getCalledFunction())
179 Node->addCalledFunction(CS, CallsExternalNode);
180 }
181 }
182
183 //
184 // destroy - Release memory for the call graph
185 virtual void destroy() {
186 /// CallsExternalNode is not in the function map, delete it explicitly.
187 delete CallsExternalNode;
188 CallsExternalNode = 0;
189 CallGraph::destroy();
190 }
191};
192
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193} //End anonymous namespace
194
Dan Gohman089efff2008-05-13 00:00:25 +0000195static RegisterAnalysisGroup<CallGraph> X("Call Graph");
196static RegisterPass<BasicCallGraph>
197Y("basiccg", "Basic CallGraph Construction", false, true);
198static RegisterAnalysisGroup<CallGraph, true> Z(Y);
199
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200char CallGraph::ID = 0;
201char BasicCallGraph::ID = 0;
202
203void CallGraph::initialize(Module &M) {
204 Mod = &M;
205}
206
207void CallGraph::destroy() {
208 if (!FunctionMap.empty()) {
209 for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
210 I != E; ++I)
211 delete I->second;
212 FunctionMap.clear();
213 }
214}
215
216void CallGraph::print(std::ostream &OS, const Module *M) const {
217 for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
218 I->second->print(OS);
219}
220
221void CallGraph::dump() const {
222 print(cerr, 0);
223}
224
225//===----------------------------------------------------------------------===//
226// Implementations of public modification methods
227//
228
229// removeFunctionFromModule - Unlink the function from this module, returning
230// it. Because this removes the function from the module, the call graph node
231// is destroyed. This is only valid if the function does not call any other
232// functions (ie, there are no edges in it's CGN). The easiest way to do this
233// is to dropAllReferences before calling this.
234//
235Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
236 assert(CGN->CalledFunctions.empty() && "Cannot remove function from call "
237 "graph if it references other functions!");
238 Function *F = CGN->getFunction(); // Get the function for the call graph node
239 delete CGN; // Delete the call graph node for this func
240 FunctionMap.erase(F); // Remove the call graph node from the map
241
242 Mod->getFunctionList().remove(F);
243 return F;
244}
245
246// changeFunction - This method changes the function associated with this
247// CallGraphNode, for use by transformations that need to change the prototype
248// of a Function (thus they must create a new Function and move the old code
249// over).
250void CallGraph::changeFunction(Function *OldF, Function *NewF) {
251 iterator I = FunctionMap.find(OldF);
252 CallGraphNode *&New = FunctionMap[NewF];
253 assert(I != FunctionMap.end() && I->second && !New &&
254 "OldF didn't exist in CG or NewF already does!");
255 New = I->second;
256 New->F = NewF;
257 FunctionMap.erase(I);
258}
259
260// getOrInsertFunction - This method is identical to calling operator[], but
261// it will insert a new CallGraphNode for the specified function if one does
262// not already exist.
263CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
264 CallGraphNode *&CGN = FunctionMap[F];
265 if (CGN) return CGN;
266
267 assert((!F || F->getParent() == Mod) && "Function not in current module!");
268 return CGN = new CallGraphNode(const_cast<Function*>(F));
269}
270
271void CallGraphNode::print(std::ostream &OS) const {
272 if (Function *F = getFunction())
273 OS << "Call graph node for function: '" << F->getName() <<"'\n";
274 else
275 OS << "Call graph node <<null function: 0x" << this << ">>:\n";
276
277 for (const_iterator I = begin(), E = end(); I != E; ++I)
278 if (I->second->getFunction())
279 OS << " Calls function '" << I->second->getFunction()->getName() <<"'\n";
280 else
281 OS << " Calls external node\n";
282 OS << "\n";
283}
284
285void CallGraphNode::dump() const { print(cerr); }
286
287void CallGraphNode::removeCallEdgeTo(CallGraphNode *Callee) {
288 for (unsigned i = CalledFunctions.size(); ; --i) {
289 assert(i && "Cannot find callee to remove!");
290 if (CalledFunctions[i-1].second == Callee) {
291 CalledFunctions.erase(CalledFunctions.begin()+i-1);
292 return;
293 }
294 }
295}
296
Chris Lattner9125c402008-04-13 19:41:25 +0000297/// removeCallEdgeFor - This method removes the edge in the node for the
298/// specified call site. Note that this method takes linear time, so it
299/// should be used sparingly.
300void CallGraphNode::removeCallEdgeFor(CallSite CS) {
301 for (unsigned i = CalledFunctions.size(); ; --i) {
302 assert(i && "Cannot find callee to remove!");
303 if (CalledFunctions[i-1].first == CS) {
304 CalledFunctions.erase(CalledFunctions.begin()+i-1);
305 return;
306 }
307 }
308}
309
310
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311// removeAnyCallEdgeTo - This method removes any call edges from this node to
312// the specified callee function. This takes more time to execute than
313// removeCallEdgeTo, so it should not be used unless necessary.
314void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
315 for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
316 if (CalledFunctions[i].second == Callee) {
317 CalledFunctions[i] = CalledFunctions.back();
318 CalledFunctions.pop_back();
319 --i; --e;
320 }
321}
322
323// Enuse that users of CallGraph.h also link with this file
324DEFINING_FILE_FOR(CallGraph)