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/Intrinsics.h"
60 #include "llvm/IR/ValueHandle.h"
61 #include "llvm/Pass.h"
70 /// \brief The basic data container for the call graph of a \c Module of IR.
72 /// This class exposes both the interface to the call graph for a module of IR.
74 /// The core call graph itself can also be updated to reflect changes to the IR.
78 typedef std::map<const Function *, std::unique_ptr<CallGraphNode>>
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 std::unique_ptr<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 explicit CallGraph(Module &M);
109 CallGraph(CallGraph &&Arg);
112 void print(raw_ostream &OS) const;
115 typedef FunctionMapTy::iterator iterator;
116 typedef FunctionMapTy::const_iterator const_iterator;
118 /// \brief Returns the module the call graph corresponds to.
119 Module &getModule() const { return M; }
121 inline iterator begin() { return FunctionMap.begin(); }
122 inline iterator end() { return FunctionMap.end(); }
123 inline const_iterator begin() const { return FunctionMap.begin(); }
124 inline const_iterator end() const { return FunctionMap.end(); }
126 /// \brief Returns the call graph node for the provided function.
127 inline const CallGraphNode *operator[](const Function *F) const {
128 const_iterator I = FunctionMap.find(F);
129 assert(I != FunctionMap.end() && "Function not in callgraph!");
130 return I->second.get();
133 /// \brief Returns the call graph node for the provided function.
134 inline CallGraphNode *operator[](const Function *F) {
135 const_iterator I = FunctionMap.find(F);
136 assert(I != FunctionMap.end() && "Function not in callgraph!");
137 return I->second.get();
140 /// \brief Returns the \c CallGraphNode which is used to represent
141 /// undetermined calls into the callgraph.
142 CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
144 CallGraphNode *getCallsExternalNode() const {
145 return CallsExternalNode.get();
148 //===---------------------------------------------------------------------
149 // Functions to keep a call graph up to date with a function that has been
153 /// \brief Unlink the function from this module, returning it.
155 /// Because this removes the function from the module, the call graph node is
156 /// destroyed. This is only valid if the function does not call any other
157 /// functions (ie, there are no edges in it's CGN). The easiest way to do
158 /// this is to dropAllReferences before calling this.
159 Function *removeFunctionFromModule(CallGraphNode *CGN);
161 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
162 /// \c F if one does not already exist.
163 CallGraphNode *getOrInsertFunction(const Function *F);
166 /// \brief A node in the call graph for a module.
168 /// Typically represents a function in the call graph. There are also special
169 /// "null" nodes used to represent theoretical entries in the call graph.
170 class CallGraphNode {
172 /// \brief A pair of the calling instruction (a call or invoke)
173 /// and the call graph node being called.
174 typedef std::pair<WeakVH, CallGraphNode *> CallRecord;
177 typedef std::vector<CallRecord> CalledFunctionsVector;
179 /// \brief Creates a node for the specified function.
180 inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
183 assert(NumReferences == 0 && "Node deleted while references remain");
186 typedef std::vector<CallRecord>::iterator iterator;
187 typedef std::vector<CallRecord>::const_iterator const_iterator;
189 /// \brief Returns the function that this call graph node represents.
190 Function *getFunction() const { return F; }
192 inline iterator begin() { return CalledFunctions.begin(); }
193 inline iterator end() { return CalledFunctions.end(); }
194 inline const_iterator begin() const { return CalledFunctions.begin(); }
195 inline const_iterator end() const { return CalledFunctions.end(); }
196 inline bool empty() const { return CalledFunctions.empty(); }
197 inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
199 /// \brief Returns the number of other CallGraphNodes in this CallGraph that
200 /// reference this node in their callee list.
201 unsigned getNumReferences() const { return NumReferences; }
203 /// \brief Returns the i'th called function.
204 CallGraphNode *operator[](unsigned i) const {
205 assert(i < CalledFunctions.size() && "Invalid index");
206 return CalledFunctions[i].second;
209 /// \brief Print out this call graph node.
211 void print(raw_ostream &OS) const;
213 //===---------------------------------------------------------------------
214 // Methods to keep a call graph up to date with a function that has been
218 /// \brief Removes all edges from this CallGraphNode to any functions it
220 void removeAllCalledFunctions() {
221 while (!CalledFunctions.empty()) {
222 CalledFunctions.back().second->DropRef();
223 CalledFunctions.pop_back();
227 /// \brief Moves all the callee information from N to this node.
228 void stealCalledFunctionsFrom(CallGraphNode *N) {
229 assert(CalledFunctions.empty() &&
230 "Cannot steal callsite information if I already have some");
231 std::swap(CalledFunctions, N->CalledFunctions);
234 /// \brief Adds a function to the list of functions called by this one.
235 void addCalledFunction(CallSite CS, CallGraphNode *M) {
236 assert(!CS.getInstruction() || !CS.getCalledFunction() ||
237 !CS.getCalledFunction()->isIntrinsic() ||
238 !Intrinsic::isLeaf(CS.getCalledFunction()->getIntrinsicID()));
239 CalledFunctions.emplace_back(CS.getInstruction(), M);
243 void removeCallEdge(iterator I) {
244 I->second->DropRef();
245 *I = CalledFunctions.back();
246 CalledFunctions.pop_back();
249 /// \brief Removes the edge in the node for the specified call site.
251 /// Note that this method takes linear time, so it should be used sparingly.
252 void removeCallEdgeFor(CallSite CS);
254 /// \brief Removes all call edges from this node to the specified callee
257 /// This takes more time to execute than removeCallEdgeTo, so it should not
258 /// be used unless necessary.
259 void removeAnyCallEdgeTo(CallGraphNode *Callee);
261 /// \brief Removes one edge associated with a null callsite from this node to
262 /// the specified callee function.
263 void removeOneAbstractEdgeTo(CallGraphNode *Callee);
265 /// \brief Replaces the edge in the node for the specified call site with a
268 /// Note that this method takes linear time, so it should be used sparingly.
269 void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
272 friend class CallGraph;
274 AssertingVH<Function> F;
276 std::vector<CallRecord> CalledFunctions;
278 /// \brief The number of times that this CallGraphNode occurs in the
279 /// CalledFunctions array of this or other CallGraphNodes.
280 unsigned NumReferences;
282 CallGraphNode(const CallGraphNode &) = delete;
283 void operator=(const CallGraphNode &) = delete;
285 void DropRef() { --NumReferences; }
286 void AddRef() { ++NumReferences; }
288 /// \brief A special function that should only be used by the CallGraph class.
289 void allReferencesDropped() { NumReferences = 0; }
292 /// \brief An analysis pass to compute the \c CallGraph for a \c Module.
294 /// This class implements the concept of an analysis pass used by the \c
295 /// ModuleAnalysisManager to run an analysis over a module and cache the
297 class CallGraphAnalysis {
299 /// \brief A formulaic typedef to inform clients of the result type.
300 typedef CallGraph Result;
302 static void *ID() { return (void *)&PassID; }
304 /// \brief Compute the \c CallGraph for the module \c M.
306 /// The real work here is done in the \c CallGraph constructor.
307 CallGraph run(Module *M) { return CallGraph(*M); }
313 /// \brief The \c ModulePass which wraps up a \c CallGraph and the logic to
316 /// This class exposes both the interface to the call graph container and the
317 /// module pass which runs over a module of IR and produces the call graph. The
318 /// call graph interface is entirelly a wrapper around a \c CallGraph object
319 /// which is stored internally for each module.
320 class CallGraphWrapperPass : public ModulePass {
321 std::unique_ptr<CallGraph> G;
324 static char ID; // Class identification, replacement for typeinfo
326 CallGraphWrapperPass();
327 ~CallGraphWrapperPass() override;
329 /// \brief The internal \c CallGraph around which the rest of this interface
331 const CallGraph &getCallGraph() const { return *G; }
332 CallGraph &getCallGraph() { return *G; }
334 typedef CallGraph::iterator iterator;
335 typedef CallGraph::const_iterator const_iterator;
337 /// \brief Returns the module the call graph corresponds to.
338 Module &getModule() const { return G->getModule(); }
340 inline iterator begin() { return G->begin(); }
341 inline iterator end() { return G->end(); }
342 inline const_iterator begin() const { return G->begin(); }
343 inline const_iterator end() const { return G->end(); }
345 /// \brief Returns the call graph node for the provided function.
346 inline const CallGraphNode *operator[](const Function *F) const {
350 /// \brief Returns the call graph node for the provided function.
351 inline CallGraphNode *operator[](const Function *F) { return (*G)[F]; }
353 /// \brief Returns the \c CallGraphNode which is used to represent
354 /// undetermined calls into the callgraph.
355 CallGraphNode *getExternalCallingNode() const {
356 return G->getExternalCallingNode();
359 CallGraphNode *getCallsExternalNode() const {
360 return G->getCallsExternalNode();
363 //===---------------------------------------------------------------------
364 // Functions to keep a call graph up to date with a function that has been
368 /// \brief Unlink the function from this module, returning it.
370 /// Because this removes the function from the module, the call graph node is
371 /// destroyed. This is only valid if the function does not call any other
372 /// functions (ie, there are no edges in it's CGN). The easiest way to do
373 /// this is to dropAllReferences before calling this.
374 Function *removeFunctionFromModule(CallGraphNode *CGN) {
375 return G->removeFunctionFromModule(CGN);
378 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
379 /// \c F if one does not already exist.
380 CallGraphNode *getOrInsertFunction(const Function *F) {
381 return G->getOrInsertFunction(F);
384 //===---------------------------------------------------------------------
385 // Implementation of the ModulePass interface needed here.
388 void getAnalysisUsage(AnalysisUsage &AU) const override;
389 bool runOnModule(Module &M) override;
390 void releaseMemory() override;
392 void print(raw_ostream &o, const Module *) const override;
396 //===----------------------------------------------------------------------===//
397 // GraphTraits specializations for call graphs so that they can be treated as
398 // graphs by the generic graph algorithms.
401 // Provide graph traits for tranversing call graphs using standard graph
403 template <> struct GraphTraits<CallGraphNode *> {
404 typedef CallGraphNode NodeType;
406 typedef CallGraphNode::CallRecord CGNPairTy;
407 typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode *>
410 static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
412 typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
414 static inline ChildIteratorType child_begin(NodeType *N) {
415 return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
417 static inline ChildIteratorType child_end(NodeType *N) {
418 return map_iterator(N->end(), CGNDerefFun(CGNDeref));
421 static CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
424 template <> struct GraphTraits<const CallGraphNode *> {
425 typedef const CallGraphNode NodeType;
427 typedef CallGraphNode::CallRecord CGNPairTy;
428 typedef std::pointer_to_unary_function<CGNPairTy, const CallGraphNode *>
431 static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
433 typedef mapped_iterator<NodeType::const_iterator, CGNDerefFun>
436 static inline ChildIteratorType child_begin(NodeType *N) {
437 return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
439 static inline ChildIteratorType child_end(NodeType *N) {
440 return map_iterator(N->end(), CGNDerefFun(CGNDeref));
443 static const CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
447 struct GraphTraits<CallGraph *> : public GraphTraits<CallGraphNode *> {
448 static NodeType *getEntryNode(CallGraph *CGN) {
449 return CGN->getExternalCallingNode(); // Start at the external node!
451 typedef std::pair<const Function *const, std::unique_ptr<CallGraphNode>>
453 typedef std::pointer_to_unary_function<const PairTy &, CallGraphNode &>
456 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
457 typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
458 static nodes_iterator nodes_begin(CallGraph *CG) {
459 return map_iterator(CG->begin(), DerefFun(CGdereference));
461 static nodes_iterator nodes_end(CallGraph *CG) {
462 return map_iterator(CG->end(), DerefFun(CGdereference));
465 static CallGraphNode &CGdereference(const PairTy &P) { return *P.second; }
469 struct GraphTraits<const CallGraph *> : public GraphTraits<
470 const CallGraphNode *> {
471 static NodeType *getEntryNode(const CallGraph *CGN) {
472 return CGN->getExternalCallingNode(); // Start at the external node!
474 typedef std::pair<const Function *const, std::unique_ptr<CallGraphNode>>
476 typedef std::pointer_to_unary_function<const PairTy &, const CallGraphNode &>
479 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
480 typedef mapped_iterator<CallGraph::const_iterator, DerefFun> nodes_iterator;
481 static nodes_iterator nodes_begin(const CallGraph *CG) {
482 return map_iterator(CG->begin(), DerefFun(CGdereference));
484 static nodes_iterator nodes_end(const CallGraph *CG) {
485 return map_iterator(CG->end(), DerefFun(CGdereference));
488 static const CallGraphNode &CGdereference(const PairTy &P) {
493 } // End llvm namespace