Update GettingStarted docs list of LLVM_TARGETS_TO_BUILD to match cmake.
[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 #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(llvm::make_unique<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   if (CallsExternalNode)
38     CallsExternalNode->allReferencesDropped();
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 }
47
48 void CallGraph::addToCallGraph(Function *F) {
49   CallGraphNode *Node = getOrInsertFunction(F);
50
51   // If this function has external linkage, anything could call it.
52   if (!F->hasLocalLinkage()) {
53     ExternalCallingNode->addCalledFunction(CallSite(), Node);
54
55     // Found the entry point?
56     if (F->getName() == "main") {
57       if (Root) // Found multiple external mains?  Don't pick one.
58         Root = ExternalCallingNode;
59       else
60         Root = Node; // Found a main, keep track of it!
61     }
62   }
63
64   // If this function has its address taken, anything could call it.
65   if (F->hasAddressTaken())
66     ExternalCallingNode->addCalledFunction(CallSite(), Node);
67
68   // If this function is not defined in this translation unit, it could call
69   // anything.
70   if (F->isDeclaration() && !F->isIntrinsic())
71     Node->addCalledFunction(CallSite(), CallsExternalNode.get());
72
73   // Look for calls by this function.
74   for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
75     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
76          ++II) {
77       CallSite CS(cast<Value>(II));
78       if (CS) {
79         const Function *Callee = CS.getCalledFunction();
80         if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
81           // Indirect calls of intrinsics are not allowed so no need to check.
82           // We can be more precise here by using TargetArg returned by
83           // Intrinsic::isLeaf.
84           Node->addCalledFunction(CS, CallsExternalNode.get());
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   // Print in a deterministic order by sorting CallGraphNodes by name.  We do
100   // this here to avoid slowing down the non-printing fast path.
101
102   SmallVector<CallGraphNode *, 16> Nodes;
103   Nodes.reserve(FunctionMap.size());
104
105   for (auto I = begin(), E = end(); I != E; ++I)
106     Nodes.push_back(I->second.get());
107
108   std::sort(Nodes.begin(), Nodes.end(),
109             [](CallGraphNode *LHS, CallGraphNode *RHS) {
110     if (Function *LF = LHS->getFunction())
111       if (Function *RF = RHS->getFunction())
112         return LF->getName() < RF->getName();
113
114     return RHS->getFunction() != nullptr;
115   });
116
117   for (CallGraphNode *CN : Nodes)
118     CN->print(OS);
119 }
120
121 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
122 void CallGraph::dump() const { print(dbgs()); }
123 #endif
124
125 // removeFunctionFromModule - Unlink the function from this module, returning
126 // it.  Because this removes the function from the module, the call graph node
127 // is destroyed.  This is only valid if the function does not call any other
128 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
129 // is to dropAllReferences before calling this.
130 //
131 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
132   assert(CGN->empty() && "Cannot remove function from call "
133          "graph if it references other functions!");
134   Function *F = CGN->getFunction(); // Get the function for the call graph node
135   FunctionMap.erase(F);             // Remove the call graph node from the map
136
137   M.getFunctionList().remove(F);
138   return F;
139 }
140
141 /// spliceFunction - Replace the function represented by this node by another.
142 /// This does not rescan the body of the function, so it is suitable when
143 /// splicing the body of the old function to the new while also updating all
144 /// callers from old to new.
145 ///
146 void CallGraph::spliceFunction(const Function *From, const Function *To) {
147   assert(FunctionMap.count(From) && "No CallGraphNode for function!");
148   assert(!FunctionMap.count(To) &&
149          "Pointing CallGraphNode at a function that already exists");
150   FunctionMapTy::iterator I = FunctionMap.find(From);
151   I->second->F = const_cast<Function*>(To);
152   FunctionMap[To] = std::move(I->second);
153   FunctionMap.erase(I);
154 }
155
156 // getOrInsertFunction - This method is identical to calling operator[], but
157 // it will insert a new CallGraphNode for the specified function if one does
158 // not already exist.
159 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
160   auto &CGN = FunctionMap[F];
161   if (CGN)
162     return CGN.get();
163
164   assert((!F || F->getParent() == &M) && "Function not in current module!");
165   CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F));
166   return CGN.get();
167 }
168
169 //===----------------------------------------------------------------------===//
170 // Implementations of the CallGraphNode class methods.
171 //
172
173 void CallGraphNode::print(raw_ostream &OS) const {
174   if (Function *F = getFunction())
175     OS << "Call graph node for function: '" << F->getName() << "'";
176   else
177     OS << "Call graph node <<null function>>";
178   
179   OS << "<<" << this << ">>  #uses=" << getNumReferences() << '\n';
180
181   for (const_iterator I = begin(), E = end(); I != E; ++I) {
182     OS << "  CS<" << I->first << "> calls ";
183     if (Function *FI = I->second->getFunction())
184       OS << "function '" << FI->getName() <<"'\n";
185     else
186       OS << "external node\n";
187   }
188   OS << '\n';
189 }
190
191 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
192 void CallGraphNode::dump() const { print(dbgs()); }
193 #endif
194
195 /// removeCallEdgeFor - This method removes the edge in the node for the
196 /// specified call site.  Note that this method takes linear time, so it
197 /// should be used sparingly.
198 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
199   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
200     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
201     if (I->first == CS.getInstruction()) {
202       I->second->DropRef();
203       *I = CalledFunctions.back();
204       CalledFunctions.pop_back();
205       return;
206     }
207   }
208 }
209
210 // removeAnyCallEdgeTo - This method removes any call edges from this node to
211 // the specified callee function.  This takes more time to execute than
212 // removeCallEdgeTo, so it should not be used unless necessary.
213 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
214   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
215     if (CalledFunctions[i].second == Callee) {
216       Callee->DropRef();
217       CalledFunctions[i] = CalledFunctions.back();
218       CalledFunctions.pop_back();
219       --i; --e;
220     }
221 }
222
223 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
224 /// from this node to the specified callee function.
225 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
226   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
227     assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
228     CallRecord &CR = *I;
229     if (CR.second == Callee && CR.first == nullptr) {
230       Callee->DropRef();
231       *I = CalledFunctions.back();
232       CalledFunctions.pop_back();
233       return;
234     }
235   }
236 }
237
238 /// replaceCallEdge - This method replaces the edge in the node for the
239 /// specified call site with a new one.  Note that this method takes linear
240 /// time, so it should be used sparingly.
241 void CallGraphNode::replaceCallEdge(CallSite CS,
242                                     CallSite NewCS, CallGraphNode *NewNode){
243   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
244     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
245     if (I->first == CS.getInstruction()) {
246       I->second->DropRef();
247       I->first = NewCS.getInstruction();
248       I->second = NewNode;
249       NewNode->AddRef();
250       return;
251     }
252   }
253 }
254
255 //===----------------------------------------------------------------------===//
256 // Out-of-line definitions of CallGraphAnalysis class members.
257 //
258
259 char CallGraphAnalysis::PassID;
260
261 //===----------------------------------------------------------------------===//
262 // Implementations of the CallGraphWrapperPass class methods.
263 //
264
265 CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
266   initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
267 }
268
269 CallGraphWrapperPass::~CallGraphWrapperPass() {}
270
271 void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
272   AU.setPreservesAll();
273 }
274
275 bool CallGraphWrapperPass::runOnModule(Module &M) {
276   // All the real work is done in the constructor for the CallGraph.
277   G.reset(new CallGraph(M));
278   return false;
279 }
280
281 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
282                 false, true)
283
284 char CallGraphWrapperPass::ID = 0;
285
286 void CallGraphWrapperPass::releaseMemory() { G.reset(); }
287
288 void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
289   if (!G) {
290     OS << "No call graph has been built!\n";
291     return;
292   }
293
294   // Just delegate.
295   G->print(OS);
296 }
297
298 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
299 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
300 #endif