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 assert (!isMutable() && "Node is incorrectly marked mutable.");
57 return reinterpret_cast<ImutAVLTree*>(Left);
60 /// getRight - Returns a pointer to the right subtree. This value is
61 /// NULL if there is no right subtree.
62 ImutAVLTree* getRight() const { return Right; }
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; }
68 /// getValue - Returns the data value associated with the tree node.
69 const value_type& getValue() const { return Value; }
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;
77 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
79 if (ImutInfo::isEqual(K,CurrentKey))
81 else if (ImutInfo::isLess(K,CurrentKey))
90 /// getMaxElement - Find the subtree associated with the highest ranged
92 ImutAVLTree* getMaxElement() {
93 ImutAVLTree *T = this;
94 ImutAVLTree *Right = T->getRight();
95 while (Right) { T = Right; Right = T->getRight(); }
99 /// size - Returns the number of nodes in the tree, which includes
100 /// both leaves and non-leaf nodes.
101 unsigned size() const {
104 if (const ImutAVLTree* L = getLeft()) n += L->size();
105 if (const ImutAVLTree* R = getRight()) n += R->size();
110 /// begin - Returns an iterator that iterates over the nodes of the tree
111 /// in an inorder traversal. The returned iterator thus refers to the
112 /// the tree node with the minimum data element.
113 iterator begin() const { return iterator(this); }
115 /// end - Returns an iterator for the tree that denotes the end of an
116 /// inorder traversal.
117 iterator end() const { return iterator(); }
119 bool ElementEqual(value_type_ref V) const {
121 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
122 ImutInfo::KeyOfValue(V)))
125 // Also compare the data values.
126 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
127 ImutInfo::DataOfValue(V)))
133 bool ElementEqual(const ImutAVLTree* RHS) const {
134 return ElementEqual(RHS->getValue());
137 /// isEqual - Compares two trees for structural equality and returns true
138 /// if they are equal. This worst case performance of this operation is
139 // linear in the sizes of the trees.
140 bool isEqual(const ImutAVLTree& RHS) const {
144 iterator LItr = begin(), LEnd = end();
145 iterator RItr = RHS.begin(), REnd = RHS.end();
147 while (LItr != LEnd && RItr != REnd) {
148 if (*LItr == *RItr) {
154 if (!LItr->ElementEqual(*RItr))
161 return LItr == LEnd && RItr == REnd;
164 /// isNotEqual - Compares two trees for structural inequality. Performance
165 /// is the same is isEqual.
166 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
168 /// contains - Returns true if this tree contains a subtree (node) that
169 /// has an data element that matches the specified key. Complexity
170 /// is logarithmic in the size of the tree.
171 bool contains(const key_type_ref K) { return (bool) find(K); }
173 /// foreach - A member template the accepts invokes operator() on a functor
174 /// object (specifed by Callback) for every node/subtree in the tree.
175 /// Nodes are visited using an inorder traversal.
176 template <typename Callback>
177 void foreach(Callback& C) {
178 if (ImutAVLTree* L = getLeft()) L->foreach(C);
182 if (ImutAVLTree* R = getRight()) R->foreach(C);
185 /// verify - A utility method that checks that the balancing and
186 /// ordering invariants of the tree are satisifed. It is a recursive
187 /// method that returns the height of the tree, which is then consumed
188 /// by the enclosing verify call. External callers should ignore the
189 /// return value. An invalid tree will cause an assertion to fire in
191 unsigned verify() const {
192 unsigned HL = getLeft() ? getLeft()->verify() : 0;
193 unsigned HR = getRight() ? getRight()->verify() : 0;
195 assert (getHeight() == ( HL > HR ? HL : HR ) + 1
196 && "Height calculation wrong.");
198 assert ((HL > HR ? HL-HR : HR-HL) <= 2
199 && "Balancing invariant violated.");
203 || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
204 ImutInfo::KeyOfValue(getValue()))
205 && "Value in left child is not less that current value.");
209 || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
210 ImutInfo::KeyOfValue(getRight()->getValue()))
211 && "Current value is not less that value of right child.");
216 /// Profile - Profiling for ImutAVLTree.
217 void Profile(llvm::FoldingSetNodeID& ID) {
218 ID.AddInteger(ComputeDigest());
221 //===----------------------------------------------------===//
223 //===----------------------------------------------------===//
232 //===----------------------------------------------------===//
233 // Internal methods (node manipulation; used by Factory).
234 //===----------------------------------------------------===//
238 enum { Mutable = 0x1 };
240 /// ImutAVLTree - Internal constructor that is only called by
242 ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
243 : Left(reinterpret_cast<uintptr_t>(l) | Mutable),
244 Right(r), Height(height), Value(v), Digest(0) {}
247 /// isMutable - Returns true if the left and right subtree references
248 /// (as well as height) can be changed. If this method returns false,
249 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
250 /// object should always have this method return true. Further, if this
251 /// method returns false for an instance of ImutAVLTree, all subtrees
252 /// will also have this method return false. The converse is not true.
253 bool isMutable() const { return Left & Mutable; }
255 /// getSafeLeft - Returns the pointer to the left tree by always masking
256 /// out the mutable bit. This is used internally by ImutAVLFactory,
257 /// as no trees returned to the client should have the mutable flag set.
258 ImutAVLTree* getSafeLeft() const {
259 return reinterpret_cast<ImutAVLTree*>(Left & ~Mutable);
262 //===----------------------------------------------------===//
263 // Mutating operations. A tree root can be manipulated as
264 // long as its reference has not "escaped" from internal
265 // methods of a factory object (see below). When a tree
266 // pointer is externally viewable by client code, the
267 // internal "mutable bit" is cleared to mark the tree
268 // immutable. Note that a tree that still has its mutable
269 // bit set may have children (subtrees) that are themselves
271 //===----------------------------------------------------===//
274 /// MarkImmutable - Clears the mutable flag for a tree. After this happens,
275 /// it is an error to call setLeft(), setRight(), and setHeight(). It
276 /// is also then safe to call getLeft() instead of getSafeLeft().
277 void MarkImmutable() {
278 assert (isMutable() && "Mutable flag already removed.");
282 /// setLeft - Changes the reference of the left subtree. Used internally
283 /// by ImutAVLFactory.
284 void setLeft(ImutAVLTree* NewLeft) {
285 assert (isMutable() &&
286 "Only a mutable tree can have its left subtree changed.");
288 Left = reinterpret_cast<uintptr_t>(NewLeft) | Mutable;
291 /// setRight - Changes the reference of the right subtree. Used internally
292 /// by ImutAVLFactory.
293 void setRight(ImutAVLTree* NewRight) {
294 assert (isMutable() &&
295 "Only a mutable tree can have its right subtree changed.");
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.");
309 unsigned ComputeDigest(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
312 if (L) digest += L->ComputeDigest();
314 { // Compute digest of stored data.
316 ImutInfo::Profile(ID,V);
317 digest += ID.ComputeHash();
320 if (R) digest += R->ComputeDigest();
325 inline unsigned ComputeDigest() {
326 if (Digest) return Digest;
328 unsigned X = ComputeDigest(getSafeLeft(), getRight(), getValue());
329 if (!isMutable()) Digest = X;
335 //===----------------------------------------------------------------------===//
336 // Immutable AVL-Tree Factory class.
337 //===----------------------------------------------------------------------===//
339 template <typename ImutInfo >
340 class ImutAVLFactory {
341 typedef ImutAVLTree<ImutInfo> TreeTy;
342 typedef typename TreeTy::value_type_ref value_type_ref;
343 typedef typename TreeTy::key_type_ref key_type_ref;
345 typedef FoldingSet<TreeTy> CacheTy;
350 bool ownsAllocator() const {
351 return Allocator & 0x1 ? false : true;
354 BumpPtrAllocator& getAllocator() const {
355 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
358 //===--------------------------------------------------===//
360 //===--------------------------------------------------===//
364 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
366 ImutAVLFactory(BumpPtrAllocator& Alloc)
367 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
370 if (ownsAllocator()) delete &getAllocator();
373 TreeTy* Add(TreeTy* T, value_type_ref V) {
374 T = Add_internal(V,T);
379 TreeTy* Remove(TreeTy* T, key_type_ref V) {
380 T = Remove_internal(V,T);
385 TreeTy* GetEmptyTree() const { return NULL; }
387 //===--------------------------------------------------===//
388 // A bunch of quick helper functions used for reasoning
389 // about the properties of trees and their children.
390 // These have succinct names so that the balancing code
391 // is as terse (and readable) as possible.
392 //===--------------------------------------------------===//
395 bool isEmpty(TreeTy* T) const { return !T; }
396 unsigned Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
397 TreeTy* Left(TreeTy* T) const { return T->getSafeLeft(); }
398 TreeTy* Right(TreeTy* T) const { return T->getRight(); }
399 value_type_ref Value(TreeTy* T) const { return T->Value; }
401 unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
402 unsigned hl = Height(L);
403 unsigned hr = Height(R);
404 return ( hl > hr ? hl : hr ) + 1;
408 static bool CompareTreeWithSection(TreeTy* T,
409 typename TreeTy::iterator& TI,
410 typename TreeTy::iterator& TE) {
412 typename TreeTy::iterator I = T->begin(), E = T->end();
414 for ( ; I!=E ; ++I, ++TI)
415 if (TI == TE || !I->ElementEqual(*TI))
421 //===--------------------------------------------------===//
422 // "CreateNode" is used to generate new tree roots that link
423 // to other trees. The functon may also simply move links
424 // in an existing root if that root is still marked mutable.
425 // This is necessary because otherwise our balancing code
426 // would leak memory as it would create nodes that are
427 // then discarded later before the finished tree is
428 // returned to the caller.
429 //===--------------------------------------------------===//
431 TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
432 // Search the FoldingSet bucket for a Tree with the same digest.
434 unsigned digest = TreeTy::ComputeDigest(L, R, V);
435 ID.AddInteger(digest);
436 unsigned hash = ID.ComputeHash();
438 typename CacheTy::bucket_iterator I = Cache.bucket_begin(hash);
439 typename CacheTy::bucket_iterator E = Cache.bucket_end(hash);
441 for (; I != E; ++I) {
444 if (T->ComputeDigest() != digest)
447 // We found a collision. Perform a comparison of Contents('T')
448 // with Contents('L')+'V'+Contents('R').
450 typename TreeTy::iterator TI = T->begin(), TE = T->end();
452 // First compare Contents('L') with the (initial) contents of T.
453 if (!CompareTreeWithSection(L, TI, TE))
456 // Now compare the new data element.
457 if (TI == TE || !TI->ElementEqual(V))
462 // Now compare the remainder of 'T' with 'R'.
463 if (!CompareTreeWithSection(R, TI, TE))
466 if (TI != TE) // Contents('R') did not match suffix of 'T'.
469 // Trees did match! Return 'T'.
473 // No tree with the contents: Contents('L')+'V'+Contents('R').
476 // Allocate the new tree node and insert it into the cache.
477 BumpPtrAllocator& A = getAllocator();
478 TreeTy* T = (TreeTy*) A.Allocate<TreeTy>();
479 new (T) TreeTy(L,R,V,IncrementHeight(L,R));
481 // We do not insert 'T' into the FoldingSet here. This is because
482 // this tree is still mutable and things may get rebalanced.
483 // Because our digest is associative and based on the contents of
484 // the set, this should hopefully not cause any strange bugs.
485 // 'T' is inserted by 'MarkImmutable'.
490 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
491 assert (!isEmpty(OldTree));
493 if (OldTree->isMutable()) {
495 OldTree->setRight(R);
496 OldTree->setHeight(IncrementHeight(L,R));
499 else return CreateNode(L, Value(OldTree), R);
502 /// Balance - Used by Add_internal and Remove_internal to
503 /// balance a newly created tree.
504 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
506 unsigned hl = Height(L);
507 unsigned hr = Height(R);
510 assert (!isEmpty(L) &&
511 "Left tree cannot be empty to have a height >= 2.");
513 TreeTy* LL = Left(L);
514 TreeTy* LR = Right(L);
516 if (Height(LL) >= Height(LR))
517 return CreateNode(LL, L, CreateNode(LR,V,R));
519 assert (!isEmpty(LR) &&
520 "LR cannot be empty because it has a height >= 1.");
522 TreeTy* LRL = Left(LR);
523 TreeTy* LRR = Right(LR);
525 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
527 else if (hr > hl + 2) {
528 assert (!isEmpty(R) &&
529 "Right tree cannot be empty to have a height >= 2.");
531 TreeTy* RL = Left(R);
532 TreeTy* RR = Right(R);
534 if (Height(RR) >= Height(RL))
535 return CreateNode(CreateNode(L,V,RL), R, RR);
537 assert (!isEmpty(RL) &&
538 "RL cannot be empty because it has a height >= 1.");
540 TreeTy* RLL = Left(RL);
541 TreeTy* RLR = Right(RL);
543 return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
546 return CreateNode(L,V,R);
549 /// Add_internal - Creates a new tree that includes the specified
550 /// data and the data from the original tree. If the original tree
551 /// already contained the data item, the original tree is returned.
552 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
554 return CreateNode(T, V, T);
556 assert (!T->isMutable());
558 key_type_ref K = ImutInfo::KeyOfValue(V);
559 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
561 if (ImutInfo::isEqual(K,KCurrent))
562 return CreateNode(Left(T), V, Right(T));
563 else if (ImutInfo::isLess(K,KCurrent))
564 return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
566 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
569 /// Remove_internal - Creates a new tree that includes all the data
570 /// from the original tree except the specified data. If the
571 /// specified data did not exist in the original tree, the original
572 /// tree is returned.
573 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
577 assert (!T->isMutable());
579 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
581 if (ImutInfo::isEqual(K,KCurrent))
582 return CombineLeftRightTrees(Left(T),Right(T));
583 else if (ImutInfo::isLess(K,KCurrent))
584 return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
586 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
589 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
590 if (isEmpty(L)) return R;
591 if (isEmpty(R)) return L;
594 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
595 return Balance(L,Value(OldNode),NewRight);
598 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
599 assert (!isEmpty(T));
601 if (isEmpty(Left(T))) {
606 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
609 /// MarkImmutable - Clears the mutable bits of a root and all of its
611 void MarkImmutable(TreeTy* T) {
612 if (!T || !T->isMutable())
616 MarkImmutable(Left(T));
617 MarkImmutable(Right(T));
619 // Now that the node is immutable it can safely be inserted
620 // into the node cache.
621 llvm::FoldingSetNodeID ID;
622 ID.AddInteger(T->ComputeDigest());
623 Cache.InsertNode(T, (void*) &*Cache.bucket_end(ID.ComputeHash()));
628 //===----------------------------------------------------------------------===//
629 // Immutable AVL-Tree Iterators.
630 //===----------------------------------------------------------------------===//
632 template <typename ImutInfo>
633 class ImutAVLTreeGenericIterator {
634 SmallVector<uintptr_t,20> stack;
636 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
639 typedef ImutAVLTree<ImutInfo> TreeTy;
640 typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
642 inline ImutAVLTreeGenericIterator() {}
643 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
644 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
647 TreeTy* operator*() const {
648 assert (!stack.empty());
649 return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
652 uintptr_t getVisitState() {
653 assert (!stack.empty());
654 return stack.back() & Flags;
658 bool AtEnd() const { return stack.empty(); }
660 bool AtBeginning() const {
661 return stack.size() == 1 && getVisitState() == VisitedNone;
664 void SkipToParent() {
665 assert (!stack.empty());
671 switch (getVisitState()) {
673 stack.back() |= VisitedLeft;
676 stack.back() |= VisitedRight;
679 assert (false && "Unreachable.");
683 inline bool operator==(const _Self& x) const {
684 if (stack.size() != x.stack.size())
687 for (unsigned i = 0 ; i < stack.size(); i++)
688 if (stack[i] != x.stack[i])
694 inline bool operator!=(const _Self& x) const { return !operator==(x); }
696 _Self& operator++() {
697 assert (!stack.empty());
699 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
702 switch (getVisitState()) {
704 if (TreeTy* L = Current->getSafeLeft())
705 stack.push_back(reinterpret_cast<uintptr_t>(L));
707 stack.back() |= VisitedLeft;
712 if (TreeTy* R = Current->getRight())
713 stack.push_back(reinterpret_cast<uintptr_t>(R));
715 stack.back() |= VisitedRight;
724 assert (false && "Unreachable.");
730 _Self& operator--() {
731 assert (!stack.empty());
733 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
736 switch (getVisitState()) {
742 stack.back() &= ~Flags; // Set state to "VisitedNone."
744 if (TreeTy* L = Current->getLeft())
745 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
750 stack.back() &= ~Flags;
751 stack.back() |= VisitedLeft;
753 if (TreeTy* R = Current->getRight())
754 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
759 assert (false && "Unreachable.");
766 template <typename ImutInfo>
767 class ImutAVLTreeInOrderIterator {
768 typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
769 InternalIteratorTy InternalItr;
772 typedef ImutAVLTree<ImutInfo> TreeTy;
773 typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
775 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
776 if (Root) operator++(); // Advance to first element.
779 ImutAVLTreeInOrderIterator() : InternalItr() {}
781 inline bool operator==(const _Self& x) const {
782 return InternalItr == x.InternalItr;
785 inline bool operator!=(const _Self& x) const { return !operator==(x); }
787 inline TreeTy* operator*() const { return *InternalItr; }
788 inline TreeTy* operator->() const { return *InternalItr; }
790 inline _Self& operator++() {
792 while (!InternalItr.AtEnd() &&
793 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
798 inline _Self& operator--() {
800 while (!InternalItr.AtBeginning() &&
801 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
806 inline void SkipSubTree() {
807 InternalItr.SkipToParent();
809 while (!InternalItr.AtEnd() &&
810 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
815 //===----------------------------------------------------------------------===//
816 // Trait classes for Profile information.
817 //===----------------------------------------------------------------------===//
819 /// Generic profile template. The default behavior is to invoke the
820 /// profile method of an object. Specializations for primitive integers
821 /// and generic handling of pointers is done below.
822 template <typename T>
823 struct ImutProfileInfo {
824 typedef const T value_type;
825 typedef const T& value_type_ref;
827 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
828 FoldingSetTrait<T>::Profile(X,ID);
832 /// Profile traits for integers.
833 template <typename T>
834 struct ImutProfileInteger {
835 typedef const T value_type;
836 typedef const T& value_type_ref;
838 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
843 #define PROFILE_INTEGER_INFO(X)\
844 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
846 PROFILE_INTEGER_INFO(char)
847 PROFILE_INTEGER_INFO(unsigned char)
848 PROFILE_INTEGER_INFO(short)
849 PROFILE_INTEGER_INFO(unsigned short)
850 PROFILE_INTEGER_INFO(unsigned)
851 PROFILE_INTEGER_INFO(signed)
852 PROFILE_INTEGER_INFO(long)
853 PROFILE_INTEGER_INFO(unsigned long)
854 PROFILE_INTEGER_INFO(long long)
855 PROFILE_INTEGER_INFO(unsigned long long)
857 #undef PROFILE_INTEGER_INFO
859 /// Generic profile trait for pointer types. We treat pointers as
860 /// references to unique objects.
861 template <typename T>
862 struct ImutProfileInfo<T*> {
863 typedef const T* value_type;
864 typedef value_type value_type_ref;
866 static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
871 //===----------------------------------------------------------------------===//
872 // Trait classes that contain element comparison operators and type
873 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
874 // inherit from the profile traits (ImutProfileInfo) to include operations
875 // for element profiling.
876 //===----------------------------------------------------------------------===//
879 /// ImutContainerInfo - Generic definition of comparison operations for
880 /// elements of immutable containers that defaults to using
881 /// std::equal_to<> and std::less<> to perform comparison of elements.
882 template <typename T>
883 struct ImutContainerInfo : public ImutProfileInfo<T> {
884 typedef typename ImutProfileInfo<T>::value_type value_type;
885 typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
886 typedef value_type key_type;
887 typedef value_type_ref key_type_ref;
888 typedef bool data_type;
889 typedef bool data_type_ref;
891 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
892 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
894 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
895 return std::equal_to<key_type>()(LHS,RHS);
898 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
899 return std::less<key_type>()(LHS,RHS);
902 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
905 /// ImutContainerInfo - Specialization for pointer values to treat pointers
906 /// as references to unique objects. Pointers are thus compared by
908 template <typename T>
909 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
910 typedef typename ImutProfileInfo<T*>::value_type value_type;
911 typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
912 typedef value_type key_type;
913 typedef value_type_ref key_type_ref;
914 typedef bool data_type;
915 typedef bool data_type_ref;
917 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
918 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
920 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
924 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
928 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
931 //===----------------------------------------------------------------------===//
933 //===----------------------------------------------------------------------===//
935 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
938 typedef typename ValInfo::value_type value_type;
939 typedef typename ValInfo::value_type_ref value_type_ref;
940 typedef ImutAVLTree<ValInfo> TreeTy;
946 /// Constructs a set from a pointer to a tree root. In general one
947 /// should use a Factory object to create sets instead of directly
948 /// invoking the constructor, but there are cases where make this
949 /// constructor public is useful.
950 explicit ImmutableSet(TreeTy* R) : Root(R) {}
953 typename TreeTy::Factory F;
958 Factory(BumpPtrAllocator& Alloc)
961 /// GetEmptySet - Returns an immutable set that contains no elements.
962 ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
964 /// Add - Creates a new immutable set that contains all of the values
965 /// of the original set with the addition of the specified value. If
966 /// the original set already included the value, then the original set is
967 /// returned and no memory is allocated. The time and space complexity
968 /// of this operation is logarithmic in the size of the original set.
969 /// The memory allocated to represent the set is released when the
970 /// factory object that created the set is destroyed.
971 ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
972 return ImmutableSet(F.Add(Old.Root,V));
975 /// Remove - Creates a new immutable set that contains all of the values
976 /// of the original set with the exception of the specified value. If
977 /// the original set did not contain the value, the original set is
978 /// returned and no memory is allocated. The time and space complexity
979 /// of this operation is logarithmic in the size of the original set.
980 /// The memory allocated to represent the set is released when the
981 /// factory object that created the set is destroyed.
982 ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
983 return ImmutableSet(F.Remove(Old.Root,V));
986 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
989 Factory(const Factory& RHS) {};
990 void operator=(const Factory& RHS) {};
993 friend class Factory;
995 /// contains - Returns true if the set contains the specified value.
996 bool contains(const value_type_ref V) const {
997 return Root ? Root->contains(V) : false;
1000 bool operator==(ImmutableSet RHS) const {
1001 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1004 bool operator!=(ImmutableSet RHS) const {
1005 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1008 TreeTy* getRoot() const { return Root; }
1010 /// isEmpty - Return true if the set contains no elements.
1011 bool isEmpty() const { return !Root; }
1013 /// isSingleton - Return true if the set contains exactly one element.
1014 /// This method runs in constant time.
1015 bool isSingleton() const { return getHeight() == 1; }
1017 template <typename Callback>
1018 void foreach(Callback& C) { if (Root) Root->foreach(C); }
1020 template <typename Callback>
1021 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
1023 //===--------------------------------------------------===//
1025 //===--------------------------------------------------===//
1028 typename TreeTy::iterator itr;
1031 iterator(TreeTy* t) : itr(t) {}
1032 friend class ImmutableSet<ValT,ValInfo>;
1034 inline value_type_ref operator*() const { return itr->getValue(); }
1035 inline iterator& operator++() { ++itr; return *this; }
1036 inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1037 inline iterator& operator--() { --itr; return *this; }
1038 inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
1039 inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1040 inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1041 inline value_type *operator->() const { return &(operator*()); }
1044 iterator begin() const { return iterator(Root); }
1045 iterator end() const { return iterator(); }
1047 //===--------------------------------------------------===//
1049 //===--------------------------------------------------===//
1051 inline unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1053 static inline void Profile(FoldingSetNodeID& ID, const ImmutableSet& S) {
1054 ID.AddPointer(S.Root);
1057 inline void Profile(FoldingSetNodeID& ID) const {
1058 return Profile(ID,*this);
1061 //===--------------------------------------------------===//
1063 //===--------------------------------------------------===//
1065 void verify() const { if (Root) Root->verify(); }
1068 } // end namespace llvm