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 assert(!hasCachedDigest() &&
287 "A mutable tree cannot have a cached digest.");
289 Left = reinterpret_cast<uintptr_t>(NewLeft) | LeftFlags;
292 /// setRight - Changes the reference of the right subtree. Used internally
293 /// by ImutAVLFactory.
294 void setRight(ImutAVLTree* NewRight) {
295 assert (isMutable() &&
296 "Only a mutable tree can have its right subtree changed.");
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());
336 MarkedCachedDigest();
343 //===----------------------------------------------------------------------===//
344 // Immutable AVL-Tree Factory class.
345 //===----------------------------------------------------------------------===//
347 template <typename ImutInfo >
348 class ImutAVLFactory {
349 typedef ImutAVLTree<ImutInfo> TreeTy;
350 typedef typename TreeTy::value_type_ref value_type_ref;
351 typedef typename TreeTy::key_type_ref key_type_ref;
353 typedef FoldingSet<TreeTy> CacheTy;
358 bool ownsAllocator() const {
359 return Allocator & 0x1 ? false : true;
362 BumpPtrAllocator& getAllocator() const {
363 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
366 //===--------------------------------------------------===//
368 //===--------------------------------------------------===//
372 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
374 ImutAVLFactory(BumpPtrAllocator& Alloc)
375 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
378 if (ownsAllocator()) delete &getAllocator();
381 TreeTy* Add(TreeTy* T, value_type_ref V) {
382 T = Add_internal(V,T);
387 TreeTy* Remove(TreeTy* T, key_type_ref V) {
388 T = Remove_internal(V,T);
393 TreeTy* GetEmptyTree() const { return NULL; }
395 //===--------------------------------------------------===//
396 // A bunch of quick helper functions used for reasoning
397 // about the properties of trees and their children.
398 // These have succinct names so that the balancing code
399 // is as terse (and readable) as possible.
400 //===--------------------------------------------------===//
403 bool isEmpty(TreeTy* T) const { return !T; }
404 unsigned Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
405 TreeTy* Left(TreeTy* T) const { return T->getLeft(); }
406 TreeTy* Right(TreeTy* T) const { return T->getRight(); }
407 value_type_ref Value(TreeTy* T) const { return T->Value; }
409 unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
410 unsigned hl = Height(L);
411 unsigned hr = Height(R);
412 return ( hl > hr ? hl : hr ) + 1;
416 static bool CompareTreeWithSection(TreeTy* T,
417 typename TreeTy::iterator& TI,
418 typename TreeTy::iterator& TE) {
420 typename TreeTy::iterator I = T->begin(), E = T->end();
422 for ( ; I!=E ; ++I, ++TI)
423 if (TI == TE || !I->ElementEqual(*TI))
429 //===--------------------------------------------------===//
430 // "CreateNode" is used to generate new tree roots that link
431 // to other trees. The functon may also simply move links
432 // in an existing root if that root is still marked mutable.
433 // This is necessary because otherwise our balancing code
434 // would leak memory as it would create nodes that are
435 // then discarded later before the finished tree is
436 // returned to the caller.
437 //===--------------------------------------------------===//
439 TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
440 // Search the FoldingSet bucket for a Tree with the same digest.
442 unsigned digest = TreeTy::ComputeDigest(L, R, V);
443 ID.AddInteger(digest);
444 unsigned hash = ID.ComputeHash();
446 typename CacheTy::bucket_iterator I = Cache.bucket_begin(hash);
447 typename CacheTy::bucket_iterator E = Cache.bucket_end(hash);
449 for (; I != E; ++I) {
452 if (T->ComputeDigest() != digest)
455 // We found a collision. Perform a comparison of Contents('T')
456 // with Contents('L')+'V'+Contents('R').
458 typename TreeTy::iterator TI = T->begin(), TE = T->end();
460 // First compare Contents('L') with the (initial) contents of T.
461 if (!CompareTreeWithSection(L, TI, TE))
464 // Now compare the new data element.
465 if (TI == TE || !TI->ElementEqual(V))
470 // Now compare the remainder of 'T' with 'R'.
471 if (!CompareTreeWithSection(R, TI, TE))
474 if (TI != TE) // Contents('R') did not match suffix of 'T'.
477 // Trees did match! Return 'T'.
481 // No tree with the contents: Contents('L')+'V'+Contents('R').
484 // Allocate the new tree node and insert it into the cache.
485 BumpPtrAllocator& A = getAllocator();
486 TreeTy* T = (TreeTy*) A.Allocate<TreeTy>();
487 new (T) TreeTy(L,R,V,IncrementHeight(L,R));
489 // We do not insert 'T' into the FoldingSet here. This is because
490 // this tree is still mutable and things may get rebalanced.
491 // Because our digest is associative and based on the contents of
492 // the set, this should hopefully not cause any strange bugs.
493 // 'T' is inserted by 'MarkImmutable'.
498 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
499 assert (!isEmpty(OldTree));
501 if (OldTree->isMutable()) {
503 OldTree->setRight(R);
504 OldTree->setHeight(IncrementHeight(L,R));
507 else return CreateNode(L, Value(OldTree), R);
510 /// Balance - Used by Add_internal and Remove_internal to
511 /// balance a newly created tree.
512 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
514 unsigned hl = Height(L);
515 unsigned hr = Height(R);
518 assert (!isEmpty(L) &&
519 "Left tree cannot be empty to have a height >= 2.");
521 TreeTy* LL = Left(L);
522 TreeTy* LR = Right(L);
524 if (Height(LL) >= Height(LR))
525 return CreateNode(LL, L, CreateNode(LR,V,R));
527 assert (!isEmpty(LR) &&
528 "LR cannot be empty because it has a height >= 1.");
530 TreeTy* LRL = Left(LR);
531 TreeTy* LRR = Right(LR);
533 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
535 else if (hr > hl + 2) {
536 assert (!isEmpty(R) &&
537 "Right tree cannot be empty to have a height >= 2.");
539 TreeTy* RL = Left(R);
540 TreeTy* RR = Right(R);
542 if (Height(RR) >= Height(RL))
543 return CreateNode(CreateNode(L,V,RL), R, RR);
545 assert (!isEmpty(RL) &&
546 "RL cannot be empty because it has a height >= 1.");
548 TreeTy* RLL = Left(RL);
549 TreeTy* RLR = Right(RL);
551 return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
554 return CreateNode(L,V,R);
557 /// Add_internal - Creates a new tree that includes the specified
558 /// data and the data from the original tree. If the original tree
559 /// already contained the data item, the original tree is returned.
560 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
562 return CreateNode(T, V, T);
564 assert (!T->isMutable());
566 key_type_ref K = ImutInfo::KeyOfValue(V);
567 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
569 if (ImutInfo::isEqual(K,KCurrent))
570 return CreateNode(Left(T), V, Right(T));
571 else if (ImutInfo::isLess(K,KCurrent))
572 return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
574 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
577 /// Remove_internal - Creates a new tree that includes all the data
578 /// from the original tree except the specified data. If the
579 /// specified data did not exist in the original tree, the original
580 /// tree is returned.
581 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
585 assert (!T->isMutable());
587 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
589 if (ImutInfo::isEqual(K,KCurrent))
590 return CombineLeftRightTrees(Left(T),Right(T));
591 else if (ImutInfo::isLess(K,KCurrent))
592 return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
594 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
597 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
598 if (isEmpty(L)) return R;
599 if (isEmpty(R)) return L;
602 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
603 return Balance(L,Value(OldNode),NewRight);
606 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
607 assert (!isEmpty(T));
609 if (isEmpty(Left(T))) {
614 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
617 /// MarkImmutable - Clears the mutable bits of a root and all of its
619 void MarkImmutable(TreeTy* T) {
620 if (!T || !T->isMutable())
624 MarkImmutable(Left(T));
625 MarkImmutable(Right(T));
627 // Now that the node is immutable it can safely be inserted
628 // into the node cache.
629 llvm::FoldingSetNodeID ID;
630 ID.AddInteger(T->ComputeDigest());
631 Cache.InsertNode(T, (void*) &*Cache.bucket_end(ID.ComputeHash()));
636 //===----------------------------------------------------------------------===//
637 // Immutable AVL-Tree Iterators.
638 //===----------------------------------------------------------------------===//
640 template <typename ImutInfo>
641 class ImutAVLTreeGenericIterator {
642 SmallVector<uintptr_t,20> stack;
644 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
647 typedef ImutAVLTree<ImutInfo> TreeTy;
648 typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
650 inline ImutAVLTreeGenericIterator() {}
651 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
652 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
655 TreeTy* operator*() const {
656 assert (!stack.empty());
657 return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
660 uintptr_t getVisitState() {
661 assert (!stack.empty());
662 return stack.back() & Flags;
666 bool AtEnd() const { return stack.empty(); }
668 bool AtBeginning() const {
669 return stack.size() == 1 && getVisitState() == VisitedNone;
672 void SkipToParent() {
673 assert (!stack.empty());
679 switch (getVisitState()) {
681 stack.back() |= VisitedLeft;
684 stack.back() |= VisitedRight;
687 assert (false && "Unreachable.");
691 inline bool operator==(const _Self& x) const {
692 if (stack.size() != x.stack.size())
695 for (unsigned i = 0 ; i < stack.size(); i++)
696 if (stack[i] != x.stack[i])
702 inline bool operator!=(const _Self& x) const { return !operator==(x); }
704 _Self& operator++() {
705 assert (!stack.empty());
707 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
710 switch (getVisitState()) {
712 if (TreeTy* L = Current->getLeft())
713 stack.push_back(reinterpret_cast<uintptr_t>(L));
715 stack.back() |= VisitedLeft;
720 if (TreeTy* R = Current->getRight())
721 stack.push_back(reinterpret_cast<uintptr_t>(R));
723 stack.back() |= VisitedRight;
732 assert (false && "Unreachable.");
738 _Self& operator--() {
739 assert (!stack.empty());
741 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
744 switch (getVisitState()) {
750 stack.back() &= ~Flags; // Set state to "VisitedNone."
752 if (TreeTy* L = Current->getLeft())
753 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
758 stack.back() &= ~Flags;
759 stack.back() |= VisitedLeft;
761 if (TreeTy* R = Current->getRight())
762 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
767 assert (false && "Unreachable.");
774 template <typename ImutInfo>
775 class ImutAVLTreeInOrderIterator {
776 typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
777 InternalIteratorTy InternalItr;
780 typedef ImutAVLTree<ImutInfo> TreeTy;
781 typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
783 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
784 if (Root) operator++(); // Advance to first element.
787 ImutAVLTreeInOrderIterator() : InternalItr() {}
789 inline bool operator==(const _Self& x) const {
790 return InternalItr == x.InternalItr;
793 inline bool operator!=(const _Self& x) const { return !operator==(x); }
795 inline TreeTy* operator*() const { return *InternalItr; }
796 inline TreeTy* operator->() const { return *InternalItr; }
798 inline _Self& operator++() {
800 while (!InternalItr.AtEnd() &&
801 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
806 inline _Self& operator--() {
808 while (!InternalItr.AtBeginning() &&
809 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
814 inline void SkipSubTree() {
815 InternalItr.SkipToParent();
817 while (!InternalItr.AtEnd() &&
818 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
823 //===----------------------------------------------------------------------===//
824 // Trait classes for Profile information.
825 //===----------------------------------------------------------------------===//
827 /// Generic profile template. The default behavior is to invoke the
828 /// profile method of an object. Specializations for primitive integers
829 /// and generic handling of pointers is done below.
830 template <typename T>
831 struct ImutProfileInfo {
832 typedef const T value_type;
833 typedef const T& value_type_ref;
835 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
836 FoldingSetTrait<T>::Profile(X,ID);
840 /// Profile traits for integers.
841 template <typename T>
842 struct ImutProfileInteger {
843 typedef const T value_type;
844 typedef const T& value_type_ref;
846 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
851 #define PROFILE_INTEGER_INFO(X)\
852 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
854 PROFILE_INTEGER_INFO(char)
855 PROFILE_INTEGER_INFO(unsigned char)
856 PROFILE_INTEGER_INFO(short)
857 PROFILE_INTEGER_INFO(unsigned short)
858 PROFILE_INTEGER_INFO(unsigned)
859 PROFILE_INTEGER_INFO(signed)
860 PROFILE_INTEGER_INFO(long)
861 PROFILE_INTEGER_INFO(unsigned long)
862 PROFILE_INTEGER_INFO(long long)
863 PROFILE_INTEGER_INFO(unsigned long long)
865 #undef PROFILE_INTEGER_INFO
867 /// Generic profile trait for pointer types. We treat pointers as
868 /// references to unique objects.
869 template <typename T>
870 struct ImutProfileInfo<T*> {
871 typedef const T* value_type;
872 typedef value_type value_type_ref;
874 static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
879 //===----------------------------------------------------------------------===//
880 // Trait classes that contain element comparison operators and type
881 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
882 // inherit from the profile traits (ImutProfileInfo) to include operations
883 // for element profiling.
884 //===----------------------------------------------------------------------===//
887 /// ImutContainerInfo - Generic definition of comparison operations for
888 /// elements of immutable containers that defaults to using
889 /// std::equal_to<> and std::less<> to perform comparison of elements.
890 template <typename T>
891 struct ImutContainerInfo : public ImutProfileInfo<T> {
892 typedef typename ImutProfileInfo<T>::value_type value_type;
893 typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
894 typedef value_type key_type;
895 typedef value_type_ref key_type_ref;
896 typedef bool data_type;
897 typedef bool data_type_ref;
899 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
900 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
902 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
903 return std::equal_to<key_type>()(LHS,RHS);
906 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
907 return std::less<key_type>()(LHS,RHS);
910 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
913 /// ImutContainerInfo - Specialization for pointer values to treat pointers
914 /// as references to unique objects. Pointers are thus compared by
916 template <typename T>
917 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
918 typedef typename ImutProfileInfo<T*>::value_type value_type;
919 typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
920 typedef value_type key_type;
921 typedef value_type_ref key_type_ref;
922 typedef bool data_type;
923 typedef bool data_type_ref;
925 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
926 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
928 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
932 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
936 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
939 //===----------------------------------------------------------------------===//
941 //===----------------------------------------------------------------------===//
943 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
946 typedef typename ValInfo::value_type value_type;
947 typedef typename ValInfo::value_type_ref value_type_ref;
948 typedef ImutAVLTree<ValInfo> TreeTy;
954 /// Constructs a set from a pointer to a tree root. In general one
955 /// should use a Factory object to create sets instead of directly
956 /// invoking the constructor, but there are cases where make this
957 /// constructor public is useful.
958 explicit ImmutableSet(TreeTy* R) : Root(R) {}
961 typename TreeTy::Factory F;
966 Factory(BumpPtrAllocator& Alloc)
969 /// GetEmptySet - Returns an immutable set that contains no elements.
970 ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
972 /// Add - Creates a new immutable set that contains all of the values
973 /// of the original set with the addition of the specified value. If
974 /// the original set already included the value, then the original set is
975 /// returned and no memory is allocated. The time and space complexity
976 /// of this operation is logarithmic in the size of the original set.
977 /// The memory allocated to represent the set is released when the
978 /// factory object that created the set is destroyed.
979 ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
980 return ImmutableSet(F.Add(Old.Root,V));
983 /// Remove - Creates a new immutable set that contains all of the values
984 /// of the original set with the exception of the specified value. If
985 /// the original set did not contain the value, the original set is
986 /// returned and no memory is allocated. The time and space complexity
987 /// of this operation is logarithmic in the size of the original set.
988 /// The memory allocated to represent the set is released when the
989 /// factory object that created the set is destroyed.
990 ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
991 return ImmutableSet(F.Remove(Old.Root,V));
994 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
997 Factory(const Factory& RHS) {};
998 void operator=(const Factory& RHS) {};
1001 friend class Factory;
1003 /// contains - Returns true if the set contains the specified value.
1004 bool contains(const value_type_ref V) const {
1005 return Root ? Root->contains(V) : false;
1008 bool operator==(ImmutableSet RHS) const {
1009 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1012 bool operator!=(ImmutableSet RHS) const {
1013 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1016 TreeTy* getRoot() const { return Root; }
1018 /// isEmpty - Return true if the set contains no elements.
1019 bool isEmpty() const { return !Root; }
1021 /// isSingleton - Return true if the set contains exactly one element.
1022 /// This method runs in constant time.
1023 bool isSingleton() const { return getHeight() == 1; }
1025 template <typename Callback>
1026 void foreach(Callback& C) { if (Root) Root->foreach(C); }
1028 template <typename Callback>
1029 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
1031 //===--------------------------------------------------===//
1033 //===--------------------------------------------------===//
1036 typename TreeTy::iterator itr;
1039 iterator(TreeTy* t) : itr(t) {}
1040 friend class ImmutableSet<ValT,ValInfo>;
1042 inline value_type_ref operator*() const { return itr->getValue(); }
1043 inline iterator& operator++() { ++itr; return *this; }
1044 inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1045 inline iterator& operator--() { --itr; return *this; }
1046 inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
1047 inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1048 inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1049 inline value_type *operator->() const { return &(operator*()); }
1052 iterator begin() const { return iterator(Root); }
1053 iterator end() const { return iterator(); }
1055 //===--------------------------------------------------===//
1057 //===--------------------------------------------------===//
1059 inline unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1061 static inline void Profile(FoldingSetNodeID& ID, const ImmutableSet& S) {
1062 ID.AddPointer(S.Root);
1065 inline void Profile(FoldingSetNodeID& ID) const {
1066 return Profile(ID,*this);
1069 //===--------------------------------------------------===//
1071 //===--------------------------------------------------===//
1073 void verify() const { if (Root) Root->verify(); }
1076 } // end namespace llvm