1 //===- CallGraph.h - Build a Module's call graph ----------------*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
11 /// This file provides interfaces used to build and manipulate a call graph,
12 /// which is a very useful tool for interprocedural optimization.
14 /// Every function in a module is represented as a node in the call graph. The
15 /// callgraph node keeps track of which functions are called by the function
16 /// corresponding to the node.
18 /// A call graph may contain nodes where the function that they correspond to
19 /// is null. These 'external' nodes are used to represent control flow that is
20 /// not represented (or analyzable) in the module. In particular, this
21 /// analysis builds one external node such that:
22 /// 1. All functions in the module without internal linkage will have edges
23 /// from this external node, indicating that they could be called by
24 /// functions outside of the module.
25 /// 2. All functions whose address is used for something more than a direct
26 /// call, for example being stored into a memory location will also have
27 /// an edge from this external node. Since they may be called by an
28 /// unknown caller later, they must be tracked as such.
30 /// There is a second external node added for calls that leave this module.
31 /// Functions have a call edge to the external node iff:
32 /// 1. The function is external, reflecting the fact that they could call
33 /// anything without internal linkage or that has its address taken.
34 /// 2. The function contains an indirect function call.
36 /// As an extension in the future, there may be multiple nodes with a null
37 /// function. These will be used when we can prove (through pointer analysis)
38 /// that an indirect call site can call only a specific set of functions.
40 /// Because of these properties, the CallGraph captures a conservative superset
41 /// of all of the caller-callee relationships, which is useful for
44 //===----------------------------------------------------------------------===//
46 #ifndef LLVM_ANALYSIS_CALLGRAPH_H
47 #define LLVM_ANALYSIS_CALLGRAPH_H
49 #include "llvm/ADT/GraphTraits.h"
50 #include "llvm/ADT/STLExtras.h"
51 #include "llvm/IR/CallSite.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/PassManager.h"
55 #include "llvm/IR/ValueHandle.h"
56 #include "llvm/Pass.h"
65 /// \brief The basic data container for the call graph of a \c Module of IR.
67 /// This class exposes both the interface to the call graph for a module of IR.
69 /// The core call graph itself can also be updated to reflect changes to the IR.
73 typedef std::map<const Function *, std::unique_ptr<CallGraphNode>>
76 /// \brief A map from \c Function* to \c CallGraphNode*.
77 FunctionMapTy FunctionMap;
79 /// \brief This node has edges to all external functions and those internal
80 /// functions that have their address taken.
81 CallGraphNode *ExternalCallingNode;
83 /// \brief This node has edges to it from all functions making indirect calls
84 /// or calling an external function.
85 std::unique_ptr<CallGraphNode> CallsExternalNode;
87 /// \brief Replace the function represented by this node by another.
89 /// This does not rescan the body of the function, so it is suitable when
90 /// splicing the body of one function to another while also updating all
91 /// callers from the old function to the new.
92 void spliceFunction(const Function *From, const Function *To);
94 /// \brief Add a function to the call graph, and link the node to all of the
95 /// functions that it calls.
96 void addToCallGraph(Function *F);
99 explicit CallGraph(Module &M);
100 CallGraph(CallGraph &&Arg);
103 void print(raw_ostream &OS) const;
106 typedef FunctionMapTy::iterator iterator;
107 typedef FunctionMapTy::const_iterator const_iterator;
109 /// \brief Returns the module the call graph corresponds to.
110 Module &getModule() const { return M; }
112 inline iterator begin() { return FunctionMap.begin(); }
113 inline iterator end() { return FunctionMap.end(); }
114 inline const_iterator begin() const { return FunctionMap.begin(); }
115 inline const_iterator end() const { return FunctionMap.end(); }
117 /// \brief Returns the call graph node for the provided function.
118 inline const CallGraphNode *operator[](const Function *F) const {
119 const_iterator I = FunctionMap.find(F);
120 assert(I != FunctionMap.end() && "Function not in callgraph!");
121 return I->second.get();
124 /// \brief Returns the call graph node for the provided function.
125 inline CallGraphNode *operator[](const Function *F) {
126 const_iterator I = FunctionMap.find(F);
127 assert(I != FunctionMap.end() && "Function not in callgraph!");
128 return I->second.get();
131 /// \brief Returns the \c CallGraphNode which is used to represent
132 /// undetermined calls into the callgraph.
133 CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
135 CallGraphNode *getCallsExternalNode() const {
136 return CallsExternalNode.get();
139 //===---------------------------------------------------------------------
140 // Functions to keep a call graph up to date with a function that has been
144 /// \brief Unlink the function from this module, returning it.
146 /// Because this removes the function from the module, the call graph node is
147 /// destroyed. This is only valid if the function does not call any other
148 /// functions (ie, there are no edges in it's CGN). The easiest way to do
149 /// this is to dropAllReferences before calling this.
150 Function *removeFunctionFromModule(CallGraphNode *CGN);
152 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
153 /// \c F if one does not already exist.
154 CallGraphNode *getOrInsertFunction(const Function *F);
157 /// \brief A node in the call graph for a module.
159 /// Typically represents a function in the call graph. There are also special
160 /// "null" nodes used to represent theoretical entries in the call graph.
161 class CallGraphNode {
163 /// \brief A pair of the calling instruction (a call or invoke)
164 /// and the call graph node being called.
165 typedef std::pair<WeakTrackingVH, CallGraphNode *> CallRecord;
168 typedef std::vector<CallRecord> CalledFunctionsVector;
170 /// \brief Creates a node for the specified function.
171 inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
174 assert(NumReferences == 0 && "Node deleted while references remain");
177 typedef std::vector<CallRecord>::iterator iterator;
178 typedef std::vector<CallRecord>::const_iterator const_iterator;
180 /// \brief Returns the function that this call graph node represents.
181 Function *getFunction() const { return F; }
183 inline iterator begin() { return CalledFunctions.begin(); }
184 inline iterator end() { return CalledFunctions.end(); }
185 inline const_iterator begin() const { return CalledFunctions.begin(); }
186 inline const_iterator end() const { return CalledFunctions.end(); }
187 inline bool empty() const { return CalledFunctions.empty(); }
188 inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
190 /// \brief Returns the number of other CallGraphNodes in this CallGraph that
191 /// reference this node in their callee list.
192 unsigned getNumReferences() const { return NumReferences; }
194 /// \brief Returns the i'th called function.
195 CallGraphNode *operator[](unsigned i) const {
196 assert(i < CalledFunctions.size() && "Invalid index");
197 return CalledFunctions[i].second;
200 /// \brief Print out this call graph node.
202 void print(raw_ostream &OS) const;
204 //===---------------------------------------------------------------------
205 // Methods to keep a call graph up to date with a function that has been
209 /// \brief Removes all edges from this CallGraphNode to any functions it
211 void removeAllCalledFunctions() {
212 while (!CalledFunctions.empty()) {
213 CalledFunctions.back().second->DropRef();
214 CalledFunctions.pop_back();
218 /// \brief Moves all the callee information from N to this node.
219 void stealCalledFunctionsFrom(CallGraphNode *N) {
220 assert(CalledFunctions.empty() &&
221 "Cannot steal callsite information if I already have some");
222 std::swap(CalledFunctions, N->CalledFunctions);
225 /// \brief Adds a function to the list of functions called by this one.
226 void addCalledFunction(CallSite CS, CallGraphNode *M) {
227 assert(!CS.getInstruction() || !CS.getCalledFunction() ||
228 !CS.getCalledFunction()->isIntrinsic() ||
229 !Intrinsic::isLeaf(CS.getCalledFunction()->getIntrinsicID()));
230 CalledFunctions.emplace_back(CS.getInstruction(), M);
234 void removeCallEdge(iterator I) {
235 I->second->DropRef();
236 *I = CalledFunctions.back();
237 CalledFunctions.pop_back();
240 /// \brief Removes the edge in the node for the specified call site.
242 /// Note that this method takes linear time, so it should be used sparingly.
243 void removeCallEdgeFor(CallSite CS);
245 /// \brief Removes all call edges from this node to the specified callee
248 /// This takes more time to execute than removeCallEdgeTo, so it should not
249 /// be used unless necessary.
250 void removeAnyCallEdgeTo(CallGraphNode *Callee);
252 /// \brief Removes one edge associated with a null callsite from this node to
253 /// the specified callee function.
254 void removeOneAbstractEdgeTo(CallGraphNode *Callee);
256 /// \brief Replaces the edge in the node for the specified call site with a
259 /// Note that this method takes linear time, so it should be used sparingly.
260 void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
263 friend class CallGraph;
267 std::vector<CallRecord> CalledFunctions;
269 /// \brief The number of times that this CallGraphNode occurs in the
270 /// CalledFunctions array of this or other CallGraphNodes.
271 unsigned NumReferences;
273 CallGraphNode(const CallGraphNode &) = delete;
274 void operator=(const CallGraphNode &) = delete;
276 void DropRef() { --NumReferences; }
277 void AddRef() { ++NumReferences; }
279 /// \brief A special function that should only be used by the CallGraph class.
280 void allReferencesDropped() { NumReferences = 0; }
283 /// \brief An analysis pass to compute the \c CallGraph for a \c Module.
285 /// This class implements the concept of an analysis pass used by the \c
286 /// ModuleAnalysisManager to run an analysis over a module and cache the
288 class CallGraphAnalysis : public AnalysisInfoMixin<CallGraphAnalysis> {
289 friend AnalysisInfoMixin<CallGraphAnalysis>;
290 static AnalysisKey Key;
293 /// \brief A formulaic typedef to inform clients of the result type.
294 typedef CallGraph Result;
296 /// \brief Compute the \c CallGraph for the module \c M.
298 /// The real work here is done in the \c CallGraph constructor.
299 CallGraph run(Module &M, ModuleAnalysisManager &) { return CallGraph(M); }
302 /// \brief Printer pass for the \c CallGraphAnalysis results.
303 class CallGraphPrinterPass : public PassInfoMixin<CallGraphPrinterPass> {
307 explicit CallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
308 PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
311 /// \brief The \c ModulePass which wraps up a \c CallGraph and the logic to
314 /// This class exposes both the interface to the call graph container and the
315 /// module pass which runs over a module of IR and produces the call graph. The
316 /// call graph interface is entirelly a wrapper around a \c CallGraph object
317 /// which is stored internally for each module.
318 class CallGraphWrapperPass : public ModulePass {
319 std::unique_ptr<CallGraph> G;
322 static char ID; // Class identification, replacement for typeinfo
324 CallGraphWrapperPass();
325 ~CallGraphWrapperPass() override;
327 /// \brief The internal \c CallGraph around which the rest of this interface
329 const CallGraph &getCallGraph() const { return *G; }
330 CallGraph &getCallGraph() { return *G; }
332 typedef CallGraph::iterator iterator;
333 typedef CallGraph::const_iterator const_iterator;
335 /// \brief Returns the module the call graph corresponds to.
336 Module &getModule() const { return G->getModule(); }
338 inline iterator begin() { return G->begin(); }
339 inline iterator end() { return G->end(); }
340 inline const_iterator begin() const { return G->begin(); }
341 inline const_iterator end() const { return G->end(); }
343 /// \brief Returns the call graph node for the provided function.
344 inline const CallGraphNode *operator[](const Function *F) const {
348 /// \brief Returns the call graph node for the provided function.
349 inline CallGraphNode *operator[](const Function *F) { return (*G)[F]; }
351 /// \brief Returns the \c CallGraphNode which is used to represent
352 /// undetermined calls into the callgraph.
353 CallGraphNode *getExternalCallingNode() const {
354 return G->getExternalCallingNode();
357 CallGraphNode *getCallsExternalNode() const {
358 return G->getCallsExternalNode();
361 //===---------------------------------------------------------------------
362 // Functions to keep a call graph up to date with a function that has been
366 /// \brief Unlink the function from this module, returning it.
368 /// Because this removes the function from the module, the call graph node is
369 /// destroyed. This is only valid if the function does not call any other
370 /// functions (ie, there are no edges in it's CGN). The easiest way to do
371 /// this is to dropAllReferences before calling this.
372 Function *removeFunctionFromModule(CallGraphNode *CGN) {
373 return G->removeFunctionFromModule(CGN);
376 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
377 /// \c F if one does not already exist.
378 CallGraphNode *getOrInsertFunction(const Function *F) {
379 return G->getOrInsertFunction(F);
382 //===---------------------------------------------------------------------
383 // Implementation of the ModulePass interface needed here.
386 void getAnalysisUsage(AnalysisUsage &AU) const override;
387 bool runOnModule(Module &M) override;
388 void releaseMemory() override;
390 void print(raw_ostream &o, const Module *) const override;
394 //===----------------------------------------------------------------------===//
395 // GraphTraits specializations for call graphs so that they can be treated as
396 // graphs by the generic graph algorithms.
399 // Provide graph traits for tranversing call graphs using standard graph
401 template <> struct GraphTraits<CallGraphNode *> {
402 typedef CallGraphNode *NodeRef;
404 typedef CallGraphNode::CallRecord CGNPairTy;
406 static NodeRef getEntryNode(CallGraphNode *CGN) { return CGN; }
408 static CallGraphNode *CGNGetValue(CGNPairTy P) { return P.second; }
410 typedef mapped_iterator<CallGraphNode::iterator, decltype(&CGNGetValue)>
413 static ChildIteratorType child_begin(NodeRef N) {
414 return ChildIteratorType(N->begin(), &CGNGetValue);
416 static ChildIteratorType child_end(NodeRef N) {
417 return ChildIteratorType(N->end(), &CGNGetValue);
421 template <> struct GraphTraits<const CallGraphNode *> {
422 typedef const CallGraphNode *NodeRef;
424 typedef CallGraphNode::CallRecord CGNPairTy;
426 static NodeRef getEntryNode(const CallGraphNode *CGN) { return CGN; }
428 static const CallGraphNode *CGNGetValue(CGNPairTy P) { return P.second; }
430 typedef mapped_iterator<CallGraphNode::const_iterator, decltype(&CGNGetValue)>
433 static ChildIteratorType child_begin(NodeRef N) {
434 return ChildIteratorType(N->begin(), &CGNGetValue);
436 static ChildIteratorType child_end(NodeRef N) {
437 return ChildIteratorType(N->end(), &CGNGetValue);
442 struct GraphTraits<CallGraph *> : public GraphTraits<CallGraphNode *> {
443 static NodeRef getEntryNode(CallGraph *CGN) {
444 return CGN->getExternalCallingNode(); // Start at the external node!
446 typedef std::pair<const Function *const, std::unique_ptr<CallGraphNode>>
448 static CallGraphNode *CGGetValuePtr(const PairTy &P) {
449 return P.second.get();
452 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
453 typedef mapped_iterator<CallGraph::iterator, decltype(&CGGetValuePtr)>
455 static nodes_iterator nodes_begin(CallGraph *CG) {
456 return nodes_iterator(CG->begin(), &CGGetValuePtr);
458 static nodes_iterator nodes_end(CallGraph *CG) {
459 return nodes_iterator(CG->end(), &CGGetValuePtr);
464 struct GraphTraits<const CallGraph *> : public GraphTraits<
465 const CallGraphNode *> {
466 static NodeRef getEntryNode(const CallGraph *CGN) {
467 return CGN->getExternalCallingNode(); // Start at the external node!
469 typedef std::pair<const Function *const, std::unique_ptr<CallGraphNode>>
471 static const CallGraphNode *CGGetValuePtr(const PairTy &P) {
472 return P.second.get();
475 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
476 typedef mapped_iterator<CallGraph::const_iterator, decltype(&CGGetValuePtr)>
478 static nodes_iterator nodes_begin(const CallGraph *CG) {
479 return nodes_iterator(CG->begin(), &CGGetValuePtr);
481 static nodes_iterator nodes_end(const CallGraph *CG) {
482 return nodes_iterator(CG->end(), &CGGetValuePtr);
486 } // End llvm namespace