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), Root(nullptr), ExternalCallingNode(getOrInsertFunction(nullptr)),
25 CallsExternalNode(llvm::make_unique<CallGraphNode>(nullptr)) {
26 // Add every function to the call graph.
30 // If we didn't find a main function, use the external call graph node
32 Root = ExternalCallingNode;
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();
41 Arg.ExternalCallingNode = nullptr;
44 CallGraph::~CallGraph() {
45 // CallsExternalNode is not in the function map, delete it explicitly.
46 if (CallsExternalNode)
47 CallsExternalNode->allReferencesDropped();
49 // Reset all node's use counts to zero before deleting them to prevent an
50 // assertion from firing.
52 for (auto &I : FunctionMap)
53 I.second->allReferencesDropped();
57 void CallGraph::addToCallGraph(Function *F) {
58 CallGraphNode *Node = getOrInsertFunction(F);
60 // If this function has external linkage, anything could call it.
61 if (!F->hasLocalLinkage()) {
62 ExternalCallingNode->addCalledFunction(CallSite(), Node);
64 // Found the entry point?
65 if (F->getName() == "main") {
66 if (Root) // Found multiple external mains? Don't pick one.
67 Root = ExternalCallingNode;
69 Root = Node; // Found a main, keep track of it!
73 // If this function has its address taken, anything could call it.
74 if (F->hasAddressTaken())
75 ExternalCallingNode->addCalledFunction(CallSite(), Node);
77 // If this function is not defined in this translation unit, it could call
79 if (F->isDeclaration() && !F->isIntrinsic())
80 Node->addCalledFunction(CallSite(), CallsExternalNode.get());
82 // Look for calls by this function.
83 for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
84 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
86 CallSite CS(cast<Value>(II));
88 const Function *Callee = CS.getCalledFunction();
89 if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
90 // Indirect calls of intrinsics are not allowed so no need to check.
91 // We can be more precise here by using TargetArg returned by
93 Node->addCalledFunction(CS, CallsExternalNode.get());
94 else if (!Callee->isIntrinsic())
95 Node->addCalledFunction(CS, getOrInsertFunction(Callee));
100 void CallGraph::print(raw_ostream &OS) const {
101 OS << "CallGraph Root is: ";
102 if (Function *F = Root->getFunction())
103 OS << F->getName() << "\n";
105 OS << "<<null function: 0x" << Root << ">>\n";
108 // Print in a deterministic order by sorting CallGraphNodes by name. We do
109 // this here to avoid slowing down the non-printing fast path.
111 SmallVector<CallGraphNode *, 16> Nodes;
112 Nodes.reserve(FunctionMap.size());
114 for (auto I = begin(), E = end(); I != E; ++I)
115 Nodes.push_back(I->second.get());
117 std::sort(Nodes.begin(), Nodes.end(),
118 [](CallGraphNode *LHS, CallGraphNode *RHS) {
119 if (Function *LF = LHS->getFunction())
120 if (Function *RF = RHS->getFunction())
121 return LF->getName() < RF->getName();
123 return RHS->getFunction() != nullptr;
126 for (CallGraphNode *CN : Nodes)
131 void CallGraph::dump() const { print(dbgs()); }
133 // removeFunctionFromModule - Unlink the function from this module, returning
134 // it. Because this removes the function from the module, the call graph node
135 // is destroyed. This is only valid if the function does not call any other
136 // functions (ie, there are no edges in it's CGN). The easiest way to do this
137 // is to dropAllReferences before calling this.
139 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
140 assert(CGN->empty() && "Cannot remove function from call "
141 "graph if it references other functions!");
142 Function *F = CGN->getFunction(); // Get the function for the call graph node
143 FunctionMap.erase(F); // Remove the call graph node from the map
145 M.getFunctionList().remove(F);
149 /// spliceFunction - Replace the function represented by this node by another.
150 /// This does not rescan the body of the function, so it is suitable when
151 /// splicing the body of the old function to the new while also updating all
152 /// callers from old to new.
154 void CallGraph::spliceFunction(const Function *From, const Function *To) {
155 assert(FunctionMap.count(From) && "No CallGraphNode for function!");
156 assert(!FunctionMap.count(To) &&
157 "Pointing CallGraphNode at a function that already exists");
158 FunctionMapTy::iterator I = FunctionMap.find(From);
159 I->second->F = const_cast<Function*>(To);
160 FunctionMap[To] = std::move(I->second);
161 FunctionMap.erase(I);
164 // getOrInsertFunction - This method is identical to calling operator[], but
165 // it will insert a new CallGraphNode for the specified function if one does
166 // not already exist.
167 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
168 auto &CGN = FunctionMap[F];
172 assert((!F || F->getParent() == &M) && "Function not in current module!");
173 CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F));
177 //===----------------------------------------------------------------------===//
178 // Implementations of the CallGraphNode class methods.
181 void CallGraphNode::print(raw_ostream &OS) const {
182 if (Function *F = getFunction())
183 OS << "Call graph node for function: '" << F->getName() << "'";
185 OS << "Call graph node <<null function>>";
187 OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
189 for (const_iterator I = begin(), E = end(); I != E; ++I) {
190 OS << " CS<" << I->first << "> calls ";
191 if (Function *FI = I->second->getFunction())
192 OS << "function '" << FI->getName() <<"'\n";
194 OS << "external node\n";
200 void CallGraphNode::dump() const { print(dbgs()); }
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();
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) {
224 CalledFunctions[i] = CalledFunctions.back();
225 CalledFunctions.pop_back();
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!");
236 if (CR.second == Callee && CR.first == nullptr) {
238 *I = CalledFunctions.back();
239 CalledFunctions.pop_back();
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();
262 //===----------------------------------------------------------------------===//
263 // Out-of-line definitions of CallGraphAnalysis class members.
266 char CallGraphAnalysis::PassID;
268 //===----------------------------------------------------------------------===//
269 // Implementations of the CallGraphWrapperPass class methods.
272 CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
273 initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
276 CallGraphWrapperPass::~CallGraphWrapperPass() {}
278 void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
279 AU.setPreservesAll();
282 bool CallGraphWrapperPass::runOnModule(Module &M) {
283 // All the real work is done in the constructor for the CallGraph.
284 G.reset(new CallGraph(M));
288 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
291 char CallGraphWrapperPass::ID = 0;
293 void CallGraphWrapperPass::releaseMemory() { G.reset(); }
295 void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
297 OS << "No call graph has been built!\n";
306 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }