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 //===----------------------------------------------------------------------===//
10 // This interface is used to build and manipulate a call graph, which is a very
11 // useful tool for interprocedural optimization.
13 // Every function in a module is represented as a node in the call graph. The
14 // callgraph node keeps track of which functions the are called by the function
15 // corresponding to the node.
17 // A call graph may contain nodes where the function that they correspond to is
18 // null. These 'external' nodes are used to represent control flow that is not
19 // represented (or analyzable) in the module. In particular, this analysis
20 // builds one external node such that:
21 // 1. All functions in the module without internal linkage will have edges
22 // from this external node, indicating that they could be called by
23 // functions outside of the module.
24 // 2. All functions whose address is used for something more than a direct
25 // call, for example being stored into a memory location will also have an
26 // edge from this external node. Since they may be called by an unknown
27 // caller later, they must be tracked as such.
29 // There is a second external node added for calls that leave this module.
30 // Functions have a call edge to the external node iff:
31 // 1. The function is external, reflecting the fact that they could call
32 // anything without internal linkage or that has its address taken.
33 // 2. The function contains an indirect function call.
35 // As an extension in the future, there may be multiple nodes with a null
36 // function. These will be used when we can prove (through pointer analysis)
37 // that an indirect call site can call only a specific set of functions.
39 // Because of these properties, the CallGraph captures a conservative superset
40 // of all of the caller-callee relationships, which is useful for
43 // The CallGraph class also attempts to figure out what the root of the
44 // CallGraph is, which it currently does by looking for a function named 'main'.
45 // If no function named 'main' is found, the external node is used as the entry
46 // node, reflecting the fact that any function without internal linkage could
47 // be called into (which is common for libraries).
49 //===----------------------------------------------------------------------===//
51 #ifndef LLVM_ANALYSIS_CALLGRAPH_H
52 #define LLVM_ANALYSIS_CALLGRAPH_H
54 #include "llvm/ADT/GraphTraits.h"
55 #include "llvm/ADT/STLExtras.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/CallSite.h"
59 #include "llvm/Support/IncludeFile.h"
60 #include "llvm/Support/ValueHandle.h"
69 /// \brief The basic data container for the call graph and the \c ModulePass
70 /// which produces it.
72 /// This class exposes both the interface to the call graph container and the
73 /// module pass which runs over a module of IR and produces the call graph.
75 /// The core call graph itself can also be updated to reflect changes to the IR.
76 class CallGraph : public ModulePass {
77 Module *Mod; // The module this call graph represents
79 typedef std::map<const Function *, CallGraphNode *> FunctionMapTy;
80 FunctionMapTy FunctionMap; // Map from a function to its node
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 static char ID; // Class identification, replacement for typeinfo
108 typedef FunctionMapTy::iterator iterator;
109 typedef FunctionMapTy::const_iterator const_iterator;
111 /// \brief Returns the module the call graph corresponds to.
112 Module &getModule() const { return *Mod; }
114 inline iterator begin() { return FunctionMap.begin(); }
115 inline iterator end() { return FunctionMap.end(); }
116 inline const_iterator begin() const { return FunctionMap.begin(); }
117 inline const_iterator end() const { return FunctionMap.end(); }
119 /// \brief Returns the call graph node for the provided function.
120 inline const CallGraphNode *operator[](const Function *F) const {
121 const_iterator I = FunctionMap.find(F);
122 assert(I != FunctionMap.end() && "Function not in callgraph!");
126 /// \brief Returns the call graph node for the provided function.
127 inline CallGraphNode *operator[](const Function *F) {
128 const_iterator I = FunctionMap.find(F);
129 assert(I != FunctionMap.end() && "Function not in callgraph!");
133 /// \brief Returns the \c CallGraphNode which is used to represent
134 /// undetermined calls into the callgraph.
135 CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
137 CallGraphNode *getCallsExternalNode() const { return CallsExternalNode; }
139 /// \brief Returns the root/main method in the module, or some other root
140 /// node, such as the externalcallingnode.
141 CallGraphNode *getRoot() { return Root; }
142 const CallGraphNode *getRoot() const { return Root; }
144 //===---------------------------------------------------------------------
145 // Functions to keep a call graph up to date with a function that has been
149 /// \brief Unlink the function from this module, returning it.
151 /// Because this removes the function from the module, the call graph node is
152 /// destroyed. This is only valid if the function does not call any other
153 /// functions (ie, there are no edges in it's CGN). The easiest way to do
154 /// this is to dropAllReferences before calling this.
155 Function *removeFunctionFromModule(CallGraphNode *CGN);
157 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
158 /// \c F if one does not already exist.
159 CallGraphNode *getOrInsertFunction(const Function *F);
162 virtual ~CallGraph() { releaseMemory(); }
164 //===---------------------------------------------------------------------
165 // Implementation of the ModulePass interface needed here.
168 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
169 virtual bool runOnModule(Module &M);
170 virtual void releaseMemory();
172 void print(raw_ostream &o, const Module *) const;
176 /// \brief A node in the call graph for a module.
178 /// Typically represents a function in the call graph. There are also special
179 /// "null" nodes used to represent theoretical entries in the call graph.
180 class CallGraphNode {
181 friend class CallGraph;
183 AssertingVH<Function> F;
186 /// \brief A pair of the calling instruction (a call or invoke)
187 /// and the call graph node being called.
188 typedef std::pair<WeakVH, CallGraphNode*> CallRecord;
191 std::vector<CallRecord> CalledFunctions;
193 /// \brief The number of times that this CallGraphNode occurs in the
194 /// CalledFunctions array of this or other CallGraphNodes.
195 unsigned NumReferences;
197 CallGraphNode(const CallGraphNode &) LLVM_DELETED_FUNCTION;
198 void operator=(const CallGraphNode &) LLVM_DELETED_FUNCTION;
200 void DropRef() { --NumReferences; }
201 void AddRef() { ++NumReferences; }
204 typedef std::vector<CallRecord> CalledFunctionsVector;
206 /// \brief Creates a node for the specified function.
207 inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
210 assert(NumReferences == 0 && "Node deleted while references remain");
213 typedef std::vector<CallRecord>::iterator iterator;
214 typedef std::vector<CallRecord>::const_iterator const_iterator;
216 /// \brief Returns the function that this call graph node represents.
217 Function *getFunction() const { return F; }
219 inline iterator begin() { return CalledFunctions.begin(); }
220 inline iterator end() { return CalledFunctions.end(); }
221 inline const_iterator begin() const { return CalledFunctions.begin(); }
222 inline const_iterator end() const { return CalledFunctions.end(); }
223 inline bool empty() const { return CalledFunctions.empty(); }
224 inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
226 /// \brief Returns the number of other CallGraphNodes in this CallGraph that
227 /// reference this node in their callee list.
228 unsigned getNumReferences() const { return NumReferences; }
230 /// \brief Returns the i'th called function.
231 CallGraphNode *operator[](unsigned i) const {
232 assert(i < CalledFunctions.size() && "Invalid index");
233 return CalledFunctions[i].second;
236 /// \brief Print out this call graph node.
238 void print(raw_ostream &OS) const;
240 //===---------------------------------------------------------------------
241 // Methods to keep a call graph up to date with a function that has been
245 /// \brief Removes all edges from this CallGraphNode to any functions it
247 void removeAllCalledFunctions() {
248 while (!CalledFunctions.empty()) {
249 CalledFunctions.back().second->DropRef();
250 CalledFunctions.pop_back();
254 /// \brief Moves all the callee information from N to this node.
255 void stealCalledFunctionsFrom(CallGraphNode *N) {
256 assert(CalledFunctions.empty() &&
257 "Cannot steal callsite information if I already have some");
258 std::swap(CalledFunctions, N->CalledFunctions);
261 /// \brief Adds a function to the list of functions called by this one.
262 void addCalledFunction(CallSite CS, CallGraphNode *M) {
263 assert(!CS.getInstruction() ||
264 !CS.getCalledFunction() ||
265 !CS.getCalledFunction()->isIntrinsic());
266 CalledFunctions.push_back(std::make_pair(CS.getInstruction(), M));
270 void removeCallEdge(iterator I) {
271 I->second->DropRef();
272 *I = CalledFunctions.back();
273 CalledFunctions.pop_back();
276 /// \brief Removes the edge in the node for the specified call site.
278 /// Note that this method takes linear time, so it should be used sparingly.
279 void removeCallEdgeFor(CallSite CS);
281 /// \brief Removes all call edges from this node to the specified callee
284 /// This takes more time to execute than removeCallEdgeTo, so it should not
285 /// be used unless necessary.
286 void removeAnyCallEdgeTo(CallGraphNode *Callee);
288 /// \brief Removes one edge associated with a null callsite from this node to
289 /// the specified callee function.
290 void removeOneAbstractEdgeTo(CallGraphNode *Callee);
292 /// \brief Replaces the edge in the node for the specified call site with a
295 /// Note that this method takes linear time, so it should be used sparingly.
296 void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
298 /// \brief A special function that should only be used by the CallGraph class.
300 // FIXME: Make this private?
301 void allReferencesDropped() {
306 //===----------------------------------------------------------------------===//
307 // GraphTraits specializations for call graphs so that they can be treated as
308 // graphs by the generic graph algorithms.
311 // Provide graph traits for tranversing call graphs using standard graph
313 template <> struct GraphTraits<CallGraphNode*> {
314 typedef CallGraphNode NodeType;
316 typedef CallGraphNode::CallRecord CGNPairTy;
317 typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode*> CGNDerefFun;
319 static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
321 typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
323 static inline ChildIteratorType child_begin(NodeType *N) {
324 return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
326 static inline ChildIteratorType child_end (NodeType *N) {
327 return map_iterator(N->end(), CGNDerefFun(CGNDeref));
330 static CallGraphNode *CGNDeref(CGNPairTy P) {
336 template <> struct GraphTraits<const CallGraphNode*> {
337 typedef const CallGraphNode NodeType;
338 typedef NodeType::const_iterator ChildIteratorType;
340 static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
341 static inline ChildIteratorType child_begin(NodeType *N) { return N->begin();}
342 static inline ChildIteratorType child_end (NodeType *N) { return N->end(); }
345 template<> struct GraphTraits<CallGraph*> : public GraphTraits<CallGraphNode*> {
346 static NodeType *getEntryNode(CallGraph *CGN) {
347 return CGN->getExternalCallingNode(); // Start at the external node!
349 typedef std::pair<const Function*, CallGraphNode*> PairTy;
350 typedef std::pointer_to_unary_function<PairTy, CallGraphNode&> DerefFun;
352 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
353 typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
354 static nodes_iterator nodes_begin(CallGraph *CG) {
355 return map_iterator(CG->begin(), DerefFun(CGdereference));
357 static nodes_iterator nodes_end (CallGraph *CG) {
358 return map_iterator(CG->end(), DerefFun(CGdereference));
361 static CallGraphNode &CGdereference(PairTy P) {
366 template<> struct GraphTraits<const CallGraph*> :
367 public GraphTraits<const CallGraphNode*> {
368 static NodeType *getEntryNode(const CallGraph *CGN) {
369 return CGN->getExternalCallingNode();
371 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
372 typedef CallGraph::const_iterator nodes_iterator;
373 static nodes_iterator nodes_begin(const CallGraph *CG) { return CG->begin(); }
374 static nodes_iterator nodes_end (const CallGraph *CG) { return CG->end(); }
377 } // End llvm namespace
379 // Make sure that any clients of this file link in CallGraph.cpp
380 FORCE_DEFINING_FILE_TO_BE_LINKED(CallGraph)