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 {
79 typedef std::map<const Function *, CallGraphNode *> FunctionMapTy;
81 /// \brief A map from \c Function* to \c CallGraphNode*.
82 FunctionMapTy FunctionMap;
84 /// \brief Root is root of the call graph, or the external node if a 'main'
85 /// function couldn't be found.
88 /// \brief This node has edges to all external functions and those internal
89 /// functions that have their address taken.
90 CallGraphNode *ExternalCallingNode;
92 /// \brief This node has edges to it from all functions making indirect calls
93 /// or calling an external function.
94 CallGraphNode *CallsExternalNode;
96 /// \brief Replace the function represented by this node by another.
98 /// This does not rescan the body of the function, so it is suitable when
99 /// splicing the body of one function to another while also updating all
100 /// callers from the old function to the new.
101 void spliceFunction(const Function *From, const Function *To);
103 /// \brief Add a function to the call graph, and link the node to all of the
104 /// functions that it calls.
105 void addToCallGraph(Function *F);
108 static char ID; // Class identification, replacement for typeinfo
110 typedef FunctionMapTy::iterator iterator;
111 typedef FunctionMapTy::const_iterator const_iterator;
113 /// \brief Returns the module the call graph corresponds to.
114 Module &getModule() const { return *M; }
116 inline iterator begin() { return FunctionMap.begin(); }
117 inline iterator end() { return FunctionMap.end(); }
118 inline const_iterator begin() const { return FunctionMap.begin(); }
119 inline const_iterator end() const { return FunctionMap.end(); }
121 /// \brief Returns the call graph node for the provided function.
122 inline const CallGraphNode *operator[](const Function *F) const {
123 const_iterator I = FunctionMap.find(F);
124 assert(I != FunctionMap.end() && "Function not in callgraph!");
128 /// \brief Returns the call graph node for the provided function.
129 inline CallGraphNode *operator[](const Function *F) {
130 const_iterator I = FunctionMap.find(F);
131 assert(I != FunctionMap.end() && "Function not in callgraph!");
135 /// \brief Returns the \c CallGraphNode which is used to represent
136 /// undetermined calls into the callgraph.
137 CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
139 CallGraphNode *getCallsExternalNode() const { return CallsExternalNode; }
141 /// \brief Returns the root/main method in the module, or some other root
142 /// node, such as the externalcallingnode.
143 CallGraphNode *getRoot() { return Root; }
144 const CallGraphNode *getRoot() const { return Root; }
146 //===---------------------------------------------------------------------
147 // Functions to keep a call graph up to date with a function that has been
151 /// \brief Unlink the function from this module, returning it.
153 /// Because this removes the function from the module, the call graph node is
154 /// destroyed. This is only valid if the function does not call any other
155 /// functions (ie, there are no edges in it's CGN). The easiest way to do
156 /// this is to dropAllReferences before calling this.
157 Function *removeFunctionFromModule(CallGraphNode *CGN);
159 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
160 /// \c F if one does not already exist.
161 CallGraphNode *getOrInsertFunction(const Function *F);
164 virtual ~CallGraph() { releaseMemory(); }
166 //===---------------------------------------------------------------------
167 // Implementation of the ModulePass interface needed here.
170 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
171 virtual bool runOnModule(Module &M);
172 virtual void releaseMemory();
174 void print(raw_ostream &o, const Module *) const;
178 /// \brief A node in the call graph for a module.
180 /// Typically represents a function in the call graph. There are also special
181 /// "null" nodes used to represent theoretical entries in the call graph.
182 class CallGraphNode {
183 friend class CallGraph;
185 AssertingVH<Function> F;
188 /// \brief A pair of the calling instruction (a call or invoke)
189 /// and the call graph node being called.
190 typedef std::pair<WeakVH, CallGraphNode *> CallRecord;
193 std::vector<CallRecord> CalledFunctions;
195 /// \brief The number of times that this CallGraphNode occurs in the
196 /// CalledFunctions array of this or other CallGraphNodes.
197 unsigned NumReferences;
199 CallGraphNode(const CallGraphNode &) LLVM_DELETED_FUNCTION;
200 void operator=(const CallGraphNode &) LLVM_DELETED_FUNCTION;
202 void DropRef() { --NumReferences; }
203 void AddRef() { ++NumReferences; }
206 typedef std::vector<CallRecord> CalledFunctionsVector;
208 /// \brief Creates a node for the specified function.
209 inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
212 assert(NumReferences == 0 && "Node deleted while references remain");
215 typedef std::vector<CallRecord>::iterator iterator;
216 typedef std::vector<CallRecord>::const_iterator const_iterator;
218 /// \brief Returns the function that this call graph node represents.
219 Function *getFunction() const { return F; }
221 inline iterator begin() { return CalledFunctions.begin(); }
222 inline iterator end() { return CalledFunctions.end(); }
223 inline const_iterator begin() const { return CalledFunctions.begin(); }
224 inline const_iterator end() const { return CalledFunctions.end(); }
225 inline bool empty() const { return CalledFunctions.empty(); }
226 inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
228 /// \brief Returns the number of other CallGraphNodes in this CallGraph that
229 /// reference this node in their callee list.
230 unsigned getNumReferences() const { return NumReferences; }
232 /// \brief Returns the i'th called function.
233 CallGraphNode *operator[](unsigned i) const {
234 assert(i < CalledFunctions.size() && "Invalid index");
235 return CalledFunctions[i].second;
238 /// \brief Print out this call graph node.
240 void print(raw_ostream &OS) const;
242 //===---------------------------------------------------------------------
243 // Methods to keep a call graph up to date with a function that has been
247 /// \brief Removes all edges from this CallGraphNode to any functions it
249 void removeAllCalledFunctions() {
250 while (!CalledFunctions.empty()) {
251 CalledFunctions.back().second->DropRef();
252 CalledFunctions.pop_back();
256 /// \brief Moves all the callee information from N to this node.
257 void stealCalledFunctionsFrom(CallGraphNode *N) {
258 assert(CalledFunctions.empty() &&
259 "Cannot steal callsite information if I already have some");
260 std::swap(CalledFunctions, N->CalledFunctions);
263 /// \brief Adds a function to the list of functions called by this one.
264 void addCalledFunction(CallSite CS, CallGraphNode *M) {
265 assert(!CS.getInstruction() || !CS.getCalledFunction() ||
266 !CS.getCalledFunction()->isIntrinsic());
267 CalledFunctions.push_back(std::make_pair(CS.getInstruction(), M));
271 void removeCallEdge(iterator I) {
272 I->second->DropRef();
273 *I = CalledFunctions.back();
274 CalledFunctions.pop_back();
277 /// \brief Removes the edge in the node for the specified call site.
279 /// Note that this method takes linear time, so it should be used sparingly.
280 void removeCallEdgeFor(CallSite CS);
282 /// \brief Removes all call edges from this node to the specified callee
285 /// This takes more time to execute than removeCallEdgeTo, so it should not
286 /// be used unless necessary.
287 void removeAnyCallEdgeTo(CallGraphNode *Callee);
289 /// \brief Removes one edge associated with a null callsite from this node to
290 /// the specified callee function.
291 void removeOneAbstractEdgeTo(CallGraphNode *Callee);
293 /// \brief Replaces the edge in the node for the specified call site with a
296 /// Note that this method takes linear time, so it should be used sparingly.
297 void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
299 /// \brief A special function that should only be used by the CallGraph class.
301 // FIXME: Make this private?
302 void allReferencesDropped() { NumReferences = 0; }
305 //===----------------------------------------------------------------------===//
306 // GraphTraits specializations for call graphs so that they can be treated as
307 // graphs by the generic graph algorithms.
310 // Provide graph traits for tranversing call graphs using standard graph
312 template <> struct GraphTraits<CallGraphNode *> {
313 typedef CallGraphNode NodeType;
315 typedef CallGraphNode::CallRecord CGNPairTy;
316 typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode *>
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) { return P.second; }
333 template <> struct GraphTraits<const CallGraphNode *> {
334 typedef const CallGraphNode NodeType;
335 typedef NodeType::const_iterator ChildIteratorType;
337 static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
338 static inline ChildIteratorType child_begin(NodeType *N) {
341 static inline ChildIteratorType child_end(NodeType *N) { return N->end(); }
345 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) { return *P.second; }
365 struct GraphTraits<const CallGraph *> : public GraphTraits<
366 const CallGraphNode *> {
367 static NodeType *getEntryNode(const CallGraph *CGN) {
368 return CGN->getExternalCallingNode();
370 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
371 typedef CallGraph::const_iterator nodes_iterator;
372 static nodes_iterator nodes_begin(const CallGraph *CG) { return CG->begin(); }
373 static nodes_iterator nodes_end(const CallGraph *CG) { return CG->end(); }
376 } // End llvm namespace
378 // Make sure that any clients of this file link in CallGraph.cpp
379 FORCE_DEFINING_FILE_TO_BE_LINKED(CallGraph)