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 the are called by the
16 /// function 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/OwningPtr.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/Pass.h"
60 #include "llvm/Support/CallSite.h"
61 #include "llvm/Support/IncludeFile.h"
62 #include "llvm/Support/ValueHandle.h"
71 /// \brief The basic data container for the call graph of a \c Module of IR.
73 /// This class exposes both the interface to the call graph for a module of IR.
75 /// The core call graph itself can also be updated to reflect changes to the IR.
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 CallGraph(Module &M);
111 void print(raw_ostream &OS) const;
114 typedef FunctionMapTy::iterator iterator;
115 typedef FunctionMapTy::const_iterator const_iterator;
117 /// \brief Returns the module the call graph corresponds to.
118 Module &getModule() const { return M; }
120 inline iterator begin() { return FunctionMap.begin(); }
121 inline iterator end() { return FunctionMap.end(); }
122 inline const_iterator begin() const { return FunctionMap.begin(); }
123 inline const_iterator end() const { return FunctionMap.end(); }
125 /// \brief Returns the call graph node for the provided function.
126 inline const CallGraphNode *operator[](const Function *F) const {
127 const_iterator I = FunctionMap.find(F);
128 assert(I != FunctionMap.end() && "Function not in callgraph!");
132 /// \brief Returns the call graph node for the provided function.
133 inline CallGraphNode *operator[](const Function *F) {
134 const_iterator I = FunctionMap.find(F);
135 assert(I != FunctionMap.end() && "Function not in callgraph!");
139 /// \brief Returns the \c CallGraphNode which is used to represent
140 /// undetermined calls into the callgraph.
141 CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
143 CallGraphNode *getCallsExternalNode() const { return CallsExternalNode; }
145 //===---------------------------------------------------------------------
146 // Functions to keep a call graph up to date with a function that has been
150 /// \brief Unlink the function from this module, returning it.
152 /// Because this removes the function from the module, the call graph node is
153 /// destroyed. This is only valid if the function does not call any other
154 /// functions (ie, there are no edges in it's CGN). The easiest way to do
155 /// this is to dropAllReferences before calling this.
156 Function *removeFunctionFromModule(CallGraphNode *CGN);
158 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
159 /// \c F if one does not already exist.
160 CallGraphNode *getOrInsertFunction(const Function *F);
163 /// \brief A node in the call graph for a module.
165 /// Typically represents a function in the call graph. There are also special
166 /// "null" nodes used to represent theoretical entries in the call graph.
167 class CallGraphNode {
168 friend class CallGraph;
170 AssertingVH<Function> F;
173 /// \brief A pair of the calling instruction (a call or invoke)
174 /// and the call graph node being called.
175 typedef std::pair<WeakVH, CallGraphNode *> CallRecord;
178 std::vector<CallRecord> CalledFunctions;
180 /// \brief The number of times that this CallGraphNode occurs in the
181 /// CalledFunctions array of this or other CallGraphNodes.
182 unsigned NumReferences;
184 CallGraphNode(const CallGraphNode &) LLVM_DELETED_FUNCTION;
185 void operator=(const CallGraphNode &) LLVM_DELETED_FUNCTION;
187 void DropRef() { --NumReferences; }
188 void AddRef() { ++NumReferences; }
191 typedef std::vector<CallRecord> CalledFunctionsVector;
193 /// \brief Creates a node for the specified function.
194 inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
197 assert(NumReferences == 0 && "Node deleted while references remain");
200 typedef std::vector<CallRecord>::iterator iterator;
201 typedef std::vector<CallRecord>::const_iterator const_iterator;
203 /// \brief Returns the function that this call graph node represents.
204 Function *getFunction() const { return F; }
206 inline iterator begin() { return CalledFunctions.begin(); }
207 inline iterator end() { return CalledFunctions.end(); }
208 inline const_iterator begin() const { return CalledFunctions.begin(); }
209 inline const_iterator end() const { return CalledFunctions.end(); }
210 inline bool empty() const { return CalledFunctions.empty(); }
211 inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
213 /// \brief Returns the number of other CallGraphNodes in this CallGraph that
214 /// reference this node in their callee list.
215 unsigned getNumReferences() const { return NumReferences; }
217 /// \brief Returns the i'th called function.
218 CallGraphNode *operator[](unsigned i) const {
219 assert(i < CalledFunctions.size() && "Invalid index");
220 return CalledFunctions[i].second;
223 /// \brief Print out this call graph node.
225 void print(raw_ostream &OS) const;
227 //===---------------------------------------------------------------------
228 // Methods to keep a call graph up to date with a function that has been
232 /// \brief Removes all edges from this CallGraphNode to any functions it
234 void removeAllCalledFunctions() {
235 while (!CalledFunctions.empty()) {
236 CalledFunctions.back().second->DropRef();
237 CalledFunctions.pop_back();
241 /// \brief Moves all the callee information from N to this node.
242 void stealCalledFunctionsFrom(CallGraphNode *N) {
243 assert(CalledFunctions.empty() &&
244 "Cannot steal callsite information if I already have some");
245 std::swap(CalledFunctions, N->CalledFunctions);
248 /// \brief Adds a function to the list of functions called by this one.
249 void addCalledFunction(CallSite CS, CallGraphNode *M) {
250 assert(!CS.getInstruction() || !CS.getCalledFunction() ||
251 !CS.getCalledFunction()->isIntrinsic());
252 CalledFunctions.push_back(std::make_pair(CS.getInstruction(), M));
256 void removeCallEdge(iterator I) {
257 I->second->DropRef();
258 *I = CalledFunctions.back();
259 CalledFunctions.pop_back();
262 /// \brief Removes the edge in the node for the specified call site.
264 /// Note that this method takes linear time, so it should be used sparingly.
265 void removeCallEdgeFor(CallSite CS);
267 /// \brief Removes all call edges from this node to the specified callee
270 /// This takes more time to execute than removeCallEdgeTo, so it should not
271 /// be used unless necessary.
272 void removeAnyCallEdgeTo(CallGraphNode *Callee);
274 /// \brief Removes one edge associated with a null callsite from this node to
275 /// the specified callee function.
276 void removeOneAbstractEdgeTo(CallGraphNode *Callee);
278 /// \brief Replaces the edge in the node for the specified call site with a
281 /// Note that this method takes linear time, so it should be used sparingly.
282 void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
284 /// \brief A special function that should only be used by the CallGraph class.
286 // FIXME: Make this private?
287 void allReferencesDropped() { NumReferences = 0; }
290 /// \brief The \c ModulePass which wraps up a \c CallGraph and the logic to
293 /// This class exposes both the interface to the call graph container and the
294 /// module pass which runs over a module of IR and produces the call graph. The
295 /// call graph interface is entirelly a wrapper around a \c CallGraph object
296 /// which is stored internally for each module.
297 class CallGraphWrapperPass : public ModulePass {
298 OwningPtr<CallGraph> G;
301 static char ID; // Class identification, replacement for typeinfo
303 CallGraphWrapperPass();
304 virtual ~CallGraphWrapperPass();
306 /// \brief The internal \c CallGraph around which the rest of this interface
308 const CallGraph &getCallGraph() const { return *G; }
309 CallGraph &getCallGraph() { return *G; }
311 typedef CallGraph::iterator iterator;
312 typedef CallGraph::const_iterator const_iterator;
314 /// \brief Returns the module the call graph corresponds to.
315 Module &getModule() const { return G->getModule(); }
317 inline iterator begin() { return G->begin(); }
318 inline iterator end() { return G->end(); }
319 inline const_iterator begin() const { return G->begin(); }
320 inline const_iterator end() const { return G->end(); }
322 /// \brief Returns the call graph node for the provided function.
323 inline const CallGraphNode *operator[](const Function *F) const {
327 /// \brief Returns the call graph node for the provided function.
328 inline CallGraphNode *operator[](const Function *F) { return (*G)[F]; }
330 /// \brief Returns the \c CallGraphNode which is used to represent
331 /// undetermined calls into the callgraph.
332 CallGraphNode *getExternalCallingNode() const {
333 return G->getExternalCallingNode();
336 CallGraphNode *getCallsExternalNode() const {
337 return G->getCallsExternalNode();
340 //===---------------------------------------------------------------------
341 // Functions to keep a call graph up to date with a function that has been
345 /// \brief Unlink the function from this module, returning it.
347 /// Because this removes the function from the module, the call graph node is
348 /// destroyed. This is only valid if the function does not call any other
349 /// functions (ie, there are no edges in it's CGN). The easiest way to do
350 /// this is to dropAllReferences before calling this.
351 Function *removeFunctionFromModule(CallGraphNode *CGN) {
352 return G->removeFunctionFromModule(CGN);
355 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
356 /// \c F if one does not already exist.
357 CallGraphNode *getOrInsertFunction(const Function *F) {
358 return G->getOrInsertFunction(F);
361 //===---------------------------------------------------------------------
362 // Implementation of the ModulePass interface needed here.
365 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
366 virtual bool runOnModule(Module &M);
367 virtual void releaseMemory();
369 void print(raw_ostream &o, const Module *) const;
373 //===----------------------------------------------------------------------===//
374 // GraphTraits specializations for call graphs so that they can be treated as
375 // graphs by the generic graph algorithms.
378 // Provide graph traits for tranversing call graphs using standard graph
380 template <> struct GraphTraits<CallGraphNode *> {
381 typedef CallGraphNode NodeType;
383 typedef CallGraphNode::CallRecord CGNPairTy;
384 typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode *>
387 static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
389 typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
391 static inline ChildIteratorType child_begin(NodeType *N) {
392 return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
394 static inline ChildIteratorType child_end(NodeType *N) {
395 return map_iterator(N->end(), CGNDerefFun(CGNDeref));
398 static CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
401 template <> struct GraphTraits<const CallGraphNode *> {
402 typedef const CallGraphNode NodeType;
403 typedef NodeType::const_iterator ChildIteratorType;
405 static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
406 static inline ChildIteratorType child_begin(NodeType *N) {
409 static inline ChildIteratorType child_end(NodeType *N) { return N->end(); }
413 struct GraphTraits<CallGraph *> : public GraphTraits<CallGraphNode *> {
414 static NodeType *getEntryNode(CallGraph *CGN) {
415 return CGN->getExternalCallingNode(); // Start at the external node!
417 typedef std::pair<const Function *, CallGraphNode *> PairTy;
418 typedef std::pointer_to_unary_function<PairTy, CallGraphNode &> DerefFun;
420 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
421 typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
422 static nodes_iterator nodes_begin(CallGraph *CG) {
423 return map_iterator(CG->begin(), DerefFun(CGdereference));
425 static nodes_iterator nodes_end(CallGraph *CG) {
426 return map_iterator(CG->end(), DerefFun(CGdereference));
429 static CallGraphNode &CGdereference(PairTy P) { return *P.second; }
433 struct GraphTraits<const CallGraph *> : public GraphTraits<
434 const CallGraphNode *> {
435 static NodeType *getEntryNode(const CallGraph *CGN) {
436 return CGN->getExternalCallingNode();
438 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
439 typedef CallGraph::const_iterator nodes_iterator;
440 static nodes_iterator nodes_begin(const CallGraph *CG) { return CG->begin(); }
441 static nodes_iterator nodes_end(const CallGraph *CG) { return CG->end(); }
444 } // End llvm namespace
446 // Make sure that any clients of this file link in CallGraph.cpp
447 FORCE_DEFINING_FILE_TO_BE_LINKED(CallGraph)