[PM] Make the (really awesome) file comment here available as part of
[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 the are called by the
16 /// function 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/Function.h"
58 #include "llvm/Pass.h"
59 #include "llvm/Support/CallSite.h"
60 #include "llvm/Support/IncludeFile.h"
61 #include "llvm/Support/ValueHandle.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 and the \c ModulePass
71 /// which produces it.
72 ///
73 /// This class exposes both the interface to the call graph container and the
74 /// module pass which runs over a module of IR and produces the call graph.
75 ///
76 /// The core call graph itself can also be updated to reflect changes to the IR.
77 class CallGraph : public ModulePass {
78   Module *M;
79
80   typedef std::map<const Function *, CallGraphNode *> FunctionMapTy;
81
82   /// \brief A map from \c Function* to \c CallGraphNode*.
83   FunctionMapTy FunctionMap;
84
85   /// \brief Root is root of the call graph, or the external node if a 'main'
86   /// function couldn't be found.
87   CallGraphNode *Root;
88
89   /// \brief This node has edges to all external functions and those internal
90   /// functions that have their address taken.
91   CallGraphNode *ExternalCallingNode;
92
93   /// \brief This node has edges to it from all functions making indirect calls
94   /// or calling an external function.
95   CallGraphNode *CallsExternalNode;
96
97   /// \brief Replace the function represented by this node by another.
98   ///
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);
103
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);
107
108 public:
109   static char ID; // Class identification, replacement for typeinfo
110
111   typedef FunctionMapTy::iterator iterator;
112   typedef FunctionMapTy::const_iterator const_iterator;
113
114   /// \brief Returns the module the call graph corresponds to.
115   Module &getModule() const { return *M; }
116
117   inline iterator begin() { return FunctionMap.begin(); }
118   inline iterator end() { return FunctionMap.end(); }
119   inline const_iterator begin() const { return FunctionMap.begin(); }
120   inline const_iterator end() const { return FunctionMap.end(); }
121
122   /// \brief Returns the call graph node for the provided function.
123   inline const CallGraphNode *operator[](const Function *F) const {
124     const_iterator I = FunctionMap.find(F);
125     assert(I != FunctionMap.end() && "Function not in callgraph!");
126     return I->second;
127   }
128
129   /// \brief Returns the call graph node for the provided function.
130   inline CallGraphNode *operator[](const Function *F) {
131     const_iterator I = FunctionMap.find(F);
132     assert(I != FunctionMap.end() && "Function not in callgraph!");
133     return I->second;
134   }
135
136   /// \brief Returns the \c CallGraphNode which is used to represent
137   /// undetermined calls into the callgraph.
138   CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
139
140   CallGraphNode *getCallsExternalNode() const { return CallsExternalNode; }
141
142   /// \brief Returns the root/main method in the module, or some other root
143   /// node, such as the externalcallingnode.
144   CallGraphNode *getRoot() { return Root; }
145   const CallGraphNode *getRoot() const { return Root; }
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   CallGraph();
165   virtual ~CallGraph() { releaseMemory(); }
166
167   //===---------------------------------------------------------------------
168   // Implementation of the ModulePass interface needed here.
169   //
170
171   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
172   virtual bool runOnModule(Module &M);
173   virtual void releaseMemory();
174
175   void print(raw_ostream &o, const Module *) const;
176   void dump() const;
177 };
178
179 /// \brief A node in the call graph for a module.
180 ///
181 /// Typically represents a function in the call graph. There are also special
182 /// "null" nodes used to represent theoretical entries in the call graph.
183 class CallGraphNode {
184   friend class CallGraph;
185
186   AssertingVH<Function> F;
187
188 public:
189   /// \brief A pair of the calling instruction (a call or invoke)
190   /// and the call graph node being called.
191   typedef std::pair<WeakVH, CallGraphNode *> CallRecord;
192
193 private:
194   std::vector<CallRecord> CalledFunctions;
195
196   /// \brief The number of times that this CallGraphNode occurs in the
197   /// CalledFunctions array of this or other CallGraphNodes.
198   unsigned NumReferences;
199
200   CallGraphNode(const CallGraphNode &) LLVM_DELETED_FUNCTION;
201   void operator=(const CallGraphNode &) LLVM_DELETED_FUNCTION;
202
203   void DropRef() { --NumReferences; }
204   void AddRef() { ++NumReferences; }
205
206 public:
207   typedef std::vector<CallRecord> CalledFunctionsVector;
208
209   /// \brief Creates a node for the specified function.
210   inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
211
212   ~CallGraphNode() {
213     assert(NumReferences == 0 && "Node deleted while references remain");
214   }
215
216   typedef std::vector<CallRecord>::iterator iterator;
217   typedef std::vector<CallRecord>::const_iterator const_iterator;
218
219   /// \brief Returns the function that this call graph node represents.
220   Function *getFunction() const { return F; }
221
222   inline iterator begin() { return CalledFunctions.begin(); }
223   inline iterator end() { return CalledFunctions.end(); }
224   inline const_iterator begin() const { return CalledFunctions.begin(); }
225   inline const_iterator end() const { return CalledFunctions.end(); }
226   inline bool empty() const { return CalledFunctions.empty(); }
227   inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
228
229   /// \brief Returns the number of other CallGraphNodes in this CallGraph that
230   /// reference this node in their callee list.
231   unsigned getNumReferences() const { return NumReferences; }
232
233   /// \brief Returns the i'th called function.
234   CallGraphNode *operator[](unsigned i) const {
235     assert(i < CalledFunctions.size() && "Invalid index");
236     return CalledFunctions[i].second;
237   }
238
239   /// \brief Print out this call graph node.
240   void dump() const;
241   void print(raw_ostream &OS) const;
242
243   //===---------------------------------------------------------------------
244   // Methods to keep a call graph up to date with a function that has been
245   // modified
246   //
247
248   /// \brief Removes all edges from this CallGraphNode to any functions it
249   /// calls.
250   void removeAllCalledFunctions() {
251     while (!CalledFunctions.empty()) {
252       CalledFunctions.back().second->DropRef();
253       CalledFunctions.pop_back();
254     }
255   }
256
257   /// \brief Moves all the callee information from N to this node.
258   void stealCalledFunctionsFrom(CallGraphNode *N) {
259     assert(CalledFunctions.empty() &&
260            "Cannot steal callsite information if I already have some");
261     std::swap(CalledFunctions, N->CalledFunctions);
262   }
263
264   /// \brief Adds a function to the list of functions called by this one.
265   void addCalledFunction(CallSite CS, CallGraphNode *M) {
266     assert(!CS.getInstruction() || !CS.getCalledFunction() ||
267            !CS.getCalledFunction()->isIntrinsic());
268     CalledFunctions.push_back(std::make_pair(CS.getInstruction(), M));
269     M->AddRef();
270   }
271
272   void removeCallEdge(iterator I) {
273     I->second->DropRef();
274     *I = CalledFunctions.back();
275     CalledFunctions.pop_back();
276   }
277
278   /// \brief Removes the edge in the node for the specified call site.
279   ///
280   /// Note that this method takes linear time, so it should be used sparingly.
281   void removeCallEdgeFor(CallSite CS);
282
283   /// \brief Removes all call edges from this node to the specified callee
284   /// function.
285   ///
286   /// This takes more time to execute than removeCallEdgeTo, so it should not
287   /// be used unless necessary.
288   void removeAnyCallEdgeTo(CallGraphNode *Callee);
289
290   /// \brief Removes one edge associated with a null callsite from this node to
291   /// the specified callee function.
292   void removeOneAbstractEdgeTo(CallGraphNode *Callee);
293
294   /// \brief Replaces the edge in the node for the specified call site with a
295   /// new one.
296   ///
297   /// Note that this method takes linear time, so it should be used sparingly.
298   void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
299
300   /// \brief A special function that should only be used by the CallGraph class.
301   //
302   // FIXME: Make this private?
303   void allReferencesDropped() { NumReferences = 0; }
304 };
305
306 //===----------------------------------------------------------------------===//
307 // GraphTraits specializations for call graphs so that they can be treated as
308 // graphs by the generic graph algorithms.
309 //
310
311 // Provide graph traits for tranversing call graphs using standard graph
312 // traversals.
313 template <> struct GraphTraits<CallGraphNode *> {
314   typedef CallGraphNode NodeType;
315
316   typedef CallGraphNode::CallRecord CGNPairTy;
317   typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode *>
318   CGNDerefFun;
319
320   static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
321
322   typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
323
324   static inline ChildIteratorType child_begin(NodeType *N) {
325     return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
326   }
327   static inline ChildIteratorType child_end(NodeType *N) {
328     return map_iterator(N->end(), CGNDerefFun(CGNDeref));
329   }
330
331   static CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
332 };
333
334 template <> struct GraphTraits<const CallGraphNode *> {
335   typedef const CallGraphNode NodeType;
336   typedef NodeType::const_iterator ChildIteratorType;
337
338   static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
339   static inline ChildIteratorType child_begin(NodeType *N) {
340     return N->begin();
341   }
342   static inline ChildIteratorType child_end(NodeType *N) { return N->end(); }
343 };
344
345 template <>
346 struct GraphTraits<CallGraph *> : public GraphTraits<CallGraphNode *> {
347   static NodeType *getEntryNode(CallGraph *CGN) {
348     return CGN->getExternalCallingNode(); // Start at the external node!
349   }
350   typedef std::pair<const Function *, CallGraphNode *> PairTy;
351   typedef std::pointer_to_unary_function<PairTy, CallGraphNode &> DerefFun;
352
353   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
354   typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
355   static nodes_iterator nodes_begin(CallGraph *CG) {
356     return map_iterator(CG->begin(), DerefFun(CGdereference));
357   }
358   static nodes_iterator nodes_end(CallGraph *CG) {
359     return map_iterator(CG->end(), DerefFun(CGdereference));
360   }
361
362   static CallGraphNode &CGdereference(PairTy P) { return *P.second; }
363 };
364
365 template <>
366 struct GraphTraits<const CallGraph *> : public GraphTraits<
367                                             const CallGraphNode *> {
368   static NodeType *getEntryNode(const CallGraph *CGN) {
369     return CGN->getExternalCallingNode();
370   }
371   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
372   typedef CallGraph::const_iterator nodes_iterator;
373   static nodes_iterator nodes_begin(const CallGraph *CG) { return CG->begin(); }
374   static nodes_iterator nodes_end(const CallGraph *CG) { return CG->end(); }
375 };
376
377 } // End llvm namespace
378
379 // Make sure that any clients of this file link in CallGraph.cpp
380 FORCE_DEFINING_FILE_TO_BE_LINKED(CallGraph)
381
382 #endif