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