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; }
65 /// getHeight - Returns the height of the tree. A tree with no subtrees
66 /// has a height of 1.
67 unsigned getHeight() const { return Height; }
69 /// getValue - Returns the data value associated with the tree node.
70 const value_type& getValue() const { return Value; }
72 /// find - Finds the subtree associated with the specified key value.
73 /// This method returns NULL if no matching subtree is found.
74 ImutAVLTree* find(key_type_ref K) {
75 ImutAVLTree *T = this;
78 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
80 if (ImutInfo::isEqual(K,CurrentKey))
82 else if (ImutInfo::isLess(K,CurrentKey))
91 /// size - Returns the number of nodes in the tree, which includes
92 /// both leaves and non-leaf nodes.
93 unsigned size() const {
96 if (const ImutAVLTree* L = getLeft()) n += L->size();
97 if (const ImutAVLTree* R = getRight()) n += R->size();
102 /// begin - Returns an iterator that iterates over the nodes of the tree
103 /// in an inorder traversal. The returned iterator thus refers to the
104 /// the tree node with the minimum data element.
105 iterator begin() const { return iterator(this); }
107 /// end - Returns an iterator for the tree that denotes the end of an
108 /// inorder traversal.
109 iterator end() const { return iterator(); }
111 bool ElementEqual(value_type_ref V) const {
113 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
114 ImutInfo::KeyOfValue(V)))
117 // Also compare the data values.
118 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
119 ImutInfo::DataOfValue(V)))
125 bool ElementEqual(const ImutAVLTree* RHS) const {
126 return ElementEqual(RHS->getValue());
129 /// isEqual - Compares two trees for structural equality and returns true
130 /// if they are equal. This worst case performance of this operation is
131 // linear in the sizes of the trees.
132 bool isEqual(const ImutAVLTree& RHS) const {
136 iterator LItr = begin(), LEnd = end();
137 iterator RItr = RHS.begin(), REnd = RHS.end();
139 while (LItr != LEnd && RItr != REnd) {
140 if (*LItr == *RItr) {
146 if (!LItr->ElementEqual(*RItr))
153 return LItr == LEnd && RItr == REnd;
156 /// isNotEqual - Compares two trees for structural inequality. Performance
157 /// is the same is isEqual.
158 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
160 /// contains - Returns true if this tree contains a subtree (node) that
161 /// has an data element that matches the specified key. Complexity
162 /// is logarithmic in the size of the tree.
163 bool contains(const key_type_ref K) { return (bool) find(K); }
165 /// foreach - A member template the accepts invokes operator() on a functor
166 /// object (specifed by Callback) for every node/subtree in the tree.
167 /// Nodes are visited using an inorder traversal.
168 template <typename Callback>
169 void foreach(Callback& C) {
170 if (ImutAVLTree* L = getLeft()) L->foreach(C);
174 if (ImutAVLTree* R = getRight()) R->foreach(C);
177 /// verify - A utility method that checks that the balancing and
178 /// ordering invariants of the tree are satisifed. It is a recursive
179 /// method that returns the height of the tree, which is then consumed
180 /// by the enclosing verify call. External callers should ignore the
181 /// return value. An invalid tree will cause an assertion to fire in
183 unsigned verify() const {
184 unsigned HL = getLeft() ? getLeft()->verify() : 0;
185 unsigned HR = getRight() ? getRight()->verify() : 0;
187 assert (getHeight() == ( HL > HR ? HL : HR ) + 1
188 && "Height calculation wrong.");
190 assert ((HL > HR ? HL-HR : HR-HL) <= 2
191 && "Balancing invariant violated.");
195 || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
196 ImutInfo::KeyOfValue(getValue()))
197 && "Value in left child is not less that current value.");
201 || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
202 ImutInfo::KeyOfValue(getRight()->getValue()))
203 && "Current value is not less that value of right child.");
208 /// Profile - Profiling for ImutAVLTree.
209 void Profile(llvm::FoldingSetNodeID& ID) {
210 ID.AddInteger(ComputeDigest());
213 //===----------------------------------------------------===//
215 //===----------------------------------------------------===//
224 //===----------------------------------------------------===//
225 // Internal methods (node manipulation; used by Factory).
226 //===----------------------------------------------------===//
230 enum { Mutable = 0x1 };
232 /// ImutAVLTree - Internal constructor that is only called by
234 ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
235 : Left(reinterpret_cast<uintptr_t>(l) | Mutable),
236 Right(r), Height(height), Value(v), Digest(0) {}
239 /// isMutable - Returns true if the left and right subtree references
240 /// (as well as height) can be changed. If this method returns false,
241 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
242 /// object should always have this method return true. Further, if this
243 /// method returns false for an instance of ImutAVLTree, all subtrees
244 /// will also have this method return false. The converse is not true.
245 bool isMutable() const { return Left & Mutable; }
247 /// getSafeLeft - Returns the pointer to the left tree by always masking
248 /// out the mutable bit. This is used internally by ImutAVLFactory,
249 /// as no trees returned to the client should have the mutable flag set.
250 ImutAVLTree* getSafeLeft() const {
251 return reinterpret_cast<ImutAVLTree*>(Left & ~Mutable);
254 //===----------------------------------------------------===//
255 // Mutating operations. A tree root can be manipulated as
256 // long as its reference has not "escaped" from internal
257 // methods of a factory object (see below). When a tree
258 // pointer is externally viewable by client code, the
259 // internal "mutable bit" is cleared to mark the tree
260 // immutable. Note that a tree that still has its mutable
261 // bit set may have children (subtrees) that are themselves
263 //===----------------------------------------------------===//
266 /// MarkImmutable - Clears the mutable flag for a tree. After this happens,
267 /// it is an error to call setLeft(), setRight(), and setHeight(). It
268 /// is also then safe to call getLeft() instead of getSafeLeft().
269 void MarkImmutable() {
270 assert (isMutable() && "Mutable flag already removed.");
274 /// setLeft - Changes the reference of the left subtree. Used internally
275 /// by ImutAVLFactory.
276 void setLeft(ImutAVLTree* NewLeft) {
277 assert (isMutable() &&
278 "Only a mutable tree can have its left subtree changed.");
280 Left = reinterpret_cast<uintptr_t>(NewLeft) | Mutable;
283 /// setRight - Changes the reference of the right subtree. Used internally
284 /// by ImutAVLFactory.
285 void setRight(ImutAVLTree* NewRight) {
286 assert (isMutable() &&
287 "Only a mutable tree can have its right subtree changed.");
292 /// setHeight - Changes the height of the tree. Used internally by
294 void setHeight(unsigned h) {
295 assert (isMutable() && "Only a mutable tree can have its height changed.");
301 unsigned ComputeDigest(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
304 if (L) digest += L->ComputeDigest();
306 { // Compute digest of stored data.
308 ImutInfo::Profile(ID,V);
309 digest += ID.ComputeHash();
312 if (R) digest += R->ComputeDigest();
317 inline unsigned ComputeDigest() {
318 if (Digest) return Digest;
320 unsigned X = ComputeDigest(getSafeLeft(), getRight(), getValue());
321 if (!isMutable()) Digest = X;
327 //===----------------------------------------------------------------------===//
328 // Immutable AVL-Tree Factory class.
329 //===----------------------------------------------------------------------===//
331 template <typename ImutInfo >
332 class ImutAVLFactory {
333 typedef ImutAVLTree<ImutInfo> TreeTy;
334 typedef typename TreeTy::value_type_ref value_type_ref;
335 typedef typename TreeTy::key_type_ref key_type_ref;
337 typedef FoldingSet<TreeTy> CacheTy;
342 bool ownsAllocator() const {
343 return Allocator & 0x1 ? false : true;
346 BumpPtrAllocator& getAllocator() const {
347 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
350 //===--------------------------------------------------===//
352 //===--------------------------------------------------===//
356 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
358 ImutAVLFactory(BumpPtrAllocator& Alloc)
359 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
362 if (ownsAllocator()) delete &getAllocator();
365 TreeTy* Add(TreeTy* T, value_type_ref V) {
366 T = Add_internal(V,T);
371 TreeTy* Remove(TreeTy* T, key_type_ref V) {
372 T = Remove_internal(V,T);
377 TreeTy* GetEmptyTree() const { return NULL; }
379 //===--------------------------------------------------===//
380 // A bunch of quick helper functions used for reasoning
381 // about the properties of trees and their children.
382 // These have succinct names so that the balancing code
383 // is as terse (and readable) as possible.
384 //===--------------------------------------------------===//
387 bool isEmpty(TreeTy* T) const { return !T; }
388 unsigned Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
389 TreeTy* Left(TreeTy* T) const { return T->getSafeLeft(); }
390 TreeTy* Right(TreeTy* T) const { return T->getRight(); }
391 value_type_ref Value(TreeTy* T) const { return T->Value; }
393 unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
394 unsigned hl = Height(L);
395 unsigned hr = Height(R);
396 return ( hl > hr ? hl : hr ) + 1;
400 static bool CompareTreeWithSection(TreeTy* T,
401 typename TreeTy::iterator& TI,
402 typename TreeTy::iterator& TE) {
404 typename TreeTy::iterator I = T->begin(), E = T->end();
406 for ( ; I!=E ; ++I, ++TI)
407 if (TI == TE || !I->ElementEqual(*TI))
413 //===--------------------------------------------------===//
414 // "CreateNode" is used to generate new tree roots that link
415 // to other trees. The functon may also simply move links
416 // in an existing root if that root is still marked mutable.
417 // This is necessary because otherwise our balancing code
418 // would leak memory as it would create nodes that are
419 // then discarded later before the finished tree is
420 // returned to the caller.
421 //===--------------------------------------------------===//
423 TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
424 // Search the FoldingSet bucket for a Tree with the same digest.
426 unsigned digest = TreeTy::ComputeDigest(L, R, V);
427 ID.AddInteger(digest);
428 unsigned hash = ID.ComputeHash();
430 typename CacheTy::bucket_iterator I = Cache.bucket_begin(hash);
431 typename CacheTy::bucket_iterator E = Cache.bucket_end(hash);
433 for (; I != E; ++I) {
436 if (T->ComputeDigest() != digest)
439 // We found a collision. Perform a comparison of Contents('T')
440 // with Contents('L')+'V'+Contents('R').
442 typename TreeTy::iterator TI = T->begin(), TE = T->end();
444 // First compare Contents('L') with the (initial) contents of T.
445 if (!CompareTreeWithSection(L, TI, TE))
448 // Now compare the new data element.
449 if (TI == TE || !TI->ElementEqual(V))
454 // Now compare the remainder of 'T' with 'R'.
455 if (!CompareTreeWithSection(R, TI, TE))
458 if (TI != TE) // Contents('R') did not match suffix of 'T'.
461 // Trees did match! Return 'T'.
465 // No tree with the contents: Contents('L')+'V'+Contents('R').
468 // Allocate the new tree node and insert it into the cache.
469 BumpPtrAllocator& A = getAllocator();
470 TreeTy* T = (TreeTy*) A.Allocate<TreeTy>();
471 new (T) TreeTy(L,R,V,IncrementHeight(L,R));
473 // We do not insert 'T' into the FoldingSet here. This is because
474 // this tree is still mutable and things may get rebalanced.
475 // Because our digest is associative and based on the contents of
476 // the set, this should hopefully not cause any strange bugs.
477 // 'T' is inserted by 'MarkImmutable'.
482 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
483 assert (!isEmpty(OldTree));
485 if (OldTree->isMutable()) {
487 OldTree->setRight(R);
488 OldTree->setHeight(IncrementHeight(L,R));
491 else return CreateNode(L, Value(OldTree), R);
494 /// Balance - Used by Add_internal and Remove_internal to
495 /// balance a newly created tree.
496 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
498 unsigned hl = Height(L);
499 unsigned hr = Height(R);
502 assert (!isEmpty(L) &&
503 "Left tree cannot be empty to have a height >= 2.");
505 TreeTy* LL = Left(L);
506 TreeTy* LR = Right(L);
508 if (Height(LL) >= Height(LR))
509 return CreateNode(LL, L, CreateNode(LR,V,R));
511 assert (!isEmpty(LR) &&
512 "LR cannot be empty because it has a height >= 1.");
514 TreeTy* LRL = Left(LR);
515 TreeTy* LRR = Right(LR);
517 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
519 else if (hr > hl + 2) {
520 assert (!isEmpty(R) &&
521 "Right tree cannot be empty to have a height >= 2.");
523 TreeTy* RL = Left(R);
524 TreeTy* RR = Right(R);
526 if (Height(RR) >= Height(RL))
527 return CreateNode(CreateNode(L,V,RL), R, RR);
529 assert (!isEmpty(RL) &&
530 "RL cannot be empty because it has a height >= 1.");
532 TreeTy* RLL = Left(RL);
533 TreeTy* RLR = Right(RL);
535 return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
538 return CreateNode(L,V,R);
541 /// Add_internal - Creates a new tree that includes the specified
542 /// data and the data from the original tree. If the original tree
543 /// already contained the data item, the original tree is returned.
544 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
546 return CreateNode(T, V, T);
548 assert (!T->isMutable());
550 key_type_ref K = ImutInfo::KeyOfValue(V);
551 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
553 if (ImutInfo::isEqual(K,KCurrent))
554 return CreateNode(Left(T), V, Right(T));
555 else if (ImutInfo::isLess(K,KCurrent))
556 return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
558 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
561 /// Remove_internal - Creates a new tree that includes all the data
562 /// from the original tree except the specified data. If the
563 /// specified data did not exist in the original tree, the original
564 /// tree is returned.
565 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
569 assert (!T->isMutable());
571 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
573 if (ImutInfo::isEqual(K,KCurrent))
574 return CombineLeftRightTrees(Left(T),Right(T));
575 else if (ImutInfo::isLess(K,KCurrent))
576 return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
578 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
581 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
582 if (isEmpty(L)) return R;
583 if (isEmpty(R)) return L;
586 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
587 return Balance(L,Value(OldNode),NewRight);
590 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
591 assert (!isEmpty(T));
593 if (isEmpty(Left(T))) {
598 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
601 /// MarkImmutable - Clears the mutable bits of a root and all of its
603 void MarkImmutable(TreeTy* T) {
604 if (!T || !T->isMutable())
608 MarkImmutable(Left(T));
609 MarkImmutable(Right(T));
611 // Now that the node is immutable it can safely be inserted
612 // into the node cache.
613 llvm::FoldingSetNodeID ID;
614 ID.AddInteger(T->ComputeDigest());
615 Cache.InsertNode(T, (void*) &*Cache.bucket_end(ID.ComputeHash()));
620 //===----------------------------------------------------------------------===//
621 // Immutable AVL-Tree Iterators.
622 //===----------------------------------------------------------------------===//
624 template <typename ImutInfo>
625 class ImutAVLTreeGenericIterator {
626 SmallVector<uintptr_t,20> stack;
628 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
631 typedef ImutAVLTree<ImutInfo> TreeTy;
632 typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
634 inline ImutAVLTreeGenericIterator() {}
635 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
636 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
639 TreeTy* operator*() const {
640 assert (!stack.empty());
641 return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
644 uintptr_t getVisitState() {
645 assert (!stack.empty());
646 return stack.back() & Flags;
650 bool AtEnd() const { return stack.empty(); }
652 bool AtBeginning() const {
653 return stack.size() == 1 && getVisitState() == VisitedNone;
656 void SkipToParent() {
657 assert (!stack.empty());
663 switch (getVisitState()) {
665 stack.back() |= VisitedLeft;
668 stack.back() |= VisitedRight;
671 assert (false && "Unreachable.");
675 inline bool operator==(const _Self& x) const {
676 if (stack.size() != x.stack.size())
679 for (unsigned i = 0 ; i < stack.size(); i++)
680 if (stack[i] != x.stack[i])
686 inline bool operator!=(const _Self& x) const { return !operator==(x); }
688 _Self& operator++() {
689 assert (!stack.empty());
691 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
694 switch (getVisitState()) {
696 if (TreeTy* L = Current->getSafeLeft())
697 stack.push_back(reinterpret_cast<uintptr_t>(L));
699 stack.back() |= VisitedLeft;
704 if (TreeTy* R = Current->getRight())
705 stack.push_back(reinterpret_cast<uintptr_t>(R));
707 stack.back() |= VisitedRight;
716 assert (false && "Unreachable.");
722 _Self& operator--() {
723 assert (!stack.empty());
725 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
728 switch (getVisitState()) {
734 stack.back() &= ~Flags; // Set state to "VisitedNone."
736 if (TreeTy* L = Current->getLeft())
737 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
742 stack.back() &= ~Flags;
743 stack.back() |= VisitedLeft;
745 if (TreeTy* R = Current->getRight())
746 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
751 assert (false && "Unreachable.");
758 template <typename ImutInfo>
759 class ImutAVLTreeInOrderIterator {
760 typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
761 InternalIteratorTy InternalItr;
764 typedef ImutAVLTree<ImutInfo> TreeTy;
765 typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
767 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
768 if (Root) operator++(); // Advance to first element.
771 ImutAVLTreeInOrderIterator() : InternalItr() {}
773 inline bool operator==(const _Self& x) const {
774 return InternalItr == x.InternalItr;
777 inline bool operator!=(const _Self& x) const { return !operator==(x); }
779 inline TreeTy* operator*() const { return *InternalItr; }
780 inline TreeTy* operator->() const { return *InternalItr; }
782 inline _Self& operator++() {
784 while (!InternalItr.AtEnd() &&
785 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
790 inline _Self& operator--() {
792 while (!InternalItr.AtBeginning() &&
793 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
798 inline void SkipSubTree() {
799 InternalItr.SkipToParent();
801 while (!InternalItr.AtEnd() &&
802 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
807 //===----------------------------------------------------------------------===//
808 // Trait classes for Profile information.
809 //===----------------------------------------------------------------------===//
811 /// Generic profile template. The default behavior is to invoke the
812 /// profile method of an object. Specializations for primitive integers
813 /// and generic handling of pointers is done below.
814 template <typename T>
815 struct ImutProfileInfo {
816 typedef const T value_type;
817 typedef const T& value_type_ref;
819 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
820 FoldingSetTrait<T>::Profile(X,ID);
824 /// Profile traits for integers.
825 template <typename T>
826 struct ImutProfileInteger {
827 typedef const T value_type;
828 typedef const T& value_type_ref;
830 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
835 #define PROFILE_INTEGER_INFO(X)\
836 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
838 PROFILE_INTEGER_INFO(char)
839 PROFILE_INTEGER_INFO(unsigned char)
840 PROFILE_INTEGER_INFO(short)
841 PROFILE_INTEGER_INFO(unsigned short)
842 PROFILE_INTEGER_INFO(unsigned)
843 PROFILE_INTEGER_INFO(signed)
844 PROFILE_INTEGER_INFO(long)
845 PROFILE_INTEGER_INFO(unsigned long)
846 PROFILE_INTEGER_INFO(long long)
847 PROFILE_INTEGER_INFO(unsigned long long)
849 #undef PROFILE_INTEGER_INFO
851 /// Generic profile trait for pointer types. We treat pointers as
852 /// references to unique objects.
853 template <typename T>
854 struct ImutProfileInfo<T*> {
855 typedef const T* value_type;
856 typedef value_type value_type_ref;
858 static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
863 //===----------------------------------------------------------------------===//
864 // Trait classes that contain element comparison operators and type
865 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
866 // inherit from the profile traits (ImutProfileInfo) to include operations
867 // for element profiling.
868 //===----------------------------------------------------------------------===//
871 /// ImutContainerInfo - Generic definition of comparison operations for
872 /// elements of immutable containers that defaults to using
873 /// std::equal_to<> and std::less<> to perform comparison of elements.
874 template <typename T>
875 struct ImutContainerInfo : public ImutProfileInfo<T> {
876 typedef typename ImutProfileInfo<T>::value_type value_type;
877 typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
878 typedef value_type key_type;
879 typedef value_type_ref key_type_ref;
880 typedef bool data_type;
881 typedef bool data_type_ref;
883 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
884 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
886 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
887 return std::equal_to<key_type>()(LHS,RHS);
890 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
891 return std::less<key_type>()(LHS,RHS);
894 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
897 /// ImutContainerInfo - Specialization for pointer values to treat pointers
898 /// as references to unique objects. Pointers are thus compared by
900 template <typename T>
901 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
902 typedef typename ImutProfileInfo<T*>::value_type value_type;
903 typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
904 typedef value_type key_type;
905 typedef value_type_ref key_type_ref;
906 typedef bool data_type;
907 typedef bool data_type_ref;
909 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
910 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
912 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
916 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
920 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
923 //===----------------------------------------------------------------------===//
925 //===----------------------------------------------------------------------===//
927 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
930 typedef typename ValInfo::value_type value_type;
931 typedef typename ValInfo::value_type_ref value_type_ref;
932 typedef ImutAVLTree<ValInfo> TreeTy;
938 /// Constructs a set from a pointer to a tree root. In general one
939 /// should use a Factory object to create sets instead of directly
940 /// invoking the constructor, but there are cases where make this
941 /// constructor public is useful.
942 explicit ImmutableSet(TreeTy* R) : Root(R) {}
945 typename TreeTy::Factory F;
950 Factory(BumpPtrAllocator& Alloc)
953 /// GetEmptySet - Returns an immutable set that contains no elements.
954 ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
956 /// Add - Creates a new immutable set that contains all of the values
957 /// of the original set with the addition of the specified value. If
958 /// the original set already included the value, then the original set is
959 /// returned and no memory is allocated. The time and space complexity
960 /// of this operation is logarithmic in the size of the original set.
961 /// The memory allocated to represent the set is released when the
962 /// factory object that created the set is destroyed.
963 ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
964 return ImmutableSet(F.Add(Old.Root,V));
967 /// Remove - Creates a new immutable set that contains all of the values
968 /// of the original set with the exception of the specified value. If
969 /// the original set did not contain the value, the original set is
970 /// returned and no memory is allocated. The time and space complexity
971 /// of this operation is logarithmic in the size of the original set.
972 /// The memory allocated to represent the set is released when the
973 /// factory object that created the set is destroyed.
974 ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
975 return ImmutableSet(F.Remove(Old.Root,V));
978 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
981 Factory(const Factory& RHS) {};
982 void operator=(const Factory& RHS) {};
985 friend class Factory;
987 /// contains - Returns true if the set contains the specified value.
988 bool contains(const value_type_ref V) const {
989 return Root ? Root->contains(V) : false;
992 bool operator==(ImmutableSet RHS) const {
993 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
996 bool operator!=(ImmutableSet RHS) const {
997 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1000 TreeTy* getRoot() const { return Root; }
1002 /// isEmpty - Return true if the set contains no elements.
1003 bool isEmpty() const { return !Root; }
1005 template <typename Callback>
1006 void foreach(Callback& C) { if (Root) Root->foreach(C); }
1008 template <typename Callback>
1009 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
1011 //===--------------------------------------------------===//
1013 //===--------------------------------------------------===//
1016 typename TreeTy::iterator itr;
1019 iterator(TreeTy* t) : itr(t) {}
1020 friend class ImmutableSet<ValT,ValInfo>;
1022 inline value_type_ref operator*() const { return itr->getValue(); }
1023 inline iterator& operator++() { ++itr; return *this; }
1024 inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1025 inline iterator& operator--() { --itr; return *this; }
1026 inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
1027 inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1028 inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1031 iterator begin() const { return iterator(Root); }
1032 iterator end() const { return iterator(); }
1034 //===--------------------------------------------------===//
1036 //===--------------------------------------------------===//
1038 inline unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1040 static inline void Profile(FoldingSetNodeID& ID, const ImmutableSet& S) {
1041 ID.AddPointer(S.Root);
1044 inline void Profile(FoldingSetNodeID& ID) const {
1045 return Profile(ID,*this);
1048 //===--------------------------------------------------===//
1050 //===--------------------------------------------------===//
1052 void verify() const { if (Root) Root->verify(); }
1055 } // end namespace llvm