OSDN Git Service

Merge "Clean up unnecessary build dependencies."
[android-x86/external-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 #include "llvm/Analysis/CallGraph.h"
11 #include "llvm/IR/CallSite.h"
12 #include "llvm/IR/Instructions.h"
13 #include "llvm/IR/IntrinsicInst.h"
14 #include "llvm/IR/Module.h"
15 #include "llvm/Support/Debug.h"
16 #include "llvm/Support/raw_ostream.h"
17 using namespace llvm;
18
19 //===----------------------------------------------------------------------===//
20 // Implementations of the CallGraph class methods.
21 //
22
23 CallGraph::CallGraph(Module &M)
24     : M(M), Root(nullptr), ExternalCallingNode(getOrInsertFunction(nullptr)),
25       CallsExternalNode(new CallGraphNode(nullptr)) {
26   // Add every function to the call graph.
27   for (Function &F : M)
28     addToCallGraph(&F);
29
30   // If we didn't find a main function, use the external call graph node
31   if (!Root)
32     Root = ExternalCallingNode;
33 }
34
35 CallGraph::~CallGraph() {
36   // CallsExternalNode is not in the function map, delete it explicitly.
37   CallsExternalNode->allReferencesDropped();
38   delete CallsExternalNode;
39
40 // Reset all node's use counts to zero before deleting them to prevent an
41 // assertion from firing.
42 #ifndef NDEBUG
43   for (auto &I : FunctionMap)
44     I.second->allReferencesDropped();
45 #endif
46   for (auto &I : FunctionMap)
47     delete I.second;
48 }
49
50 void CallGraph::addToCallGraph(Function *F) {
51   CallGraphNode *Node = getOrInsertFunction(F);
52
53   // If this function has external linkage, anything could call it.
54   if (!F->hasLocalLinkage()) {
55     ExternalCallingNode->addCalledFunction(CallSite(), Node);
56
57     // Found the entry point?
58     if (F->getName() == "main") {
59       if (Root) // Found multiple external mains?  Don't pick one.
60         Root = ExternalCallingNode;
61       else
62         Root = Node; // Found a main, keep track of it!
63     }
64   }
65
66   // If this function has its address taken, anything could call it.
67   if (F->hasAddressTaken())
68     ExternalCallingNode->addCalledFunction(CallSite(), Node);
69
70   // If this function is not defined in this translation unit, it could call
71   // anything.
72   if (F->isDeclaration() && !F->isIntrinsic())
73     Node->addCalledFunction(CallSite(), CallsExternalNode);
74
75   // Look for calls by this function.
76   for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
77     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
78          ++II) {
79       CallSite CS(cast<Value>(II));
80       if (CS) {
81         const Function *Callee = CS.getCalledFunction();
82         if (!Callee)
83           // Indirect calls of intrinsics are not allowed so no need to check.
84           Node->addCalledFunction(CS, CallsExternalNode);
85         else if (!Callee->isIntrinsic())
86           Node->addCalledFunction(CS, getOrInsertFunction(Callee));
87       }
88     }
89 }
90
91 void CallGraph::print(raw_ostream &OS) const {
92   OS << "CallGraph Root is: ";
93   if (Function *F = Root->getFunction())
94     OS << F->getName() << "\n";
95   else {
96     OS << "<<null function: 0x" << Root << ">>\n";
97   }
98
99   for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
100     I->second->print(OS);
101 }
102
103 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
104 void CallGraph::dump() const { print(dbgs()); }
105 #endif
106
107 // removeFunctionFromModule - Unlink the function from this module, returning
108 // it.  Because this removes the function from the module, the call graph node
109 // is destroyed.  This is only valid if the function does not call any other
110 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
111 // is to dropAllReferences before calling this.
112 //
113 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
114   assert(CGN->empty() && "Cannot remove function from call "
115          "graph if it references other functions!");
116   Function *F = CGN->getFunction(); // Get the function for the call graph node
117   delete CGN;                       // Delete the call graph node for this func
118   FunctionMap.erase(F);             // Remove the call graph node from the map
119
120   M.getFunctionList().remove(F);
121   return F;
122 }
123
124 /// spliceFunction - Replace the function represented by this node by another.
125 /// This does not rescan the body of the function, so it is suitable when
126 /// splicing the body of the old function to the new while also updating all
127 /// callers from old to new.
128 ///
129 void CallGraph::spliceFunction(const Function *From, const Function *To) {
130   assert(FunctionMap.count(From) && "No CallGraphNode for function!");
131   assert(!FunctionMap.count(To) &&
132          "Pointing CallGraphNode at a function that already exists");
133   FunctionMapTy::iterator I = FunctionMap.find(From);
134   I->second->F = const_cast<Function*>(To);
135   FunctionMap[To] = I->second;
136   FunctionMap.erase(I);
137 }
138
139 // getOrInsertFunction - This method is identical to calling operator[], but
140 // it will insert a new CallGraphNode for the specified function if one does
141 // not already exist.
142 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
143   CallGraphNode *&CGN = FunctionMap[F];
144   if (CGN)
145     return CGN;
146
147   assert((!F || F->getParent() == &M) && "Function not in current module!");
148   return CGN = new CallGraphNode(const_cast<Function*>(F));
149 }
150
151 //===----------------------------------------------------------------------===//
152 // Implementations of the CallGraphNode class methods.
153 //
154
155 void CallGraphNode::print(raw_ostream &OS) const {
156   if (Function *F = getFunction())
157     OS << "Call graph node for function: '" << F->getName() << "'";
158   else
159     OS << "Call graph node <<null function>>";
160   
161   OS << "<<" << this << ">>  #uses=" << getNumReferences() << '\n';
162
163   for (const_iterator I = begin(), E = end(); I != E; ++I) {
164     OS << "  CS<" << I->first << "> calls ";
165     if (Function *FI = I->second->getFunction())
166       OS << "function '" << FI->getName() <<"'\n";
167     else
168       OS << "external node\n";
169   }
170   OS << '\n';
171 }
172
173 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
174 void CallGraphNode::dump() const { print(dbgs()); }
175 #endif
176
177 /// removeCallEdgeFor - This method removes the edge in the node for the
178 /// specified call site.  Note that this method takes linear time, so it
179 /// should be used sparingly.
180 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
181   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
182     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
183     if (I->first == CS.getInstruction()) {
184       I->second->DropRef();
185       *I = CalledFunctions.back();
186       CalledFunctions.pop_back();
187       return;
188     }
189   }
190 }
191
192 // removeAnyCallEdgeTo - This method removes any call edges from this node to
193 // the specified callee function.  This takes more time to execute than
194 // removeCallEdgeTo, so it should not be used unless necessary.
195 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
196   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
197     if (CalledFunctions[i].second == Callee) {
198       Callee->DropRef();
199       CalledFunctions[i] = CalledFunctions.back();
200       CalledFunctions.pop_back();
201       --i; --e;
202     }
203 }
204
205 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
206 /// from this node to the specified callee function.
207 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
208   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
209     assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
210     CallRecord &CR = *I;
211     if (CR.second == Callee && CR.first == nullptr) {
212       Callee->DropRef();
213       *I = CalledFunctions.back();
214       CalledFunctions.pop_back();
215       return;
216     }
217   }
218 }
219
220 /// replaceCallEdge - This method replaces the edge in the node for the
221 /// specified call site with a new one.  Note that this method takes linear
222 /// time, so it should be used sparingly.
223 void CallGraphNode::replaceCallEdge(CallSite CS,
224                                     CallSite NewCS, CallGraphNode *NewNode){
225   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
226     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
227     if (I->first == CS.getInstruction()) {
228       I->second->DropRef();
229       I->first = NewCS.getInstruction();
230       I->second = NewNode;
231       NewNode->AddRef();
232       return;
233     }
234   }
235 }
236
237 //===----------------------------------------------------------------------===//
238 // Out-of-line definitions of CallGraphAnalysis class members.
239 //
240
241 char CallGraphAnalysis::PassID;
242
243 //===----------------------------------------------------------------------===//
244 // Implementations of the CallGraphWrapperPass class methods.
245 //
246
247 CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
248   initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
249 }
250
251 CallGraphWrapperPass::~CallGraphWrapperPass() {}
252
253 void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
254   AU.setPreservesAll();
255 }
256
257 bool CallGraphWrapperPass::runOnModule(Module &M) {
258   // All the real work is done in the constructor for the CallGraph.
259   G.reset(new CallGraph(M));
260   return false;
261 }
262
263 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
264                 false, true)
265
266 char CallGraphWrapperPass::ID = 0;
267
268 void CallGraphWrapperPass::releaseMemory() { G.reset(); }
269
270 void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
271   if (!G) {
272     OS << "No call graph has been built!\n";
273     return;
274   }
275
276   // Just delegate.
277   G->print(OS);
278 }
279
280 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
281 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
282 #endif