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/Support/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(const 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.");
201 || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
202 ImutInfo::KeyOfValue(getValue()))
203 && "Value in left child is not less that current value.");
207 || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
208 ImutInfo::KeyOfValue(getRight()->getValue()))
209 && "Current value is not less that value of right child.");
214 /// Profile - Profiling for ImutAVLTree.
215 void Profile(llvm::FoldingSetNodeID& ID) {
216 ID.AddInteger(ComputeDigest());
219 //===----------------------------------------------------===//
221 //===----------------------------------------------------===//
230 //===----------------------------------------------------===//
231 // Internal methods (node manipulation; used by Factory).
232 //===----------------------------------------------------===//
236 enum { Mutable = 0x1, NoCachedDigest = 0x2, LeftFlags = 0x3 };
238 /// ImutAVLTree - Internal constructor that is only called by
240 ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
241 : Left(reinterpret_cast<uintptr_t>(l) | (Mutable | NoCachedDigest)),
242 Right(r), Height(height), Value(v), Digest(0) {}
245 /// isMutable - Returns true if the left and right subtree references
246 /// (as well as height) can be changed. If this method returns false,
247 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
248 /// object should always have this method return true. Further, if this
249 /// method returns false for an instance of ImutAVLTree, all subtrees
250 /// will also have this method return false. The converse is not true.
251 bool isMutable() const { return Left & Mutable; }
253 /// hasCachedDigest - Returns true if the digest for this tree is cached.
254 /// This can only be true if the tree is immutable.
255 bool hasCachedDigest() const { return !(Left & NoCachedDigest); }
257 //===----------------------------------------------------===//
258 // Mutating operations. A tree root can be manipulated as
259 // long as its reference has not "escaped" from internal
260 // methods of a factory object (see below). When a tree
261 // pointer is externally viewable by client code, the
262 // internal "mutable bit" is cleared to mark the tree
263 // immutable. Note that a tree that still has its mutable
264 // bit set may have children (subtrees) that are themselves
266 //===----------------------------------------------------===//
268 /// MarkImmutable - Clears the mutable flag for a tree. After this happens,
269 /// it is an error to call setLeft(), setRight(), and setHeight().
270 void MarkImmutable() {
271 assert(isMutable() && "Mutable flag already removed.");
275 /// MarkedCachedDigest - Clears the NoCachedDigest flag for a tree.
276 void MarkedCachedDigest() {
277 assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
278 Left &= ~NoCachedDigest;
281 /// setLeft - Changes the reference of the left subtree. Used internally
282 /// by ImutAVLFactory.
283 void setLeft(ImutAVLTree* NewLeft) {
284 assert(isMutable() &&
285 "Only a mutable tree can have its left subtree changed.");
286 Left = reinterpret_cast<uintptr_t>(NewLeft) | LeftFlags;
289 /// setRight - Changes the reference of the right subtree. Used internally
290 /// by ImutAVLFactory.
291 void setRight(ImutAVLTree* NewRight) {
292 assert(isMutable() &&
293 "Only a mutable tree can have its right subtree changed.");
296 // Set the NoCachedDigest flag.
297 Left = Left | NoCachedDigest;
301 /// setHeight - Changes the height of the tree. Used internally by
303 void setHeight(unsigned h) {
304 assert(isMutable() && "Only a mutable tree can have its height changed.");
309 uint32_t ComputeDigest(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
313 digest += L->ComputeDigest();
315 // Compute digest of stored data.
317 ImutInfo::Profile(ID,V);
318 digest += ID.ComputeHash();
321 digest += R->ComputeDigest();
326 inline uint32_t ComputeDigest() {
327 // Check the lowest bit to determine if digest has actually been
329 if (hasCachedDigest())
332 uint32_t X = ComputeDigest(getLeft(), getRight(), getValue());
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 // Search the FoldingSet bucket for a Tree with the same digest.
436 unsigned digest = TreeTy::ComputeDigest(L, R, V);
437 ID.AddInteger(digest);
438 unsigned hash = ID.ComputeHash();
440 typename CacheTy::bucket_iterator I = Cache.bucket_begin(hash);
441 typename CacheTy::bucket_iterator E = Cache.bucket_end(hash);
443 for (; I != E; ++I) {
446 if (T->ComputeDigest() != digest)
449 // We found a collision. Perform a comparison of Contents('T')
450 // with Contents('L')+'V'+Contents('R').
451 typename TreeTy::iterator TI = T->begin(), TE = T->end();
453 // First compare Contents('L') with the (initial) contents of T.
454 if (!CompareTreeWithSection(L, TI, TE))
457 // Now compare the new data element.
458 if (TI == TE || !TI->ElementEqual(V))
463 // Now compare the remainder of 'T' with 'R'.
464 if (!CompareTreeWithSection(R, TI, TE))
468 continue; // Contents('R') did not match suffix of 'T'.
470 // Trees did match! Return 'T'.
474 // No tree with the contents: Contents('L')+'V'+Contents('R').
475 // Create it. Allocate the new tree node and insert it into the cache.
476 BumpPtrAllocator& A = getAllocator();
477 TreeTy* T = (TreeTy*) A.Allocate<TreeTy>();
478 new (T) TreeTy(L,R,V,IncrementHeight(L,R));
480 // We do not insert 'T' into the FoldingSet here. This is because
481 // this tree is still mutable and things may get rebalanced.
482 // Because our digest is associative and based on the contents of
483 // the set, this should hopefully not cause any strange bugs.
484 // 'T' is inserted by 'MarkImmutable'.
488 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
489 assert (!isEmpty(OldTree));
491 if (OldTree->isMutable()) {
493 OldTree->setRight(R);
494 OldTree->setHeight(IncrementHeight(L,R));
498 return CreateNode(L, Value(OldTree), R);
501 /// Balance - Used by Add_internal and Remove_internal to
502 /// balance a newly created tree.
503 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
505 unsigned hl = Height(L);
506 unsigned hr = Height(R);
509 assert (!isEmpty(L) &&
510 "Left tree cannot be empty to have a height >= 2.");
512 TreeTy* LL = Left(L);
513 TreeTy* LR = Right(L);
515 if (Height(LL) >= Height(LR))
516 return CreateNode(LL, L, CreateNode(LR,V,R));
518 assert (!isEmpty(LR) &&
519 "LR cannot be empty because it has a height >= 1.");
521 TreeTy* LRL = Left(LR);
522 TreeTy* LRR = Right(LR);
524 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
526 else if (hr > hl + 2) {
527 assert (!isEmpty(R) &&
528 "Right tree cannot be empty to have a height >= 2.");
530 TreeTy* RL = Left(R);
531 TreeTy* RR = Right(R);
533 if (Height(RR) >= Height(RL))
534 return CreateNode(CreateNode(L,V,RL), R, RR);
536 assert (!isEmpty(RL) &&
537 "RL cannot be empty because it has a height >= 1.");
539 TreeTy* RLL = Left(RL);
540 TreeTy* RLR = Right(RL);
542 return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
545 return CreateNode(L,V,R);
548 /// Add_internal - Creates a new tree that includes the specified
549 /// data and the data from the original tree. If the original tree
550 /// already contained the data item, the original tree is returned.
551 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
553 return CreateNode(T, V, T);
555 assert (!T->isMutable());
557 key_type_ref K = ImutInfo::KeyOfValue(V);
558 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
560 if (ImutInfo::isEqual(K,KCurrent))
561 return CreateNode(Left(T), V, Right(T));
562 else if (ImutInfo::isLess(K,KCurrent))
563 return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
565 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
568 /// Remove_internal - Creates a new tree that includes all the data
569 /// from the original tree except the specified data. If the
570 /// specified data did not exist in the original tree, the original
571 /// tree is returned.
572 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
576 assert (!T->isMutable());
578 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
580 if (ImutInfo::isEqual(K,KCurrent))
581 return CombineLeftRightTrees(Left(T),Right(T));
582 else if (ImutInfo::isLess(K,KCurrent))
583 return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
585 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
588 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
589 if (isEmpty(L)) return R;
590 if (isEmpty(R)) return L;
593 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
594 return Balance(L,Value(OldNode),NewRight);
597 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
598 assert (!isEmpty(T));
600 if (isEmpty(Left(T))) {
605 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
608 /// MarkImmutable - Clears the mutable bits of a root and all of its
610 void MarkImmutable(TreeTy* T) {
611 if (!T || !T->isMutable())
615 MarkImmutable(Left(T));
616 MarkImmutable(Right(T));
618 // Now that the node is immutable it can safely be inserted
619 // into the node cache.
620 llvm::FoldingSetNodeID ID;
621 ID.AddInteger(T->ComputeDigest());
622 Cache.InsertNode(T, (void*) &*Cache.bucket_end(ID.ComputeHash()));
627 //===----------------------------------------------------------------------===//
628 // Immutable AVL-Tree Iterators.
629 //===----------------------------------------------------------------------===//
631 template <typename ImutInfo>
632 class ImutAVLTreeGenericIterator {
633 SmallVector<uintptr_t,20> stack;
635 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
638 typedef ImutAVLTree<ImutInfo> TreeTy;
639 typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
641 inline ImutAVLTreeGenericIterator() {}
642 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
643 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
646 TreeTy* operator*() const {
647 assert (!stack.empty());
648 return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
651 uintptr_t getVisitState() {
652 assert (!stack.empty());
653 return stack.back() & Flags;
657 bool AtEnd() const { return stack.empty(); }
659 bool AtBeginning() const {
660 return stack.size() == 1 && getVisitState() == VisitedNone;
663 void SkipToParent() {
664 assert (!stack.empty());
670 switch (getVisitState()) {
672 stack.back() |= VisitedLeft;
675 stack.back() |= VisitedRight;
678 assert (false && "Unreachable.");
682 inline bool operator==(const _Self& x) const {
683 if (stack.size() != x.stack.size())
686 for (unsigned i = 0 ; i < stack.size(); i++)
687 if (stack[i] != x.stack[i])
693 inline bool operator!=(const _Self& x) const { return !operator==(x); }
695 _Self& operator++() {
696 assert (!stack.empty());
698 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
701 switch (getVisitState()) {
703 if (TreeTy* L = Current->getLeft())
704 stack.push_back(reinterpret_cast<uintptr_t>(L));
706 stack.back() |= VisitedLeft;
711 if (TreeTy* R = Current->getRight())
712 stack.push_back(reinterpret_cast<uintptr_t>(R));
714 stack.back() |= VisitedRight;
723 assert (false && "Unreachable.");
729 _Self& operator--() {
730 assert (!stack.empty());
732 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
735 switch (getVisitState()) {
741 stack.back() &= ~Flags; // Set state to "VisitedNone."
743 if (TreeTy* L = Current->getLeft())
744 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
749 stack.back() &= ~Flags;
750 stack.back() |= VisitedLeft;
752 if (TreeTy* R = Current->getRight())
753 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
758 assert (false && "Unreachable.");
765 template <typename ImutInfo>
766 class ImutAVLTreeInOrderIterator {
767 typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
768 InternalIteratorTy InternalItr;
771 typedef ImutAVLTree<ImutInfo> TreeTy;
772 typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
774 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
775 if (Root) operator++(); // Advance to first element.
778 ImutAVLTreeInOrderIterator() : InternalItr() {}
780 inline bool operator==(const _Self& x) const {
781 return InternalItr == x.InternalItr;
784 inline bool operator!=(const _Self& x) const { return !operator==(x); }
786 inline TreeTy* operator*() const { return *InternalItr; }
787 inline TreeTy* operator->() const { return *InternalItr; }
789 inline _Self& operator++() {
791 while (!InternalItr.AtEnd() &&
792 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
797 inline _Self& operator--() {
799 while (!InternalItr.AtBeginning() &&
800 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
805 inline void SkipSubTree() {
806 InternalItr.SkipToParent();
808 while (!InternalItr.AtEnd() &&
809 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
814 //===----------------------------------------------------------------------===//
815 // Trait classes for Profile information.
816 //===----------------------------------------------------------------------===//
818 /// Generic profile template. The default behavior is to invoke the
819 /// profile method of an object. Specializations for primitive integers
820 /// and generic handling of pointers is done below.
821 template <typename T>
822 struct ImutProfileInfo {
823 typedef const T value_type;
824 typedef const T& value_type_ref;
826 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
827 FoldingSetTrait<T>::Profile(X,ID);
831 /// Profile traits for integers.
832 template <typename T>
833 struct ImutProfileInteger {
834 typedef const T value_type;
835 typedef const T& value_type_ref;
837 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
842 #define PROFILE_INTEGER_INFO(X)\
843 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
845 PROFILE_INTEGER_INFO(char)
846 PROFILE_INTEGER_INFO(unsigned char)
847 PROFILE_INTEGER_INFO(short)
848 PROFILE_INTEGER_INFO(unsigned short)
849 PROFILE_INTEGER_INFO(unsigned)
850 PROFILE_INTEGER_INFO(signed)
851 PROFILE_INTEGER_INFO(long)
852 PROFILE_INTEGER_INFO(unsigned long)
853 PROFILE_INTEGER_INFO(long long)
854 PROFILE_INTEGER_INFO(unsigned long long)
856 #undef PROFILE_INTEGER_INFO
858 /// Generic profile trait for pointer types. We treat pointers as
859 /// references to unique objects.
860 template <typename T>
861 struct ImutProfileInfo<T*> {
862 typedef const T* value_type;
863 typedef value_type value_type_ref;
865 static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
870 //===----------------------------------------------------------------------===//
871 // Trait classes that contain element comparison operators and type
872 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
873 // inherit from the profile traits (ImutProfileInfo) to include operations
874 // for element profiling.
875 //===----------------------------------------------------------------------===//
878 /// ImutContainerInfo - Generic definition of comparison operations for
879 /// elements of immutable containers that defaults to using
880 /// std::equal_to<> and std::less<> to perform comparison of elements.
881 template <typename T>
882 struct ImutContainerInfo : public ImutProfileInfo<T> {
883 typedef typename ImutProfileInfo<T>::value_type value_type;
884 typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
885 typedef value_type key_type;
886 typedef value_type_ref key_type_ref;
887 typedef bool data_type;
888 typedef bool data_type_ref;
890 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
891 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
893 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
894 return std::equal_to<key_type>()(LHS,RHS);
897 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
898 return std::less<key_type>()(LHS,RHS);
901 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
904 /// ImutContainerInfo - Specialization for pointer values to treat pointers
905 /// as references to unique objects. Pointers are thus compared by
907 template <typename T>
908 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
909 typedef typename ImutProfileInfo<T*>::value_type value_type;
910 typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
911 typedef value_type key_type;
912 typedef value_type_ref key_type_ref;
913 typedef bool data_type;
914 typedef bool data_type_ref;
916 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
917 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
919 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
923 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
927 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
930 //===----------------------------------------------------------------------===//
932 //===----------------------------------------------------------------------===//
934 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
937 typedef typename ValInfo::value_type value_type;
938 typedef typename ValInfo::value_type_ref value_type_ref;
939 typedef ImutAVLTree<ValInfo> TreeTy;
945 /// Constructs a set from a pointer to a tree root. In general one
946 /// should use a Factory object to create sets instead of directly
947 /// invoking the constructor, but there are cases where make this
948 /// constructor public is useful.
949 explicit ImmutableSet(TreeTy* R) : Root(R) {}
952 typename TreeTy::Factory F;
957 Factory(BumpPtrAllocator& Alloc)
960 /// GetEmptySet - Returns an immutable set that contains no elements.
961 ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
963 /// Add - Creates a new immutable set that contains all of the values
964 /// of the original set with the addition of the specified value. If
965 /// the original set already included the value, then the original set is
966 /// returned and no memory is allocated. The time and space complexity
967 /// of this operation is logarithmic in the size of the original set.
968 /// The memory allocated to represent the set is released when the
969 /// factory object that created the set is destroyed.
970 ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
971 return ImmutableSet(F.Add(Old.Root,V));
974 /// Remove - Creates a new immutable set that contains all of the values
975 /// of the original set with the exception of the specified value. If
976 /// the original set did not contain the value, the original set is
977 /// returned and no memory is allocated. The time and space complexity
978 /// of this operation is logarithmic in the size of the original set.
979 /// The memory allocated to represent the set is released when the
980 /// factory object that created the set is destroyed.
981 ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
982 return ImmutableSet(F.Remove(Old.Root,V));
985 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
988 Factory(const Factory& RHS) {};
989 void operator=(const Factory& RHS) {};
992 friend class Factory;
994 /// contains - Returns true if the set contains the specified value.
995 bool contains(const value_type_ref V) const {
996 return Root ? Root->contains(V) : false;
999 bool operator==(ImmutableSet RHS) const {
1000 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1003 bool operator!=(ImmutableSet RHS) const {
1004 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1007 TreeTy* getRoot() const { return 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;
1030 iterator(TreeTy* t) : itr(t) {}
1031 friend class ImmutableSet<ValT,ValInfo>;
1033 inline value_type_ref operator*() const { return itr->getValue(); }
1034 inline iterator& operator++() { ++itr; return *this; }
1035 inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1036 inline iterator& operator--() { --itr; return *this; }
1037 inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
1038 inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1039 inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1040 inline value_type *operator->() const { return &(operator*()); }
1043 iterator begin() const { return iterator(Root); }
1044 iterator end() const { return iterator(); }
1046 //===--------------------------------------------------===//
1048 //===--------------------------------------------------===//
1050 inline unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1052 static inline void Profile(FoldingSetNodeID& ID, const ImmutableSet& S) {
1053 ID.AddPointer(S.Root);
1056 inline void Profile(FoldingSetNodeID& ID) const {
1057 return Profile(ID,*this);
1060 //===--------------------------------------------------===//
1062 //===--------------------------------------------------===//
1064 void verify() const { if (Root) Root->verify(); }
1067 } // end namespace llvm