-Wdeprecated cleanup: Make CallGraph movable by default by using unique_ptr members...
[oota-llvm.git] / include / llvm / Analysis / CallGraph.h
1 //===- CallGraph.h - Build a Module's call graph ----------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
11 /// This file provides interfaces used to build and manipulate a call graph,
12 /// which is a very useful tool for interprocedural optimization.
13 ///
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.
17 ///
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.
29 ///
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.
35 ///
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.
39 ///
40 /// Because of these properties, the CallGraph captures a conservative superset
41 /// of all of the caller-callee relationships, which is useful for
42 /// transformations.
43 ///
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).
49 ///
50 //===----------------------------------------------------------------------===//
51
52 #ifndef LLVM_ANALYSIS_CALLGRAPH_H
53 #define LLVM_ANALYSIS_CALLGRAPH_H
54
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"
62 #include <map>
63
64 namespace llvm {
65
66 class Function;
67 class Module;
68 class CallGraphNode;
69
70 /// \brief The basic data container for the call graph of a \c Module of IR.
71 ///
72 /// This class exposes both the interface to the call graph for a module of IR.
73 ///
74 /// The core call graph itself can also be updated to reflect changes to the IR.
75 class CallGraph {
76   Module &M;
77
78   typedef std::map<const Function *, std::unique_ptr<CallGraphNode>>
79       FunctionMapTy;
80
81   /// \brief A map from \c Function* to \c CallGraphNode*.
82   FunctionMapTy FunctionMap;
83
84   /// \brief Root is root of the call graph, or the external node if a 'main'
85   /// function couldn't be found.
86   CallGraphNode *Root;
87
88   /// \brief This node has edges to all external functions and those internal
89   /// functions that have their address taken.
90   CallGraphNode *ExternalCallingNode;
91
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;
95
96   /// \brief Replace the function represented by this node by another.
97   ///
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);
102
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);
106
107 public:
108   CallGraph(Module &M);
109   // Default move ctor is fine, the dtor just does things to CallsExternalNode
110   // (if non-null) and the values in the FunctionMap, all of which should be
111   // null post-move, so no-op the dtor on the moved-from side.
112   CallGraph(CallGraph &&) = default;
113   ~CallGraph();
114
115   void print(raw_ostream &OS) const;
116   void dump() const;
117
118   typedef FunctionMapTy::iterator iterator;
119   typedef FunctionMapTy::const_iterator const_iterator;
120
121   /// \brief Returns the module the call graph corresponds to.
122   Module &getModule() const { return M; }
123
124   inline iterator begin() { return FunctionMap.begin(); }
125   inline iterator end() { return FunctionMap.end(); }
126   inline const_iterator begin() const { return FunctionMap.begin(); }
127   inline const_iterator end() const { return FunctionMap.end(); }
128
129   /// \brief Returns the call graph node for the provided function.
130   inline const CallGraphNode *operator[](const Function *F) const {
131     const_iterator I = FunctionMap.find(F);
132     assert(I != FunctionMap.end() && "Function not in callgraph!");
133     return I->second.get();
134   }
135
136   /// \brief Returns the call graph node for the provided function.
137   inline CallGraphNode *operator[](const Function *F) {
138     const_iterator I = FunctionMap.find(F);
139     assert(I != FunctionMap.end() && "Function not in callgraph!");
140     return I->second.get();
141   }
142
143   /// \brief Returns the \c CallGraphNode which is used to represent
144   /// undetermined calls into the callgraph.
145   CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
146
147   CallGraphNode *getCallsExternalNode() const {
148     return CallsExternalNode.get();
149   }
150
151   //===---------------------------------------------------------------------
152   // Functions to keep a call graph up to date with a function that has been
153   // modified.
154   //
155
156   /// \brief Unlink the function from this module, returning it.
157   ///
158   /// Because this removes the function from the module, the call graph node is
159   /// destroyed.  This is only valid if the function does not call any other
160   /// functions (ie, there are no edges in it's CGN).  The easiest way to do
161   /// this is to dropAllReferences before calling this.
162   Function *removeFunctionFromModule(CallGraphNode *CGN);
163
164   /// \brief Similar to operator[], but this will insert a new CallGraphNode for
165   /// \c F if one does not already exist.
166   CallGraphNode *getOrInsertFunction(const Function *F);
167 };
168
169 /// \brief A node in the call graph for a module.
170 ///
171 /// Typically represents a function in the call graph. There are also special
172 /// "null" nodes used to represent theoretical entries in the call graph.
173 class CallGraphNode {
174 public:
175   /// \brief A pair of the calling instruction (a call or invoke)
176   /// and the call graph node being called.
177   typedef std::pair<WeakVH, CallGraphNode *> CallRecord;
178
179 public:
180   typedef std::vector<CallRecord> CalledFunctionsVector;
181
182   /// \brief Creates a node for the specified function.
183   inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
184
185   ~CallGraphNode() {
186     assert(NumReferences == 0 && "Node deleted while references remain");
187   }
188
189   typedef std::vector<CallRecord>::iterator iterator;
190   typedef std::vector<CallRecord>::const_iterator const_iterator;
191
192   /// \brief Returns the function that this call graph node represents.
193   Function *getFunction() const { return F; }
194
195   inline iterator begin() { return CalledFunctions.begin(); }
196   inline iterator end() { return CalledFunctions.end(); }
197   inline const_iterator begin() const { return CalledFunctions.begin(); }
198   inline const_iterator end() const { return CalledFunctions.end(); }
199   inline bool empty() const { return CalledFunctions.empty(); }
200   inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
201
202   /// \brief Returns the number of other CallGraphNodes in this CallGraph that
203   /// reference this node in their callee list.
204   unsigned getNumReferences() const { return NumReferences; }
205
206   /// \brief Returns the i'th called function.
207   CallGraphNode *operator[](unsigned i) const {
208     assert(i < CalledFunctions.size() && "Invalid index");
209     return CalledFunctions[i].second;
210   }
211
212   /// \brief Print out this call graph node.
213   void dump() const;
214   void print(raw_ostream &OS) const;
215
216   //===---------------------------------------------------------------------
217   // Methods to keep a call graph up to date with a function that has been
218   // modified
219   //
220
221   /// \brief Removes all edges from this CallGraphNode to any functions it
222   /// calls.
223   void removeAllCalledFunctions() {
224     while (!CalledFunctions.empty()) {
225       CalledFunctions.back().second->DropRef();
226       CalledFunctions.pop_back();
227     }
228   }
229
230   /// \brief Moves all the callee information from N to this node.
231   void stealCalledFunctionsFrom(CallGraphNode *N) {
232     assert(CalledFunctions.empty() &&
233            "Cannot steal callsite information if I already have some");
234     std::swap(CalledFunctions, N->CalledFunctions);
235   }
236
237   /// \brief Adds a function to the list of functions called by this one.
238   void addCalledFunction(CallSite CS, CallGraphNode *M) {
239     assert(!CS.getInstruction() || !CS.getCalledFunction() ||
240            !CS.getCalledFunction()->isIntrinsic() ||
241            !Intrinsic::isLeaf(CS.getCalledFunction()->getIntrinsicID()));
242     CalledFunctions.emplace_back(CS.getInstruction(), M);
243     M->AddRef();
244   }
245
246   void removeCallEdge(iterator I) {
247     I->second->DropRef();
248     *I = CalledFunctions.back();
249     CalledFunctions.pop_back();
250   }
251
252   /// \brief Removes the edge in the node for the specified call site.
253   ///
254   /// Note that this method takes linear time, so it should be used sparingly.
255   void removeCallEdgeFor(CallSite CS);
256
257   /// \brief Removes all call edges from this node to the specified callee
258   /// function.
259   ///
260   /// This takes more time to execute than removeCallEdgeTo, so it should not
261   /// be used unless necessary.
262   void removeAnyCallEdgeTo(CallGraphNode *Callee);
263
264   /// \brief Removes one edge associated with a null callsite from this node to
265   /// the specified callee function.
266   void removeOneAbstractEdgeTo(CallGraphNode *Callee);
267
268   /// \brief Replaces the edge in the node for the specified call site with a
269   /// new one.
270   ///
271   /// Note that this method takes linear time, so it should be used sparingly.
272   void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
273
274 private:
275   friend class CallGraph;
276
277   AssertingVH<Function> F;
278
279   std::vector<CallRecord> CalledFunctions;
280
281   /// \brief The number of times that this CallGraphNode occurs in the
282   /// CalledFunctions array of this or other CallGraphNodes.
283   unsigned NumReferences;
284
285   CallGraphNode(const CallGraphNode &) = delete;
286   void operator=(const CallGraphNode &) = delete;
287
288   void DropRef() { --NumReferences; }
289   void AddRef() { ++NumReferences; }
290
291   /// \brief A special function that should only be used by the CallGraph class.
292   void allReferencesDropped() { NumReferences = 0; }
293 };
294
295 /// \brief An analysis pass to compute the \c CallGraph for a \c Module.
296 ///
297 /// This class implements the concept of an analysis pass used by the \c
298 /// ModuleAnalysisManager to run an analysis over a module and cache the
299 /// resulting data.
300 class CallGraphAnalysis {
301 public:
302   /// \brief A formulaic typedef to inform clients of the result type.
303   typedef CallGraph Result;
304
305   static void *ID() { return (void *)&PassID; }
306
307   /// \brief Compute the \c CallGraph for the module \c M.
308   ///
309   /// The real work here is done in the \c CallGraph constructor.
310   CallGraph run(Module *M) { return CallGraph(*M); }
311
312 private:
313   static char PassID;
314 };
315
316 /// \brief The \c ModulePass which wraps up a \c CallGraph and the logic to
317 /// build it.
318 ///
319 /// This class exposes both the interface to the call graph container and the
320 /// module pass which runs over a module of IR and produces the call graph. The
321 /// call graph interface is entirelly a wrapper around a \c CallGraph object
322 /// which is stored internally for each module.
323 class CallGraphWrapperPass : public ModulePass {
324   std::unique_ptr<CallGraph> G;
325
326 public:
327   static char ID; // Class identification, replacement for typeinfo
328
329   CallGraphWrapperPass();
330   ~CallGraphWrapperPass() override;
331
332   /// \brief The internal \c CallGraph around which the rest of this interface
333   /// is wrapped.
334   const CallGraph &getCallGraph() const { return *G; }
335   CallGraph &getCallGraph() { return *G; }
336
337   typedef CallGraph::iterator iterator;
338   typedef CallGraph::const_iterator const_iterator;
339
340   /// \brief Returns the module the call graph corresponds to.
341   Module &getModule() const { return G->getModule(); }
342
343   inline iterator begin() { return G->begin(); }
344   inline iterator end() { return G->end(); }
345   inline const_iterator begin() const { return G->begin(); }
346   inline const_iterator end() const { return G->end(); }
347
348   /// \brief Returns the call graph node for the provided function.
349   inline const CallGraphNode *operator[](const Function *F) const {
350     return (*G)[F];
351   }
352
353   /// \brief Returns the call graph node for the provided function.
354   inline CallGraphNode *operator[](const Function *F) { return (*G)[F]; }
355
356   /// \brief Returns the \c CallGraphNode which is used to represent
357   /// undetermined calls into the callgraph.
358   CallGraphNode *getExternalCallingNode() const {
359     return G->getExternalCallingNode();
360   }
361
362   CallGraphNode *getCallsExternalNode() const {
363     return G->getCallsExternalNode();
364   }
365
366   //===---------------------------------------------------------------------
367   // Functions to keep a call graph up to date with a function that has been
368   // modified.
369   //
370
371   /// \brief Unlink the function from this module, returning it.
372   ///
373   /// Because this removes the function from the module, the call graph node is
374   /// destroyed.  This is only valid if the function does not call any other
375   /// functions (ie, there are no edges in it's CGN).  The easiest way to do
376   /// this is to dropAllReferences before calling this.
377   Function *removeFunctionFromModule(CallGraphNode *CGN) {
378     return G->removeFunctionFromModule(CGN);
379   }
380
381   /// \brief Similar to operator[], but this will insert a new CallGraphNode for
382   /// \c F if one does not already exist.
383   CallGraphNode *getOrInsertFunction(const Function *F) {
384     return G->getOrInsertFunction(F);
385   }
386
387   //===---------------------------------------------------------------------
388   // Implementation of the ModulePass interface needed here.
389   //
390
391   void getAnalysisUsage(AnalysisUsage &AU) const override;
392   bool runOnModule(Module &M) override;
393   void releaseMemory() override;
394
395   void print(raw_ostream &o, const Module *) const override;
396   void dump() const;
397 };
398
399 //===----------------------------------------------------------------------===//
400 // GraphTraits specializations for call graphs so that they can be treated as
401 // graphs by the generic graph algorithms.
402 //
403
404 // Provide graph traits for tranversing call graphs using standard graph
405 // traversals.
406 template <> struct GraphTraits<CallGraphNode *> {
407   typedef CallGraphNode NodeType;
408
409   typedef CallGraphNode::CallRecord CGNPairTy;
410   typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode *>
411   CGNDerefFun;
412
413   static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
414
415   typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
416
417   static inline ChildIteratorType child_begin(NodeType *N) {
418     return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
419   }
420   static inline ChildIteratorType child_end(NodeType *N) {
421     return map_iterator(N->end(), CGNDerefFun(CGNDeref));
422   }
423
424   static CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
425 };
426
427 template <> struct GraphTraits<const CallGraphNode *> {
428   typedef const CallGraphNode NodeType;
429
430   typedef CallGraphNode::CallRecord CGNPairTy;
431   typedef std::pointer_to_unary_function<CGNPairTy, const CallGraphNode *>
432       CGNDerefFun;
433
434   static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
435
436   typedef mapped_iterator<NodeType::const_iterator, CGNDerefFun>
437       ChildIteratorType;
438
439   static inline ChildIteratorType child_begin(NodeType *N) {
440     return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
441   }
442   static inline ChildIteratorType child_end(NodeType *N) {
443     return map_iterator(N->end(), CGNDerefFun(CGNDeref));
444   }
445
446   static const CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
447 };
448
449 template <>
450 struct GraphTraits<CallGraph *> : public GraphTraits<CallGraphNode *> {
451   static NodeType *getEntryNode(CallGraph *CGN) {
452     return CGN->getExternalCallingNode(); // Start at the external node!
453   }
454   typedef std::pair<const Function *const, std::unique_ptr<CallGraphNode>>
455       PairTy;
456   typedef std::pointer_to_unary_function<const PairTy &, CallGraphNode &>
457       DerefFun;
458
459   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
460   typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
461   static nodes_iterator nodes_begin(CallGraph *CG) {
462     return map_iterator(CG->begin(), DerefFun(CGdereference));
463   }
464   static nodes_iterator nodes_end(CallGraph *CG) {
465     return map_iterator(CG->end(), DerefFun(CGdereference));
466   }
467
468   static CallGraphNode &CGdereference(const PairTy &P) { return *P.second; }
469 };
470
471 template <>
472 struct GraphTraits<const CallGraph *> : public GraphTraits<
473                                             const CallGraphNode *> {
474   static NodeType *getEntryNode(const CallGraph *CGN) {
475     return CGN->getExternalCallingNode(); // Start at the external node!
476   }
477   typedef std::pair<const Function *const, std::unique_ptr<CallGraphNode>>
478       PairTy;
479   typedef std::pointer_to_unary_function<const PairTy &, const CallGraphNode &>
480       DerefFun;
481
482   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
483   typedef mapped_iterator<CallGraph::const_iterator, DerefFun> nodes_iterator;
484   static nodes_iterator nodes_begin(const CallGraph *CG) {
485     return map_iterator(CG->begin(), DerefFun(CGdereference));
486   }
487   static nodes_iterator nodes_end(const CallGraph *CG) {
488     return map_iterator(CG->end(), DerefFun(CGdereference));
489   }
490
491   static const CallGraphNode &CGdereference(const PairTy &P) {
492     return *P.second;
493   }
494 };
495
496 } // End llvm namespace
497
498 #endif