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