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/PassManager.h"
61 #include "llvm/IR/ValueHandle.h"
62 #include "llvm/Pass.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 *, std::unique_ptr<CallGraphNode>>
82 /// \brief A map from \c Function* to \c CallGraphNode*.
83 FunctionMapTy FunctionMap;
85 /// \brief Root is root of the call graph, or the external node if a 'main'
86 /// function couldn't be found.
89 /// \brief This node has edges to all external functions and those internal
90 /// functions that have their address taken.
91 CallGraphNode *ExternalCallingNode;
93 /// \brief This node has edges to it from all functions making indirect calls
94 /// or calling an external function.
95 std::unique_ptr<CallGraphNode> CallsExternalNode;
97 /// \brief Replace the function represented by this node by another.
99 /// This does not rescan the body of the function, so it is suitable when
100 /// splicing the body of one function to another while also updating all
101 /// callers from the old function to the new.
102 void spliceFunction(const Function *From, const Function *To);
104 /// \brief Add a function to the call graph, and link the node to all of the
105 /// functions that it calls.
106 void addToCallGraph(Function *F);
109 explicit CallGraph(Module &M);
110 CallGraph(CallGraph &&Arg);
113 void print(raw_ostream &OS) const;
116 typedef FunctionMapTy::iterator iterator;
117 typedef FunctionMapTy::const_iterator const_iterator;
119 /// \brief Returns the module the call graph corresponds to.
120 Module &getModule() const { return M; }
122 inline iterator begin() { return FunctionMap.begin(); }
123 inline iterator end() { return FunctionMap.end(); }
124 inline const_iterator begin() const { return FunctionMap.begin(); }
125 inline const_iterator end() const { return FunctionMap.end(); }
127 /// \brief Returns the call graph node for the provided function.
128 inline const CallGraphNode *operator[](const Function *F) const {
129 const_iterator I = FunctionMap.find(F);
130 assert(I != FunctionMap.end() && "Function not in callgraph!");
131 return I->second.get();
134 /// \brief Returns the call graph node for the provided function.
135 inline CallGraphNode *operator[](const Function *F) {
136 const_iterator I = FunctionMap.find(F);
137 assert(I != FunctionMap.end() && "Function not in callgraph!");
138 return I->second.get();
141 /// \brief Returns the \c CallGraphNode which is used to represent
142 /// undetermined calls into the callgraph.
143 CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
145 CallGraphNode *getCallsExternalNode() const {
146 return CallsExternalNode.get();
149 //===---------------------------------------------------------------------
150 // Functions to keep a call graph up to date with a function that has been
154 /// \brief Unlink the function from this module, returning it.
156 /// Because this removes the function from the module, the call graph node is
157 /// destroyed. This is only valid if the function does not call any other
158 /// functions (ie, there are no edges in it's CGN). The easiest way to do
159 /// this is to dropAllReferences before calling this.
160 Function *removeFunctionFromModule(CallGraphNode *CGN);
162 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
163 /// \c F if one does not already exist.
164 CallGraphNode *getOrInsertFunction(const Function *F);
167 /// \brief A node in the call graph for a module.
169 /// Typically represents a function in the call graph. There are also special
170 /// "null" nodes used to represent theoretical entries in the call graph.
171 class CallGraphNode {
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 typedef std::vector<CallRecord> CalledFunctionsVector;
180 /// \brief Creates a node for the specified function.
181 inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
184 assert(NumReferences == 0 && "Node deleted while references remain");
187 typedef std::vector<CallRecord>::iterator iterator;
188 typedef std::vector<CallRecord>::const_iterator const_iterator;
190 /// \brief Returns the function that this call graph node represents.
191 Function *getFunction() const { return F; }
193 inline iterator begin() { return CalledFunctions.begin(); }
194 inline iterator end() { return CalledFunctions.end(); }
195 inline const_iterator begin() const { return CalledFunctions.begin(); }
196 inline const_iterator end() const { return CalledFunctions.end(); }
197 inline bool empty() const { return CalledFunctions.empty(); }
198 inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
200 /// \brief Returns the number of other CallGraphNodes in this CallGraph that
201 /// reference this node in their callee list.
202 unsigned getNumReferences() const { return NumReferences; }
204 /// \brief Returns the i'th called function.
205 CallGraphNode *operator[](unsigned i) const {
206 assert(i < CalledFunctions.size() && "Invalid index");
207 return CalledFunctions[i].second;
210 /// \brief Print out this call graph node.
212 void print(raw_ostream &OS) const;
214 //===---------------------------------------------------------------------
215 // Methods to keep a call graph up to date with a function that has been
219 /// \brief Removes all edges from this CallGraphNode to any functions it
221 void removeAllCalledFunctions() {
222 while (!CalledFunctions.empty()) {
223 CalledFunctions.back().second->DropRef();
224 CalledFunctions.pop_back();
228 /// \brief Moves all the callee information from N to this node.
229 void stealCalledFunctionsFrom(CallGraphNode *N) {
230 assert(CalledFunctions.empty() &&
231 "Cannot steal callsite information if I already have some");
232 std::swap(CalledFunctions, N->CalledFunctions);
235 /// \brief Adds a function to the list of functions called by this one.
236 void addCalledFunction(CallSite CS, CallGraphNode *M) {
237 assert(!CS.getInstruction() || !CS.getCalledFunction() ||
238 !CS.getCalledFunction()->isIntrinsic() ||
239 !Intrinsic::isLeaf(CS.getCalledFunction()->getIntrinsicID()));
240 CalledFunctions.emplace_back(CS.getInstruction(), M);
244 void removeCallEdge(iterator I) {
245 I->second->DropRef();
246 *I = CalledFunctions.back();
247 CalledFunctions.pop_back();
250 /// \brief Removes the edge in the node for the specified call site.
252 /// Note that this method takes linear time, so it should be used sparingly.
253 void removeCallEdgeFor(CallSite CS);
255 /// \brief Removes all call edges from this node to the specified callee
258 /// This takes more time to execute than removeCallEdgeTo, so it should not
259 /// be used unless necessary.
260 void removeAnyCallEdgeTo(CallGraphNode *Callee);
262 /// \brief Removes one edge associated with a null callsite from this node to
263 /// the specified callee function.
264 void removeOneAbstractEdgeTo(CallGraphNode *Callee);
266 /// \brief Replaces the edge in the node for the specified call site with a
269 /// Note that this method takes linear time, so it should be used sparingly.
270 void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
273 friend class CallGraph;
275 AssertingVH<Function> F;
277 std::vector<CallRecord> CalledFunctions;
279 /// \brief The number of times that this CallGraphNode occurs in the
280 /// CalledFunctions array of this or other CallGraphNodes.
281 unsigned NumReferences;
283 CallGraphNode(const CallGraphNode &) = delete;
284 void operator=(const CallGraphNode &) = delete;
286 void DropRef() { --NumReferences; }
287 void AddRef() { ++NumReferences; }
289 /// \brief A special function that should only be used by the CallGraph class.
290 void allReferencesDropped() { NumReferences = 0; }
293 /// \brief An analysis pass to compute the \c CallGraph for a \c Module.
295 /// This class implements the concept of an analysis pass used by the \c
296 /// ModuleAnalysisManager to run an analysis over a module and cache the
298 class CallGraphAnalysis : public AnalysisInfoMixin<CallGraphAnalysis> {
299 friend AnalysisInfoMixin<CallGraphAnalysis>;
303 /// \brief A formulaic typedef to inform clients of the result type.
304 typedef CallGraph Result;
306 /// \brief Compute the \c CallGraph for the module \c M.
308 /// The real work here is done in the \c CallGraph constructor.
309 CallGraph run(Module &M, ModuleAnalysisManager &) { return CallGraph(M); }
312 /// \brief Printer pass for the \c CallGraphAnalysis results.
313 class CallGraphPrinterPass : public PassInfoMixin<CallGraphPrinterPass> {
317 explicit CallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
318 PreservedAnalyses run(Module &M, AnalysisManager<Module> &AM);
321 /// \brief The \c ModulePass which wraps up a \c CallGraph and the logic to
324 /// This class exposes both the interface to the call graph container and the
325 /// module pass which runs over a module of IR and produces the call graph. The
326 /// call graph interface is entirelly a wrapper around a \c CallGraph object
327 /// which is stored internally for each module.
328 class CallGraphWrapperPass : public ModulePass {
329 std::unique_ptr<CallGraph> G;
332 static char ID; // Class identification, replacement for typeinfo
334 CallGraphWrapperPass();
335 ~CallGraphWrapperPass() override;
337 /// \brief The internal \c CallGraph around which the rest of this interface
339 const CallGraph &getCallGraph() const { return *G; }
340 CallGraph &getCallGraph() { return *G; }
342 typedef CallGraph::iterator iterator;
343 typedef CallGraph::const_iterator const_iterator;
345 /// \brief Returns the module the call graph corresponds to.
346 Module &getModule() const { return G->getModule(); }
348 inline iterator begin() { return G->begin(); }
349 inline iterator end() { return G->end(); }
350 inline const_iterator begin() const { return G->begin(); }
351 inline const_iterator end() const { return G->end(); }
353 /// \brief Returns the call graph node for the provided function.
354 inline const CallGraphNode *operator[](const Function *F) const {
358 /// \brief Returns the call graph node for the provided function.
359 inline CallGraphNode *operator[](const Function *F) { return (*G)[F]; }
361 /// \brief Returns the \c CallGraphNode which is used to represent
362 /// undetermined calls into the callgraph.
363 CallGraphNode *getExternalCallingNode() const {
364 return G->getExternalCallingNode();
367 CallGraphNode *getCallsExternalNode() const {
368 return G->getCallsExternalNode();
371 //===---------------------------------------------------------------------
372 // Functions to keep a call graph up to date with a function that has been
376 /// \brief Unlink the function from this module, returning it.
378 /// Because this removes the function from the module, the call graph node is
379 /// destroyed. This is only valid if the function does not call any other
380 /// functions (ie, there are no edges in it's CGN). The easiest way to do
381 /// this is to dropAllReferences before calling this.
382 Function *removeFunctionFromModule(CallGraphNode *CGN) {
383 return G->removeFunctionFromModule(CGN);
386 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
387 /// \c F if one does not already exist.
388 CallGraphNode *getOrInsertFunction(const Function *F) {
389 return G->getOrInsertFunction(F);
392 //===---------------------------------------------------------------------
393 // Implementation of the ModulePass interface needed here.
396 void getAnalysisUsage(AnalysisUsage &AU) const override;
397 bool runOnModule(Module &M) override;
398 void releaseMemory() override;
400 void print(raw_ostream &o, const Module *) const override;
404 //===----------------------------------------------------------------------===//
405 // GraphTraits specializations for call graphs so that they can be treated as
406 // graphs by the generic graph algorithms.
409 // Provide graph traits for tranversing call graphs using standard graph
411 template <> struct GraphTraits<CallGraphNode *> {
412 typedef CallGraphNode NodeType;
413 typedef CallGraphNode *NodeRef;
415 typedef CallGraphNode::CallRecord CGNPairTy;
416 typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode *>
419 static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
421 typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
423 static inline ChildIteratorType child_begin(NodeType *N) {
424 return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
426 static inline ChildIteratorType child_end(NodeType *N) {
427 return map_iterator(N->end(), CGNDerefFun(CGNDeref));
430 static CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
433 template <> struct GraphTraits<const CallGraphNode *> {
434 typedef const CallGraphNode NodeType;
435 typedef const CallGraphNode *NodeRef;
437 typedef CallGraphNode::CallRecord CGNPairTy;
438 typedef std::pointer_to_unary_function<CGNPairTy, const CallGraphNode *>
441 static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
443 typedef mapped_iterator<NodeType::const_iterator, CGNDerefFun>
446 static inline ChildIteratorType child_begin(NodeType *N) {
447 return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
449 static inline ChildIteratorType child_end(NodeType *N) {
450 return map_iterator(N->end(), CGNDerefFun(CGNDeref));
453 static const CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
457 struct GraphTraits<CallGraph *> : public GraphTraits<CallGraphNode *> {
458 static NodeType *getEntryNode(CallGraph *CGN) {
459 return CGN->getExternalCallingNode(); // Start at the external node!
461 typedef std::pair<const Function *const, std::unique_ptr<CallGraphNode>>
463 typedef std::pointer_to_unary_function<const PairTy &, CallGraphNode &>
466 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
467 typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
468 static nodes_iterator nodes_begin(CallGraph *CG) {
469 return map_iterator(CG->begin(), DerefFun(CGdereference));
471 static nodes_iterator nodes_end(CallGraph *CG) {
472 return map_iterator(CG->end(), DerefFun(CGdereference));
475 static CallGraphNode &CGdereference(const PairTy &P) { return *P.second; }
479 struct GraphTraits<const CallGraph *> : public GraphTraits<
480 const CallGraphNode *> {
481 static NodeType *getEntryNode(const CallGraph *CGN) {
482 return CGN->getExternalCallingNode(); // Start at the external node!
484 typedef std::pair<const Function *const, std::unique_ptr<CallGraphNode>>
486 typedef std::pointer_to_unary_function<const PairTy &, const CallGraphNode &>
489 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
490 typedef mapped_iterator<CallGraph::const_iterator, DerefFun> nodes_iterator;
491 static nodes_iterator nodes_begin(const CallGraph *CG) {
492 return map_iterator(CG->begin(), DerefFun(CGdereference));
494 static nodes_iterator nodes_end(const CallGraph *CG) {
495 return map_iterator(CG->end(), DerefFun(CGdereference));
498 static const CallGraphNode &CGdereference(const PairTy &P) {
503 } // End llvm namespace