Simplify this some more. No functionality change.
[oota-llvm.git] / 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/Support/CallSite.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/Streams.h"
21 #include <ostream>
22 using namespace llvm;
23
24 namespace {
25
26 //===----------------------------------------------------------------------===//
27 // BasicCallGraph class definition
28 //
29 class VISIBILITY_HIDDEN BasicCallGraph : public CallGraph, public ModulePass {
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
48   // runOnModule - Compute the call graph for the specified module.
49   virtual bool runOnModule(Module &M) {
50     CallGraph::initialize(M);
51     
52     ExternalCallingNode = getOrInsertFunction(0);
53     CallsExternalNode = new CallGraphNode(0);
54     Root = 0;
55   
56     // Add every function to the call graph...
57     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
58       addToCallGraph(I);
59   
60     // If we didn't find a main function, use the external call graph node
61     if (Root == 0) Root = ExternalCallingNode;
62     
63     return false;
64   }
65
66   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67     AU.setPreservesAll();
68   }
69
70   void print(std::ostream *o, const Module *M) const {
71     if (o) print(*o, M);
72   }
73
74   virtual void print(std::ostream &o, const Module *M) const {
75     o << "CallGraph Root is: ";
76     if (Function *F = getRoot()->getFunction())
77       o << F->getName() << "\n";
78     else
79       o << "<<null function: 0x" << getRoot() << ">>\n";
80     
81     CallGraph::print(o, M);
82   }
83
84   virtual void releaseMemory() {
85     destroy();
86   }
87   
88   /// dump - Print out this call graph.
89   ///
90   inline void dump() const {
91     print(cerr, Mod);
92   }
93
94   CallGraphNode* getExternalCallingNode() const { return ExternalCallingNode; }
95   CallGraphNode* getCallsExternalNode()   const { return CallsExternalNode; }
96
97   // getRoot - Return the root of the call graph, which is either main, or if
98   // main cannot be found, the external node.
99   //
100   CallGraphNode *getRoot()             { return Root; }
101   const CallGraphNode *getRoot() const { return Root; }
102
103 private:
104   //===---------------------------------------------------------------------
105   // Implementation of CallGraph construction
106   //
107
108   // addToCallGraph - Add a function to the call graph, and link the node to all
109   // of the functions that it calls.
110   //
111   void addToCallGraph(Function *F) {
112     CallGraphNode *Node = getOrInsertFunction(F);
113
114     // If this function has external linkage, anything could call it.
115     if (!F->hasInternalLinkage()) {
116       ExternalCallingNode->addCalledFunction(CallSite(), Node);
117
118       // Found the entry point?
119       if (F->getName() == "main") {
120         if (Root)    // Found multiple external mains?  Don't pick one.
121           Root = ExternalCallingNode;
122         else
123           Root = Node;          // Found a main, keep track of it!
124       }
125     }
126
127     // Loop over all of the users of the function, looking for non-call uses.
128     for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I)
129       if ((!isa<CallInst>(*I) && !isa<InvokeInst>(*I)) || I.getOperandNo()) {
130         // Not a call, or being used as a parameter rather than as the callee.
131         ExternalCallingNode->addCalledFunction(CallSite(), Node);
132         break;
133       }
134
135     // If this function is not defined in this translation unit, it could call
136     // anything.
137     if (F->isDeclaration() && !F->isIntrinsic())
138       Node->addCalledFunction(CallSite(), CallsExternalNode);
139
140     // Look for calls by this function.
141     for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
142       for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
143            II != IE; ++II) {
144         CallSite CS = CallSite::get(II);
145         if (CS.getInstruction()) {
146           const Function *Callee = CS.getCalledFunction();
147           if (Callee)
148             Node->addCalledFunction(CS, getOrInsertFunction(Callee));
149           else
150             Node->addCalledFunction(CS, CallsExternalNode);
151         }
152       }
153   }
154
155   //
156   // destroy - Release memory for the call graph
157   virtual void destroy() {
158     /// CallsExternalNode is not in the function map, delete it explicitly.
159     delete CallsExternalNode;
160     CallsExternalNode = 0;
161     CallGraph::destroy();
162   }
163 };
164
165 } //End anonymous namespace
166
167 static RegisterAnalysisGroup<CallGraph> X("Call Graph");
168 static RegisterPass<BasicCallGraph>
169 Y("basiccg", "Basic CallGraph Construction", false, true);
170 static RegisterAnalysisGroup<CallGraph, true> Z(Y);
171
172 char CallGraph::ID = 0;
173 char BasicCallGraph::ID = 0;
174
175 void CallGraph::initialize(Module &M) {
176   Mod = &M;
177 }
178
179 void CallGraph::destroy() {
180   if (!FunctionMap.empty()) {
181     for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
182         I != E; ++I)
183       delete I->second;
184     FunctionMap.clear();
185   }
186 }
187
188 void CallGraph::print(std::ostream &OS, const Module *M) const {
189   for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
190     I->second->print(OS);
191 }
192
193 void CallGraph::dump() const {
194   print(cerr, 0);
195 }
196
197 //===----------------------------------------------------------------------===//
198 // Implementations of public modification methods
199 //
200
201 // removeFunctionFromModule - Unlink the function from this module, returning
202 // it.  Because this removes the function from the module, the call graph node
203 // is destroyed.  This is only valid if the function does not call any other
204 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
205 // is to dropAllReferences before calling this.
206 //
207 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
208   assert(CGN->CalledFunctions.empty() && "Cannot remove function from call "
209          "graph if it references other functions!");
210   Function *F = CGN->getFunction(); // Get the function for the call graph node
211   delete CGN;                       // Delete the call graph node for this func
212   FunctionMap.erase(F);             // Remove the call graph node from the map
213
214   Mod->getFunctionList().remove(F);
215   return F;
216 }
217
218 // changeFunction - This method changes the function associated with this
219 // CallGraphNode, for use by transformations that need to change the prototype
220 // of a Function (thus they must create a new Function and move the old code
221 // over).
222 void CallGraph::changeFunction(Function *OldF, Function *NewF) {
223   iterator I = FunctionMap.find(OldF);
224   CallGraphNode *&New = FunctionMap[NewF];
225   assert(I != FunctionMap.end() && I->second && !New &&
226          "OldF didn't exist in CG or NewF already does!");
227   New = I->second;
228   New->F = NewF;
229   FunctionMap.erase(I);
230 }
231
232 // getOrInsertFunction - This method is identical to calling operator[], but
233 // it will insert a new CallGraphNode for the specified function if one does
234 // not already exist.
235 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
236   CallGraphNode *&CGN = FunctionMap[F];
237   if (CGN) return CGN;
238   
239   assert((!F || F->getParent() == Mod) && "Function not in current module!");
240   return CGN = new CallGraphNode(const_cast<Function*>(F));
241 }
242
243 void CallGraphNode::print(std::ostream &OS) const {
244   if (Function *F = getFunction())
245     OS << "Call graph node for function: '" << F->getName() <<"'\n";
246   else
247     OS << "Call graph node <<null function: 0x" << this << ">>:\n";
248
249   for (const_iterator I = begin(), E = end(); I != E; ++I)
250     if (I->second->getFunction())
251       OS << "  Calls function '" << I->second->getFunction()->getName() <<"'\n";
252   else
253     OS << "  Calls external node\n";
254   OS << "\n";
255 }
256
257 void CallGraphNode::dump() const { print(cerr); }
258
259 /// removeCallEdgeFor - This method removes the edge in the node for the
260 /// specified call site.  Note that this method takes linear time, so it
261 /// should be used sparingly.
262 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
263   for (unsigned i = CalledFunctions.size(); ; --i) {
264     assert(i && "Cannot find callsite to remove!");
265     if (CalledFunctions[i-1].first == CS) {
266       CalledFunctions.erase(CalledFunctions.begin()+i-1);
267       return;
268     }
269   }
270 }
271
272
273 // removeAnyCallEdgeTo - This method removes any call edges from this node to
274 // the specified callee function.  This takes more time to execute than
275 // removeCallEdgeTo, so it should not be used unless necessary.
276 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
277   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
278     if (CalledFunctions[i].second == Callee) {
279       CalledFunctions[i] = CalledFunctions.back();
280       CalledFunctions.pop_back();
281       --i; --e;
282     }
283 }
284
285 /// replaceCallSite - Make the edge in the node for Old CallSite be for
286 /// New CallSite instead.  Note that this method takes linear time, so it
287 /// should be used sparingly.
288 void CallGraphNode::replaceCallSite(CallSite Old, CallSite New) {
289   for (unsigned i = CalledFunctions.size(); ; --i) {
290     assert(i && "Cannot find callsite to replace!");
291     if (CalledFunctions[i-1].first == Old) {
292       CalledFunctions[i-1].first = New;
293       return;
294     }
295   }
296 }
297
298 // Enuse that users of CallGraph.h also link with this file
299 DEFINING_FILE_FOR(CallGraph)