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 /// The CallGraph class also attempts to figure out what the root of the
45 /// CallGraph is, which it currently does by looking for a function named
46 /// 'main'. If no function named 'main' is found, the external node is used as
47 /// the entry node, reflecting the fact that any function without internal
48 /// linkage could be called into (which is common for libraries).
50 //===----------------------------------------------------------------------===//
52 #ifndef LLVM_ANALYSIS_CALLGRAPH_H
53 #define LLVM_ANALYSIS_CALLGRAPH_H
55 #include "llvm/ADT/GraphTraits.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/IR/CallSite.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/ValueHandle.h"
60 #include "llvm/Pass.h"
69 /// \brief The basic data container for the call graph of a \c Module of IR.
71 /// This class exposes both the interface to the call graph for a module of IR.
73 /// The core call graph itself can also be updated to reflect changes to the IR.
77 typedef std::map<const Function *, CallGraphNode *> FunctionMapTy;
79 /// \brief A map from \c Function* to \c CallGraphNode*.
80 FunctionMapTy FunctionMap;
82 /// \brief Root is root of the call graph, or the external node if a 'main'
83 /// function couldn't be found.
86 /// \brief This node has edges to all external functions and those internal
87 /// functions that have their address taken.
88 CallGraphNode *ExternalCallingNode;
90 /// \brief This node has edges to it from all functions making indirect calls
91 /// or calling an external function.
92 CallGraphNode *CallsExternalNode;
94 /// \brief Replace the function represented by this node by another.
96 /// This does not rescan the body of the function, so it is suitable when
97 /// splicing the body of one function to another while also updating all
98 /// callers from the old function to the new.
99 void spliceFunction(const Function *From, const Function *To);
101 /// \brief Add a function to the call graph, and link the node to all of the
102 /// functions that it calls.
103 void addToCallGraph(Function *F);
106 CallGraph(Module &M);
109 void print(raw_ostream &OS) const;
112 typedef FunctionMapTy::iterator iterator;
113 typedef FunctionMapTy::const_iterator const_iterator;
115 /// \brief Returns the module the call graph corresponds to.
116 Module &getModule() const { return M; }
118 inline iterator begin() { return FunctionMap.begin(); }
119 inline iterator end() { return FunctionMap.end(); }
120 inline const_iterator begin() const { return FunctionMap.begin(); }
121 inline const_iterator end() const { return FunctionMap.end(); }
123 /// \brief Returns the call graph node for the provided function.
124 inline const CallGraphNode *operator[](const Function *F) const {
125 const_iterator I = FunctionMap.find(F);
126 assert(I != FunctionMap.end() && "Function not in callgraph!");
130 /// \brief Returns the call graph node for the provided function.
131 inline CallGraphNode *operator[](const Function *F) {
132 const_iterator I = FunctionMap.find(F);
133 assert(I != FunctionMap.end() && "Function not in callgraph!");
137 /// \brief Returns the \c CallGraphNode which is used to represent
138 /// undetermined calls into the callgraph.
139 CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
141 CallGraphNode *getCallsExternalNode() const { return CallsExternalNode; }
143 //===---------------------------------------------------------------------
144 // Functions to keep a call graph up to date with a function that has been
148 /// \brief Unlink the function from this module, returning it.
150 /// Because this removes the function from the module, the call graph node is
151 /// destroyed. This is only valid if the function does not call any other
152 /// functions (ie, there are no edges in it's CGN). The easiest way to do
153 /// this is to dropAllReferences before calling this.
154 Function *removeFunctionFromModule(CallGraphNode *CGN);
156 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
157 /// \c F if one does not already exist.
158 CallGraphNode *getOrInsertFunction(const Function *F);
161 /// \brief A node in the call graph for a module.
163 /// Typically represents a function in the call graph. There are also special
164 /// "null" nodes used to represent theoretical entries in the call graph.
165 class CallGraphNode {
167 /// \brief A pair of the calling instruction (a call or invoke)
168 /// and the call graph node being called.
169 typedef std::pair<WeakVH, CallGraphNode *> CallRecord;
172 typedef std::vector<CallRecord> CalledFunctionsVector;
174 /// \brief Creates a node for the specified function.
175 inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
178 assert(NumReferences == 0 && "Node deleted while references remain");
181 typedef std::vector<CallRecord>::iterator iterator;
182 typedef std::vector<CallRecord>::const_iterator const_iterator;
184 /// \brief Returns the function that this call graph node represents.
185 Function *getFunction() const { return F; }
187 inline iterator begin() { return CalledFunctions.begin(); }
188 inline iterator end() { return CalledFunctions.end(); }
189 inline const_iterator begin() const { return CalledFunctions.begin(); }
190 inline const_iterator end() const { return CalledFunctions.end(); }
191 inline bool empty() const { return CalledFunctions.empty(); }
192 inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
194 /// \brief Returns the number of other CallGraphNodes in this CallGraph that
195 /// reference this node in their callee list.
196 unsigned getNumReferences() const { return NumReferences; }
198 /// \brief Returns the i'th called function.
199 CallGraphNode *operator[](unsigned i) const {
200 assert(i < CalledFunctions.size() && "Invalid index");
201 return CalledFunctions[i].second;
204 /// \brief Print out this call graph node.
206 void print(raw_ostream &OS) const;
208 //===---------------------------------------------------------------------
209 // Methods to keep a call graph up to date with a function that has been
213 /// \brief Removes all edges from this CallGraphNode to any functions it
215 void removeAllCalledFunctions() {
216 while (!CalledFunctions.empty()) {
217 CalledFunctions.back().second->DropRef();
218 CalledFunctions.pop_back();
222 /// \brief Moves all the callee information from N to this node.
223 void stealCalledFunctionsFrom(CallGraphNode *N) {
224 assert(CalledFunctions.empty() &&
225 "Cannot steal callsite information if I already have some");
226 std::swap(CalledFunctions, N->CalledFunctions);
229 /// \brief Adds a function to the list of functions called by this one.
230 void addCalledFunction(CallSite CS, CallGraphNode *M) {
231 assert(!CS.getInstruction() || !CS.getCalledFunction() ||
232 !CS.getCalledFunction()->isIntrinsic());
233 CalledFunctions.push_back(std::make_pair(CS.getInstruction(), M));
237 void removeCallEdge(iterator I) {
238 I->second->DropRef();
239 *I = CalledFunctions.back();
240 CalledFunctions.pop_back();
243 /// \brief Removes the edge in the node for the specified call site.
245 /// Note that this method takes linear time, so it should be used sparingly.
246 void removeCallEdgeFor(CallSite CS);
248 /// \brief Removes all call edges from this node to the specified callee
251 /// This takes more time to execute than removeCallEdgeTo, so it should not
252 /// be used unless necessary.
253 void removeAnyCallEdgeTo(CallGraphNode *Callee);
255 /// \brief Removes one edge associated with a null callsite from this node to
256 /// the specified callee function.
257 void removeOneAbstractEdgeTo(CallGraphNode *Callee);
259 /// \brief Replaces the edge in the node for the specified call site with a
262 /// Note that this method takes linear time, so it should be used sparingly.
263 void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
266 friend class CallGraph;
268 AssertingVH<Function> F;
270 std::vector<CallRecord> CalledFunctions;
272 /// \brief The number of times that this CallGraphNode occurs in the
273 /// CalledFunctions array of this or other CallGraphNodes.
274 unsigned NumReferences;
276 CallGraphNode(const CallGraphNode &) = delete;
277 void operator=(const CallGraphNode &) = delete;
279 void DropRef() { --NumReferences; }
280 void AddRef() { ++NumReferences; }
282 /// \brief A special function that should only be used by the CallGraph class.
283 void allReferencesDropped() { NumReferences = 0; }
286 /// \brief An analysis pass to compute the \c CallGraph for a \c Module.
288 /// This class implements the concept of an analysis pass used by the \c
289 /// ModuleAnalysisManager to run an analysis over a module and cache the
291 class CallGraphAnalysis {
293 /// \brief A formulaic typedef to inform clients of the result type.
294 typedef CallGraph Result;
296 static void *ID() { return (void *)&PassID; }
298 /// \brief Compute the \c CallGraph for the module \c M.
300 /// The real work here is done in the \c CallGraph constructor.
301 CallGraph run(Module *M) { return CallGraph(*M); }
307 /// \brief The \c ModulePass which wraps up a \c CallGraph and the logic to
310 /// This class exposes both the interface to the call graph container and the
311 /// module pass which runs over a module of IR and produces the call graph. The
312 /// call graph interface is entirelly a wrapper around a \c CallGraph object
313 /// which is stored internally for each module.
314 class CallGraphWrapperPass : public ModulePass {
315 std::unique_ptr<CallGraph> G;
318 static char ID; // Class identification, replacement for typeinfo
320 CallGraphWrapperPass();
321 virtual ~CallGraphWrapperPass();
323 /// \brief The internal \c CallGraph around which the rest of this interface
325 const CallGraph &getCallGraph() const { return *G; }
326 CallGraph &getCallGraph() { return *G; }
328 typedef CallGraph::iterator iterator;
329 typedef CallGraph::const_iterator const_iterator;
331 /// \brief Returns the module the call graph corresponds to.
332 Module &getModule() const { return G->getModule(); }
334 inline iterator begin() { return G->begin(); }
335 inline iterator end() { return G->end(); }
336 inline const_iterator begin() const { return G->begin(); }
337 inline const_iterator end() const { return G->end(); }
339 /// \brief Returns the call graph node for the provided function.
340 inline const CallGraphNode *operator[](const Function *F) const {
344 /// \brief Returns the call graph node for the provided function.
345 inline CallGraphNode *operator[](const Function *F) { return (*G)[F]; }
347 /// \brief Returns the \c CallGraphNode which is used to represent
348 /// undetermined calls into the callgraph.
349 CallGraphNode *getExternalCallingNode() const {
350 return G->getExternalCallingNode();
353 CallGraphNode *getCallsExternalNode() const {
354 return G->getCallsExternalNode();
357 //===---------------------------------------------------------------------
358 // Functions to keep a call graph up to date with a function that has been
362 /// \brief Unlink the function from this module, returning it.
364 /// Because this removes the function from the module, the call graph node is
365 /// destroyed. This is only valid if the function does not call any other
366 /// functions (ie, there are no edges in it's CGN). The easiest way to do
367 /// this is to dropAllReferences before calling this.
368 Function *removeFunctionFromModule(CallGraphNode *CGN) {
369 return G->removeFunctionFromModule(CGN);
372 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
373 /// \c F if one does not already exist.
374 CallGraphNode *getOrInsertFunction(const Function *F) {
375 return G->getOrInsertFunction(F);
378 //===---------------------------------------------------------------------
379 // Implementation of the ModulePass interface needed here.
382 void getAnalysisUsage(AnalysisUsage &AU) const override;
383 bool runOnModule(Module &M) override;
384 void releaseMemory() override;
386 void print(raw_ostream &o, const Module *) const override;
390 //===----------------------------------------------------------------------===//
391 // GraphTraits specializations for call graphs so that they can be treated as
392 // graphs by the generic graph algorithms.
395 // Provide graph traits for tranversing call graphs using standard graph
397 template <> struct GraphTraits<CallGraphNode *> {
398 typedef CallGraphNode NodeType;
400 typedef CallGraphNode::CallRecord CGNPairTy;
401 typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode *>
404 static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
406 typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
408 static inline ChildIteratorType child_begin(NodeType *N) {
409 return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
411 static inline ChildIteratorType child_end(NodeType *N) {
412 return map_iterator(N->end(), CGNDerefFun(CGNDeref));
415 static CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
418 template <> struct GraphTraits<const CallGraphNode *> {
419 typedef const CallGraphNode NodeType;
421 typedef CallGraphNode::CallRecord CGNPairTy;
422 typedef std::pointer_to_unary_function<CGNPairTy, const CallGraphNode *>
425 static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
427 typedef mapped_iterator<NodeType::const_iterator, CGNDerefFun>
430 static inline ChildIteratorType child_begin(NodeType *N) {
431 return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
433 static inline ChildIteratorType child_end(NodeType *N) {
434 return map_iterator(N->end(), CGNDerefFun(CGNDeref));
437 static const CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
441 struct GraphTraits<CallGraph *> : public GraphTraits<CallGraphNode *> {
442 static NodeType *getEntryNode(CallGraph *CGN) {
443 return CGN->getExternalCallingNode(); // Start at the external node!
445 typedef std::pair<const Function *, CallGraphNode *> PairTy;
446 typedef std::pointer_to_unary_function<PairTy, CallGraphNode &> DerefFun;
448 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
449 typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
450 static nodes_iterator nodes_begin(CallGraph *CG) {
451 return map_iterator(CG->begin(), DerefFun(CGdereference));
453 static nodes_iterator nodes_end(CallGraph *CG) {
454 return map_iterator(CG->end(), DerefFun(CGdereference));
457 static CallGraphNode &CGdereference(PairTy P) { return *P.second; }
461 struct GraphTraits<const CallGraph *> : public GraphTraits<
462 const CallGraphNode *> {
463 static NodeType *getEntryNode(const CallGraph *CGN) {
464 return CGN->getExternalCallingNode(); // Start at the external node!
466 typedef std::pair<const Function *, const CallGraphNode *> PairTy;
467 typedef std::pointer_to_unary_function<PairTy, const CallGraphNode &>
470 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
471 typedef mapped_iterator<CallGraph::const_iterator, DerefFun> nodes_iterator;
472 static nodes_iterator nodes_begin(const CallGraph *CG) {
473 return map_iterator(CG->begin(), DerefFun(CGdereference));
475 static nodes_iterator nodes_end(const CallGraph *CG) {
476 return map_iterator(CG->end(), DerefFun(CGdereference));
479 static const CallGraphNode &CGdereference(PairTy P) { return *P.second; }
482 } // End llvm namespace