* Remove a lot of obsolete #if 0'd code
[oota-llvm.git] / include / llvm / Analysis / DSGraph.h
1 //===- DSGraph.h - Represent a collection of data structures ----*- C++ -*-===//
2 //
3 // This header defines the primative classes that make up a data structure
4 // graph.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #ifndef LLVM_ANALYSIS_DSGRAPH_H
9 #define LLVM_ANALYSIS_DSGRAPH_H
10
11 #include <vector>
12 #include <map>
13
14 class Function;
15 class Value;
16 class GlobalValue;
17 class Type;
18
19 class DSNode;                  // Each node in the graph
20 class DSGraph;                 // A graph for a function
21 class DSNodeIterator;          // Data structure graph traversal iterator
22
23 //===----------------------------------------------------------------------===//
24 /// DSNodeHandle - Implement a "handle" to a data structure node that takes care
25 /// of all of the add/un'refing of the node to prevent the backpointers in the
26 /// graph from getting out of date.  This class represents a "pointer" in the
27 /// graph, whose destination is an indexed offset into a node.
28 ///
29 class DSNodeHandle {
30   DSNode *N;
31   unsigned Offset;
32 public:
33   // Allow construction, destruction, and assignment...
34   DSNodeHandle(DSNode *n = 0, unsigned offs = 0) : N(0), Offset(offs) {
35     setNode(n);
36   }
37   DSNodeHandle(const DSNodeHandle &H) : N(0), Offset(H.Offset) { setNode(H.N); }
38   ~DSNodeHandle() { setNode((DSNode*)0); }
39   DSNodeHandle &operator=(const DSNodeHandle &H) {
40     setNode(H.N); Offset = H.Offset;
41     return *this;
42   }
43
44   bool operator<(const DSNodeHandle &H) const {  // Allow sorting
45     return N < H.N || (N == H.N && Offset < H.Offset);
46   }
47   bool operator==(const DSNodeHandle &H) const { // Allow comparison
48     return N == H.N && Offset == H.Offset;
49   }
50   bool operator!=(const DSNodeHandle &H) const { return !operator==(H); }
51
52   // Allow explicit conversion to DSNode...
53   DSNode *getNode() const { return N; }
54   unsigned getOffset() const { return Offset; }
55
56   inline void setNode(DSNode *N);  // Defined inline later...
57   void setOffset(unsigned O) { Offset = O; }
58
59   void addEdgeTo(unsigned LinkNo, const DSNodeHandle &N);
60   void addEdgeTo(const DSNodeHandle &N) { addEdgeTo(0, N); }
61
62   /// mergeWith - Merge the logical node pointed to by 'this' with the node
63   /// pointed to by 'N'.
64   ///
65   void mergeWith(const DSNodeHandle &N);
66
67   // hasLink - Return true if there is a link at the specified offset...
68   inline bool hasLink(unsigned Num) const;
69
70   /// getLink - Treat this current node pointer as a pointer to a structure of
71   /// some sort.  This method will return the pointer a mem[this+Num]
72   ///
73   inline const DSNodeHandle *getLink(unsigned Num) const;
74   inline DSNodeHandle *getLink(unsigned Num);
75
76   inline void setLink(unsigned Num, const DSNodeHandle &NH);
77 };
78
79
80 //===----------------------------------------------------------------------===//
81 /// DSNode - Data structure node class
82 ///
83 /// This class represents an untyped memory object of Size bytes.  It keeps
84 /// track of any pointers that have been stored into the object as well as the
85 /// different types represented in this object.
86 ///
87 class DSNode {
88   /// Links - Contains one entry for every _distinct_ pointer field in the
89   /// memory block.  These are demand allocated and indexed by the MergeMap
90   /// vector.
91   ///
92   std::vector<DSNodeHandle> Links;
93
94   /// MergeMap - Maps from every byte in the object to a signed byte number.
95   /// This map is neccesary due to the merging that is possible as part of the
96   /// unification algorithm.  To merge two distinct bytes of the object together
97   /// into a single logical byte, the indexes for the two bytes are set to the
98   /// same value.  This fully general merging is capable of representing all
99   /// manners of array merging if neccesary.
100   ///
101   /// This map is also used to map outgoing pointers to various byte offsets in
102   /// this data structure node.  If this value is >= 0, then it indicates that
103   /// the numbered entry in the Links vector contains the outgoing edge for this
104   /// byte offset.  In this way, the Links vector can be demand allocated and
105   /// byte elements of the node may be merged without needing a Link allocated
106   /// for it.
107   ///
108   /// Initially, each each element of the MergeMap is assigned a unique negative
109   /// number, which are then merged as the unification occurs.
110   ///
111   std::vector<signed char> MergeMap;
112
113   /// Referrers - Keep track of all of the node handles that point to this
114   /// DSNode.  These pointers may need to be updated to point to a different
115   /// node if this node gets merged with it.
116   ///
117   std::vector<DSNodeHandle*> Referrers;
118
119   /// TypeEntries - As part of the merging process of this algorithm, nodes of
120   /// different types can be represented by this single DSNode.  This vector is
121   /// kept sorted.
122   ///
123   typedef std::pair<const Type *, unsigned> TypeRec;
124   std::vector<TypeRec> TypeEntries;
125
126   /// Globals - The list of global values that are merged into this node.
127   ///
128   std::vector<GlobalValue*> Globals;
129
130   void operator=(const DSNode &); // DO NOT IMPLEMENT
131 public:
132   enum NodeTy {
133     ShadowNode = 0,        // Nothing is known about this node...
134     ScalarNode = 1 << 0,   // Scalar of the current function contains this value
135     AllocaNode = 1 << 1,   // This node was allocated with alloca
136     NewNode    = 1 << 2,   // This node was allocated with malloc
137     GlobalNode = 1 << 3,   // This node was allocated by a global var decl
138     Incomplete = 1 << 4,   // This node may not be complete
139   };
140   
141   /// NodeType - A union of the above bits.  "Shadow" nodes do not add any flags
142   /// to the nodes in the data structure graph, so it is possible to have nodes
143   /// with a value of 0 for their NodeType.  Scalar and Alloca markers go away
144   /// when function graphs are inlined.
145   ///
146   unsigned char NodeType;
147
148   DSNode(enum NodeTy NT, const Type *T);
149   DSNode(const DSNode &);
150
151   ~DSNode() {
152 #ifndef NDEBUG
153     dropAllReferences();  // Only needed to satisfy assertion checks...
154     assert(Referrers.empty() && "Referrers to dead node exist!");
155 #endif
156   }
157
158   // Iterator for graph interface...
159   typedef DSNodeIterator iterator;
160   typedef DSNodeIterator const_iterator;
161   inline iterator begin() const;   // Defined in DSGraphTraits.h
162   inline iterator end() const;
163
164   //===--------------------------------------------------
165   // Accessors
166
167   // getSize - Return the maximum number of bytes occupied by this object...
168   unsigned getSize() const { return MergeMap.size(); }
169
170   // getTypeEntries - Return the possible types and their offsets in this object
171   const std::vector<TypeRec> &getTypeEntries() const { return TypeEntries; }
172
173   // getReferrers - Return a list of the pointers to this node...
174   const std::vector<DSNodeHandle*> &getReferrers() const { return Referrers; }
175
176
177   /// hasLink - Return true if this memory object has a link at the specified
178   /// location.
179   ///
180   bool hasLink(unsigned i) const {
181     assert(i < getSize() && "Field Link index is out of range!");
182     return MergeMap[i] >= 0;
183   }
184
185   DSNodeHandle *getLink(unsigned i) {
186     if (hasLink(i))
187       return &Links[MergeMap[i]];
188     return 0;
189   }
190   const DSNodeHandle *getLink(unsigned i) const {
191     if (hasLink(i))
192       return &Links[MergeMap[i]];
193     return 0;
194   }
195
196   int getMergeMapLabel(unsigned i) const {
197     assert(i < MergeMap.size() && "MergeMap index out of range!");
198     return MergeMap[i];
199   }
200
201   /// setLink - Set the link at the specified offset to the specified
202   /// NodeHandle, replacing what was there.  It is uncommon to use this method,
203   /// instead one of the higher level methods should be used, below.
204   ///
205   void setLink(unsigned i, const DSNodeHandle &NH);
206
207   /// addEdgeTo - Add an edge from the current node to the specified node.  This
208   /// can cause merging of nodes in the graph.
209   ///
210   void addEdgeTo(unsigned Offset, const DSNodeHandle &NH);
211
212   /// mergeWith - Merge this node and the specified node, moving all links to
213   /// and from the argument node into the current node, deleting the node
214   /// argument.  Offset indicates what offset the specified node is to be merged
215   /// into the current node.
216   ///
217   /// The specified node may be a null pointer (in which case, nothing happens).
218   ///
219   void mergeWith(const DSNodeHandle &NH, unsigned Offset);
220
221   /// mergeIndexes - If we discover that two indexes are equivalent and must be
222   /// merged, this function is used to do the dirty work.
223   ///
224   void mergeIndexes(unsigned idx1, unsigned idx2) {
225     assert(idx1 < getSize() && idx2 < getSize() && "Indexes out of range!");
226     signed char MV1 = MergeMap[idx1];
227     signed char MV2 = MergeMap[idx2];
228     if (MV1 != MV2)
229       mergeMappedValues(MV1, MV2);
230   }
231
232
233   /// addGlobal - Add an entry for a global value to the Globals list.  This
234   /// also marks the node with the 'G' flag if it does not already have it.
235   ///
236   void addGlobal(GlobalValue *GV);
237   const std::vector<GlobalValue*> &getGlobals() const { return Globals; }
238   std::vector<GlobalValue*> &getGlobals() { return Globals; }
239
240   void print(std::ostream &O, const DSGraph *G) const;
241   void dump() const;
242
243   void dropAllReferences() {
244     Links.clear();
245   }
246
247   /// remapLinks - Change all of the Links in the current node according to the
248   /// specified mapping.
249   void remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap);
250
251 private:
252   friend class DSNodeHandle;
253   // addReferrer - Keep the referrer set up to date...
254   void addReferrer(DSNodeHandle *H) { Referrers.push_back(H); }
255   void removeReferrer(DSNodeHandle *H);
256
257   /// rewriteMergeMap - Loop over the mergemap, replacing any references to the
258   /// index From to be references to the index To.
259   ///
260   void rewriteMergeMap(signed char From, signed char To) {
261     assert(From != To && "Cannot change something into itself!");
262     for (unsigned i = 0, e = MergeMap.size(); i != e; ++i)
263       if (MergeMap[i] == From)
264         MergeMap[i] = To;
265   }
266
267   /// mergeMappedValues - This is the higher level form of rewriteMergeMap.  It
268   /// is fully capable of merging links together if neccesary as well as simply
269   /// rewriting the map entries.
270   ///
271   void mergeMappedValues(signed char V1, signed char V2);
272 };
273
274
275 //===----------------------------------------------------------------------===//
276 // Define inline DSNodeHandle functions that depend on the definition of DSNode
277 //
278
279 inline void DSNodeHandle::setNode(DSNode *n) {
280   if (N) N->removeReferrer(this);
281   N = n;
282   if (N) N->addReferrer(this);
283 }
284
285 inline bool DSNodeHandle::hasLink(unsigned Num) const {
286   assert(N && "DSNodeHandle does not point to a node yet!");
287   return N->hasLink(Num+Offset);
288 }
289
290
291 /// getLink - Treat this current node pointer as a pointer to a structure of
292 /// some sort.  This method will return the pointer a mem[this+Num]
293 ///
294 inline const DSNodeHandle *DSNodeHandle::getLink(unsigned Num) const {
295   assert(N && "DSNodeHandle does not point to a node yet!");
296   return N->getLink(Num+Offset);
297 }
298 inline DSNodeHandle *DSNodeHandle::getLink(unsigned Num) {
299   assert(N && "DSNodeHandle does not point to a node yet!");
300   return N->getLink(Num+Offset);
301 }
302
303 inline void DSNodeHandle::setLink(unsigned Num, const DSNodeHandle &NH) {
304   assert(N && "DSNodeHandle does not point to a node yet!");
305   N->setLink(Num+Offset, NH);
306 }
307
308 ///  addEdgeTo - Add an edge from the current node to the specified node.  This
309 /// can cause merging of nodes in the graph.
310 ///
311 inline void DSNodeHandle::addEdgeTo(unsigned LinkNo, const DSNodeHandle &Node) {
312   assert(N && "DSNodeHandle does not point to a node yet!");
313   N->addEdgeTo(LinkNo+Offset, Node);
314 }
315
316 /// mergeWith - Merge the logical node pointed to by 'this' with the node
317 /// pointed to by 'N'.
318 ///
319 inline void DSNodeHandle::mergeWith(const DSNodeHandle &Node) {
320   assert(N && "DSNodeHandle does not point to a node yet!");
321   N->mergeWith(Node, Offset);
322 }
323
324
325 //===----------------------------------------------------------------------===//
326 /// DSGraph - The graph that represents a function.
327 ///
328 class DSGraph {
329   Function *Func;
330   std::vector<DSNode*> Nodes;
331   DSNodeHandle RetNode;                          // Node that gets returned...
332   std::map<Value*, DSNodeHandle> ValueMap;
333
334 #if 0
335   // GlobalsGraph -- Reference to the common graph of globally visible objects.
336   // This includes GlobalValues, New nodes, Cast nodes, and Calls.
337   // 
338   GlobalDSGraph* GlobalsGraph;
339 #endif
340
341   // FunctionCalls - This vector maintains a single entry for each call
342   // instruction in the current graph.  Each call entry contains DSNodeHandles
343   // that refer to the arguments that are passed into the function call.  The
344   // first entry in the vector is the scalar that holds the return value for the
345   // call, the second is the function scalar being invoked, and the rest are
346   // pointer arguments to the function.
347   //
348   std::vector<std::vector<DSNodeHandle> > FunctionCalls;
349
350   void operator=(const DSGraph &); // DO NOT IMPLEMENT
351 public:
352   DSGraph() : Func(0) {}           // Create a new, empty, DSGraph.
353   DSGraph(Function &F);            // Compute the local DSGraph
354   DSGraph(const DSGraph &DSG);     // Copy ctor
355   ~DSGraph();
356
357   bool hasFunction() const { return Func != 0; }
358   Function &getFunction() const { return *Func; }
359
360   /// getNodes - Get a vector of all the nodes in the graph
361   /// 
362   const std::vector<DSNode*> &getNodes() const { return Nodes; }
363         std::vector<DSNode*> &getNodes()       { return Nodes; }
364
365   /// addNode - Add a new node to the graph.
366   ///
367   void addNode(DSNode *N) { Nodes.push_back(N); }
368
369   /// getValueMap - Get a map that describes what the nodes the scalars in this
370   /// function point to...
371   ///
372   std::map<Value*, DSNodeHandle> &getValueMap() { return ValueMap; }
373   const std::map<Value*, DSNodeHandle> &getValueMap() const { return ValueMap;}
374
375   std::vector<std::vector<DSNodeHandle> > &getFunctionCalls() {
376     return FunctionCalls;
377   }
378   const std::vector<std::vector<DSNodeHandle> > &getFunctionCalls() const {
379     return FunctionCalls;
380   }
381
382   /// getNodeForValue - Given a value that is used or defined in the body of the
383   /// current function, return the DSNode that it points to.
384   ///
385   DSNodeHandle &getNodeForValue(Value *V) { return ValueMap[V]; }
386
387   const DSNodeHandle &getRetNode() const { return RetNode; }
388         DSNodeHandle &getRetNode()       { return RetNode; }
389
390   unsigned getGraphSize() const {
391     return Nodes.size();
392   }
393
394   void print(std::ostream &O) const;
395   void dump() const;
396   void writeGraphToFile(std::ostream &O, const std::string &GraphName) const;
397
398   // maskNodeTypes - Apply a mask to all of the node types in the graph.  This
399   // is useful for clearing out markers like Scalar or Incomplete.
400   //
401   void maskNodeTypes(unsigned char Mask);
402   void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
403
404   // markIncompleteNodes - Traverse the graph, identifying nodes that may be
405   // modified by other functions that have not been resolved yet.  This marks
406   // nodes that are reachable through three sources of "unknownness":
407   //   Global Variables, Function Calls, and Incoming Arguments
408   //
409   // For any node that may have unknown components (because something outside
410   // the scope of current analysis may have modified it), the 'Incomplete' flag
411   // is added to the NodeType.
412   //
413   void markIncompleteNodes(bool markFormalArgs = true);
414
415   // removeTriviallyDeadNodes - After the graph has been constructed, this
416   // method removes all unreachable nodes that are created because they got
417   // merged with other nodes in the graph.
418   //
419   void removeTriviallyDeadNodes(bool KeepAllGlobals = false);
420
421   // removeDeadNodes - Use a more powerful reachability analysis to eliminate
422   // subgraphs that are unreachable.  This often occurs because the data
423   // structure doesn't "escape" into it's caller, and thus should be eliminated
424   // from the caller's graph entirely.  This is only appropriate to use when
425   // inlining graphs.
426   //
427   void removeDeadNodes(bool KeepAllGlobals = false, bool KeepCalls = true);
428
429   // cloneInto - Clone the specified DSGraph into the current graph, returning
430   // the Return node of the graph.  The translated ValueMap for the old function
431   // is filled into the OldValMap member.
432   // If StripScalars (StripAllocas) is set to true, Scalar (Alloca) markers
433   // are removed from the graph as the graph is being cloned.
434   // If CopyCallers is set to true, the PendingCallers list is copied.
435   // If CopyOrigCalls is set to true, the OrigFunctionCalls list is copied.
436   //
437   DSNodeHandle cloneInto(const DSGraph &G,
438                          std::map<Value*, DSNodeHandle> &OldValMap,
439                          std::map<const DSNode*, DSNode*> &OldNodeMap,
440                          bool StripScalars = false, bool StripAllocas = false,
441                          bool CopyCallers = true, bool CopyOrigCalls = true);
442
443 #if 0
444   // cloneGlobalInto - Clone the given global node (or the node for the given
445   // GlobalValue) from the GlobalsGraph and all its target links (recursively).
446   // 
447   DSNode* cloneGlobalInto(const DSNode* GNode);
448   DSNode* cloneGlobalInto(GlobalValue* GV) {
449     assert(!GV || (((DSGraph*) GlobalsGraph)->ValueMap[GV] != 0));
450     return GV? cloneGlobalInto(((DSGraph*) GlobalsGraph)->ValueMap[GV]) : 0;
451   }
452 #endif
453
454 private:
455   bool isNodeDead(DSNode *N);
456 };
457
458 #endif