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