LLVM  8.0.0svn
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/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/Config/llvm-config.h"
14 #include "llvm/IR/CallSite.h"
15 #include "llvm/IR/Module.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include "llvm/IR/PassManager.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/Debug.h"
23 #include <algorithm>
24 #include <cassert>
25 
26 using namespace llvm;
27 
28 //===----------------------------------------------------------------------===//
29 // Implementations of the CallGraph class methods.
30 //
31 
33  : M(M), ExternalCallingNode(getOrInsertFunction(nullptr)),
34  CallsExternalNode(llvm::make_unique<CallGraphNode>(nullptr)) {
35  // Add every function to the call graph.
36  for (Function &F : M)
37  addToCallGraph(&F);
38 }
39 
41  : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)),
42  ExternalCallingNode(Arg.ExternalCallingNode),
43  CallsExternalNode(std::move(Arg.CallsExternalNode)) {
44  Arg.FunctionMap.clear();
45  Arg.ExternalCallingNode = nullptr;
46 }
47 
49  // CallsExternalNode is not in the function map, delete it explicitly.
50  if (CallsExternalNode)
51  CallsExternalNode->allReferencesDropped();
52 
53 // Reset all node's use counts to zero before deleting them to prevent an
54 // assertion from firing.
55 #ifndef NDEBUG
56  for (auto &I : FunctionMap)
57  I.second->allReferencesDropped();
58 #endif
59 }
60 
61 void CallGraph::addToCallGraph(Function *F) {
63 
64  // If this function has external linkage or has its address taken, anything
65  // could call it.
66  if (!F->hasLocalLinkage() || F->hasAddressTaken())
67  ExternalCallingNode->addCalledFunction(CallSite(), Node);
68 
69  // If this function is not defined in this translation unit, it could call
70  // anything.
71  if (F->isDeclaration() && !F->isIntrinsic())
72  Node->addCalledFunction(CallSite(), CallsExternalNode.get());
73 
74  // Look for calls by this function.
75  for (BasicBlock &BB : *F)
76  for (Instruction &I : BB) {
77  if (auto CS = CallSite(&I)) {
78  const Function *Callee = CS.getCalledFunction();
79  if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
80  // Indirect calls of intrinsics are not allowed so no need to check.
81  // We can be more precise here by using TargetArg returned by
82  // Intrinsic::isLeaf.
83  Node->addCalledFunction(CS, CallsExternalNode.get());
84  else if (!Callee->isIntrinsic())
85  Node->addCalledFunction(CS, getOrInsertFunction(Callee));
86  }
87  }
88 }
89 
90 void CallGraph::print(raw_ostream &OS) const {
91  // Print in a deterministic order by sorting CallGraphNodes by name. We do
92  // this here to avoid slowing down the non-printing fast path.
93 
95  Nodes.reserve(FunctionMap.size());
96 
97  for (const auto &I : *this)
98  Nodes.push_back(I.second.get());
99 
100  llvm::sort(Nodes.begin(), Nodes.end(),
101  [](CallGraphNode *LHS, CallGraphNode *RHS) {
102  if (Function *LF = LHS->getFunction())
103  if (Function *RF = RHS->getFunction())
104  return LF->getName() < RF->getName();
105 
106  return RHS->getFunction() != nullptr;
107  });
108 
109  for (CallGraphNode *CN : Nodes)
110  CN->print(OS);
111 }
112 
113 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
115 #endif
116 
117 // removeFunctionFromModule - Unlink the function from this module, returning
118 // it. Because this removes the function from the module, the call graph node
119 // is destroyed. This is only valid if the function does not call any other
120 // functions (ie, there are no edges in it's CGN). The easiest way to do this
121 // is to dropAllReferences before calling this.
122 //
124  assert(CGN->empty() && "Cannot remove function from call "
125  "graph if it references other functions!");
126  Function *F = CGN->getFunction(); // Get the function for the call graph node
127  FunctionMap.erase(F); // Remove the call graph node from the map
128 
129  M.getFunctionList().remove(F);
130  return F;
131 }
132 
133 /// spliceFunction - Replace the function represented by this node by another.
134 /// This does not rescan the body of the function, so it is suitable when
135 /// splicing the body of the old function to the new while also updating all
136 /// callers from old to new.
137 void CallGraph::spliceFunction(const Function *From, const Function *To) {
138  assert(FunctionMap.count(From) && "No CallGraphNode for function!");
139  assert(!FunctionMap.count(To) &&
140  "Pointing CallGraphNode at a function that already exists");
141  FunctionMapTy::iterator I = FunctionMap.find(From);
142  I->second->F = const_cast<Function*>(To);
143  FunctionMap[To] = std::move(I->second);
144  FunctionMap.erase(I);
145 }
146 
147 // getOrInsertFunction - This method is identical to calling operator[], but
148 // it will insert a new CallGraphNode for the specified function if one does
149 // not already exist.
151  auto &CGN = FunctionMap[F];
152  if (CGN)
153  return CGN.get();
154 
155  assert((!F || F->getParent() == &M) && "Function not in current module!");
156  CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F));
157  return CGN.get();
158 }
159 
160 //===----------------------------------------------------------------------===//
161 // Implementations of the CallGraphNode class methods.
162 //
163 
165  if (Function *F = getFunction())
166  OS << "Call graph node for function: '" << F->getName() << "'";
167  else
168  OS << "Call graph node <<null function>>";
169 
170  OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
171 
172  for (const auto &I : *this) {
173  OS << " CS<" << I.first << "> calls ";
174  if (Function *FI = I.second->getFunction())
175  OS << "function '" << FI->getName() <<"'\n";
176  else
177  OS << "external node\n";
178  }
179  OS << '\n';
180 }
181 
182 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
184 #endif
185 
186 /// removeCallEdgeFor - This method removes the edge in the node for the
187 /// specified call site. Note that this method takes linear time, so it
188 /// should be used sparingly.
190  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
191  assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
192  if (I->first == CS.getInstruction()) {
193  I->second->DropRef();
194  *I = CalledFunctions.back();
195  CalledFunctions.pop_back();
196  return;
197  }
198  }
199 }
200 
201 // removeAnyCallEdgeTo - This method removes any call edges from this node to
202 // the specified callee function. This takes more time to execute than
203 // removeCallEdgeTo, so it should not be used unless necessary.
205  for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
206  if (CalledFunctions[i].second == Callee) {
207  Callee->DropRef();
208  CalledFunctions[i] = CalledFunctions.back();
209  CalledFunctions.pop_back();
210  --i; --e;
211  }
212 }
213 
214 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
215 /// from this node to the specified callee function.
217  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
218  assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
219  CallRecord &CR = *I;
220  if (CR.second == Callee && CR.first == nullptr) {
221  Callee->DropRef();
222  *I = CalledFunctions.back();
223  CalledFunctions.pop_back();
224  return;
225  }
226  }
227 }
228 
229 /// replaceCallEdge - This method replaces the edge in the node for the
230 /// specified call site with a new one. Note that this method takes linear
231 /// time, so it should be used sparingly.
233  CallSite NewCS, CallGraphNode *NewNode){
234  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
235  assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
236  if (I->first == CS.getInstruction()) {
237  I->second->DropRef();
238  I->first = NewCS.getInstruction();
239  I->second = NewNode;
240  NewNode->AddRef();
241  return;
242  }
243  }
244 }
245 
246 // Provide an explicit template instantiation for the static ID.
247 AnalysisKey CallGraphAnalysis::Key;
248 
250  ModuleAnalysisManager &AM) {
251  AM.getResult<CallGraphAnalysis>(M).print(OS);
252  return PreservedAnalyses::all();
253 }
254 
255 //===----------------------------------------------------------------------===//
256 // Out-of-line definitions of CallGraphAnalysis class members.
257 //
258 
259 //===----------------------------------------------------------------------===//
260 // Implementations of the CallGraphWrapperPass class methods.
261 //
262 
265 }
266 
268 
270  AU.setPreservesAll();
271 }
272 
274  // All the real work is done in the constructor for the CallGraph.
275  G.reset(new CallGraph(M));
276  return false;
277 }
278 
279 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
280  false, true)
281 
282 char CallGraphWrapperPass::ID = 0;
283 
284 void CallGraphWrapperPass::releaseMemory() { G.reset(); }
285 
287  if (!G) {
288  OS << "No call graph has been built!\n";
289  return;
290  }
291 
292  // Just delegate.
293  G->print(OS);
294 }
295 
296 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
298 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
299 #endif
300 
301 namespace {
302 
303 struct CallGraphPrinterLegacyPass : public ModulePass {
304  static char ID; // Pass ID, replacement for typeid
305 
306  CallGraphPrinterLegacyPass() : ModulePass(ID) {
308  }
309 
310  void getAnalysisUsage(AnalysisUsage &AU) const override {
311  AU.setPreservesAll();
313  }
314 
315  bool runOnModule(Module &M) override {
316  getAnalysis<CallGraphWrapperPass>().print(errs(), &M);
317  return false;
318  }
319 };
320 
321 } // end anonymous namespace
322 
324 
325 INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph",
326  "Print a call graph", true, true)
328 INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph",
329  "Print a call graph", true, true)
const Function & getFunction() const
Definition: Function.h:134
bool isIntrinsic() const
isIntrinsic - Returns true if the function&#39;s name starts with "llvm.".
Definition: Function.h:185
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool hasLocalLinkage() const
Definition: GlobalValue.h:435
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:687
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
unsigned second
F(f)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:452
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:1175
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on...
Definition: CallGraph.cpp:273
void reserve(size_type N)
Definition: SmallVector.h:376
A node in the call graph for a module.
Definition: CallGraph.h:165
void removeOneAbstractEdgeTo(CallGraphNode *Callee)
Removes one edge associated with a null callsite from this node to the specified callee function...
Definition: CallGraph.cpp:216
void addCalledFunction(CallSite CS, CallGraphNode *M)
Adds a function to the list of functions called by this one.
Definition: CallGraph.h:233
print callgraph
Definition: CallGraph.cpp:328
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
Definition: BitVector.h:921
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:232
void print(raw_ostream &OS) const
Definition: CallGraph.cpp:164
ModulePass(char &pid)
Definition: Pass.h:227
Function * removeFunctionFromModule(CallGraphNode *CGN)
Unlink the function from this module, returning it.
Definition: CallGraph.cpp:123
InstrTy * getInstruction() const
Definition: CallSite.h:92
void dump() const
Print out this call graph node.
Definition: CallGraph.cpp:183
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
static Function * getFunction(Constant *C)
Definition: Evaluator.cpp:221
amdgpu Simplify well known AMD library false Value * Callee
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void initializeCallGraphPrinterLegacyPassPass(PassRegistry &)
void removeAnyCallEdgeTo(CallGraphNode *Callee)
Removes all call edges from this node to the specified callee function.
Definition: CallGraph.cpp:204
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
The ModulePass which wraps up a CallGraph and the logic to build it.
Definition: CallGraph.h:324
bool isLeaf(ID id)
Returns true if the intrinsic is a leaf, i.e.
Definition: Function.cpp:990
const FunctionListType & getFunctionList() const
Get the Module&#39;s list of functions (constant).
Definition: Module.h:519
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
void initializeCallGraphWrapperPassPass(PassRegistry &)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:129
Represent the analysis usage information of a pass.
CallGraph(Module &M)
Definition: CallGraph.cpp:32
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:34
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:969
Function * getFunction() const
Returns the function that this call graph node represents.
Definition: CallGraph.h:188
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Module.h This file contains the declarations for the Module class.
bool empty() const
Definition: CallGraph.h:194
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Definition: CallGraph.cpp:249
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:180
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph", "Print a call graph", true, true) INITIALIZE_PASS_END(CallGraphPrinterLegacyPass
void setPreservesAll()
Set by analyses that do not transform their input at all.
amdgpu Simplify well known AMD library false Value Value * Arg
An analysis pass to compute the CallGraph for a Module.
Definition: CallGraph.h:292
pointer remove(iterator &IT)
Definition: ilist.h:251
The basic data container for the call graph of a Module of IR.
Definition: CallGraph.h:74
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:133
print Print a call true
Definition: CallGraph.cpp:328
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
std::pair< WeakTrackingVH, CallGraphNode * > CallRecord
A pair of the calling instruction (a call or invoke) and the call graph node being called...
Definition: CallGraph.h:169
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:225
AnalysisUsage & addRequiredTransitive()
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:201
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:1241
print Print a call graph
Definition: CallGraph.cpp:328
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
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:150
void removeCallEdgeFor(CallSite CS)
Removes the edge in the node for the specified call site.
Definition: CallGraph.cpp:189
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
A container for analyses that lazily runs them and caches their results.
void dump() const
Definition: CallGraph.cpp:114
This header defines various interfaces for pass management in LLVM.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: CallGraph.cpp:269
void print(raw_ostream &o, const Module *) const override
print - Print out the internal state of the pass.
Definition: CallGraph.cpp:286
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70
void print(raw_ostream &OS) const
Definition: CallGraph.cpp:90