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