1 //===--- ImmutableSet.h - Immutable (functional) set interface --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ImutAVLTree and ImmutableSet classes.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_IMSET_H
15 #define LLVM_ADT_IMSET_H
17 #include "llvm/Support/Allocator.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/System/DataTypes.h"
25 //===----------------------------------------------------------------------===//
26 // Immutable AVL-Tree Definition.
27 //===----------------------------------------------------------------------===//
29 template <typename ImutInfo> class ImutAVLFactory;
30 template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
31 template <typename ImutInfo> class ImutAVLTreeGenericIterator;
33 template <typename ImutInfo >
34 class ImutAVLTree : public FoldingSetNode {
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;
40 typedef ImutAVLFactory<ImutInfo> Factory;
41 friend class ImutAVLFactory<ImutInfo>;
43 friend class ImutAVLTreeGenericIterator<ImutInfo>;
44 friend class FoldingSet<ImutAVLTree>;
46 typedef ImutAVLTreeInOrderIterator<ImutInfo> iterator;
48 //===----------------------------------------------------===//
50 //===----------------------------------------------------===//
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 return reinterpret_cast<ImutAVLTree*>(Left & ~LeftFlags);
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; }
62 /// getHeight - Returns the height of the tree. A tree with no subtrees
63 /// has a height of 1.
64 unsigned getHeight() const { return Height; }
66 /// getValue - Returns the data value associated with the tree node.
67 const value_type& getValue() const { return Value; }
69 /// find - Finds the subtree associated with the specified key value.
70 /// This method returns NULL if no matching subtree is found.
71 ImutAVLTree* find(key_type_ref K) {
72 ImutAVLTree *T = this;
75 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
77 if (ImutInfo::isEqual(K,CurrentKey))
79 else if (ImutInfo::isLess(K,CurrentKey))
88 /// getMaxElement - Find the subtree associated with the highest ranged
90 ImutAVLTree* getMaxElement() {
91 ImutAVLTree *T = this;
92 ImutAVLTree *Right = T->getRight();
93 while (Right) { T = Right; Right = T->getRight(); }
97 /// size - Returns the number of nodes in the tree, which includes
98 /// both leaves and non-leaf nodes.
99 unsigned size() const {
102 if (const ImutAVLTree* L = getLeft()) n += L->size();
103 if (const ImutAVLTree* R = getRight()) n += R->size();
108 /// begin - Returns an iterator that iterates over the nodes of the tree
109 /// in an inorder traversal. The returned iterator thus refers to the
110 /// the tree node with the minimum data element.
111 iterator begin() const { return iterator(this); }
113 /// end - Returns an iterator for the tree that denotes the end of an
114 /// inorder traversal.
115 iterator end() const { return iterator(); }
117 bool ElementEqual(value_type_ref V) const {
119 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
120 ImutInfo::KeyOfValue(V)))
123 // Also compare the data values.
124 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
125 ImutInfo::DataOfValue(V)))
131 bool ElementEqual(const ImutAVLTree* RHS) const {
132 return ElementEqual(RHS->getValue());
135 /// isEqual - Compares two trees for structural equality and returns true
136 /// if they are equal. This worst case performance of this operation is
137 // linear in the sizes of the trees.
138 bool isEqual(const ImutAVLTree& RHS) const {
142 iterator LItr = begin(), LEnd = end();
143 iterator RItr = RHS.begin(), REnd = RHS.end();
145 while (LItr != LEnd && RItr != REnd) {
146 if (*LItr == *RItr) {
152 if (!LItr->ElementEqual(*RItr))
159 return LItr == LEnd && RItr == REnd;
162 /// isNotEqual - Compares two trees for structural inequality. Performance
163 /// is the same is isEqual.
164 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
166 /// contains - Returns true if this tree contains a subtree (node) that
167 /// has an data element that matches the specified key. Complexity
168 /// is logarithmic in the size of the tree.
169 bool contains(key_type_ref K) { return (bool) find(K); }
171 /// foreach - A member template the accepts invokes operator() on a functor
172 /// object (specifed by Callback) for every node/subtree in the tree.
173 /// Nodes are visited using an inorder traversal.
174 template <typename Callback>
175 void foreach(Callback& C) {
176 if (ImutAVLTree* L = getLeft()) L->foreach(C);
180 if (ImutAVLTree* R = getRight()) R->foreach(C);
183 /// verify - A utility method that checks that the balancing and
184 /// ordering invariants of the tree are satisifed. It is a recursive
185 /// method that returns the height of the tree, which is then consumed
186 /// by the enclosing verify call. External callers should ignore the
187 /// return value. An invalid tree will cause an assertion to fire in
189 unsigned verify() const {
190 unsigned HL = getLeft() ? getLeft()->verify() : 0;
191 unsigned HR = getRight() ? getRight()->verify() : 0;
193 assert(getHeight() == ( HL > HR ? HL : HR ) + 1
194 && "Height calculation wrong");
196 assert((HL > HR ? HL-HR : HR-HL) <= 2
197 && "Balancing invariant violated");
200 || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
201 ImutInfo::KeyOfValue(getValue()))
202 && "Value in left child is not less that current value");
206 || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
207 ImutInfo::KeyOfValue(getRight()->getValue()))
208 && "Current value is not less that value of right child");
213 /// Profile - Profiling for ImutAVLTree.
214 void Profile(llvm::FoldingSetNodeID& ID) {
215 ID.AddInteger(ComputeDigest());
218 //===----------------------------------------------------===//
220 //===----------------------------------------------------===//
229 //===----------------------------------------------------===//
230 // Internal methods (node manipulation; used by Factory).
231 //===----------------------------------------------------===//
235 enum { Mutable = 0x1, NoCachedDigest = 0x2, LeftFlags = 0x3 };
237 /// ImutAVLTree - Internal constructor that is only called by
239 ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
240 : Left(reinterpret_cast<uintptr_t>(l) | (Mutable | NoCachedDigest)),
241 Right(r), Height(height), Value(v), Digest(0) {}
244 /// isMutable - Returns true if the left and right subtree references
245 /// (as well as height) can be changed. If this method returns false,
246 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
247 /// object should always have this method return true. Further, if this
248 /// method returns false for an instance of ImutAVLTree, all subtrees
249 /// will also have this method return false. The converse is not true.
250 bool isMutable() const { return Left & Mutable; }
252 /// hasCachedDigest - Returns true if the digest for this tree is cached.
253 /// This can only be true if the tree is immutable.
254 bool hasCachedDigest() const { return !(Left & NoCachedDigest); }
256 //===----------------------------------------------------===//
257 // Mutating operations. A tree root can be manipulated as
258 // long as its reference has not "escaped" from internal
259 // methods of a factory object (see below). When a tree
260 // pointer is externally viewable by client code, the
261 // internal "mutable bit" is cleared to mark the tree
262 // immutable. Note that a tree that still has its mutable
263 // bit set may have children (subtrees) that are themselves
265 //===----------------------------------------------------===//
267 /// MarkImmutable - Clears the mutable flag for a tree. After this happens,
268 /// it is an error to call setLeft(), setRight(), and setHeight().
269 void MarkImmutable() {
270 assert(isMutable() && "Mutable flag already removed.");
274 /// MarkedCachedDigest - Clears the NoCachedDigest flag for a tree.
275 void MarkedCachedDigest() {
276 assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
277 Left &= ~NoCachedDigest;
280 /// setLeft - Changes the reference of the left subtree. Used internally
281 /// by ImutAVLFactory.
282 void setLeft(ImutAVLTree* NewLeft) {
283 assert(isMutable() &&
284 "Only a mutable tree can have its left subtree changed.");
285 Left = reinterpret_cast<uintptr_t>(NewLeft) | LeftFlags;
288 /// setRight - Changes the reference of the right subtree. Used internally
289 /// by ImutAVLFactory.
290 void setRight(ImutAVLTree* NewRight) {
291 assert(isMutable() &&
292 "Only a mutable tree can have its right subtree changed.");
295 // Set the NoCachedDigest flag.
296 Left = Left | NoCachedDigest;
300 /// setHeight - Changes the height of the tree. Used internally by
302 void setHeight(unsigned h) {
303 assert(isMutable() && "Only a mutable tree can have its height changed.");
308 uint32_t ComputeDigest(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
312 digest += L->ComputeDigest();
314 // Compute digest of stored data.
316 ImutInfo::Profile(ID,V);
317 digest += ID.ComputeHash();
320 digest += R->ComputeDigest();
325 inline uint32_t ComputeDigest() {
326 // Check the lowest bit to determine if digest has actually been
328 if (hasCachedDigest())
331 uint32_t X = ComputeDigest(getLeft(), getRight(), getValue());
333 MarkedCachedDigest();
338 //===----------------------------------------------------------------------===//
339 // Immutable AVL-Tree Factory class.
340 //===----------------------------------------------------------------------===//
342 template <typename ImutInfo >
343 class ImutAVLFactory {
344 typedef ImutAVLTree<ImutInfo> TreeTy;
345 typedef typename TreeTy::value_type_ref value_type_ref;
346 typedef typename TreeTy::key_type_ref key_type_ref;
348 typedef FoldingSet<TreeTy> CacheTy;
353 bool ownsAllocator() const {
354 return Allocator & 0x1 ? false : true;
357 BumpPtrAllocator& getAllocator() const {
358 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
361 //===--------------------------------------------------===//
363 //===--------------------------------------------------===//
367 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
369 ImutAVLFactory(BumpPtrAllocator& Alloc)
370 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
373 if (ownsAllocator()) delete &getAllocator();
376 TreeTy* Add(TreeTy* T, value_type_ref V) {
377 T = Add_internal(V,T);
382 TreeTy* Remove(TreeTy* T, key_type_ref V) {
383 T = Remove_internal(V,T);
388 TreeTy* GetEmptyTree() const { return NULL; }
390 //===--------------------------------------------------===//
391 // A bunch of quick helper functions used for reasoning
392 // about the properties of trees and their children.
393 // These have succinct names so that the balancing code
394 // is as terse (and readable) as possible.
395 //===--------------------------------------------------===//
398 bool isEmpty(TreeTy* T) const { return !T; }
399 unsigned Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
400 TreeTy* Left(TreeTy* T) const { return T->getLeft(); }
401 TreeTy* Right(TreeTy* T) const { return T->getRight(); }
402 value_type_ref Value(TreeTy* T) const { return T->Value; }
404 unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
405 unsigned hl = Height(L);
406 unsigned hr = Height(R);
407 return ( hl > hr ? hl : hr ) + 1;
410 static bool CompareTreeWithSection(TreeTy* T,
411 typename TreeTy::iterator& TI,
412 typename TreeTy::iterator& TE) {
414 typename TreeTy::iterator I = T->begin(), E = T->end();
416 for ( ; I!=E ; ++I, ++TI)
417 if (TI == TE || !I->ElementEqual(*TI))
423 //===--------------------------------------------------===//
424 // "CreateNode" is used to generate new tree roots that link
425 // to other trees. The functon may also simply move links
426 // in an existing root if that root is still marked mutable.
427 // This is necessary because otherwise our balancing code
428 // would leak memory as it would create nodes that are
429 // then discarded later before the finished tree is
430 // returned to the caller.
431 //===--------------------------------------------------===//
433 TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
434 BumpPtrAllocator& A = getAllocator();
435 TreeTy* T = (TreeTy*) A.Allocate<TreeTy>();
436 new (T) TreeTy(L,R,V,IncrementHeight(L,R));
440 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
441 assert(!isEmpty(OldTree));
443 if (OldTree->isMutable()) {
445 OldTree->setRight(R);
446 OldTree->setHeight(IncrementHeight(L,R));
450 return CreateNode(L, Value(OldTree), R);
453 /// Balance - Used by Add_internal and Remove_internal to
454 /// balance a newly created tree.
455 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
457 unsigned hl = Height(L);
458 unsigned hr = Height(R);
461 assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
463 TreeTy* LL = Left(L);
464 TreeTy* LR = Right(L);
466 if (Height(LL) >= Height(LR))
467 return CreateNode(LL, L, CreateNode(LR,V,R));
469 assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
471 TreeTy* LRL = Left(LR);
472 TreeTy* LRR = Right(LR);
474 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
476 else if (hr > hl + 2) {
477 assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
479 TreeTy* RL = Left(R);
480 TreeTy* RR = Right(R);
482 if (Height(RR) >= Height(RL))
483 return CreateNode(CreateNode(L,V,RL), R, RR);
485 assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
487 TreeTy* RLL = Left(RL);
488 TreeTy* RLR = Right(RL);
490 return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
493 return CreateNode(L,V,R);
496 /// Add_internal - Creates a new tree that includes the specified
497 /// data and the data from the original tree. If the original tree
498 /// already contained the data item, the original tree is returned.
499 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
501 return CreateNode(T, V, T);
503 assert(!T->isMutable());
505 key_type_ref K = ImutInfo::KeyOfValue(V);
506 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
508 if (ImutInfo::isEqual(K,KCurrent))
509 return CreateNode(Left(T), V, Right(T));
510 else if (ImutInfo::isLess(K,KCurrent))
511 return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
513 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
516 /// Remove_internal - Creates a new tree that includes all the data
517 /// from the original tree except the specified data. If the
518 /// specified data did not exist in the original tree, the original
519 /// tree is returned.
520 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
524 assert(!T->isMutable());
526 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
528 if (ImutInfo::isEqual(K,KCurrent))
529 return CombineLeftRightTrees(Left(T),Right(T));
530 else if (ImutInfo::isLess(K,KCurrent))
531 return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
533 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
536 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
537 if (isEmpty(L)) return R;
538 if (isEmpty(R)) return L;
541 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
542 return Balance(L,Value(OldNode),NewRight);
545 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
548 if (isEmpty(Left(T))) {
553 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
556 /// MarkImmutable - Clears the mutable bits of a root and all of its
558 void MarkImmutable(TreeTy* T) {
559 if (!T || !T->isMutable())
563 MarkImmutable(Left(T));
564 MarkImmutable(Right(T));
568 TreeTy *GetCanonicalTree(TreeTy *TNew) {
572 // Search the FoldingSet bucket for a Tree with the same digest.
574 unsigned digest = TNew->ComputeDigest();
575 ID.AddInteger(digest);
576 unsigned hash = ID.ComputeHash();
578 typename CacheTy::bucket_iterator I = Cache.bucket_begin(hash);
579 typename CacheTy::bucket_iterator E = Cache.bucket_end(hash);
581 for (; I != E; ++I) {
584 if (T->ComputeDigest() != digest)
587 // We found a collision. Perform a comparison of Contents('T')
588 // with Contents('L')+'V'+Contents('R').
589 typename TreeTy::iterator TI = T->begin(), TE = T->end();
591 // First compare Contents('L') with the (initial) contents of T.
592 if (!CompareTreeWithSection(TNew->getLeft(), TI, TE))
595 // Now compare the new data element.
596 if (TI == TE || !TI->ElementEqual(TNew->getValue()))
601 // Now compare the remainder of 'T' with 'R'.
602 if (!CompareTreeWithSection(TNew->getRight(), TI, TE))
606 continue; // Contents('R') did not match suffix of 'T'.
608 // Trees did match! Return 'T'.
612 // 'TNew' is the only tree of its kind. Return it.
613 Cache.InsertNode(TNew, (void*) &*Cache.bucket_end(hash));
619 //===----------------------------------------------------------------------===//
620 // Immutable AVL-Tree Iterators.
621 //===----------------------------------------------------------------------===//
623 template <typename ImutInfo>
624 class ImutAVLTreeGenericIterator {
625 SmallVector<uintptr_t,20> stack;
627 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
630 typedef ImutAVLTree<ImutInfo> TreeTy;
631 typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
633 inline ImutAVLTreeGenericIterator() {}
634 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
635 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
638 TreeTy* operator*() const {
639 assert(!stack.empty());
640 return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
643 uintptr_t getVisitState() {
644 assert(!stack.empty());
645 return stack.back() & Flags;
649 bool AtEnd() const { return stack.empty(); }
651 bool AtBeginning() const {
652 return stack.size() == 1 && getVisitState() == VisitedNone;
655 void SkipToParent() {
656 assert(!stack.empty());
662 switch (getVisitState()) {
664 stack.back() |= VisitedLeft;
667 stack.back() |= VisitedRight;
670 assert(false && "Unreachable.");
674 inline bool operator==(const _Self& x) const {
675 if (stack.size() != x.stack.size())
678 for (unsigned i = 0 ; i < stack.size(); i++)
679 if (stack[i] != x.stack[i])
685 inline bool operator!=(const _Self& x) const { return !operator==(x); }
687 _Self& operator++() {
688 assert(!stack.empty());
690 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
693 switch (getVisitState()) {
695 if (TreeTy* L = Current->getLeft())
696 stack.push_back(reinterpret_cast<uintptr_t>(L));
698 stack.back() |= VisitedLeft;
703 if (TreeTy* R = Current->getRight())
704 stack.push_back(reinterpret_cast<uintptr_t>(R));
706 stack.back() |= VisitedRight;
715 assert(false && "Unreachable.");
721 _Self& operator--() {
722 assert(!stack.empty());
724 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
727 switch (getVisitState()) {
733 stack.back() &= ~Flags; // Set state to "VisitedNone."
735 if (TreeTy* L = Current->getLeft())
736 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
741 stack.back() &= ~Flags;
742 stack.back() |= VisitedLeft;
744 if (TreeTy* R = Current->getRight())
745 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
750 assert(false && "Unreachable.");
757 template <typename ImutInfo>
758 class ImutAVLTreeInOrderIterator {
759 typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
760 InternalIteratorTy InternalItr;
763 typedef ImutAVLTree<ImutInfo> TreeTy;
764 typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
766 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
767 if (Root) operator++(); // Advance to first element.
770 ImutAVLTreeInOrderIterator() : InternalItr() {}
772 inline bool operator==(const _Self& x) const {
773 return InternalItr == x.InternalItr;
776 inline bool operator!=(const _Self& x) const { return !operator==(x); }
778 inline TreeTy* operator*() const { return *InternalItr; }
779 inline TreeTy* operator->() const { return *InternalItr; }
781 inline _Self& operator++() {
783 while (!InternalItr.AtEnd() &&
784 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
789 inline _Self& operator--() {
791 while (!InternalItr.AtBeginning() &&
792 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
797 inline void SkipSubTree() {
798 InternalItr.SkipToParent();
800 while (!InternalItr.AtEnd() &&
801 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
806 //===----------------------------------------------------------------------===//
807 // Trait classes for Profile information.
808 //===----------------------------------------------------------------------===//
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;
818 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
819 FoldingSetTrait<T>::Profile(X,ID);
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;
829 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
834 #define PROFILE_INTEGER_INFO(X)\
835 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
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)
848 #undef PROFILE_INTEGER_INFO
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;
857 static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
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 //===----------------------------------------------------------------------===//
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;
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; }
885 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
886 return std::equal_to<key_type>()(LHS,RHS);
889 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
890 return std::less<key_type>()(LHS,RHS);
893 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
896 /// ImutContainerInfo - Specialization for pointer values to treat pointers
897 /// as references to unique objects. Pointers are thus compared by
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;
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; }
911 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
915 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
919 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
922 //===----------------------------------------------------------------------===//
924 //===----------------------------------------------------------------------===//
926 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
929 typedef typename ValInfo::value_type value_type;
930 typedef typename ValInfo::value_type_ref value_type_ref;
931 typedef ImutAVLTree<ValInfo> TreeTy;
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) {}
944 typename TreeTy::Factory F;
945 const bool Canonicalize;
948 Factory(bool canonicalize = true)
949 : Canonicalize(canonicalize) {}
951 Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
952 : F(Alloc), Canonicalize(canonicalize) {}
954 /// GetEmptySet - Returns an immutable set that contains no elements.
955 ImmutableSet GetEmptySet() {
956 return ImmutableSet(F.GetEmptyTree());
959 /// Add - Creates a new immutable set that contains all of the values
960 /// of the original set with the addition of the specified value. If
961 /// the original set already included the value, then the original set is
962 /// returned and no memory is allocated. The time and space complexity
963 /// of this operation is logarithmic in the size of the original set.
964 /// The memory allocated to represent the set is released when the
965 /// factory object that created the set is destroyed.
966 ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
967 TreeTy *NewT = F.Add(Old.Root, V);
968 return ImmutableSet(Canonicalize ? F.GetCanonicalTree(NewT) : NewT);
971 /// Remove - Creates a new immutable set that contains all of the values
972 /// of the original set with the exception of the specified value. If
973 /// the original set did not contain the value, the original set is
974 /// returned and no memory is allocated. The time and space complexity
975 /// of this operation is logarithmic in the size of the original set.
976 /// The memory allocated to represent the set is released when the
977 /// factory object that created the set is destroyed.
978 ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
979 TreeTy *NewT = F.Remove(Old.Root, V);
980 return ImmutableSet(Canonicalize ? F.GetCanonicalTree(NewT) : NewT);
983 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
986 Factory(const Factory& RHS); // DO NOT IMPLEMENT
987 void operator=(const Factory& RHS); // DO NOT IMPLEMENT
990 friend class Factory;
992 /// contains - Returns true if the set contains the specified value.
993 bool contains(value_type_ref V) const {
994 return Root ? Root->contains(V) : false;
997 bool operator==(ImmutableSet RHS) const {
998 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1001 bool operator!=(ImmutableSet RHS) const {
1002 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1009 /// isEmpty - Return true if the set contains no elements.
1010 bool isEmpty() const { return !Root; }
1012 /// isSingleton - Return true if the set contains exactly one element.
1013 /// This method runs in constant time.
1014 bool isSingleton() const { return getHeight() == 1; }
1016 template <typename Callback>
1017 void foreach(Callback& C) { if (Root) Root->foreach(C); }
1019 template <typename Callback>
1020 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
1022 //===--------------------------------------------------===//
1024 //===--------------------------------------------------===//
1027 typename TreeTy::iterator itr;
1028 iterator(TreeTy* t) : itr(t) {}
1029 friend class ImmutableSet<ValT,ValInfo>;
1032 inline value_type_ref operator*() const { return itr->getValue(); }
1033 inline iterator& operator++() { ++itr; return *this; }
1034 inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1035 inline iterator& operator--() { --itr; return *this; }
1036 inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
1037 inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1038 inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1039 inline value_type *operator->() const { return &(operator*()); }
1042 iterator begin() const { return iterator(Root); }
1043 iterator end() const { return iterator(); }
1045 //===--------------------------------------------------===//
1047 //===--------------------------------------------------===//
1049 inline unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1051 static inline void Profile(FoldingSetNodeID& ID, const ImmutableSet& S) {
1052 ID.AddPointer(S.Root);
1055 inline void Profile(FoldingSetNodeID& ID) const {
1056 return Profile(ID,*this);
1059 //===--------------------------------------------------===//
1061 //===--------------------------------------------------===//
1063 void verify() const { if (Root) Root->verify(); }
1066 } // end namespace llvm