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