Moved method call within a conditional branch because its effects will
[oota-llvm.git] / include / llvm / ADT / ImmutableSet.h
1 //===--- ImmutableSet.h - Immutable (functional) set interface --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ImutAVLTree and ImmutableSet classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ADT_IMSET_H
15 #define LLVM_ADT_IMSET_H
16
17 #include "llvm/Support/Allocator.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include <cassert>
20
21 namespace llvm {
22   
23 //===----------------------------------------------------------------------===//    
24 // Immutable AVL-Tree Definition.
25 //===----------------------------------------------------------------------===//
26
27 template <typename ImutInfo> class ImutAVLFactory;
28
29 template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
30   
31 template <typename ImutInfo >
32 class ImutAVLTree : public FoldingSetNode {
33 public:
34   typedef typename ImutInfo::key_type_ref   key_type_ref;
35   typedef typename ImutInfo::value_type     value_type;
36   typedef typename ImutInfo::value_type_ref value_type_ref;
37
38   typedef ImutAVLFactory<ImutInfo>          Factory;
39   friend class ImutAVLFactory<ImutInfo>;
40   
41   typedef ImutAVLTreeInOrderIterator<ImutInfo>  iterator;
42   
43   //===----------------------------------------------------===//  
44   // Public Interface.
45   //===----------------------------------------------------===//  
46   
47   /// getLeft - Returns a pointer to the left subtree.  This value
48   ///  is NULL if there is no left subtree.
49   ImutAVLTree* getLeft() const { 
50     assert (!isMutable() && "Node is incorrectly marked mutable.");
51     
52     return reinterpret_cast<ImutAVLTree*>(Left);
53   }
54   
55   /// getRight - Returns a pointer to the right subtree.  This value is
56   ///  NULL if there is no right subtree.
57   ImutAVLTree* getRight() const { return Right; }  
58   
59   
60   /// getHeight - Returns the height of the tree.  A tree with no subtrees
61   ///  has a height of 1.
62   unsigned getHeight() const { return Height; }  
63   
64   /// getValue - Returns the data value associated with the tree node.
65   const value_type& getValue() const { return Value; }
66   
67   /// find - Finds the subtree associated with the specified key value.
68   ///  This method returns NULL if no matching subtree is found.
69   ImutAVLTree* find(key_type_ref K) {
70     ImutAVLTree *T = this;
71     
72     while (T) {
73       key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
74       
75       if (ImutInfo::isEqual(K,CurrentKey))
76         return T;
77       else if (ImutInfo::isLess(K,CurrentKey))
78         T = T->getLeft();
79       else
80         T = T->getRight();
81     }
82     
83     return NULL;
84   }
85   
86   /// size - Returns the number of nodes in the tree, which includes
87   ///  both leaves and non-leaf nodes.
88   unsigned size() const {
89     unsigned n = 1;
90     
91     if (const ImutAVLTree* L = getLeft())  n += L->size();
92     if (const ImutAVLTree* R = getRight()) n += R->size();
93     
94     return n;
95   }
96   
97   /// begin - Returns an iterator that iterates over the nodes of the tree
98   ///  in an inorder traversal.  The returned iterator thus refers to the
99   ///  the tree node with the minimum data element.
100   iterator begin() const { return iterator(this); }
101   
102   /// end - Returns an iterator for the tree that denotes the end of an
103   ///  inorder traversal.
104   iterator end() const { return iterator(); }
105   
106   /// isEqual - Compares two trees for structural equality and returns true
107   ///   if they are equal.  This worst case performance of this operation is
108   //    linear in the sizes of the trees.
109   bool isEqual(const ImutAVLTree& RHS) const {
110     if (&RHS == this)
111       return true;
112     
113     iterator LItr = begin(), LEnd = end();
114     iterator RItr = RHS.begin(), REnd = RHS.end();
115     
116     while (LItr != LEnd && RItr != REnd) {
117       if (*LItr == *RItr) {
118         LItr.SkipSubTree();
119         RItr.SkipSubTree();
120         continue;
121       }
122       
123       // Compare the keys.
124       if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(LItr->getValue()),
125                              ImutInfo::KeyOfValue(RItr->getValue())))
126         return false;
127       
128       // Also compare the data values.
129       if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(LItr->getValue()),
130                                  ImutInfo::DataOfValue(RItr->getValue())))
131         return false;
132       
133       ++LItr;
134       ++RItr;
135     }
136     
137     return LItr == LEnd && RItr == REnd;
138   }
139
140   /// isNotEqual - Compares two trees for structural inequality.  Performance
141   ///  is the same is isEqual.
142   bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
143   
144   /// contains - Returns true if this tree contains a subtree (node) that
145   ///  has an data element that matches the specified key.  Complexity
146   ///  is logarithmic in the size of the tree.
147   bool contains(const key_type_ref K) { return (bool) find(K); }
148   
149   /// foreach - A member template the accepts invokes operator() on a functor
150   ///  object (specifed by Callback) for every node/subtree in the tree.
151   ///  Nodes are visited using an inorder traversal.
152   template <typename Callback>
153   void foreach(Callback& C) {
154     if (ImutAVLTree* L = getLeft()) L->foreach(C);
155     
156     C(Value);    
157     
158     if (ImutAVLTree* R = getRight()) R->foreach(C);
159   }
160   
161   /// verify - A utility method that checks that the balancing and
162   ///  ordering invariants of the tree are satisifed.  It is a recursive
163   ///  method that returns the height of the tree, which is then consumed
164   ///  by the enclosing verify call.  External callers should ignore the
165   ///  return value.  An invalid tree will cause an assertion to fire in
166   ///  a debug build.
167   unsigned verify() const {
168     unsigned HL = getLeft() ? getLeft()->verify() : 0;
169     unsigned HR = getRight() ? getRight()->verify() : 0;
170     
171     assert (getHeight() == ( HL > HR ? HL : HR ) + 1 
172             && "Height calculation wrong.");
173     
174     assert ((HL > HR ? HL-HR : HR-HL) <= 2
175             && "Balancing invariant violated.");
176     
177     
178     assert (!getLeft()
179             || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
180                                 ImutInfo::KeyOfValue(getValue()))
181             && "Value in left child is not less that current value.");
182     
183     
184     assert (!getRight()
185             || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
186                                 ImutInfo::KeyOfValue(getRight()->getValue()))
187             && "Current value is not less that value of right child.");
188     
189     return getHeight();
190   }  
191   
192   //===----------------------------------------------------===//  
193   // Internal Values.
194   //===----------------------------------------------------===//
195   
196 private:
197   uintptr_t        Left;
198   ImutAVLTree*     Right;
199   unsigned         Height;
200   value_type       Value;
201   unsigned         Hash;
202   
203   //===----------------------------------------------------===//  
204   // Profiling or FoldingSet.
205   //===----------------------------------------------------===//
206
207 private:
208
209   static inline
210   unsigned ComputeHash(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
211     FoldingSetNodeID ID;
212     
213     if (L) ID.AddInteger(L->ComputeHash());
214     ImutInfo::Profile(ID,V);
215     
216     // Compute the "intermediate" hash.  Basically, we want the net profile to
217     // be:  H(H(....H(H(H(item0),item1),item2)...),itemN), where
218     //  H(item) is the hash of the data item and H(hash,item) is a hash
219     //  of the last item hash and the the next item.
220     
221     unsigned X = ID.ComputeHash();
222     
223     if (R) {
224       ID.clear();
225       ID.AddInteger(X);
226       ID.AddInteger(R->ComputeHash());
227       X = ID.ComputeHash();
228     }
229     
230     return X;
231   }
232   
233   inline unsigned ComputeHash() {
234     if (!isMutable() && Hash) return Hash;
235     Hash = ComputeHash(getSafeLeft(), getRight(), getValue());
236     return Hash;
237   }    
238   
239   /// Profile - Generates a FoldingSet profile for a tree node before it is
240   ///   created.  This is used by the ImutAVLFactory when creating
241   ///   trees.
242   static inline
243   void Profile(FoldingSetNodeID& ID, ImutAVLTree* L, ImutAVLTree* R,
244                value_type_ref V) {
245     
246     ID.AddInteger(ComputeHash(L, R, V));
247   }
248   
249 public:
250
251   /// Profile - Generates a FoldingSet profile for an existing tree node.
252   void Profile(FoldingSetNodeID& ID) {
253     ID.AddInteger(ComputeHash());
254   }
255   
256   //===----------------------------------------------------===//    
257   // Internal methods (node manipulation; used by Factory).
258   //===----------------------------------------------------===//
259   
260 private:
261   
262   enum { Mutable = 0x1 };
263   
264   /// ImutAVLTree - Internal constructor that is only called by
265   ///   ImutAVLFactory.
266   ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
267   : Left(reinterpret_cast<uintptr_t>(l) | Mutable),
268     Right(r), Height(height), Value(v), Hash(0) {}
269   
270   
271   /// isMutable - Returns true if the left and right subtree references
272   ///  (as well as height) can be changed.  If this method returns false,
273   ///  the tree is truly immutable.  Trees returned from an ImutAVLFactory
274   ///  object should always have this method return true.  Further, if this
275   ///  method returns false for an instance of ImutAVLTree, all subtrees
276   ///  will also have this method return false.  The converse is not true.
277   bool isMutable() const { return Left & Mutable; }
278   
279   /// getSafeLeft - Returns the pointer to the left tree by always masking
280   ///  out the mutable bit.  This is used internally by ImutAVLFactory,
281   ///  as no trees returned to the client should have the mutable flag set.
282   ImutAVLTree* getSafeLeft() const { 
283     return reinterpret_cast<ImutAVLTree*>(Left & ~Mutable);
284   }
285   
286   //===----------------------------------------------------===//    
287   // Mutating operations.  A tree root can be manipulated as
288   // long as its reference has not "escaped" from internal 
289   // methods of a factory object (see below).  When a tree
290   // pointer is externally viewable by client code, the 
291   // internal "mutable bit" is cleared to mark the tree 
292   // immutable.  Note that a tree that still has its mutable
293   // bit set may have children (subtrees) that are themselves
294   // immutable.
295   //===----------------------------------------------------===//
296   
297   
298   /// MarkImmutable - Clears the mutable flag for a tree.  After this happens,
299   ///   it is an error to call setLeft(), setRight(), and setHeight().  It
300   ///   is also then safe to call getLeft() instead of getSafeLeft().  
301   void MarkImmutable() {
302     assert (isMutable() && "Mutable flag already removed.");
303     Left &= ~Mutable;
304   }
305   
306   /// setLeft - Changes the reference of the left subtree.  Used internally
307   ///   by ImutAVLFactory.
308   void setLeft(ImutAVLTree* NewLeft) {
309     assert (isMutable() && 
310             "Only a mutable tree can have its left subtree changed.");
311     
312     Left = reinterpret_cast<uintptr_t>(NewLeft) | Mutable;
313   }
314   
315   /// setRight - Changes the reference of the right subtree.  Used internally
316   ///  by ImutAVLFactory.
317   void setRight(ImutAVLTree* NewRight) {
318     assert (isMutable() &&
319             "Only a mutable tree can have its right subtree changed.");
320     
321     Right = NewRight;
322   }
323   
324   /// setHeight - Changes the height of the tree.  Used internally by
325   ///  ImutAVLFactory.
326   void setHeight(unsigned h) {
327     assert (isMutable() && "Only a mutable tree can have its height changed.");
328     Height = h;
329   }
330 };
331
332 //===----------------------------------------------------------------------===//    
333 // Immutable AVL-Tree Factory class.
334 //===----------------------------------------------------------------------===//
335
336 template <typename ImutInfo >  
337 class ImutAVLFactory {
338   typedef ImutAVLTree<ImutInfo> TreeTy;
339   typedef typename TreeTy::value_type_ref value_type_ref;
340   typedef typename TreeTy::key_type_ref   key_type_ref;
341   
342   typedef FoldingSet<TreeTy> CacheTy;
343   
344   CacheTy Cache;  
345   BumpPtrAllocator Allocator;    
346   
347   //===--------------------------------------------------===//    
348   // Public interface.
349   //===--------------------------------------------------===//
350   
351 public:
352   ImutAVLFactory() {}
353   
354   TreeTy* Add(TreeTy* T, value_type_ref V) {
355     T = Add_internal(V,T);
356     MarkImmutable(T);
357     return T;
358   }
359   
360   TreeTy* Remove(TreeTy* T, key_type_ref V) {
361     T = Remove_internal(V,T);
362     MarkImmutable(T);
363     return T;
364   }
365   
366   TreeTy* GetEmptyTree() const { return NULL; }
367   
368   BumpPtrAllocator& getAllocator() { return Allocator; }
369   
370   //===--------------------------------------------------===//    
371   // A bunch of quick helper functions used for reasoning
372   // about the properties of trees and their children.
373   // These have succinct names so that the balancing code
374   // is as terse (and readable) as possible.
375   //===--------------------------------------------------===//
376 private:
377   
378   bool           isEmpty(TreeTy* T) const { return !T; }
379   unsigned        Height(TreeTy* T) const { return T ? T->getHeight() : 0; }  
380   TreeTy*           Left(TreeTy* T) const { return T->getSafeLeft(); }
381   TreeTy*          Right(TreeTy* T) const { return T->getRight(); }  
382   value_type_ref   Value(TreeTy* T) const { return T->Value; }
383   
384   unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
385     unsigned hl = Height(L);
386     unsigned hr = Height(R);
387     return ( hl > hr ? hl : hr ) + 1;
388   }
389   
390   //===--------------------------------------------------===//    
391   // "CreateNode" is used to generate new tree roots that link
392   // to other trees.  The functon may also simply move links
393   // in an existing root if that root is still marked mutable.
394   // This is necessary because otherwise our balancing code
395   // would leak memory as it would create nodes that are
396   // then discarded later before the finished tree is
397   // returned to the caller.
398   //===--------------------------------------------------===//
399   
400   TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
401     FoldingSetNodeID ID;      
402     TreeTy::Profile(ID,L,R,V);      
403     void* InsertPos;
404     
405     if (TreeTy* T = Cache.FindNodeOrInsertPos(ID,InsertPos))
406       return T;
407     
408     assert (InsertPos != NULL);
409     
410     // Allocate the new tree node and insert it into the cache.
411     TreeTy* T = (TreeTy*) Allocator.Allocate<TreeTy>();    
412     new (T) TreeTy(L,R,V,IncrementHeight(L,R));
413     Cache.InsertNode(T,InsertPos);
414
415     return T;      
416   }
417   
418   TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {      
419     assert (!isEmpty(OldTree));
420     
421     if (OldTree->isMutable()) {
422       OldTree->setLeft(L);
423       OldTree->setRight(R);
424       OldTree->setHeight(IncrementHeight(L,R));
425       return OldTree;
426     }
427     else return CreateNode(L, Value(OldTree), R);
428   }
429   
430   /// Balance - Used by Add_internal and Remove_internal to
431   ///  balance a newly created tree.
432   TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
433     
434     unsigned hl = Height(L);
435     unsigned hr = Height(R);
436     
437     if (hl > hr + 2) {
438       assert (!isEmpty(L) &&
439               "Left tree cannot be empty to have a height >= 2.");
440       
441       TreeTy* LL = Left(L);
442       TreeTy* LR = Right(L);
443       
444       if (Height(LL) >= Height(LR))
445         return CreateNode(LL, L, CreateNode(LR,V,R));
446       
447       assert (!isEmpty(LR) &&
448               "LR cannot be empty because it has a height >= 1.");
449       
450       TreeTy* LRL = Left(LR);
451       TreeTy* LRR = Right(LR);
452       
453       return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));                              
454     }
455     else if (hr > hl + 2) {
456       assert (!isEmpty(R) &&
457               "Right tree cannot be empty to have a height >= 2.");
458       
459       TreeTy* RL = Left(R);
460       TreeTy* RR = Right(R);
461       
462       if (Height(RR) >= Height(RL))
463         return CreateNode(CreateNode(L,V,RL), R, RR);
464       
465       assert (!isEmpty(RL) &&
466               "RL cannot be empty because it has a height >= 1.");
467       
468       TreeTy* RLL = Left(RL);
469       TreeTy* RLR = Right(RL);
470       
471       return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
472     }
473     else
474       return CreateNode(L,V,R);
475   }
476   
477   /// Add_internal - Creates a new tree that includes the specified
478   ///  data and the data from the original tree.  If the original tree
479   ///  already contained the data item, the original tree is returned.
480   TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
481     if (isEmpty(T))
482       return CreateNode(T, V, T);
483     
484     assert (!T->isMutable());
485     
486     key_type_ref K = ImutInfo::KeyOfValue(V);
487     key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
488     
489     if (ImutInfo::isEqual(K,KCurrent))
490       return CreateNode(Left(T), V, Right(T));
491     else if (ImutInfo::isLess(K,KCurrent))
492       return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
493     else
494       return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
495   }
496   
497   /// Remove_interal - Creates a new tree that includes all the data
498   ///  from the original tree except the specified data.  If the
499   ///  specified data did not exist in the original tree, the original
500   ///  tree is returned.
501   TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
502     if (isEmpty(T))
503       return T;
504     
505     assert (!T->isMutable());
506     
507     key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
508     
509     if (ImutInfo::isEqual(K,KCurrent))
510       return CombineLeftRightTrees(Left(T),Right(T));
511     else if (ImutInfo::isLess(K,KCurrent))
512       return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
513     else
514       return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
515   }
516   
517   TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
518     if (isEmpty(L)) return R;      
519     if (isEmpty(R)) return L;
520     
521     TreeTy* OldNode;          
522     TreeTy* NewRight = RemoveMinBinding(R,OldNode);
523     return Balance(L,Value(OldNode),NewRight);
524   }
525   
526   TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
527     assert (!isEmpty(T));
528     
529     if (isEmpty(Left(T))) {
530       NodeRemoved = T;
531       return Right(T);
532     }
533     
534     return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
535   }    
536   
537   /// MarkImmutable - Clears the mutable bits of a root and all of its
538   ///  descendants.
539   void MarkImmutable(TreeTy* T) {
540     if (!T || !T->isMutable())
541       return;
542     
543     T->MarkImmutable();
544     MarkImmutable(Left(T));
545     MarkImmutable(Right(T));
546   }
547 };
548   
549   
550 //===----------------------------------------------------------------------===//    
551 // Immutable AVL-Tree Iterators.
552 //===----------------------------------------------------------------------===//  
553
554 template <typename ImutInfo>
555 class ImutAVLTreeGenericIterator {
556   SmallVector<uintptr_t,20> stack;
557 public:
558   enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3, 
559                    Flags=0x3 };
560   
561   typedef ImutAVLTree<ImutInfo> TreeTy;      
562   typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
563
564   inline ImutAVLTreeGenericIterator() {}
565   inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
566     if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
567   }  
568   
569   TreeTy* operator*() const {
570     assert (!stack.empty());    
571     return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
572   }
573   
574   uintptr_t getVisitState() {
575     assert (!stack.empty());
576     return stack.back() & Flags;
577   }
578   
579   
580   bool AtEnd() const { return stack.empty(); }
581
582   bool AtBeginning() const { 
583     return stack.size() == 1 && getVisitState() == VisitedNone;
584   }
585   
586   void SkipToParent() {
587     assert (!stack.empty());
588     stack.pop_back();
589     
590     if (stack.empty())
591       return;
592     
593     switch (getVisitState()) {
594       case VisitedNone:
595         stack.back() |= VisitedLeft;
596         break;
597       case VisitedLeft:
598         stack.back() |= VisitedRight;
599         break;
600       default:
601         assert (false && "Unreachable.");            
602     }
603   }
604   
605   inline bool operator==(const _Self& x) const {
606     if (stack.size() != x.stack.size())
607       return false;
608     
609     for (unsigned i = 0 ; i < stack.size(); i++)
610       if (stack[i] != x.stack[i])
611         return false;
612     
613     return true;
614   }
615   
616   inline bool operator!=(const _Self& x) const { return !operator==(x); }  
617   
618   _Self& operator++() {
619     assert (!stack.empty());
620     
621     TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
622     assert (Current);
623     
624     switch (getVisitState()) {
625       case VisitedNone:
626         if (TreeTy* L = Current->getLeft())
627           stack.push_back(reinterpret_cast<uintptr_t>(L));
628         else
629           stack.back() |= VisitedLeft;
630         
631         break;
632         
633       case VisitedLeft:
634         if (TreeTy* R = Current->getRight())
635           stack.push_back(reinterpret_cast<uintptr_t>(R));
636         else
637           stack.back() |= VisitedRight;
638         
639         break;
640         
641       case VisitedRight:
642         SkipToParent();        
643         break;
644         
645       default:
646         assert (false && "Unreachable.");
647     }
648     
649     return *this;
650   }
651   
652   _Self& operator--() {
653     assert (!stack.empty());
654     
655     TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
656     assert (Current);
657     
658     switch (getVisitState()) {
659       case VisitedNone:
660         stack.pop_back();
661         break;
662         
663       case VisitedLeft:                
664         stack.back() &= ~Flags; // Set state to "VisitedNone."
665         
666         if (TreeTy* L = Current->getLeft())
667           stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
668           
669         break;
670         
671       case VisitedRight:        
672         stack.back() &= ~Flags;
673         stack.back() |= VisitedLeft;
674         
675         if (TreeTy* R = Current->getRight())
676           stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
677           
678         break;
679         
680       default:
681         assert (false && "Unreachable.");
682     }
683     
684     return *this;
685   }
686 };
687   
688 template <typename ImutInfo>
689 class ImutAVLTreeInOrderIterator {
690   typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
691   InternalIteratorTy InternalItr;
692
693 public:
694   typedef ImutAVLTree<ImutInfo> TreeTy;
695   typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
696
697   ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) { 
698     if (Root) operator++(); // Advance to first element.
699   }
700   
701   ImutAVLTreeInOrderIterator() : InternalItr() {}
702
703   inline bool operator==(const _Self& x) const {
704     return InternalItr == x.InternalItr;
705   }
706   
707   inline bool operator!=(const _Self& x) const { return !operator==(x); }  
708   
709   inline TreeTy* operator*() const { return *InternalItr; }
710   inline TreeTy* operator->() const { return *InternalItr; }
711   
712   inline _Self& operator++() { 
713     do ++InternalItr;
714     while (!InternalItr.AtEnd() && 
715            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
716
717     return *this;
718   }
719   
720   inline _Self& operator--() { 
721     do --InternalItr;
722     while (!InternalItr.AtBeginning() && 
723            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
724     
725     return *this;
726   }
727   
728   inline void SkipSubTree() {
729     InternalItr.SkipToParent();
730     
731     while (!InternalItr.AtEnd() &&
732            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
733       ++InternalItr;        
734   }
735 };
736     
737 //===----------------------------------------------------------------------===//    
738 // Trait classes for Profile information.
739 //===----------------------------------------------------------------------===//
740
741 /// Generic profile template.  The default behavior is to invoke the
742 /// profile method of an object.  Specializations for primitive integers
743 /// and generic handling of pointers is done below.
744 template <typename T>
745 struct ImutProfileInfo {
746   typedef const T  value_type;
747   typedef const T& value_type_ref;
748   
749   static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
750     FoldingSetTrait<T>::Profile(X,ID);
751   }
752 };
753
754 /// Profile traits for integers.
755 template <typename T>
756 struct ImutProfileInteger {    
757   typedef const T  value_type;
758   typedef const T& value_type_ref;
759   
760   static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
761     ID.AddInteger(X);
762   }  
763 };
764
765 #define PROFILE_INTEGER_INFO(X)\
766 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
767
768 PROFILE_INTEGER_INFO(char)
769 PROFILE_INTEGER_INFO(unsigned char)
770 PROFILE_INTEGER_INFO(short)
771 PROFILE_INTEGER_INFO(unsigned short)
772 PROFILE_INTEGER_INFO(unsigned)
773 PROFILE_INTEGER_INFO(signed)
774 PROFILE_INTEGER_INFO(long)
775 PROFILE_INTEGER_INFO(unsigned long)
776 PROFILE_INTEGER_INFO(long long)
777 PROFILE_INTEGER_INFO(unsigned long long)
778
779 #undef PROFILE_INTEGER_INFO
780
781 /// Generic profile trait for pointer types.  We treat pointers as
782 /// references to unique objects.
783 template <typename T>
784 struct ImutProfileInfo<T*> {
785   typedef const T*   value_type;
786   typedef value_type value_type_ref;
787   
788   static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
789     ID.AddPointer(X);
790   }
791 };
792
793 //===----------------------------------------------------------------------===//    
794 // Trait classes that contain element comparison operators and type
795 //  definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap.  These
796 //  inherit from the profile traits (ImutProfileInfo) to include operations
797 //  for element profiling.
798 //===----------------------------------------------------------------------===//
799
800
801 /// ImutContainerInfo - Generic definition of comparison operations for
802 ///   elements of immutable containers that defaults to using
803 ///   std::equal_to<> and std::less<> to perform comparison of elements.
804 template <typename T>
805 struct ImutContainerInfo : public ImutProfileInfo<T> {
806   typedef typename ImutProfileInfo<T>::value_type      value_type;
807   typedef typename ImutProfileInfo<T>::value_type_ref  value_type_ref;
808   typedef value_type      key_type;
809   typedef value_type_ref  key_type_ref;
810   typedef bool            data_type;
811   typedef bool            data_type_ref;
812   
813   static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
814   static inline data_type_ref DataOfValue(value_type_ref) { return true; }
815   
816   static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) { 
817     return std::equal_to<key_type>()(LHS,RHS);
818   }
819   
820   static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
821     return std::less<key_type>()(LHS,RHS);
822   }
823   
824   static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
825 };
826
827 /// ImutContainerInfo - Specialization for pointer values to treat pointers
828 ///  as references to unique objects.  Pointers are thus compared by
829 ///  their addresses.
830 template <typename T>
831 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
832   typedef typename ImutProfileInfo<T*>::value_type      value_type;
833   typedef typename ImutProfileInfo<T*>::value_type_ref  value_type_ref;
834   typedef value_type      key_type;
835   typedef value_type_ref  key_type_ref;
836   typedef bool            data_type;
837   typedef bool            data_type_ref;
838   
839   static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
840   static inline data_type_ref DataOfValue(value_type_ref) { return true; }
841   
842   static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
843     return LHS == RHS;
844   }
845   
846   static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
847     return LHS < RHS;
848   }
849   
850   static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
851 };
852
853 //===----------------------------------------------------------------------===//    
854 // Immutable Set
855 //===----------------------------------------------------------------------===//
856
857 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
858 class ImmutableSet {
859 public:
860   typedef typename ValInfo::value_type      value_type;
861   typedef typename ValInfo::value_type_ref  value_type_ref;
862   
863 private:  
864   typedef ImutAVLTree<ValInfo> TreeTy;
865   TreeTy* Root;
866   
867   ImmutableSet(TreeTy* R) : Root(R) {}
868   
869 public:
870   
871   class Factory {
872     typename TreeTy::Factory F;
873     
874   public:
875     Factory() {}
876     
877     /// GetEmptySet - Returns an immutable set that contains no elements.
878     ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
879     
880     /// Add - Creates a new immutable set that contains all of the values
881     ///  of the original set with the addition of the specified value.  If
882     ///  the original set already included the value, then the original set is
883     ///  returned and no memory is allocated.  The time and space complexity
884     ///  of this operation is logarithmic in the size of the original set.
885     ///  The memory allocated to represent the set is released when the
886     ///  factory object that created the set is destroyed.
887     ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
888       return ImmutableSet(F.Add(Old.Root,V));
889     }
890     
891     /// Remove - Creates a new immutable set that contains all of the values
892     ///  of the original set with the exception of the specified value.  If
893     ///  the original set did not contain the value, the original set is
894     ///  returned and no memory is allocated.  The time and space complexity
895     ///  of this operation is logarithmic in the size of the original set.
896     ///  The memory allocated to represent the set is released when the
897     ///  factory object that created the set is destroyed.
898     ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
899       return ImmutableSet(F.Remove(Old.Root,V));
900     }
901     
902     BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
903
904   private:
905     Factory(const Factory& RHS) {};
906     void operator=(const Factory& RHS) {};    
907   };
908   
909   friend class Factory;  
910
911   /// contains - Returns true if the set contains the specified value.
912   bool contains(const value_type_ref V) const {
913     return Root ? Root->contains(V) : false;
914   }
915   
916   bool operator==(ImmutableSet RHS) const {
917     return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
918   }
919   
920   bool operator!=(ImmutableSet RHS) const {
921     return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
922   }
923   
924   /// isEmpty - Return true if the set contains no elements.
925   bool isEmpty() const { return !Root; }
926   
927   template <typename Callback>
928   void foreach(Callback& C) { if (Root) Root->foreach(C); }
929   
930   template <typename Callback>
931   void foreach() { if (Root) { Callback C; Root->foreach(C); } }
932     
933   //===--------------------------------------------------===//    
934   // Iterators.
935   //===--------------------------------------------------===//  
936
937   class iterator {
938     typename TreeTy::iterator itr;
939     
940     iterator() {}
941     iterator(TreeTy* t) : itr(t) {}
942     friend class ImmutableSet<ValT,ValInfo>;
943   public:
944     inline value_type_ref operator*() const { return itr->getValue(); }
945     inline iterator& operator++() { ++itr; return *this; }
946     inline iterator  operator++(int) { iterator tmp(*this); ++itr; return tmp; }
947     inline iterator& operator--() { --itr; return *this; }
948     inline iterator  operator--(int) { iterator tmp(*this); --itr; return tmp; }
949     inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
950     inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }        
951   };
952   
953   iterator begin() const { return iterator(Root); }
954   iterator end() const { return iterator(); }  
955   
956   //===--------------------------------------------------===//    
957   // For testing.
958   //===--------------------------------------------------===//  
959   
960   void verify() const { if (Root) Root->verify(); }
961   unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
962 };
963
964 } // end namespace llvm
965
966 #endif