move header
[oota-llvm.git] / include / llvm / Analysis / DataStructure / DSNode.h
1 //===- DSNode.h - Node definition for datastructure graphs ------*- 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 // Data structure graph nodes and some implementation of DSNodeHandle.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ANALYSIS_DSNODE_H
15 #define LLVM_ANALYSIS_DSNODE_H
16
17 #include "llvm/Analysis/DataStructure/DSSupport.h"
18 #include "llvm/ADT/hash_map"
19
20 namespace llvm {
21
22 template<typename BaseType>
23 class DSNodeIterator;          // Data structure graph traversal iterator
24 class TargetData;
25
26 //===----------------------------------------------------------------------===//
27 /// DSNode - Data structure node class
28 ///
29 /// This class represents an untyped memory object of Size bytes.  It keeps
30 /// track of any pointers that have been stored into the object as well as the
31 /// different types represented in this object.
32 ///
33 class DSNode {
34   /// NumReferrers - The number of DSNodeHandles pointing to this node... if
35   /// this is a forwarding node, then this is the number of node handles which
36   /// are still forwarding over us.
37   ///
38   unsigned NumReferrers;
39
40   /// ForwardNH - This NodeHandle contain the node (and offset into the node)
41   /// that this node really is.  When nodes get folded together, the node to be
42   /// eliminated has these fields filled in, otherwise ForwardNH.getNode() is
43   /// null.
44   ///
45   DSNodeHandle ForwardNH;
46
47   /// Next, Prev - These instance variables are used to keep the node on a
48   /// doubly-linked ilist in the DSGraph.
49   ///
50   DSNode *Next, *Prev;
51   friend struct ilist_traits<DSNode>;
52
53   /// Size - The current size of the node.  This should be equal to the size of
54   /// the current type record.
55   ///
56   unsigned Size;
57
58   /// ParentGraph - The graph this node is currently embedded into.
59   ///
60   DSGraph *ParentGraph;
61
62   /// Ty - Keep track of the current outer most type of this object, in addition
63   /// to whether or not it has been indexed like an array or not.  If the
64   /// isArray bit is set, the node cannot grow.
65   ///
66   const Type *Ty;                 // The type itself...
67
68   /// Links - Contains one entry for every sizeof(void*) bytes in this memory
69   /// object.  Note that if the node is not a multiple of size(void*) bytes
70   /// large, that there is an extra entry for the "remainder" of the node as
71   /// well.  For this reason, nodes of 1 byte in size do have one link.
72   ///
73   std::vector<DSNodeHandle> Links;
74
75   /// Globals - The list of global values that are merged into this node.
76   ///
77   std::vector<GlobalValue*> Globals;
78
79   void operator=(const DSNode &); // DO NOT IMPLEMENT
80   DSNode(const DSNode &);         // DO NOT IMPLEMENT
81 public:
82   enum NodeTy {
83     ShadowNode  = 0,        // Nothing is known about this node...
84     AllocaNode  = 1 << 0,   // This node was allocated with alloca
85     HeapNode    = 1 << 1,   // This node was allocated with malloc
86     GlobalNode  = 1 << 2,   // This node was allocated by a global var decl
87     UnknownNode = 1 << 3,   // This node points to unknown allocated memory
88     Incomplete  = 1 << 4,   // This node may not be complete
89
90     Modified    = 1 << 5,   // This node is modified in this context
91     Read        = 1 << 6,   // This node is read in this context
92
93     Array       = 1 << 7,   // This node is treated like an array
94     //#ifndef NDEBUG
95     DEAD        = 1 << 8,   // This node is dead and should not be pointed to
96     //#endif
97
98     Composition = AllocaNode | HeapNode | GlobalNode | UnknownNode
99   };
100
101   /// NodeType - A union of the above bits.  "Shadow" nodes do not add any flags
102   /// to the nodes in the data structure graph, so it is possible to have nodes
103   /// with a value of 0 for their NodeType.
104   ///
105 private:
106   unsigned short NodeType;
107 public:
108
109   /// DSNode ctor - Create a node of the specified type, inserting it into the
110   /// specified graph.
111   ///
112   DSNode(const Type *T, DSGraph *G);
113
114   /// DSNode "copy ctor" - Copy the specified node, inserting it into the
115   /// specified graph.  If NullLinks is true, then null out all of the links,
116   /// but keep the same number of them.  This can be used for efficiency if the
117   /// links are just going to be clobbered anyway.
118   ///
119   DSNode(const DSNode &, DSGraph *G, bool NullLinks = false);
120
121   ~DSNode() {
122     dropAllReferences();
123     assert(hasNoReferrers() && "Referrers to dead node exist!");
124   }
125
126   // Iterator for graph interface... Defined in DSGraphTraits.h
127   typedef DSNodeIterator<DSNode> iterator;
128   typedef DSNodeIterator<const DSNode> const_iterator;
129   inline iterator begin();
130   inline iterator end();
131   inline const_iterator begin() const;
132   inline const_iterator end() const;
133
134   //===--------------------------------------------------
135   // Accessors
136
137   /// getSize - Return the maximum number of bytes occupied by this object...
138   ///
139   unsigned getSize() const { return Size; }
140
141   /// getType - Return the node type of this object...
142   ///
143   const Type *getType() const { return Ty; }
144
145   bool isArray() const { return NodeType & Array; }
146
147   /// hasNoReferrers - Return true if nothing is pointing to this node at all.
148   ///
149   bool hasNoReferrers() const { return getNumReferrers() == 0; }
150
151   /// getNumReferrers - This method returns the number of referrers to the
152   /// current node.  Note that if this node is a forwarding node, this will
153   /// return the number of nodes forwarding over the node!
154   unsigned getNumReferrers() const { return NumReferrers; }
155
156   DSGraph *getParentGraph() const { return ParentGraph; }
157   void setParentGraph(DSGraph *G) { ParentGraph = G; }
158
159
160   /// getTargetData - Get the target data object used to construct this node.
161   ///
162   const TargetData &getTargetData() const;
163
164   /// getForwardNode - This method returns the node that this node is forwarded
165   /// to, if any.
166   ///
167   DSNode *getForwardNode() const { return ForwardNH.getNode(); }
168
169   /// isForwarding - Return true if this node is forwarding to another.
170   ///
171   bool isForwarding() const { return !ForwardNH.isNull(); }
172
173   /// stopForwarding - When the last reference to this forwarding node has been
174   /// dropped, delete the node.
175   ///
176   void stopForwarding() {
177     assert(isForwarding() &&
178            "Node isn't forwarding, cannot stopForwarding()!");
179     ForwardNH.setTo(0, 0);
180     assert(ParentGraph == 0 &&
181            "Forwarding nodes must have been removed from graph!");
182     delete this;
183   }
184
185   /// hasLink - Return true if this memory object has a link in slot LinkNo
186   ///
187   bool hasLink(unsigned Offset) const {
188     assert((Offset & ((1 << DS::PointerShift)-1)) == 0 &&
189            "Pointer offset not aligned correctly!");
190     unsigned Index = Offset >> DS::PointerShift;
191     assert(Index < Links.size() && "Link index is out of range!");
192     return Links[Index].getNode();
193   }
194
195   /// getLink - Return the link at the specified offset.
196   ///
197   DSNodeHandle &getLink(unsigned Offset) {
198     assert((Offset & ((1 << DS::PointerShift)-1)) == 0 &&
199            "Pointer offset not aligned correctly!");
200     unsigned Index = Offset >> DS::PointerShift;
201     assert(Index < Links.size() && "Link index is out of range!");
202     return Links[Index];
203   }
204   const DSNodeHandle &getLink(unsigned Offset) const {
205     assert((Offset & ((1 << DS::PointerShift)-1)) == 0 &&
206            "Pointer offset not aligned correctly!");
207     unsigned Index = Offset >> DS::PointerShift;
208     assert(Index < Links.size() && "Link index is out of range!");
209     return Links[Index];
210   }
211
212   /// getNumLinks - Return the number of links in a node...
213   ///
214   unsigned getNumLinks() const { return Links.size(); }
215
216   /// edge_* - Provide iterators for accessing outgoing edges.  Some outgoing
217   /// edges may be null.
218   typedef std::vector<DSNodeHandle>::iterator edge_iterator;
219   typedef std::vector<DSNodeHandle>::const_iterator const_edge_iterator;
220   edge_iterator edge_begin() { return Links.begin(); }
221   edge_iterator edge_end() { return Links.end(); }
222   const_edge_iterator edge_begin() const { return Links.begin(); }
223   const_edge_iterator edge_end() const { return Links.end(); }
224
225
226   /// mergeTypeInfo - This method merges the specified type into the current
227   /// node at the specified offset.  This may update the current node's type
228   /// record if this gives more information to the node, it may do nothing to
229   /// the node if this information is already known, or it may merge the node
230   /// completely (and return true) if the information is incompatible with what
231   /// is already known.
232   ///
233   /// This method returns true if the node is completely folded, otherwise
234   /// false.
235   ///
236   bool mergeTypeInfo(const Type *Ty, unsigned Offset,
237                      bool FoldIfIncompatible = true);
238
239   /// foldNodeCompletely - If we determine that this node has some funny
240   /// behavior happening to it that we cannot represent, we fold it down to a
241   /// single, completely pessimistic, node.  This node is represented as a
242   /// single byte with a single TypeEntry of "void" with isArray = true.
243   ///
244   void foldNodeCompletely();
245
246   /// isNodeCompletelyFolded - Return true if this node has been completely
247   /// folded down to something that can never be expanded, effectively losing
248   /// all of the field sensitivity that may be present in the node.
249   ///
250   bool isNodeCompletelyFolded() const;
251
252   /// setLink - Set the link at the specified offset to the specified
253   /// NodeHandle, replacing what was there.  It is uncommon to use this method,
254   /// instead one of the higher level methods should be used, below.
255   ///
256   void setLink(unsigned Offset, const DSNodeHandle &NH) {
257     assert((Offset & ((1 << DS::PointerShift)-1)) == 0 &&
258            "Pointer offset not aligned correctly!");
259     unsigned Index = Offset >> DS::PointerShift;
260     assert(Index < Links.size() && "Link index is out of range!");
261     Links[Index] = NH;
262   }
263
264   /// getPointerSize - Return the size of a pointer for the current target.
265   ///
266   unsigned getPointerSize() const { return DS::PointerSize; }
267
268   /// addEdgeTo - Add an edge from the current node to the specified node.  This
269   /// can cause merging of nodes in the graph.
270   ///
271   void addEdgeTo(unsigned Offset, const DSNodeHandle &NH);
272
273   /// mergeWith - Merge this node and the specified node, moving all links to
274   /// and from the argument node into the current node, deleting the node
275   /// argument.  Offset indicates what offset the specified node is to be merged
276   /// into the current node.
277   ///
278   /// The specified node may be a null pointer (in which case, nothing happens).
279   ///
280   void mergeWith(const DSNodeHandle &NH, unsigned Offset);
281
282   /// addGlobal - Add an entry for a global value to the Globals list.  This
283   /// also marks the node with the 'G' flag if it does not already have it.
284   ///
285   void addGlobal(GlobalValue *GV);
286
287   /// removeGlobal - Remove the specified global that is explicitly in the
288   /// globals list.
289   void removeGlobal(GlobalValue *GV);
290
291   void mergeGlobals(const std::vector<GlobalValue*> &RHS);
292   void clearGlobals() { std::vector<GlobalValue*>().swap(Globals); }
293
294   /// getGlobalsList - Return the set of global leaders that are represented by
295   /// this node.  Note that globals that are in this equivalence class but are
296   /// not leaders are not returned: for that, use addFullGlobalsList().
297   const std::vector<GlobalValue*> &getGlobalsList() const { return Globals; }
298
299   /// addFullGlobalsList - Compute the full set of global values that are
300   /// represented by this node.  Unlike getGlobalsList(), this requires fair
301   /// amount of work to compute, so don't treat this method call as free.
302   void addFullGlobalsList(std::vector<GlobalValue*> &List) const;
303
304   /// addFullFunctionList - Identical to addFullGlobalsList, but only return the
305   /// functions in the full list.
306   void addFullFunctionList(std::vector<Function*> &List) const;
307
308   /// globals_iterator/begin/end - Provide iteration methods over the global
309   /// value leaders set that is merged into this node.  Like the getGlobalsList
310   /// method, these iterators do not return globals that are part of the
311   /// equivalence classes for globals in this node, but aren't leaders.
312   typedef std::vector<GlobalValue*>::const_iterator globals_iterator;
313   globals_iterator globals_begin() const { return Globals.begin(); }
314   globals_iterator globals_end() const { return Globals.end(); }
315
316
317   /// maskNodeTypes - Apply a mask to the node types bitfield.
318   ///
319   void maskNodeTypes(unsigned Mask) {
320     NodeType &= Mask;
321   }
322
323   void mergeNodeFlags(unsigned RHS) {
324     NodeType |= RHS;
325   }
326
327   /// getNodeFlags - Return all of the flags set on the node.  If the DEAD flag
328   /// is set, hide it from the caller.
329   ///
330   unsigned getNodeFlags() const { return NodeType & ~DEAD; }
331
332   bool isAllocaNode()  const { return NodeType & AllocaNode; }
333   bool isHeapNode()    const { return NodeType & HeapNode; }
334   bool isGlobalNode()  const { return NodeType & GlobalNode; }
335   bool isUnknownNode() const { return NodeType & UnknownNode; }
336
337   bool isModified() const   { return NodeType & Modified; }
338   bool isRead() const       { return NodeType & Read; }
339
340   bool isIncomplete() const { return NodeType & Incomplete; }
341   bool isComplete() const   { return !isIncomplete(); }
342   bool isDeadNode() const   { return NodeType & DEAD; }
343
344   DSNode *setAllocaNodeMarker()  { NodeType |= AllocaNode;  return this; }
345   DSNode *setHeapNodeMarker()    { NodeType |= HeapNode;    return this; }
346   DSNode *setGlobalNodeMarker()  { NodeType |= GlobalNode;  return this; }
347   DSNode *setUnknownNodeMarker() { NodeType |= UnknownNode; return this; }
348
349   DSNode *setIncompleteMarker() { NodeType |= Incomplete; return this; }
350   DSNode *setModifiedMarker()   { NodeType |= Modified;   return this; }
351   DSNode *setReadMarker()       { NodeType |= Read;       return this; }
352   DSNode *setArrayMarker()      { NodeType |= Array; return this; }
353
354   void makeNodeDead() {
355     Globals.clear();
356     assert(hasNoReferrers() && "Dead node shouldn't have refs!");
357     NodeType = DEAD;
358   }
359
360   /// forwardNode - Mark this node as being obsolete, and all references to it
361   /// should be forwarded to the specified node and offset.
362   ///
363   void forwardNode(DSNode *To, unsigned Offset);
364
365   void print(std::ostream &O, const DSGraph *G) const;
366   void dump() const;
367
368   void assertOK() const;
369
370   void dropAllReferences() {
371     Links.clear();
372     if (isForwarding())
373       ForwardNH.setTo(0, 0);
374   }
375
376   /// remapLinks - Change all of the Links in the current node according to the
377   /// specified mapping.
378   ///
379   void remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap);
380
381   /// markReachableNodes - This method recursively traverses the specified
382   /// DSNodes, marking any nodes which are reachable.  All reachable nodes it
383   /// adds to the set, which allows it to only traverse visited nodes once.
384   ///
385   void markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const;
386
387 private:
388   friend class DSNodeHandle;
389
390   // static mergeNodes - Helper for mergeWith()
391   static void MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH);
392 };
393
394 //===----------------------------------------------------------------------===//
395 // Define the ilist_traits specialization for the DSGraph ilist.
396 //
397 template<>
398 struct ilist_traits<DSNode> {
399   static DSNode *getPrev(const DSNode *N) { return N->Prev; }
400   static DSNode *getNext(const DSNode *N) { return N->Next; }
401
402   static void setPrev(DSNode *N, DSNode *Prev) { N->Prev = Prev; }
403   static void setNext(DSNode *N, DSNode *Next) { N->Next = Next; }
404
405   static DSNode *createSentinel() { return new DSNode(0,0); }
406   static void destroySentinel(DSNode *N) { delete N; }
407   //static DSNode *createNode(const DSNode &V) { return new DSNode(V); }
408
409
410   void addNodeToList(DSNode *NTy) {}
411   void removeNodeFromList(DSNode *NTy) {}
412   void transferNodesFromList(iplist<DSNode, ilist_traits> &L2,
413                              ilist_iterator<DSNode> first,
414                              ilist_iterator<DSNode> last) {}
415 };
416
417 template<>
418 struct ilist_traits<const DSNode> : public ilist_traits<DSNode> {};
419
420 //===----------------------------------------------------------------------===//
421 // Define inline DSNodeHandle functions that depend on the definition of DSNode
422 //
423 inline DSNode *DSNodeHandle::getNode() const {
424   // Disabling this assertion because it is failing on a "magic" struct
425   // in named (from bind).  The fourth field is an array of length 0,
426   // presumably used to create struct instances of different sizes.
427   // In a variable length struct, Offset could exceed Size when getNode()
428   // is called before such a node is folded. In this case, the DS Analysis now 
429   // correctly folds this node after calling getNode.
430   /*  assert((!N ||
431           N->isNodeCompletelyFolded() ||
432           (N->Size == 0 && Offset == 0) ||
433           (int(Offset) >= 0 && Offset < N->Size) ||
434           (int(Offset) < 0 && -int(Offset) < int(N->Size)) ||
435           N->isForwarding()) && "Node handle offset out of range!");
436   */
437   if (N == 0 || !N->isForwarding())
438     return N;
439
440   return HandleForwarding();
441 }
442
443 inline void DSNodeHandle::setTo(DSNode *n, unsigned NewOffset) const {
444   assert(!n || !n->isForwarding() && "Cannot set node to a forwarded node!");
445   if (N) getNode()->NumReferrers--;
446   N = n;
447   Offset = NewOffset;
448   if (N) {
449     N->NumReferrers++;
450     if (Offset >= N->Size) {
451       assert((Offset == 0 || N->Size == 1) &&
452              "Pointer to non-collapsed node with invalid offset!");
453       Offset = 0;
454     }
455   }
456   assert(!N || ((N->NodeType & DSNode::DEAD) == 0));
457   assert((!N || Offset < N->Size || (N->Size == 0 && Offset == 0) ||
458           N->isForwarding()) && "Node handle offset out of range!");
459 }
460
461 inline bool DSNodeHandle::hasLink(unsigned Num) const {
462   assert(N && "DSNodeHandle does not point to a node yet!");
463   return getNode()->hasLink(Num+Offset);
464 }
465
466
467 /// getLink - Treat this current node pointer as a pointer to a structure of
468 /// some sort.  This method will return the pointer a mem[this+Num]
469 ///
470 inline const DSNodeHandle &DSNodeHandle::getLink(unsigned Off) const {
471   assert(N && "DSNodeHandle does not point to a node yet!");
472   return getNode()->getLink(Offset+Off);
473 }
474 inline DSNodeHandle &DSNodeHandle::getLink(unsigned Off) {
475   assert(N && "DSNodeHandle does not point to a node yet!");
476   return getNode()->getLink(Off+Offset);
477 }
478
479 inline void DSNodeHandle::setLink(unsigned Off, const DSNodeHandle &NH) {
480   assert(N && "DSNodeHandle does not point to a node yet!");
481   getNode()->setLink(Off+Offset, NH);
482 }
483
484 /// addEdgeTo - Add an edge from the current node to the specified node.  This
485 /// can cause merging of nodes in the graph.
486 ///
487 inline void DSNodeHandle::addEdgeTo(unsigned Off, const DSNodeHandle &Node) {
488   assert(N && "DSNodeHandle does not point to a node yet!");
489   getNode()->addEdgeTo(Off+Offset, Node);
490 }
491
492 /// mergeWith - Merge the logical node pointed to by 'this' with the node
493 /// pointed to by 'N'.
494 ///
495 inline void DSNodeHandle::mergeWith(const DSNodeHandle &Node) const {
496   if (!isNull())
497     getNode()->mergeWith(Node, Offset);
498   else {   // No node to merge with, so just point to Node
499     Offset = 0;
500     DSNode *NN = Node.getNode();
501     setTo(NN, Node.getOffset());
502   }
503 }
504
505 } // End llvm namespace
506
507 #endif