LLVM  6.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/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), 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 
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;
37 }
38 
40  // CallsExternalNode is not in the function map, delete it explicitly.
41  if (CallsExternalNode)
42  CallsExternalNode->allReferencesDropped();
43 
44 // Reset all node's use counts to zero before deleting them to prevent an
45 // assertion from firing.
46 #ifndef NDEBUG
47  for (auto &I : FunctionMap)
48  I.second->allReferencesDropped();
49 #endif
50 }
51 
52 void CallGraph::addToCallGraph(Function *F) {
54 
55  // If this function has external linkage or has its address taken, anything
56  // could call it.
57  if (!F->hasLocalLinkage() || F->hasAddressTaken())
58  ExternalCallingNode->addCalledFunction(CallSite(), Node);
59 
60  // If this function is not defined in this translation unit, it could call
61  // anything.
62  if (F->isDeclaration() && !F->isIntrinsic())
63  Node->addCalledFunction(CallSite(), CallsExternalNode.get());
64 
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
73  // Intrinsic::isLeaf.
74  Node->addCalledFunction(CS, CallsExternalNode.get());
75  else if (!Callee->isIntrinsic())
76  Node->addCalledFunction(CS, getOrInsertFunction(Callee));
77  }
78  }
79 }
80 
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.
84 
86  Nodes.reserve(FunctionMap.size());
87 
88  for (const auto &I : *this)
89  Nodes.push_back(I.second.get());
90 
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();
96 
97  return RHS->getFunction() != nullptr;
98  });
99 
100  for (CallGraphNode *CN : Nodes)
101  CN->print(OS);
102 }
103 
104 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
106 #endif
107 
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.
113 //
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
119 
120  M.getFunctionList().remove(F);
121  return F;
122 }
123 
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.
128 ///
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);
137 }
138 
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.
143  auto &CGN = FunctionMap[F];
144  if (CGN)
145  return CGN.get();
146 
147  assert((!F || F->getParent() == &M) && "Function not in current module!");
148  CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F));
149  return CGN.get();
150 }
151 
152 //===----------------------------------------------------------------------===//
153 // Implementations of the CallGraphNode class methods.
154 //
155 
157  if (Function *F = getFunction())
158  OS << "Call graph node for function: '" << F->getName() << "'";
159  else
160  OS << "Call graph node <<null function>>";
161 
162  OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
163 
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";
168  else
169  OS << "external node\n";
170  }
171  OS << '\n';
172 }
173 
174 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
176 #endif
177 
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.
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();
188  return;
189  }
190  }
191 }
192 
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.
197  for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
198  if (CalledFunctions[i].second == Callee) {
199  Callee->DropRef();
200  CalledFunctions[i] = CalledFunctions.back();
201  CalledFunctions.pop_back();
202  --i; --e;
203  }
204 }
205 
206 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
207 /// from this node to the specified callee function.
209  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
210  assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
211  CallRecord &CR = *I;
212  if (CR.second == Callee && CR.first == nullptr) {
213  Callee->DropRef();
214  *I = CalledFunctions.back();
215  CalledFunctions.pop_back();
216  return;
217  }
218  }
219 }
220 
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.
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();
231  I->second = NewNode;
232  NewNode->AddRef();
233  return;
234  }
235  }
236 }
237 
238 // Provide an explicit template instantiation for the static ID.
239 AnalysisKey CallGraphAnalysis::Key;
240 
242  ModuleAnalysisManager &AM) {
243  AM.getResult<CallGraphAnalysis>(M).print(OS);
244  return PreservedAnalyses::all();
245 }
246 
247 //===----------------------------------------------------------------------===//
248 // Out-of-line definitions of CallGraphAnalysis class members.
249 //
250 
251 //===----------------------------------------------------------------------===//
252 // Implementations of the CallGraphWrapperPass class methods.
253 //
254 
257 }
258 
260 
262  AU.setPreservesAll();
263 }
264 
266  // All the real work is done in the constructor for the CallGraph.
267  G.reset(new CallGraph(M));
268  return false;
269 }
270 
271 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
272  false, true)
273 
274 char CallGraphWrapperPass::ID = 0;
275 
276 void CallGraphWrapperPass::releaseMemory() { G.reset(); }
277 
279  if (!G) {
280  OS << "No call graph has been built!\n";
281  return;
282  }
283 
284  // Just delegate.
285  G->print(OS);
286 }
287 
288 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
290 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
291 #endif
292 
293 namespace {
294 struct CallGraphPrinterLegacyPass : public ModulePass {
295  static char ID; // Pass ID, replacement for typeid
296  CallGraphPrinterLegacyPass() : ModulePass(ID) {
298  }
299 
300  void getAnalysisUsage(AnalysisUsage &AU) const override {
301  AU.setPreservesAll();
303  }
304  bool runOnModule(Module &M) override {
305  getAnalysis<CallGraphWrapperPass>().print(errs(), &M);
306  return false;
307  }
308 };
309 }
310 
312 
313 INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph",
314  "Print a call graph", true, true)
316 INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph",
317  "Print a call graph", true, true)
bool isIntrinsic() const
isIntrinsic - Returns true if the function&#39;s name starts with "llvm.".
Definition: Function.h:172
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool hasLocalLinkage() const
Definition: GlobalValue.h:416
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
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
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:449
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
unsigned second
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:943
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on...
Definition: CallGraph.cpp:265
void reserve(size_type N)
Definition: SmallVector.h:380
A node in the call graph for a module.
Definition: CallGraph.h:161
void removeOneAbstractEdgeTo(CallGraphNode *Callee)
Removes one edge associated with a null callsite from this node to the specified callee function...
Definition: CallGraph.cpp:208
void addCalledFunction(CallSite CS, CallGraphNode *M)
Adds a function to the list of functions called by this one.
Definition: CallGraph.h:226
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:165
print callgraph
Definition: CallGraph.cpp:316
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
Definition: BitVector.h:920
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:224
void print(raw_ostream &OS) const
Definition: CallGraph.cpp:156
ModulePass(char &pid)
Definition: Pass.h:250
Function * removeFunctionFromModule(CallGraphNode *CGN)
Unlink the function from this module, returning it.
Definition: CallGraph.cpp:114
InstrTy * getInstruction() const
Definition: CallSite.h:89
void dump() const
Print out this call graph node.
Definition: CallGraph.cpp:175
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:55
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:196
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:318
bool isLeaf(ID id)
Returns true if the intrinsic is a leaf, i.e.
Definition: Function.cpp:958
const FunctionListType & getFunctionList() const
Get the Module&#39;s list of functions (constant).
Definition: Module.h:507
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
void initializeCallGraphWrapperPassPass(PassRegistry &)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:116
Represent the analysis usage information of a pass.
CallGraph(Module &M)
Definition: CallGraph.cpp:23
~CallGraphWrapperPass() override
Definition: CallGraph.cpp:259
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
Function * getFunction() const
Returns the function that this call graph node represents.
Definition: CallGraph.h:181
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
Module.h This file contains the declarations for the Module class.
bool empty() const
Definition: CallGraph.h:187
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Definition: CallGraph.cpp:241
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:167
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
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.
An analysis pass to compute the CallGraph for a Module.
Definition: CallGraph.h:288
pointer remove(iterator &IT)
Definition: ilist.h:264
The basic data container for the call graph of a Module of IR.
Definition: CallGraph.h:70
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:120
print Print a call true
Definition: CallGraph.cpp:316
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:218
#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:235
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:200
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:1208
print Print a call graph
Definition: CallGraph.cpp:316
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:545
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:142
void removeCallEdgeFor(CallSite CS)
Removes the edge in the node for the specified call site.
Definition: CallGraph.cpp:181
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 sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition: Parallel.h:201
void dump() const
Definition: CallGraph.cpp:105
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: CallGraph.cpp:261
void print(raw_ostream &o, const Module *) const override
print - Print out the internal state of the pass.
Definition: CallGraph.cpp:278
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:81