1 //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
19 //===----------------------------------------------------------------------===//
20 // Implementations of the CallGraph class methods.
23 CallGraph::CallGraph(Module &M)
24 : M(M), ExternalCallingNode(getOrInsertFunction(nullptr)),
25 CallsExternalNode(llvm::make_unique<CallGraphNode>(nullptr)) {
26 // Add every function to the call graph.
31 CallGraph::CallGraph(CallGraph &&Arg)
32 : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)),
33 ExternalCallingNode(Arg.ExternalCallingNode),
34 CallsExternalNode(std::move(Arg.CallsExternalNode)) {
35 Arg.FunctionMap.clear();
36 Arg.ExternalCallingNode = nullptr;
39 CallGraph::~CallGraph() {
40 // CallsExternalNode is not in the function map, delete it explicitly.
41 if (CallsExternalNode)
42 CallsExternalNode->allReferencesDropped();
44 // Reset all node's use counts to zero before deleting them to prevent an
45 // assertion from firing.
47 for (auto &I : FunctionMap)
48 I.second->allReferencesDropped();
52 void CallGraph::addToCallGraph(Function *F) {
53 CallGraphNode *Node = getOrInsertFunction(F);
55 // If this function has external linkage or has its address taken, anything
57 if (!F->hasLocalLinkage() || F->hasAddressTaken())
58 ExternalCallingNode->addCalledFunction(CallSite(), Node);
60 // If this function is not defined in this translation unit, it could call
62 if (F->isDeclaration() && !F->isIntrinsic())
63 Node->addCalledFunction(CallSite(), CallsExternalNode.get());
65 // Look for calls by this function.
66 for (BasicBlock &BB : *F)
67 for (Instruction &I : BB) {
68 if (auto CS = CallSite(&I)) {
69 const Function *Callee = CS.getCalledFunction();
70 if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
71 // Indirect calls of intrinsics are not allowed so no need to check.
72 // We can be more precise here by using TargetArg returned by
74 Node->addCalledFunction(CS, CallsExternalNode.get());
75 else if (!Callee->isIntrinsic())
76 Node->addCalledFunction(CS, getOrInsertFunction(Callee));
81 void CallGraph::print(raw_ostream &OS) const {
82 // Print in a deterministic order by sorting CallGraphNodes by name. We do
83 // this here to avoid slowing down the non-printing fast path.
85 SmallVector<CallGraphNode *, 16> Nodes;
86 Nodes.reserve(FunctionMap.size());
88 for (const auto &I : *this)
89 Nodes.push_back(I.second.get());
91 std::sort(Nodes.begin(), Nodes.end(),
92 [](CallGraphNode *LHS, CallGraphNode *RHS) {
93 if (Function *LF = LHS->getFunction())
94 if (Function *RF = RHS->getFunction())
95 return LF->getName() < RF->getName();
97 return RHS->getFunction() != nullptr;
100 for (CallGraphNode *CN : Nodes)
104 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
105 LLVM_DUMP_METHOD void CallGraph::dump() const { print(dbgs()); }
108 // removeFunctionFromModule - Unlink the function from this module, returning
109 // it. Because this removes the function from the module, the call graph node
110 // is destroyed. This is only valid if the function does not call any other
111 // functions (ie, there are no edges in it's CGN). The easiest way to do this
112 // is to dropAllReferences before calling this.
114 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
115 assert(CGN->empty() && "Cannot remove function from call "
116 "graph if it references other functions!");
117 Function *F = CGN->getFunction(); // Get the function for the call graph node
118 FunctionMap.erase(F); // Remove the call graph node from the map
120 M.getFunctionList().remove(F);
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.
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] = std::move(I->second);
136 FunctionMap.erase(I);
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 auto &CGN = FunctionMap[F];
147 assert((!F || F->getParent() == &M) && "Function not in current module!");
148 CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F));
152 //===----------------------------------------------------------------------===//
153 // Implementations of the CallGraphNode class methods.
156 void CallGraphNode::print(raw_ostream &OS) const {
157 if (Function *F = getFunction())
158 OS << "Call graph node for function: '" << F->getName() << "'";
160 OS << "Call graph node <<null function>>";
162 OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
164 for (const auto &I : *this) {
165 OS << " CS<" << I.first << "> calls ";
166 if (Function *FI = I.second->getFunction())
167 OS << "function '" << FI->getName() <<"'\n";
169 OS << "external node\n";
174 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
175 LLVM_DUMP_METHOD void CallGraphNode::dump() const { print(dbgs()); }
178 /// removeCallEdgeFor - This method removes the edge in the node for the
179 /// specified call site. Note that this method takes linear time, so it
180 /// should be used sparingly.
181 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
182 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
183 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
184 if (I->first == CS.getInstruction()) {
185 I->second->DropRef();
186 *I = CalledFunctions.back();
187 CalledFunctions.pop_back();
193 // removeAnyCallEdgeTo - This method removes any call edges from this node to
194 // the specified callee function. This takes more time to execute than
195 // removeCallEdgeTo, so it should not be used unless necessary.
196 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
197 for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
198 if (CalledFunctions[i].second == Callee) {
200 CalledFunctions[i] = CalledFunctions.back();
201 CalledFunctions.pop_back();
206 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
207 /// from this node to the specified callee function.
208 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
209 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
210 assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
212 if (CR.second == Callee && CR.first == nullptr) {
214 *I = CalledFunctions.back();
215 CalledFunctions.pop_back();
221 /// replaceCallEdge - This method replaces the edge in the node for the
222 /// specified call site with a new one. Note that this method takes linear
223 /// time, so it should be used sparingly.
224 void CallGraphNode::replaceCallEdge(CallSite CS,
225 CallSite NewCS, CallGraphNode *NewNode){
226 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
227 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
228 if (I->first == CS.getInstruction()) {
229 I->second->DropRef();
230 I->first = NewCS.getInstruction();
238 // Provide an explicit template instantiation for the static ID.
239 AnalysisKey CallGraphAnalysis::Key;
241 PreservedAnalyses CallGraphPrinterPass::run(Module &M,
242 ModuleAnalysisManager &AM) {
243 AM.getResult<CallGraphAnalysis>(M).print(OS);
244 return PreservedAnalyses::all();
247 //===----------------------------------------------------------------------===//
248 // Out-of-line definitions of CallGraphAnalysis class members.
251 //===----------------------------------------------------------------------===//
252 // Implementations of the CallGraphWrapperPass class methods.
255 CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
256 initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
259 CallGraphWrapperPass::~CallGraphWrapperPass() {}
261 void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
262 AU.setPreservesAll();
265 bool CallGraphWrapperPass::runOnModule(Module &M) {
266 // All the real work is done in the constructor for the CallGraph.
267 G.reset(new CallGraph(M));
271 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
274 char CallGraphWrapperPass::ID = 0;
276 void CallGraphWrapperPass::releaseMemory() { G.reset(); }
278 void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
280 OS << "No call graph has been built!\n";
288 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
290 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
294 struct CallGraphPrinterLegacyPass : public ModulePass {
295 static char ID; // Pass ID, replacement for typeid
296 CallGraphPrinterLegacyPass() : ModulePass(ID) {
297 initializeCallGraphPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
300 void getAnalysisUsage(AnalysisUsage &AU) const override {
301 AU.setPreservesAll();
302 AU.addRequiredTransitive<CallGraphWrapperPass>();
304 bool runOnModule(Module &M) override {
305 getAnalysis<CallGraphWrapperPass>().print(errs(), &M);
311 char CallGraphPrinterLegacyPass::ID = 0;
313 INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph",
314 "Print a call graph", true, true)
315 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
316 INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph",
317 "Print a call graph", true, true)