* cloneReachable* and clonePartiallyInto are not obsolete
[oota-llvm.git] / include / llvm / Analysis / DSGraph.h
1 //===- DSGraph.h - Represent a collection of data structures ----*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This header defines the data structure graph (DSGraph) and the
11 // ReachabilityCloner class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_DSGRAPH_H
16 #define LLVM_ANALYSIS_DSGRAPH_H
17
18 #include "llvm/Analysis/DSNode.h"
19
20 namespace llvm {
21
22 class GlobalValue;
23
24 //===----------------------------------------------------------------------===//
25 /// DSGraph - The graph that represents a function.
26 ///
27 struct DSGraph {
28   // Public data-type declarations...
29   typedef hash_map<Value*, DSNodeHandle> ScalarMapTy;
30   typedef hash_map<Function*, DSNodeHandle> ReturnNodesTy;
31   typedef hash_set<GlobalValue*> GlobalSetTy;
32
33   /// NodeMapTy - This data type is used when cloning one graph into another to
34   /// keep track of the correspondence between the nodes in the old and new
35   /// graphs.
36   typedef hash_map<const DSNode*, DSNodeHandle> NodeMapTy;
37 private:
38   DSGraph *GlobalsGraph;   // Pointer to the common graph of global objects
39   bool PrintAuxCalls;      // Should this graph print the Aux calls vector?
40
41   std::vector<DSNode*> Nodes;
42   ScalarMapTy ScalarMap;
43
44   // ReturnNodes - A return value for every function merged into this graph.
45   // Each DSGraph may have multiple functions merged into it at any time, which
46   // is used for representing SCCs.
47   //
48   ReturnNodesTy ReturnNodes;
49
50   // FunctionCalls - This vector maintains a single entry for each call
51   // instruction in the current graph.  The first entry in the vector is the
52   // scalar that holds the return value for the call, the second is the function
53   // scalar being invoked, and the rest are pointer arguments to the function.
54   // This vector is built by the Local graph and is never modified after that.
55   //
56   std::vector<DSCallSite> FunctionCalls;
57
58   // AuxFunctionCalls - This vector contains call sites that have been processed
59   // by some mechanism.  In pratice, the BU Analysis uses this vector to hold
60   // the _unresolved_ call sites, because it cannot modify FunctionCalls.
61   //
62   std::vector<DSCallSite> AuxFunctionCalls;
63
64   // InlinedGlobals - This set records which globals have been inlined from
65   // other graphs (callers or callees, depending on the pass) into this one.
66   // 
67   GlobalSetTy InlinedGlobals;
68
69   /// TD - This is the target data object for the machine this graph is
70   /// constructed for.
71   const TargetData &TD;
72
73   void operator=(const DSGraph &); // DO NOT IMPLEMENT
74
75 public:
76   // Create a new, empty, DSGraph.
77   DSGraph(const TargetData &td)
78     : GlobalsGraph(0), PrintAuxCalls(false), TD(td) {}
79
80   // Compute the local DSGraph
81   DSGraph(const TargetData &td, Function &F, DSGraph *GlobalsGraph);
82
83   // Copy ctor - If you want to capture the node mapping between the source and
84   // destination graph, you may optionally do this by specifying a map to record
85   // this into.
86   //
87   // Note that a copied graph does not retain the GlobalsGraph pointer of the
88   // source.  You need to set a new GlobalsGraph with the setGlobalsGraph
89   // method.
90   //
91   DSGraph(const DSGraph &DSG);
92   DSGraph(const DSGraph &DSG, NodeMapTy &NodeMap);
93   ~DSGraph();
94
95   DSGraph *getGlobalsGraph() const { return GlobalsGraph; }
96   void setGlobalsGraph(DSGraph *G) { GlobalsGraph = G; }
97
98   /// getTargetData - Return the TargetData object for the current target.
99   ///
100   const TargetData &getTargetData() const { return TD; }
101
102   /// setPrintAuxCalls - If you call this method, the auxillary call vector will
103   /// be printed instead of the standard call vector to the dot file.
104   ///
105   void setPrintAuxCalls() { PrintAuxCalls = true; }
106   bool shouldPrintAuxCalls() const { return PrintAuxCalls; }
107
108   /// getNodes - Get a vector of all the nodes in the graph
109   /// 
110   const std::vector<DSNode*> &getNodes() const { return Nodes; }
111         std::vector<DSNode*> &getNodes()       { return Nodes; }
112
113   /// getFunctionNames - Return a space separated list of the name of the
114   /// functions in this graph (if any)
115   std::string getFunctionNames() const;
116
117   /// addNode - Add a new node to the graph.
118   ///
119   void addNode(DSNode *N) { Nodes.push_back(N); }
120
121   /// getScalarMap - Get a map that describes what the nodes the scalars in this
122   /// function point to...
123   ///
124   ScalarMapTy &getScalarMap() { return ScalarMap; }
125   const ScalarMapTy &getScalarMap() const { return ScalarMap; }
126
127   /// getFunctionCalls - Return the list of call sites in the original local
128   /// graph...
129   ///
130   const std::vector<DSCallSite> &getFunctionCalls() const {
131     return FunctionCalls;
132   }
133
134   /// getAuxFunctionCalls - Get the call sites as modified by whatever passes
135   /// have been run.
136   ///
137   std::vector<DSCallSite> &getAuxFunctionCalls() {
138     return AuxFunctionCalls;
139   }
140   const std::vector<DSCallSite> &getAuxFunctionCalls() const {
141     return AuxFunctionCalls;
142   }
143
144   /// getInlinedGlobals - Get the set of globals that are have been inlined
145   /// (from callees in BU or from callers in TD) into the current graph.
146   ///
147   GlobalSetTy& getInlinedGlobals() {
148     return InlinedGlobals;
149   }
150
151   /// getNodeForValue - Given a value that is used or defined in the body of the
152   /// current function, return the DSNode that it points to.
153   ///
154   DSNodeHandle &getNodeForValue(Value *V) { return ScalarMap[V]; }
155
156   const DSNodeHandle &getNodeForValue(Value *V) const {
157     ScalarMapTy::const_iterator I = ScalarMap.find(V);
158     assert(I != ScalarMap.end() &&
159            "Use non-const lookup function if node may not be in the map");
160     return I->second;
161   }
162
163   /// getReturnNodes - Return the mapping of functions to their return nodes for
164   /// this graph.
165   const ReturnNodesTy &getReturnNodes() const { return ReturnNodes; }
166         ReturnNodesTy &getReturnNodes()       { return ReturnNodes; }
167
168   /// getReturnNodeFor - Return the return node for the specified function.
169   ///
170   DSNodeHandle &getReturnNodeFor(Function &F) {
171     ReturnNodesTy::iterator I = ReturnNodes.find(&F);
172     assert(I != ReturnNodes.end() && "F not in this DSGraph!");
173     return I->second;
174   }
175
176   const DSNodeHandle &getReturnNodeFor(Function &F) const {
177     ReturnNodesTy::const_iterator I = ReturnNodes.find(&F);
178     assert(I != ReturnNodes.end() && "F not in this DSGraph!");
179     return I->second;
180   }
181
182   /// getGraphSize - Return the number of nodes in this graph.
183   ///
184   unsigned getGraphSize() const {
185     return Nodes.size();
186   }
187
188   /// print - Print a dot graph to the specified ostream...
189   ///
190   void print(std::ostream &O) const;
191
192   /// dump - call print(std::cerr), for use from the debugger...
193   ///
194   void dump() const;
195
196   /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
197   /// then cleanup.  For use from the debugger.
198   void viewGraph() const;
199
200   void writeGraphToFile(std::ostream &O, const std::string &GraphName) const;
201
202   /// maskNodeTypes - Apply a mask to all of the node types in the graph.  This
203   /// is useful for clearing out markers like Incomplete.
204   ///
205   void maskNodeTypes(unsigned Mask) {
206     for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
207       Nodes[i]->maskNodeTypes(Mask);
208   }
209   void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
210
211   // markIncompleteNodes - Traverse the graph, identifying nodes that may be
212   // modified by other functions that have not been resolved yet.  This marks
213   // nodes that are reachable through three sources of "unknownness":
214   //   Global Variables, Function Calls, and Incoming Arguments
215   //
216   // For any node that may have unknown components (because something outside
217   // the scope of current analysis may have modified it), the 'Incomplete' flag
218   // is added to the NodeType.
219   //
220   enum MarkIncompleteFlags {
221     MarkFormalArgs = 1, IgnoreFormalArgs = 0,
222     IgnoreGlobals = 2, MarkGlobalsIncomplete = 0,
223   };
224   void markIncompleteNodes(unsigned Flags);
225
226   // removeDeadNodes - Use a reachability analysis to eliminate subgraphs that
227   // are unreachable.  This often occurs because the data structure doesn't
228   // "escape" into it's caller, and thus should be eliminated from the caller's
229   // graph entirely.  This is only appropriate to use when inlining graphs.
230   //
231   enum RemoveDeadNodesFlags {
232     RemoveUnreachableGlobals = 1, KeepUnreachableGlobals = 0,
233   };
234   void removeDeadNodes(unsigned Flags);
235
236   /// CloneFlags enum - Bits that may be passed into the cloneInto method to
237   /// specify how to clone the function graph.
238   enum CloneFlags {
239     StripAllocaBit        = 1 << 0, KeepAllocaBit     = 0,
240     DontCloneCallNodes    = 1 << 1, CloneCallNodes    = 0,
241     DontCloneAuxCallNodes = 1 << 2, CloneAuxCallNodes = 0,
242     StripModRefBits       = 1 << 3, KeepModRefBits    = 0,
243     StripIncompleteBit    = 1 << 4, KeepIncompleteBit = 0,
244     UpdateInlinedGlobals  = 1 << 5, DontUpdateInlinedGlobals = 0,
245   };
246
247   void updateFromGlobalGraph();
248
249   /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
250   /// nodes reachable from the two graphs, computing the mapping of nodes from
251   /// the first to the second graph.
252   ///
253   static void computeNodeMapping(const DSNodeHandle &NH1,
254                                  const DSNodeHandle &NH2, NodeMapTy &NodeMap,
255                                  bool StrictChecking = true);
256
257
258   /// cloneInto - Clone the specified DSGraph into the current graph.  The
259   /// translated ScalarMap for the old function is filled into the OldValMap
260   /// member, and the translated ReturnNodes map is returned into ReturnNodes.
261   /// OldNodeMap contains a mapping from the original nodes to the newly cloned
262   /// nodes.
263   ///
264   /// The CloneFlags member controls various aspects of the cloning process.
265   ///
266   void cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
267                  ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
268                  unsigned CloneFlags = 0);
269
270   /// mergeInGraph - The method is used for merging graphs together.  If the
271   /// argument graph is not *this, it makes a clone of the specified graph, then
272   /// merges the nodes specified in the call site with the formal arguments in
273   /// the graph.  If the StripAlloca's argument is 'StripAllocaBit' then Alloca
274   /// markers are removed from nodes.
275   ///
276   void mergeInGraph(const DSCallSite &CS, Function &F, const DSGraph &Graph,
277                     unsigned CloneFlags);
278
279
280   /// getCallSiteForArguments - Get the arguments and return value bindings for
281   /// the specified function in the current graph.
282   ///
283   DSCallSite getCallSiteForArguments(Function &F) const;
284
285   // Methods for checking to make sure graphs are well formed...
286   void AssertNodeInGraph(const DSNode *N) const {
287     assert((!N || N->getParentGraph() == this) &&
288            "AssertNodeInGraph: Node is not in graph!");
289   }
290   void AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
291     assert(std::find(N->getGlobals().begin(), N->getGlobals().end(), GV) !=
292            N->getGlobals().end() && "Global value not in node!");
293   }
294
295   void AssertCallSiteInGraph(const DSCallSite &CS) const {
296     if (CS.isIndirectCall())
297       AssertNodeInGraph(CS.getCalleeNode());
298     AssertNodeInGraph(CS.getRetVal().getNode());
299     for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
300       AssertNodeInGraph(CS.getPtrArg(j).getNode());
301   }
302
303   void AssertCallNodesInGraph() const {
304     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
305       AssertCallSiteInGraph(FunctionCalls[i]);
306   }
307   void AssertAuxCallNodesInGraph() const {
308     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
309       AssertCallSiteInGraph(AuxFunctionCalls[i]);
310   }
311
312   void AssertGraphOK() const;
313
314   /// removeTriviallyDeadNodes - After the graph has been constructed, this
315   /// method removes all unreachable nodes that are created because they got
316   /// merged with other nodes in the graph.  This is used as the first step of
317   /// removeDeadNodes.
318   ///
319   void removeTriviallyDeadNodes();
320 };
321
322
323   /// ReachabilityCloner - This class is used to incrementally clone and merge
324   /// nodes from a non-changing source graph into a potentially mutating
325   /// destination graph.  Nodes are only cloned over on demand, either in
326   /// responds to a merge() or getClonedNH() call.  When a node is cloned over,
327   /// all of the nodes reachable from it are automatically brought over as well.
328   class ReachabilityCloner {
329     DSGraph &Dest;
330     const DSGraph &Src;
331
332     /// BitsToKeep - These bits are retained from the source node when the
333     /// source nodes are merged into the destination graph.
334     unsigned BitsToKeep;
335     unsigned CloneFlags;
336
337     // NodeMap - A mapping from nodes in the source graph to the nodes that
338     // represent them in the destination graph.
339     DSGraph::NodeMapTy NodeMap;
340   public:
341     ReachabilityCloner(DSGraph &dest, const DSGraph &src, unsigned cloneFlags)
342       : Dest(dest), Src(src), CloneFlags(cloneFlags) {
343       assert(&Dest != &Src && "Cannot clone from graph to same graph!");
344       BitsToKeep = ~DSNode::DEAD;
345       if (CloneFlags & DSGraph::StripAllocaBit)
346         BitsToKeep &= ~DSNode::AllocaNode;
347       if (CloneFlags & DSGraph::StripModRefBits)
348         BitsToKeep &= ~(DSNode::Modified | DSNode::Read);
349       if (CloneFlags & DSGraph::StripIncompleteBit)
350         BitsToKeep &= ~DSNode::Incomplete;
351     }
352     
353     DSNodeHandle getClonedNH(const DSNodeHandle &SrcNH);
354
355     void merge(const DSNodeHandle &NH, const DSNodeHandle &SrcNH);
356
357     /// mergeCallSite - Merge the nodes reachable from the specified src call
358     /// site into the nodes reachable from DestCS.
359     void mergeCallSite(const DSCallSite &DestCS, const DSCallSite &SrcCS);
360
361     bool clonedNode() const { return !NodeMap.empty(); }
362
363     void destroy() { NodeMap.clear(); }
364   };
365 } // End llvm namespace
366
367 #endif