[PM/AA] Have memdep explicitly get and use TargetLibraryInfo rather than
[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   ~CallGraph();
110
111   void print(raw_ostream &OS) const;
112   void dump() const;
113
114   typedef FunctionMapTy::iterator iterator;
115   typedef FunctionMapTy::const_iterator const_iterator;
116
117   /// \brief Returns the module the call graph corresponds to.
118   Module &getModule() const { return M; }
119
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(); }
124
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!");
129     return I->second.get();
130   }
131
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!");
136     return I->second.get();
137   }
138
139   /// \brief Returns the \c CallGraphNode which is used to represent
140   /// undetermined calls into the callgraph.
141   CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
142
143   CallGraphNode *getCallsExternalNode() const {
144     return CallsExternalNode.get();
145   }
146
147   //===---------------------------------------------------------------------
148   // Functions to keep a call graph up to date with a function that has been
149   // modified.
150   //
151
152   /// \brief Unlink the function from this module, returning it.
153   ///
154   /// Because this removes the function from the module, the call graph node is
155   /// destroyed.  This is only valid if the function does not call any other
156   /// functions (ie, there are no edges in it's CGN).  The easiest way to do
157   /// this is to dropAllReferences before calling this.
158   Function *removeFunctionFromModule(CallGraphNode *CGN);
159
160   /// \brief Similar to operator[], but this will insert a new CallGraphNode for
161   /// \c F if one does not already exist.
162   CallGraphNode *getOrInsertFunction(const Function *F);
163 };
164
165 /// \brief A node in the call graph for a module.
166 ///
167 /// Typically represents a function in the call graph. There are also special
168 /// "null" nodes used to represent theoretical entries in the call graph.
169 class CallGraphNode {
170 public:
171   /// \brief A pair of the calling instruction (a call or invoke)
172   /// and the call graph node being called.
173   typedef std::pair<WeakVH, CallGraphNode *> CallRecord;
174
175 public:
176   typedef std::vector<CallRecord> CalledFunctionsVector;
177
178   /// \brief Creates a node for the specified function.
179   inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
180
181   ~CallGraphNode() {
182     assert(NumReferences == 0 && "Node deleted while references remain");
183   }
184
185   typedef std::vector<CallRecord>::iterator iterator;
186   typedef std::vector<CallRecord>::const_iterator const_iterator;
187
188   /// \brief Returns the function that this call graph node represents.
189   Function *getFunction() const { return F; }
190
191   inline iterator begin() { return CalledFunctions.begin(); }
192   inline iterator end() { return CalledFunctions.end(); }
193   inline const_iterator begin() const { return CalledFunctions.begin(); }
194   inline const_iterator end() const { return CalledFunctions.end(); }
195   inline bool empty() const { return CalledFunctions.empty(); }
196   inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
197
198   /// \brief Returns the number of other CallGraphNodes in this CallGraph that
199   /// reference this node in their callee list.
200   unsigned getNumReferences() const { return NumReferences; }
201
202   /// \brief Returns the i'th called function.
203   CallGraphNode *operator[](unsigned i) const {
204     assert(i < CalledFunctions.size() && "Invalid index");
205     return CalledFunctions[i].second;
206   }
207
208   /// \brief Print out this call graph node.
209   void dump() const;
210   void print(raw_ostream &OS) const;
211
212   //===---------------------------------------------------------------------
213   // Methods to keep a call graph up to date with a function that has been
214   // modified
215   //
216
217   /// \brief Removes all edges from this CallGraphNode to any functions it
218   /// calls.
219   void removeAllCalledFunctions() {
220     while (!CalledFunctions.empty()) {
221       CalledFunctions.back().second->DropRef();
222       CalledFunctions.pop_back();
223     }
224   }
225
226   /// \brief Moves all the callee information from N to this node.
227   void stealCalledFunctionsFrom(CallGraphNode *N) {
228     assert(CalledFunctions.empty() &&
229            "Cannot steal callsite information if I already have some");
230     std::swap(CalledFunctions, N->CalledFunctions);
231   }
232
233   /// \brief Adds a function to the list of functions called by this one.
234   void addCalledFunction(CallSite CS, CallGraphNode *M) {
235     assert(!CS.getInstruction() || !CS.getCalledFunction() ||
236            !CS.getCalledFunction()->isIntrinsic() ||
237            !Intrinsic::isLeaf(CS.getCalledFunction()->getIntrinsicID()));
238     CalledFunctions.emplace_back(CS.getInstruction(), M);
239     M->AddRef();
240   }
241
242   void removeCallEdge(iterator I) {
243     I->second->DropRef();
244     *I = CalledFunctions.back();
245     CalledFunctions.pop_back();
246   }
247
248   /// \brief Removes the edge in the node for the specified call site.
249   ///
250   /// Note that this method takes linear time, so it should be used sparingly.
251   void removeCallEdgeFor(CallSite CS);
252
253   /// \brief Removes all call edges from this node to the specified callee
254   /// function.
255   ///
256   /// This takes more time to execute than removeCallEdgeTo, so it should not
257   /// be used unless necessary.
258   void removeAnyCallEdgeTo(CallGraphNode *Callee);
259
260   /// \brief Removes one edge associated with a null callsite from this node to
261   /// the specified callee function.
262   void removeOneAbstractEdgeTo(CallGraphNode *Callee);
263
264   /// \brief Replaces the edge in the node for the specified call site with a
265   /// new one.
266   ///
267   /// Note that this method takes linear time, so it should be used sparingly.
268   void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
269
270 private:
271   friend class CallGraph;
272
273   AssertingVH<Function> F;
274
275   std::vector<CallRecord> CalledFunctions;
276
277   /// \brief The number of times that this CallGraphNode occurs in the
278   /// CalledFunctions array of this or other CallGraphNodes.
279   unsigned NumReferences;
280
281   CallGraphNode(const CallGraphNode &) = delete;
282   void operator=(const CallGraphNode &) = delete;
283
284   void DropRef() { --NumReferences; }
285   void AddRef() { ++NumReferences; }
286
287   /// \brief A special function that should only be used by the CallGraph class.
288   void allReferencesDropped() { NumReferences = 0; }
289 };
290
291 /// \brief The \c ModulePass which wraps up a \c CallGraph and the logic to
292 /// build it.
293 ///
294 /// This class exposes both the interface to the call graph container and the
295 /// module pass which runs over a module of IR and produces the call graph. The
296 /// call graph interface is entirelly a wrapper around a \c CallGraph object
297 /// which is stored internally for each module.
298 class CallGraphWrapperPass : public ModulePass {
299   std::unique_ptr<CallGraph> G;
300
301 public:
302   static char ID; // Class identification, replacement for typeinfo
303
304   CallGraphWrapperPass();
305   ~CallGraphWrapperPass() override;
306
307   /// \brief The internal \c CallGraph around which the rest of this interface
308   /// is wrapped.
309   const CallGraph &getCallGraph() const { return *G; }
310   CallGraph &getCallGraph() { return *G; }
311
312   typedef CallGraph::iterator iterator;
313   typedef CallGraph::const_iterator const_iterator;
314
315   /// \brief Returns the module the call graph corresponds to.
316   Module &getModule() const { return G->getModule(); }
317
318   inline iterator begin() { return G->begin(); }
319   inline iterator end() { return G->end(); }
320   inline const_iterator begin() const { return G->begin(); }
321   inline const_iterator end() const { return G->end(); }
322
323   /// \brief Returns the call graph node for the provided function.
324   inline const CallGraphNode *operator[](const Function *F) const {
325     return (*G)[F];
326   }
327
328   /// \brief Returns the call graph node for the provided function.
329   inline CallGraphNode *operator[](const Function *F) { return (*G)[F]; }
330
331   /// \brief Returns the \c CallGraphNode which is used to represent
332   /// undetermined calls into the callgraph.
333   CallGraphNode *getExternalCallingNode() const {
334     return G->getExternalCallingNode();
335   }
336
337   CallGraphNode *getCallsExternalNode() const {
338     return G->getCallsExternalNode();
339   }
340
341   //===---------------------------------------------------------------------
342   // Functions to keep a call graph up to date with a function that has been
343   // modified.
344   //
345
346   /// \brief Unlink the function from this module, returning it.
347   ///
348   /// Because this removes the function from the module, the call graph node is
349   /// destroyed.  This is only valid if the function does not call any other
350   /// functions (ie, there are no edges in it's CGN).  The easiest way to do
351   /// this is to dropAllReferences before calling this.
352   Function *removeFunctionFromModule(CallGraphNode *CGN) {
353     return G->removeFunctionFromModule(CGN);
354   }
355
356   /// \brief Similar to operator[], but this will insert a new CallGraphNode for
357   /// \c F if one does not already exist.
358   CallGraphNode *getOrInsertFunction(const Function *F) {
359     return G->getOrInsertFunction(F);
360   }
361
362   //===---------------------------------------------------------------------
363   // Implementation of the ModulePass interface needed here.
364   //
365
366   void getAnalysisUsage(AnalysisUsage &AU) const override;
367   bool runOnModule(Module &M) override;
368   void releaseMemory() override;
369
370   void print(raw_ostream &o, const Module *) const override;
371   void dump() const;
372 };
373
374 //===----------------------------------------------------------------------===//
375 // GraphTraits specializations for call graphs so that they can be treated as
376 // graphs by the generic graph algorithms.
377 //
378
379 // Provide graph traits for tranversing call graphs using standard graph
380 // traversals.
381 template <> struct GraphTraits<CallGraphNode *> {
382   typedef CallGraphNode NodeType;
383
384   typedef CallGraphNode::CallRecord CGNPairTy;
385   typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode *>
386   CGNDerefFun;
387
388   static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
389
390   typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
391
392   static inline ChildIteratorType child_begin(NodeType *N) {
393     return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
394   }
395   static inline ChildIteratorType child_end(NodeType *N) {
396     return map_iterator(N->end(), CGNDerefFun(CGNDeref));
397   }
398
399   static CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
400 };
401
402 template <> struct GraphTraits<const CallGraphNode *> {
403   typedef const CallGraphNode NodeType;
404
405   typedef CallGraphNode::CallRecord CGNPairTy;
406   typedef std::pointer_to_unary_function<CGNPairTy, const CallGraphNode *>
407       CGNDerefFun;
408
409   static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
410
411   typedef mapped_iterator<NodeType::const_iterator, CGNDerefFun>
412       ChildIteratorType;
413
414   static inline ChildIteratorType child_begin(NodeType *N) {
415     return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
416   }
417   static inline ChildIteratorType child_end(NodeType *N) {
418     return map_iterator(N->end(), CGNDerefFun(CGNDeref));
419   }
420
421   static const CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
422 };
423
424 template <>
425 struct GraphTraits<CallGraph *> : public GraphTraits<CallGraphNode *> {
426   static NodeType *getEntryNode(CallGraph *CGN) {
427     return CGN->getExternalCallingNode(); // Start at the external node!
428   }
429   typedef std::pair<const Function *const, std::unique_ptr<CallGraphNode>>
430       PairTy;
431   typedef std::pointer_to_unary_function<const PairTy &, CallGraphNode &>
432       DerefFun;
433
434   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
435   typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
436   static nodes_iterator nodes_begin(CallGraph *CG) {
437     return map_iterator(CG->begin(), DerefFun(CGdereference));
438   }
439   static nodes_iterator nodes_end(CallGraph *CG) {
440     return map_iterator(CG->end(), DerefFun(CGdereference));
441   }
442
443   static CallGraphNode &CGdereference(const PairTy &P) { return *P.second; }
444 };
445
446 template <>
447 struct GraphTraits<const CallGraph *> : public GraphTraits<
448                                             const CallGraphNode *> {
449   static NodeType *getEntryNode(const CallGraph *CGN) {
450     return CGN->getExternalCallingNode(); // Start at the external node!
451   }
452   typedef std::pair<const Function *const, std::unique_ptr<CallGraphNode>>
453       PairTy;
454   typedef std::pointer_to_unary_function<const PairTy &, const CallGraphNode &>
455       DerefFun;
456
457   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
458   typedef mapped_iterator<CallGraph::const_iterator, DerefFun> nodes_iterator;
459   static nodes_iterator nodes_begin(const CallGraph *CG) {
460     return map_iterator(CG->begin(), DerefFun(CGdereference));
461   }
462   static nodes_iterator nodes_end(const CallGraph *CG) {
463     return map_iterator(CG->end(), DerefFun(CGdereference));
464   }
465
466   static const CallGraphNode &CGdereference(const PairTy &P) {
467     return *P.second;
468   }
469 };
470
471 } // End llvm namespace
472
473 #endif