1 //===- CallGraph.cpp - Build a Module's 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 CallGraph class and provides the BasicCallGraph
11 // default implementation.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/CallGraph.h"
16 #include "llvm/IR/Instructions.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
26 //===----------------------------------------------------------------------===//
27 // BasicCallGraph class definition
29 class BasicCallGraph : public ModulePass, public CallGraph {
30 // Root is root of the call graph, or the external node if a 'main' function
35 // ExternalCallingNode - This node has edges to all external functions and
36 // those internal functions that have their address taken.
37 CallGraphNode *ExternalCallingNode;
39 // CallsExternalNode - This node has edges to it from all functions making
40 // indirect calls or calling an external function.
41 CallGraphNode *CallsExternalNode;
44 static char ID; // Class identification, replacement for typeinfo
45 BasicCallGraph() : ModulePass(ID), Root(0),
46 ExternalCallingNode(0), CallsExternalNode(0) {
47 initializeBasicCallGraphPass(*PassRegistry::getPassRegistry());
50 // runOnModule - Compute the call graph for the specified module.
51 virtual bool runOnModule(Module &M) {
52 CallGraph::initialize(M);
54 ExternalCallingNode = getOrInsertFunction(0);
55 CallsExternalNode = new CallGraphNode(0);
58 // Add every function to the call graph.
59 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
62 // If we didn't find a main function, use the external call graph node
63 if (Root == 0) Root = ExternalCallingNode;
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72 virtual void print(raw_ostream &OS, const Module *) const {
73 OS << "CallGraph Root is: ";
74 if (Function *F = getRoot()->getFunction())
75 OS << F->getName() << "\n";
77 OS << "<<null function: 0x" << getRoot() << ">>\n";
80 CallGraph::print(OS, 0);
83 virtual void releaseMemory() {
87 /// getAdjustedAnalysisPointer - This method is used when a pass implements
88 /// an analysis interface through multiple inheritance. If needed, it should
89 /// override this to adjust the this pointer as needed for the specified pass
91 virtual void *getAdjustedAnalysisPointer(AnalysisID PI) {
92 if (PI == &CallGraph::ID)
93 return (CallGraph*)this;
97 CallGraphNode* getExternalCallingNode() const { return ExternalCallingNode; }
98 CallGraphNode* getCallsExternalNode() const { return CallsExternalNode; }
100 // getRoot - Return the root of the call graph, which is either main, or if
101 // main cannot be found, the external node.
103 CallGraphNode *getRoot() { return Root; }
104 const CallGraphNode *getRoot() const { return Root; }
107 //===---------------------------------------------------------------------
108 // Implementation of CallGraph construction
111 // addToCallGraph - Add a function to the call graph, and link the node to all
112 // of the functions that it calls.
114 void addToCallGraph(Function *F) {
115 CallGraphNode *Node = getOrInsertFunction(F);
117 // If this function has external linkage, anything could call it.
118 if (!F->hasLocalLinkage()) {
119 ExternalCallingNode->addCalledFunction(CallSite(), Node);
121 // Found the entry point?
122 if (F->getName() == "main") {
123 if (Root) // Found multiple external mains? Don't pick one.
124 Root = ExternalCallingNode;
126 Root = Node; // Found a main, keep track of it!
130 // If this function has its address taken, anything could call it.
131 if (F->hasAddressTaken())
132 ExternalCallingNode->addCalledFunction(CallSite(), Node);
134 // If this function is not defined in this translation unit, it could call
136 if (F->isDeclaration() && !F->isIntrinsic())
137 Node->addCalledFunction(CallSite(), CallsExternalNode);
139 // Look for calls by this function.
140 for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
141 for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
143 CallSite CS(cast<Value>(II));
145 const Function *Callee = CS.getCalledFunction();
147 // Indirect calls of intrinsics are not allowed so no need to check.
148 Node->addCalledFunction(CS, CallsExternalNode);
149 else if (!Callee->isIntrinsic())
150 Node->addCalledFunction(CS, getOrInsertFunction(Callee));
156 // destroy - Release memory for the call graph
157 virtual void destroy() {
158 /// CallsExternalNode is not in the function map, delete it explicitly.
159 if (CallsExternalNode) {
160 CallsExternalNode->allReferencesDropped();
161 delete CallsExternalNode;
162 CallsExternalNode = 0;
164 CallGraph::destroy();
168 } //End anonymous namespace
170 INITIALIZE_ANALYSIS_GROUP(CallGraph, "Call Graph", BasicCallGraph)
171 INITIALIZE_AG_PASS(BasicCallGraph, CallGraph, "basiccg",
172 "Basic CallGraph Construction", false, true, true)
174 char CallGraph::ID = 0;
175 char BasicCallGraph::ID = 0;
177 void CallGraph::initialize(Module &M) {
181 void CallGraph::destroy() {
182 if (FunctionMap.empty()) return;
184 // Reset all node's use counts to zero before deleting them to prevent an
185 // assertion from firing.
187 for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
189 I->second->allReferencesDropped();
192 for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
198 void CallGraph::print(raw_ostream &OS, Module*) const {
199 for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
200 I->second->print(OS);
202 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
203 void CallGraph::dump() const {
208 //===----------------------------------------------------------------------===//
209 // Implementations of public modification methods
212 // removeFunctionFromModule - Unlink the function from this module, returning
213 // it. Because this removes the function from the module, the call graph node
214 // is destroyed. This is only valid if the function does not call any other
215 // functions (ie, there are no edges in it's CGN). The easiest way to do this
216 // is to dropAllReferences before calling this.
218 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
219 assert(CGN->empty() && "Cannot remove function from call "
220 "graph if it references other functions!");
221 Function *F = CGN->getFunction(); // Get the function for the call graph node
222 delete CGN; // Delete the call graph node for this func
223 FunctionMap.erase(F); // Remove the call graph node from the map
225 Mod->getFunctionList().remove(F);
229 /// spliceFunction - Replace the function represented by this node by another.
230 /// This does not rescan the body of the function, so it is suitable when
231 /// splicing the body of the old function to the new while also updating all
232 /// callers from old to new.
234 void CallGraph::spliceFunction(const Function *From, const Function *To) {
235 assert(FunctionMap.count(From) && "No CallGraphNode for function!");
236 assert(!FunctionMap.count(To) &&
237 "Pointing CallGraphNode at a function that already exists");
238 FunctionMapTy::iterator I = FunctionMap.find(From);
239 I->second->F = const_cast<Function*>(To);
240 FunctionMap[To] = I->second;
241 FunctionMap.erase(I);
244 // getOrInsertFunction - This method is identical to calling operator[], but
245 // it will insert a new CallGraphNode for the specified function if one does
246 // not already exist.
247 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
248 CallGraphNode *&CGN = FunctionMap[F];
251 assert((!F || F->getParent() == Mod) && "Function not in current module!");
252 return CGN = new CallGraphNode(const_cast<Function*>(F));
255 void CallGraphNode::print(raw_ostream &OS) const {
256 if (Function *F = getFunction())
257 OS << "Call graph node for function: '" << F->getName() << "'";
259 OS << "Call graph node <<null function>>";
261 OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
263 for (const_iterator I = begin(), E = end(); I != E; ++I) {
264 OS << " CS<" << I->first << "> calls ";
265 if (Function *FI = I->second->getFunction())
266 OS << "function '" << FI->getName() <<"'\n";
268 OS << "external node\n";
273 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
274 void CallGraphNode::dump() const { print(dbgs()); }
277 /// removeCallEdgeFor - This method removes the edge in the node for the
278 /// specified call site. Note that this method takes linear time, so it
279 /// should be used sparingly.
280 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
281 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
282 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
283 if (I->first == CS.getInstruction()) {
284 I->second->DropRef();
285 *I = CalledFunctions.back();
286 CalledFunctions.pop_back();
292 // removeAnyCallEdgeTo - This method removes any call edges from this node to
293 // the specified callee function. This takes more time to execute than
294 // removeCallEdgeTo, so it should not be used unless necessary.
295 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
296 for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
297 if (CalledFunctions[i].second == Callee) {
299 CalledFunctions[i] = CalledFunctions.back();
300 CalledFunctions.pop_back();
305 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
306 /// from this node to the specified callee function.
307 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
308 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
309 assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
311 if (CR.second == Callee && CR.first == 0) {
313 *I = CalledFunctions.back();
314 CalledFunctions.pop_back();
320 /// replaceCallEdge - This method replaces the edge in the node for the
321 /// specified call site with a new one. Note that this method takes linear
322 /// time, so it should be used sparingly.
323 void CallGraphNode::replaceCallEdge(CallSite CS,
324 CallSite NewCS, CallGraphNode *NewNode){
325 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
326 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
327 if (I->first == CS.getInstruction()) {
328 I->second->DropRef();
329 I->first = NewCS.getInstruction();
337 // Enuse that users of CallGraph.h also link with this file
338 DEFINING_FILE_FOR(CallGraph)