]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/lib/Analysis/IPA/CallGraph.cpp
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / llvm / lib / Analysis / IPA / CallGraph.cpp
1 //===- CallGraph.cpp - Build 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 // 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/IntrinsicInst.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 using namespace llvm;
23
24 namespace {
25
26 //===----------------------------------------------------------------------===//
27 // BasicCallGraph class definition
28 //
29 class BasicCallGraph : public ModulePass, public CallGraph {
30   // Root is root of the call graph, or the external node if a 'main' function
31   // couldn't be found.
32   //
33   CallGraphNode *Root;
34
35   // ExternalCallingNode - This node has edges to all external functions and
36   // those internal functions that have their address taken.
37   CallGraphNode *ExternalCallingNode;
38
39   // CallsExternalNode - This node has edges to it from all functions making
40   // indirect calls or calling an external function.
41   CallGraphNode *CallsExternalNode;
42
43 public:
44   static char ID; // Class identification, replacement for typeinfo
45   BasicCallGraph() : ModulePass(ID), Root(0), 
46     ExternalCallingNode(0), CallsExternalNode(0) {
47       initializeBasicCallGraphPass(*PassRegistry::getPassRegistry());
48     }
49
50   // runOnModule - Compute the call graph for the specified module.
51   virtual bool runOnModule(Module &M) {
52     CallGraph::initialize(M);
53     
54     ExternalCallingNode = getOrInsertFunction(0);
55     CallsExternalNode = new CallGraphNode(0);
56     Root = 0;
57   
58     // Add every function to the call graph.
59     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
60       addToCallGraph(I);
61   
62     // If we didn't find a main function, use the external call graph node
63     if (Root == 0) Root = ExternalCallingNode;
64     
65     return false;
66   }
67
68   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69     AU.setPreservesAll();
70   }
71
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";
76     else {
77       OS << "<<null function: 0x" << getRoot() << ">>\n";
78     }
79     
80     CallGraph::print(OS, 0);
81   }
82
83   virtual void releaseMemory() {
84     destroy();
85   }
86   
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
90   /// info.
91   virtual void *getAdjustedAnalysisPointer(AnalysisID PI) {
92     if (PI == &CallGraph::ID)
93       return (CallGraph*)this;
94     return this;
95   }
96   
97   CallGraphNode* getExternalCallingNode() const { return ExternalCallingNode; }
98   CallGraphNode* getCallsExternalNode()   const { return CallsExternalNode; }
99
100   // getRoot - Return the root of the call graph, which is either main, or if
101   // main cannot be found, the external node.
102   //
103   CallGraphNode *getRoot()             { return Root; }
104   const CallGraphNode *getRoot() const { return Root; }
105
106 private:
107   //===---------------------------------------------------------------------
108   // Implementation of CallGraph construction
109   //
110
111   // addToCallGraph - Add a function to the call graph, and link the node to all
112   // of the functions that it calls.
113   //
114   void addToCallGraph(Function *F) {
115     CallGraphNode *Node = getOrInsertFunction(F);
116
117     // If this function has external linkage, anything could call it.
118     if (!F->hasLocalLinkage()) {
119       ExternalCallingNode->addCalledFunction(CallSite(), Node);
120
121       // Found the entry point?
122       if (F->getName() == "main") {
123         if (Root)    // Found multiple external mains?  Don't pick one.
124           Root = ExternalCallingNode;
125         else
126           Root = Node;          // Found a main, keep track of it!
127       }
128     }
129
130     // Loop over all of the users of the function, looking for non-call uses.
131     for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I){
132       User *U = *I;
133       if ((!isa<CallInst>(U) && !isa<InvokeInst>(U))
134           || !CallSite(cast<Instruction>(U)).isCallee(I)) {
135         // Not a call, or being used as a parameter rather than as the callee.
136         ExternalCallingNode->addCalledFunction(CallSite(), Node);
137         break;
138       }
139     }
140
141     // If this function is not defined in this translation unit, it could call
142     // anything.
143     if (F->isDeclaration() && !F->isIntrinsic())
144       Node->addCalledFunction(CallSite(), CallsExternalNode);
145
146     // Look for calls by this function.
147     for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
148       for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
149            II != IE; ++II) {
150         CallSite CS(cast<Value>(II));
151         if (CS && !isa<IntrinsicInst>(II)) {
152           const Function *Callee = CS.getCalledFunction();
153           if (Callee)
154             Node->addCalledFunction(CS, getOrInsertFunction(Callee));
155           else
156             Node->addCalledFunction(CS, CallsExternalNode);
157         }
158       }
159   }
160
161   //
162   // destroy - Release memory for the call graph
163   virtual void destroy() {
164     /// CallsExternalNode is not in the function map, delete it explicitly.
165     if (CallsExternalNode) {
166       CallsExternalNode->allReferencesDropped();
167       delete CallsExternalNode;
168       CallsExternalNode = 0;
169     }
170     CallGraph::destroy();
171   }
172 };
173
174 } //End anonymous namespace
175
176 INITIALIZE_ANALYSIS_GROUP(CallGraph, "Call Graph", BasicCallGraph)
177 INITIALIZE_AG_PASS(BasicCallGraph, CallGraph, "basiccg",
178                    "Basic CallGraph Construction", false, true, true)
179
180 char CallGraph::ID = 0;
181 char BasicCallGraph::ID = 0;
182
183 void CallGraph::initialize(Module &M) {
184   Mod = &M;
185 }
186
187 void CallGraph::destroy() {
188   if (FunctionMap.empty()) return;
189   
190   // Reset all node's use counts to zero before deleting them to prevent an
191   // assertion from firing.
192 #ifndef NDEBUG
193   for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
194        I != E; ++I)
195     I->second->allReferencesDropped();
196 #endif
197   
198   for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
199       I != E; ++I)
200     delete I->second;
201   FunctionMap.clear();
202 }
203
204 void CallGraph::print(raw_ostream &OS, Module*) const {
205   for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
206     I->second->print(OS);
207 }
208 void CallGraph::dump() const {
209   print(dbgs(), 0);
210 }
211
212 //===----------------------------------------------------------------------===//
213 // Implementations of public modification methods
214 //
215
216 // removeFunctionFromModule - Unlink the function from this module, returning
217 // it.  Because this removes the function from the module, the call graph node
218 // is destroyed.  This is only valid if the function does not call any other
219 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
220 // is to dropAllReferences before calling this.
221 //
222 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
223   assert(CGN->empty() && "Cannot remove function from call "
224          "graph if it references other functions!");
225   Function *F = CGN->getFunction(); // Get the function for the call graph node
226   delete CGN;                       // Delete the call graph node for this func
227   FunctionMap.erase(F);             // Remove the call graph node from the map
228
229   Mod->getFunctionList().remove(F);
230   return F;
231 }
232
233 /// spliceFunction - Replace the function represented by this node by another.
234 /// This does not rescan the body of the function, so it is suitable when
235 /// splicing the body of the old function to the new while also updating all
236 /// callers from old to new.
237 ///
238 void CallGraph::spliceFunction(const Function *From, const Function *To) {
239   assert(FunctionMap.count(From) && "No CallGraphNode for function!");
240   assert(!FunctionMap.count(To) &&
241          "Pointing CallGraphNode at a function that already exists");
242   FunctionMapTy::iterator I = FunctionMap.find(From);
243   I->second->F = const_cast<Function*>(To);
244   FunctionMap[To] = I->second;
245   FunctionMap.erase(I);
246 }
247
248 // getOrInsertFunction - This method is identical to calling operator[], but
249 // it will insert a new CallGraphNode for the specified function if one does
250 // not already exist.
251 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
252   CallGraphNode *&CGN = FunctionMap[F];
253   if (CGN) return CGN;
254   
255   assert((!F || F->getParent() == Mod) && "Function not in current module!");
256   return CGN = new CallGraphNode(const_cast<Function*>(F));
257 }
258
259 void CallGraphNode::print(raw_ostream &OS) const {
260   if (Function *F = getFunction())
261     OS << "Call graph node for function: '" << F->getName() << "'";
262   else
263     OS << "Call graph node <<null function>>";
264   
265   OS << "<<" << this << ">>  #uses=" << getNumReferences() << '\n';
266
267   for (const_iterator I = begin(), E = end(); I != E; ++I) {
268     OS << "  CS<" << I->first << "> calls ";
269     if (Function *FI = I->second->getFunction())
270       OS << "function '" << FI->getName() <<"'\n";
271     else
272       OS << "external node\n";
273   }
274   OS << '\n';
275 }
276
277 void CallGraphNode::dump() const { print(dbgs()); }
278
279 /// removeCallEdgeFor - This method removes the edge in the node for the
280 /// specified call site.  Note that this method takes linear time, so it
281 /// should be used sparingly.
282 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
283   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
284     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
285     if (I->first == CS.getInstruction()) {
286       I->second->DropRef();
287       *I = CalledFunctions.back();
288       CalledFunctions.pop_back();
289       return;
290     }
291   }
292 }
293
294 // removeAnyCallEdgeTo - This method removes any call edges from this node to
295 // the specified callee function.  This takes more time to execute than
296 // removeCallEdgeTo, so it should not be used unless necessary.
297 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
298   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
299     if (CalledFunctions[i].second == Callee) {
300       Callee->DropRef();
301       CalledFunctions[i] = CalledFunctions.back();
302       CalledFunctions.pop_back();
303       --i; --e;
304     }
305 }
306
307 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
308 /// from this node to the specified callee function.
309 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
310   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
311     assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
312     CallRecord &CR = *I;
313     if (CR.second == Callee && CR.first == 0) {
314       Callee->DropRef();
315       *I = CalledFunctions.back();
316       CalledFunctions.pop_back();
317       return;
318     }
319   }
320 }
321
322 /// replaceCallEdge - This method replaces the edge in the node for the
323 /// specified call site with a new one.  Note that this method takes linear
324 /// time, so it should be used sparingly.
325 void CallGraphNode::replaceCallEdge(CallSite CS,
326                                     CallSite NewCS, CallGraphNode *NewNode){
327   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
328     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
329     if (I->first == CS.getInstruction()) {
330       I->second->DropRef();
331       I->first = NewCS.getInstruction();
332       I->second = NewNode;
333       NewNode->AddRef();
334       return;
335     }
336   }
337 }
338
339 // Enuse that users of CallGraph.h also link with this file
340 DEFINING_FILE_FOR(CallGraph)