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