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(new 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() {
36 // CallsExternalNode is not in the function map, delete it explicitly.
37 CallsExternalNode->allReferencesDropped();
38 delete CallsExternalNode;
40 // Reset all node's use counts to zero before deleting them to prevent an
41 // assertion from firing.
43 for (auto &I : FunctionMap)
44 I.second->allReferencesDropped();
46 for (auto &I : FunctionMap)
50 void CallGraph::addToCallGraph(Function *F) {
51 CallGraphNode *Node = getOrInsertFunction(F);
53 // If this function has external linkage, anything could call it.
54 if (!F->hasLocalLinkage()) {
55 ExternalCallingNode->addCalledFunction(CallSite(), Node);
57 // Found the entry point?
58 if (F->getName() == "main") {
59 if (Root) // Found multiple external mains? Don't pick one.
60 Root = ExternalCallingNode;
62 Root = Node; // Found a main, keep track of it!
66 // If this function has its address taken, anything could call it.
67 if (F->hasAddressTaken())
68 ExternalCallingNode->addCalledFunction(CallSite(), Node);
70 // If this function is not defined in this translation unit, it could call
72 if (F->isDeclaration() && !F->isIntrinsic())
73 Node->addCalledFunction(CallSite(), CallsExternalNode);
75 // Look for calls by this function.
76 for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
77 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
79 CallSite CS(cast<Value>(II));
81 const Function *Callee = CS.getCalledFunction();
83 // Indirect calls of intrinsics are not allowed so no need to check.
84 Node->addCalledFunction(CS, CallsExternalNode);
85 else if (!Callee->isIntrinsic())
86 Node->addCalledFunction(CS, getOrInsertFunction(Callee));
91 void CallGraph::print(raw_ostream &OS) const {
92 OS << "CallGraph Root is: ";
93 if (Function *F = Root->getFunction())
94 OS << F->getName() << "\n";
96 OS << "<<null function: 0x" << Root << ">>\n";
99 for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
100 I->second->print(OS);
103 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
104 void CallGraph::dump() const { print(dbgs()); }
107 // removeFunctionFromModule - Unlink the function from this module, returning
108 // it. Because this removes the function from the module, the call graph node
109 // is destroyed. This is only valid if the function does not call any other
110 // functions (ie, there are no edges in it's CGN). The easiest way to do this
111 // is to dropAllReferences before calling this.
113 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
114 assert(CGN->empty() && "Cannot remove function from call "
115 "graph if it references other functions!");
116 Function *F = CGN->getFunction(); // Get the function for the call graph node
117 delete CGN; // Delete the call graph node for this func
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] = 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 CallGraphNode *&CGN = FunctionMap[F];
147 assert((!F || F->getParent() == &M) && "Function not in current module!");
148 return CGN = new CallGraphNode(const_cast<Function*>(F));
151 //===----------------------------------------------------------------------===//
152 // Implementations of the CallGraphNode class methods.
155 void CallGraphNode::print(raw_ostream &OS) const {
156 if (Function *F = getFunction())
157 OS << "Call graph node for function: '" << F->getName() << "'";
159 OS << "Call graph node <<null function>>";
161 OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
163 for (const_iterator I = begin(), E = end(); I != E; ++I) {
164 OS << " CS<" << I->first << "> calls ";
165 if (Function *FI = I->second->getFunction())
166 OS << "function '" << FI->getName() <<"'\n";
168 OS << "external node\n";
173 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
174 void CallGraphNode::dump() const { print(dbgs()); }
177 /// removeCallEdgeFor - This method removes the edge in the node for the
178 /// specified call site. Note that this method takes linear time, so it
179 /// should be used sparingly.
180 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
181 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
182 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
183 if (I->first == CS.getInstruction()) {
184 I->second->DropRef();
185 *I = CalledFunctions.back();
186 CalledFunctions.pop_back();
192 // removeAnyCallEdgeTo - This method removes any call edges from this node to
193 // the specified callee function. This takes more time to execute than
194 // removeCallEdgeTo, so it should not be used unless necessary.
195 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
196 for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
197 if (CalledFunctions[i].second == Callee) {
199 CalledFunctions[i] = CalledFunctions.back();
200 CalledFunctions.pop_back();
205 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
206 /// from this node to the specified callee function.
207 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
208 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
209 assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
211 if (CR.second == Callee && CR.first == nullptr) {
213 *I = CalledFunctions.back();
214 CalledFunctions.pop_back();
220 /// replaceCallEdge - This method replaces the edge in the node for the
221 /// specified call site with a new one. Note that this method takes linear
222 /// time, so it should be used sparingly.
223 void CallGraphNode::replaceCallEdge(CallSite CS,
224 CallSite NewCS, CallGraphNode *NewNode){
225 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
226 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
227 if (I->first == CS.getInstruction()) {
228 I->second->DropRef();
229 I->first = NewCS.getInstruction();
237 //===----------------------------------------------------------------------===//
238 // Out-of-line definitions of CallGraphAnalysis class members.
241 char CallGraphAnalysis::PassID;
243 //===----------------------------------------------------------------------===//
244 // Implementations of the CallGraphWrapperPass class methods.
247 CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
248 initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
251 CallGraphWrapperPass::~CallGraphWrapperPass() {}
253 void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
254 AU.setPreservesAll();
257 bool CallGraphWrapperPass::runOnModule(Module &M) {
258 // All the real work is done in the constructor for the CallGraph.
259 G.reset(new CallGraph(M));
263 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
266 char CallGraphWrapperPass::ID = 0;
268 void CallGraphWrapperPass::releaseMemory() { G.reset(); }
270 void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
272 OS << "No call graph has been built!\n";
280 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
281 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }