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