LLVM  4.0.0
CallGraph.cpp
Go to the documentation of this file.
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 
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"
17 using namespace llvm;
18 
19 //===----------------------------------------------------------------------===//
20 // Implementations of the CallGraph class methods.
21 //
22 
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 
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 
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) {
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 
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 
129 void CallGraph::dump() const { print(dbgs()); }
130 
131 // removeFunctionFromModule - Unlink the function from this module, returning
132 // it. Because this removes the function from the module, the call graph node
133 // is destroyed. This is only valid if the function does not call any other
134 // functions (ie, there are no edges in it's CGN). The easiest way to do this
135 // is to dropAllReferences before calling this.
136 //
138  assert(CGN->empty() && "Cannot remove function from call "
139  "graph if it references other functions!");
140  Function *F = CGN->getFunction(); // Get the function for the call graph node
141  FunctionMap.erase(F); // Remove the call graph node from the map
142 
143  M.getFunctionList().remove(F);
144  return F;
145 }
146 
147 /// spliceFunction - Replace the function represented by this node by another.
148 /// This does not rescan the body of the function, so it is suitable when
149 /// splicing the body of the old function to the new while also updating all
150 /// callers from old to new.
151 ///
152 void CallGraph::spliceFunction(const Function *From, const Function *To) {
153  assert(FunctionMap.count(From) && "No CallGraphNode for function!");
154  assert(!FunctionMap.count(To) &&
155  "Pointing CallGraphNode at a function that already exists");
156  FunctionMapTy::iterator I = FunctionMap.find(From);
157  I->second->F = const_cast<Function*>(To);
158  FunctionMap[To] = std::move(I->second);
159  FunctionMap.erase(I);
160 }
161 
162 // getOrInsertFunction - This method is identical to calling operator[], but
163 // it will insert a new CallGraphNode for the specified function if one does
164 // not already exist.
166  auto &CGN = FunctionMap[F];
167  if (CGN)
168  return CGN.get();
169 
170  assert((!F || F->getParent() == &M) && "Function not in current module!");
171  CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F));
172  return CGN.get();
173 }
174 
175 //===----------------------------------------------------------------------===//
176 // Implementations of the CallGraphNode class methods.
177 //
178 
180  if (Function *F = getFunction())
181  OS << "Call graph node for function: '" << F->getName() << "'";
182  else
183  OS << "Call graph node <<null function>>";
184 
185  OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
186 
187  for (const auto &I : *this) {
188  OS << " CS<" << I.first << "> calls ";
189  if (Function *FI = I.second->getFunction())
190  OS << "function '" << FI->getName() <<"'\n";
191  else
192  OS << "external node\n";
193  }
194  OS << '\n';
195 }
196 
198 void CallGraphNode::dump() const { print(dbgs()); }
199 
200 /// removeCallEdgeFor - This method removes the edge in the node for the
201 /// specified call site. Note that this method takes linear time, so it
202 /// should be used sparingly.
204  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
205  assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
206  if (I->first == CS.getInstruction()) {
207  I->second->DropRef();
208  *I = CalledFunctions.back();
209  CalledFunctions.pop_back();
210  return;
211  }
212  }
213 }
214 
215 // removeAnyCallEdgeTo - This method removes any call edges from this node to
216 // the specified callee function. This takes more time to execute than
217 // removeCallEdgeTo, so it should not be used unless necessary.
219  for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
220  if (CalledFunctions[i].second == Callee) {
221  Callee->DropRef();
222  CalledFunctions[i] = CalledFunctions.back();
223  CalledFunctions.pop_back();
224  --i; --e;
225  }
226 }
227 
228 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
229 /// from this node to the specified callee function.
231  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
232  assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
233  CallRecord &CR = *I;
234  if (CR.second == Callee && CR.first == nullptr) {
235  Callee->DropRef();
236  *I = CalledFunctions.back();
237  CalledFunctions.pop_back();
238  return;
239  }
240  }
241 }
242 
243 /// replaceCallEdge - This method replaces the edge in the node for the
244 /// specified call site with a new one. Note that this method takes linear
245 /// time, so it should be used sparingly.
247  CallSite NewCS, CallGraphNode *NewNode){
248  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
249  assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
250  if (I->first == CS.getInstruction()) {
251  I->second->DropRef();
252  I->first = NewCS.getInstruction();
253  I->second = NewNode;
254  NewNode->AddRef();
255  return;
256  }
257  }
258 }
259 
260 // Provide an explicit template instantiation for the static ID.
261 AnalysisKey CallGraphAnalysis::Key;
262 
264  ModuleAnalysisManager &AM) {
265  AM.getResult<CallGraphAnalysis>(M).print(OS);
266  return PreservedAnalyses::all();
267 }
268 
269 //===----------------------------------------------------------------------===//
270 // Out-of-line definitions of CallGraphAnalysis class members.
271 //
272 
273 //===----------------------------------------------------------------------===//
274 // Implementations of the CallGraphWrapperPass class methods.
275 //
276 
279 }
280 
282 
284  AU.setPreservesAll();
285 }
286 
288  // All the real work is done in the constructor for the CallGraph.
289  G.reset(new CallGraph(M));
290  return false;
291 }
292 
293 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
294  false, true)
295 
296 char CallGraphWrapperPass::ID = 0;
297 
298 void CallGraphWrapperPass::releaseMemory() { G.reset(); }
299 
301  if (!G) {
302  OS << "No call graph has been built!\n";
303  return;
304  }
305 
306  // Just delegate.
307  G->print(OS);
308 }
309 
311 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
312 
313 namespace {
314 struct CallGraphPrinterLegacyPass : public ModulePass {
315  static char ID; // Pass ID, replacement for typeid
316  CallGraphPrinterLegacyPass() : ModulePass(ID) {
318  }
319 
320  void getAnalysisUsage(AnalysisUsage &AU) const override {
321  AU.setPreservesAll();
323  }
324  bool runOnModule(Module &M) override {
325  getAnalysis<CallGraphWrapperPass>().print(errs(), &M);
326  return false;
327  }
328 };
329 }
330 
332 
333 INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph",
334  "Print a call graph", true, true)
336 INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph",
337  "Print a call graph", true, true)
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void Print(const Unit &v, const char *PrintAfter)
Definition: FuzzerUtil.cpp:34
size_t i
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:450
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
void dump() const
Print out this call graph node.
Definition: CallGraph.cpp:198
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition: Function.h:151
bool empty() const
Definition: CallGraph.h:197
void dump() const
Definition: CallGraph.cpp:129
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on...
Definition: CallGraph.cpp:287
void reserve(size_type N)
Definition: SmallVector.h:377
A node in the call graph for a module.
Definition: CallGraph.h:171
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:191
Function * getFunction() const
Returns the function that this call graph node represents.
Definition: CallGraph.h:191
unsigned getNumReferences() const
Returns the number of other CallGraphNodes in this CallGraph that reference this node in their callee...
Definition: CallGraph.h:202
void removeOneAbstractEdgeTo(CallGraphNode *Callee)
Removes one edge associated with a null callsite from this node to the specified callee function...
Definition: CallGraph.cpp:230
void addCalledFunction(CallSite CS, CallGraphNode *M)
Adds a function to the list of functions called by this one.
Definition: CallGraph.h:236
print callgraph
Definition: CallGraph.cpp:336
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:53
void print(raw_ostream &OS) const
Definition: CallGraph.cpp:98
void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode)
Replaces the edge in the node for the specified call site with a new one.
Definition: CallGraph.cpp:246
Function * removeFunctionFromModule(CallGraphNode *CGN)
Unlink the function from this module, returning it.
Definition: CallGraph.cpp:137
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
#define F(x, y, z)
Definition: MD5.cpp:51
void initializeCallGraphPrinterLegacyPassPass(PassRegistry &)
void removeAnyCallEdgeTo(CallGraphNode *Callee)
Removes all call edges from this node to the specified callee function.
Definition: CallGraph.cpp:218
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:107
The ModulePass which wraps up a CallGraph and the logic to build it.
Definition: CallGraph.h:328
bool isLeaf(ID id)
Returns true if the intrinsic is a leaf, i.e.
Definition: Function.cpp:932
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:653
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&...args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
Definition: STLExtras.h:845
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
void initializeCallGraphWrapperPassPass(PassRegistry &)
INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass,"print-callgraph","Print a call graph", true, true) INITIALIZE_PASS_END(CallGraphPrinterLegacyPass
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
Represent the analysis usage information of a pass.
CallGraph(Module &M)
Definition: CallGraph.cpp:23
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
~CallGraphWrapperPass() override
Definition: CallGraph.cpp:281
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:113
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:36
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
Definition: Module.h:478
InstrTy * getInstruction() const
Definition: CallSite.h:93
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Module.h This file contains the declarations for the Module class.
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Definition: CallGraph.cpp:263
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:146
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void setPreservesAll()
Set by analyses that do not transform their input at all.
void print(raw_ostream &OS) const
Definition: CallGraph.cpp:179
An analysis pass to compute the CallGraph for a Module.
Definition: CallGraph.h:298
pointer remove(iterator &IT)
Definition: ilist.h:264
The basic data container for the call graph of a Module of IR.
Definition: CallGraph.h:76
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Definition: Function.cpp:1171
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:188
print Print a call true
Definition: CallGraph.cpp:336
#define I(x, y, z)
Definition: MD5.cpp:54
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:235
AnalysisUsage & addRequiredTransitive()
bool hasLocalLinkage() const
Definition: GlobalValue.h:415
std::pair< WeakVH, CallGraphNode * > CallRecord
A pair of the calling instruction (a call or invoke) and the call graph node being called...
Definition: CallGraph.h:175
print Print a call graph
Definition: CallGraph.cpp:336
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:537
CallGraphNode * getOrInsertFunction(const Function *F)
Similar to operator[], but this will insert a new CallGraphNode for F if one does not already exist...
Definition: CallGraph.cpp:165
void removeCallEdgeFor(CallSite CS)
Removes the edge in the node for the specified call site.
Definition: CallGraph.cpp:203
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
A container for analyses that lazily runs them and caches their results.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: CallGraph.cpp:283
void print(raw_ostream &o, const Module *) const override
print - Print out the internal state of the pass.
Definition: CallGraph.cpp:300
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:64