Move method out of line
[oota-llvm.git] / include / llvm / Analysis / DataStructure / 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/DataStructure/DSNode.h"
19
20 namespace llvm {
21
22 class GlobalValue;
23
24 //===----------------------------------------------------------------------===//
25 /// DSScalarMap - An instance of this class is used to keep track of all of 
26 /// which DSNode each scalar in a function points to.  This is specialized to
27 /// keep track of globals with nodes in the function, and to keep track of the 
28 /// unique DSNodeHandle being used by the scalar map.
29 ///
30 /// This class is crucial to the efficiency of DSA with some large SCC's.  In 
31 /// these cases, the cost of iterating over the scalar map dominates the cost
32 /// of DSA.  In all of these cases, the DSA phase is really trying to identify 
33 /// globals or unique node handles active in the function.
34 ///
35 class DSScalarMap {
36   typedef hash_map<Value*, DSNodeHandle> ValueMapTy;
37   ValueMapTy ValueMap;
38
39   typedef hash_set<GlobalValue*> GlobalSetTy;
40   GlobalSetTy GlobalSet;
41 public:
42
43   // Compatibility methods: provide an interface compatible with a map of 
44   // Value* to DSNodeHandle's.
45   typedef ValueMapTy::const_iterator const_iterator;
46   typedef ValueMapTy::iterator iterator;
47   iterator begin() { return ValueMap.begin(); }
48   iterator end()   { return ValueMap.end(); }
49   const_iterator begin() const { return ValueMap.begin(); }
50   const_iterator end() const { return ValueMap.end(); }
51   iterator find(Value *V) { return ValueMap.find(V); }
52   const_iterator find(Value *V) const { return ValueMap.find(V); }
53   unsigned count(Value *V) const { return ValueMap.count(V); }
54
55   void erase(Value *V) { erase(find(V)); }
56
57   /// replaceScalar - When an instruction needs to be modified, this method can
58   /// be used to update the scalar map to remove the old and insert the new.
59   ///
60   void replaceScalar(Value *Old, Value *New) {
61     iterator I = find(Old);
62     assert(I != end() && "Old value is not in the map!");
63     ValueMap.insert(std::make_pair(New, I->second));
64     erase(I);
65   }
66
67   DSNodeHandle &operator[](Value *V) {
68     std::pair<iterator,bool> IP = 
69       ValueMap.insert(std::make_pair(V, DSNodeHandle()));
70     if (IP.second) {  // Inserted the new entry into the map.
71       if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
72         GlobalSet.insert(GV);
73     }
74     return IP.first->second;
75   }
76
77   void erase(iterator I) { 
78     assert(I != ValueMap.end() && "Cannot erase end!");
79     if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first))
80       GlobalSet.erase(GV);
81     ValueMap.erase(I); 
82   }
83
84   void clear() {
85     ValueMap.clear();
86     GlobalSet.clear();
87   }
88
89   // Access to the global set: the set of all globals currently in the
90   // scalar map.
91   typedef GlobalSetTy::const_iterator global_iterator;
92   global_iterator global_begin() const { return GlobalSet.begin(); }
93   global_iterator global_end() const { return GlobalSet.end(); }
94 };
95
96
97 //===----------------------------------------------------------------------===//
98 /// DSGraph - The graph that represents a function.
99 ///
100 struct DSGraph {
101   // Public data-type declarations...
102   typedef DSScalarMap ScalarMapTy;
103   typedef hash_map<Function*, DSNodeHandle> ReturnNodesTy;
104   typedef hash_set<GlobalValue*> GlobalSetTy;
105   typedef ilist<DSNode> NodeListTy;
106
107   /// NodeMapTy - This data type is used when cloning one graph into another to
108   /// keep track of the correspondence between the nodes in the old and new
109   /// graphs.
110   typedef hash_map<const DSNode*, DSNodeHandle> NodeMapTy;
111 private:
112   DSGraph *GlobalsGraph;   // Pointer to the common graph of global objects
113   bool PrintAuxCalls;      // Should this graph print the Aux calls vector?
114
115   NodeListTy Nodes;
116   ScalarMapTy ScalarMap;
117
118   // ReturnNodes - A return value for every function merged into this graph.
119   // Each DSGraph may have multiple functions merged into it at any time, which
120   // is used for representing SCCs.
121   //
122   ReturnNodesTy ReturnNodes;
123
124   // FunctionCalls - This vector maintains a single entry for each call
125   // instruction in the current graph.  The first entry in the vector is the
126   // scalar that holds the return value for the call, the second is the function
127   // scalar being invoked, and the rest are pointer arguments to the function.
128   // This vector is built by the Local graph and is never modified after that.
129   //
130   std::vector<DSCallSite> FunctionCalls;
131
132   // AuxFunctionCalls - This vector contains call sites that have been processed
133   // by some mechanism.  In pratice, the BU Analysis uses this vector to hold
134   // the _unresolved_ call sites, because it cannot modify FunctionCalls.
135   //
136   std::vector<DSCallSite> AuxFunctionCalls;
137
138   // InlinedGlobals - This set records which globals have been inlined from
139   // other graphs (callers or callees, depending on the pass) into this one.
140   // 
141   GlobalSetTy InlinedGlobals;
142
143   /// TD - This is the target data object for the machine this graph is
144   /// constructed for.
145   const TargetData &TD;
146
147   void operator=(const DSGraph &); // DO NOT IMPLEMENT
148
149 public:
150   // Create a new, empty, DSGraph.
151   DSGraph(const TargetData &td)
152     : GlobalsGraph(0), PrintAuxCalls(false), TD(td) {}
153
154   // Compute the local DSGraph
155   DSGraph(const TargetData &td, Function &F, DSGraph *GlobalsGraph);
156
157   // Copy ctor - If you want to capture the node mapping between the source and
158   // destination graph, you may optionally do this by specifying a map to record
159   // this into.
160   //
161   // Note that a copied graph does not retain the GlobalsGraph pointer of the
162   // source.  You need to set a new GlobalsGraph with the setGlobalsGraph
163   // method.
164   //
165   DSGraph(const DSGraph &DSG);
166   DSGraph(const DSGraph &DSG, NodeMapTy &NodeMap);
167   ~DSGraph();
168
169   DSGraph *getGlobalsGraph() const { return GlobalsGraph; }
170   void setGlobalsGraph(DSGraph *G) { GlobalsGraph = G; }
171
172   /// getTargetData - Return the TargetData object for the current target.
173   ///
174   const TargetData &getTargetData() const { return TD; }
175
176   /// setPrintAuxCalls - If you call this method, the auxillary call vector will
177   /// be printed instead of the standard call vector to the dot file.
178   ///
179   void setPrintAuxCalls() { PrintAuxCalls = true; }
180   bool shouldPrintAuxCalls() const { return PrintAuxCalls; }
181
182   /// node_iterator/begin/end - Iterate over all of the nodes in the graph.  Be
183   /// extremely careful with these methods because any merging of nodes could
184   /// cause the node to be removed from this list.  This means that if you are
185   /// iterating over nodes and doing something that could cause _any_ node to
186   /// merge, your node_iterators into this graph can be invalidated.
187   typedef NodeListTy::compat_iterator node_iterator;
188   node_iterator node_begin() const { return Nodes.compat_begin(); }
189   node_iterator node_end()   const { return Nodes.compat_end(); }
190
191   /// getFunctionNames - Return a space separated list of the name of the
192   /// functions in this graph (if any)
193   ///
194   std::string getFunctionNames() const;
195
196   /// addNode - Add a new node to the graph.
197   ///
198   void addNode(DSNode *N) { Nodes.push_back(N); }
199   void unlinkNode(DSNode *N) { Nodes.remove(N); }
200
201   /// getScalarMap - Get a map that describes what the nodes the scalars in this
202   /// function point to...
203   ///
204   ScalarMapTy &getScalarMap() { return ScalarMap; }
205   const ScalarMapTy &getScalarMap() const { return ScalarMap; }
206
207   /// getFunctionCalls - Return the list of call sites in the original local
208   /// graph...
209   ///
210   const std::vector<DSCallSite> &getFunctionCalls() const {
211     return FunctionCalls;
212   }
213
214   /// getAuxFunctionCalls - Get the call sites as modified by whatever passes
215   /// have been run.
216   ///
217   std::vector<DSCallSite> &getAuxFunctionCalls() {
218     return AuxFunctionCalls;
219   }
220   const std::vector<DSCallSite> &getAuxFunctionCalls() const {
221     return AuxFunctionCalls;
222   }
223
224   /// getInlinedGlobals - Get the set of globals that are have been inlined
225   /// (from callees in BU or from callers in TD) into the current graph.
226   ///
227   GlobalSetTy& getInlinedGlobals() {
228     return InlinedGlobals;
229   }
230
231   /// getNodeForValue - Given a value that is used or defined in the body of the
232   /// current function, return the DSNode that it points to.
233   ///
234   DSNodeHandle &getNodeForValue(Value *V) { return ScalarMap[V]; }
235
236   const DSNodeHandle &getNodeForValue(Value *V) const {
237     ScalarMapTy::const_iterator I = ScalarMap.find(V);
238     assert(I != ScalarMap.end() &&
239            "Use non-const lookup function if node may not be in the map");
240     return I->second;
241   }
242
243   /// getReturnNodes - Return the mapping of functions to their return nodes for
244   /// this graph.
245   ///
246   const ReturnNodesTy &getReturnNodes() const { return ReturnNodes; }
247         ReturnNodesTy &getReturnNodes()       { return ReturnNodes; }
248
249   /// getReturnNodeFor - Return the return node for the specified function.
250   ///
251   DSNodeHandle &getReturnNodeFor(Function &F) {
252     ReturnNodesTy::iterator I = ReturnNodes.find(&F);
253     assert(I != ReturnNodes.end() && "F not in this DSGraph!");
254     return I->second;
255   }
256
257   const DSNodeHandle &getReturnNodeFor(Function &F) const {
258     ReturnNodesTy::const_iterator I = ReturnNodes.find(&F);
259     assert(I != ReturnNodes.end() && "F not in this DSGraph!");
260     return I->second;
261   }
262
263   /// getGraphSize - Return the number of nodes in this graph.
264   ///
265   unsigned getGraphSize() const {
266     return Nodes.size();
267   }
268
269   /// print - Print a dot graph to the specified ostream...
270   ///
271   void print(std::ostream &O) const;
272
273   /// dump - call print(std::cerr), for use from the debugger...
274   ///
275   void dump() const;
276
277   /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
278   /// then cleanup.  For use from the debugger.
279   ///
280   void viewGraph() const;
281
282   void writeGraphToFile(std::ostream &O, const std::string &GraphName) const;
283
284   /// maskNodeTypes - Apply a mask to all of the node types in the graph.  This
285   /// is useful for clearing out markers like Incomplete.
286   ///
287   void maskNodeTypes(unsigned Mask) {
288     for (node_iterator I = node_begin(), E = node_end(); I != E; ++I)
289       (*I)->maskNodeTypes(Mask);
290   }
291   void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
292
293   // markIncompleteNodes - Traverse the graph, identifying nodes that may be
294   // modified by other functions that have not been resolved yet.  This marks
295   // nodes that are reachable through three sources of "unknownness":
296   //   Global Variables, Function Calls, and Incoming Arguments
297   //
298   // For any node that may have unknown components (because something outside
299   // the scope of current analysis may have modified it), the 'Incomplete' flag
300   // is added to the NodeType.
301   //
302   enum MarkIncompleteFlags {
303     MarkFormalArgs = 1, IgnoreFormalArgs = 0,
304     IgnoreGlobals = 2, MarkGlobalsIncomplete = 0,
305   };
306   void markIncompleteNodes(unsigned Flags);
307
308   // removeDeadNodes - Use a reachability analysis to eliminate subgraphs that
309   // are unreachable.  This often occurs because the data structure doesn't
310   // "escape" into it's caller, and thus should be eliminated from the caller's
311   // graph entirely.  This is only appropriate to use when inlining graphs.
312   //
313   enum RemoveDeadNodesFlags {
314     RemoveUnreachableGlobals = 1, KeepUnreachableGlobals = 0,
315   };
316   void removeDeadNodes(unsigned Flags);
317
318   /// CloneFlags enum - Bits that may be passed into the cloneInto method to
319   /// specify how to clone the function graph.
320   enum CloneFlags {
321     StripAllocaBit        = 1 << 0, KeepAllocaBit     = 0,
322     DontCloneCallNodes    = 1 << 1, CloneCallNodes    = 0,
323     DontCloneAuxCallNodes = 1 << 2, CloneAuxCallNodes = 0,
324     StripModRefBits       = 1 << 3, KeepModRefBits    = 0,
325     StripIncompleteBit    = 1 << 4, KeepIncompleteBit = 0,
326     UpdateInlinedGlobals  = 1 << 5, DontUpdateInlinedGlobals = 0,
327   };
328
329   void updateFromGlobalGraph();
330
331   /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
332   /// nodes reachable from the two graphs, computing the mapping of nodes from
333   /// the first to the second graph.
334   ///
335   static void computeNodeMapping(const DSNodeHandle &NH1,
336                                  const DSNodeHandle &NH2, NodeMapTy &NodeMap,
337                                  bool StrictChecking = true);
338
339
340   /// cloneInto - Clone the specified DSGraph into the current graph.  The
341   /// translated ScalarMap for the old function is filled into the OldValMap
342   /// member, and the translated ReturnNodes map is returned into ReturnNodes.
343   /// OldNodeMap contains a mapping from the original nodes to the newly cloned
344   /// nodes.
345   ///
346   /// The CloneFlags member controls various aspects of the cloning process.
347   ///
348   void cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
349                  ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
350                  unsigned CloneFlags = 0);
351
352   /// mergeInGraph - The method is used for merging graphs together.  If the
353   /// argument graph is not *this, it makes a clone of the specified graph, then
354   /// merges the nodes specified in the call site with the formal arguments in
355   /// the graph.  If the StripAlloca's argument is 'StripAllocaBit' then Alloca
356   /// markers are removed from nodes.
357   ///
358   void mergeInGraph(const DSCallSite &CS, Function &F, const DSGraph &Graph,
359                     unsigned CloneFlags);
360
361   /// getCallSiteForArguments - Get the arguments and return value bindings for
362   /// the specified function in the current graph.
363   ///
364   DSCallSite getCallSiteForArguments(Function &F) const;
365
366   /// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
367   /// the context of this graph, return the DSCallSite for it.
368   DSCallSite getDSCallSiteForCallSite(CallSite CS) const;
369
370   // Methods for checking to make sure graphs are well formed...
371   void AssertNodeInGraph(const DSNode *N) const {
372     assert((!N || N->getParentGraph() == this) &&
373            "AssertNodeInGraph: Node is not in graph!");
374   }
375   void AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const;
376
377   void AssertCallSiteInGraph(const DSCallSite &CS) const;
378   void AssertCallNodesInGraph() const;
379   void AssertAuxCallNodesInGraph() const;
380
381   void AssertGraphOK() const;
382
383   /// removeTriviallyDeadNodes - After the graph has been constructed, this
384   /// method removes all unreachable nodes that are created because they got
385   /// merged with other nodes in the graph.  This is used as the first step of
386   /// removeDeadNodes.
387   ///
388   void removeTriviallyDeadNodes();
389 };
390
391
392 /// ReachabilityCloner - This class is used to incrementally clone and merge
393 /// nodes from a non-changing source graph into a potentially mutating
394 /// destination graph.  Nodes are only cloned over on demand, either in
395 /// responds to a merge() or getClonedNH() call.  When a node is cloned over,
396 /// all of the nodes reachable from it are automatically brought over as well.
397 ///
398 class ReachabilityCloner {
399   DSGraph &Dest;
400   const DSGraph &Src;
401
402   /// BitsToKeep - These bits are retained from the source node when the
403   /// source nodes are merged into the destination graph.
404   unsigned BitsToKeep;
405   unsigned CloneFlags;
406
407   // NodeMap - A mapping from nodes in the source graph to the nodes that
408   // represent them in the destination graph.
409   DSGraph::NodeMapTy NodeMap;
410 public:
411   ReachabilityCloner(DSGraph &dest, const DSGraph &src, unsigned cloneFlags)
412     : Dest(dest), Src(src), CloneFlags(cloneFlags) {
413     assert(&Dest != &Src && "Cannot clone from graph to same graph!");
414     BitsToKeep = ~DSNode::DEAD;
415     if (CloneFlags & DSGraph::StripAllocaBit)
416       BitsToKeep &= ~DSNode::AllocaNode;
417     if (CloneFlags & DSGraph::StripModRefBits)
418       BitsToKeep &= ~(DSNode::Modified | DSNode::Read);
419     if (CloneFlags & DSGraph::StripIncompleteBit)
420       BitsToKeep &= ~DSNode::Incomplete;
421   }
422   
423   DSNodeHandle getClonedNH(const DSNodeHandle &SrcNH);
424
425   void merge(const DSNodeHandle &NH, const DSNodeHandle &SrcNH);
426
427   /// mergeCallSite - Merge the nodes reachable from the specified src call
428   /// site into the nodes reachable from DestCS.
429   ///
430   void mergeCallSite(const DSCallSite &DestCS, const DSCallSite &SrcCS);
431
432   bool clonedAnyNodes() const { return !NodeMap.empty(); }
433
434   /// hasClonedNode - Return true if the specified node has been cloned from
435   /// the source graph into the destination graph.
436   bool hasClonedNode(const DSNode *N) {
437     return NodeMap.count(N);
438   }
439
440   void destroy() { NodeMap.clear(); }
441 };
442
443 } // End llvm namespace
444
445 #endif