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_IMMUTABLESET_H
15 #define LLVM_ADT_IMMUTABLESET_H
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/iterator.h"
21 #include "llvm/Support/Allocator.h"
22 #include "llvm/Support/ErrorHandling.h"
32 //===----------------------------------------------------------------------===//
33 // Immutable AVL-Tree Definition.
34 //===----------------------------------------------------------------------===//
36 template <typename ImutInfo> class ImutAVLFactory;
37 template <typename ImutInfo> class ImutIntervalAVLFactory;
38 template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
39 template <typename ImutInfo> class ImutAVLTreeGenericIterator;
41 template <typename ImutInfo >
44 using key_type_ref = typename ImutInfo::key_type_ref;
45 using value_type = typename ImutInfo::value_type;
46 using value_type_ref = typename ImutInfo::value_type_ref;
47 using Factory = ImutAVLFactory<ImutInfo>;
48 using iterator = ImutAVLTreeInOrderIterator<ImutInfo>;
50 friend class ImutAVLFactory<ImutInfo>;
51 friend class ImutIntervalAVLFactory<ImutInfo>;
52 friend class ImutAVLTreeGenericIterator<ImutInfo>;
54 //===----------------------------------------------------===//
56 //===----------------------------------------------------===//
58 /// Return a pointer to the left subtree. This value
59 /// is NULL if there is no left subtree.
60 ImutAVLTree *getLeft() const { return left; }
62 /// Return a pointer to the right subtree. This value is
63 /// NULL if there is no right subtree.
64 ImutAVLTree *getRight() const { return right; }
66 /// getHeight - Returns the height of the tree. A tree with no subtrees
67 /// has a height of 1.
68 unsigned getHeight() const { return height; }
70 /// getValue - Returns the data value associated with the tree node.
71 const value_type& getValue() const { return value; }
73 /// find - Finds the subtree associated with the specified key value.
74 /// This method returns NULL if no matching subtree is found.
75 ImutAVLTree* find(key_type_ref K) {
76 ImutAVLTree *T = this;
78 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
79 if (ImutInfo::isEqual(K,CurrentKey))
81 else if (ImutInfo::isLess(K,CurrentKey))
89 /// getMaxElement - Find the subtree associated with the highest ranged
91 ImutAVLTree* getMaxElement() {
92 ImutAVLTree *T = this;
93 ImutAVLTree *Right = T->getRight();
94 while (Right) { T = Right; Right = T->getRight(); }
98 /// size - Returns the number of nodes in the tree, which includes
99 /// both leaves and non-leaf nodes.
100 unsigned size() const {
102 if (const ImutAVLTree* L = getLeft())
104 if (const ImutAVLTree* R = getRight())
109 /// begin - Returns an iterator that iterates over the nodes of the tree
110 /// in an inorder traversal. The returned iterator thus refers to the
111 /// the tree node with the minimum data element.
112 iterator begin() const { return iterator(this); }
114 /// end - Returns an iterator for the tree that denotes the end of an
115 /// inorder traversal.
116 iterator end() const { return iterator(); }
118 bool isElementEqual(value_type_ref V) const {
120 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
121 ImutInfo::KeyOfValue(V)))
124 // Also compare the data values.
125 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
126 ImutInfo::DataOfValue(V)))
132 bool isElementEqual(const ImutAVLTree* RHS) const {
133 return isElementEqual(RHS->getValue());
136 /// isEqual - Compares two trees for structural equality and returns true
137 /// if they are equal. This worst case performance of this operation is
138 // linear in the sizes of the trees.
139 bool isEqual(const ImutAVLTree& RHS) const {
143 iterator LItr = begin(), LEnd = end();
144 iterator RItr = RHS.begin(), REnd = RHS.end();
146 while (LItr != LEnd && RItr != REnd) {
147 if (&*LItr == &*RItr) {
153 if (!LItr->isElementEqual(&*RItr))
160 return LItr == LEnd && RItr == REnd;
163 /// isNotEqual - Compares two trees for structural inequality. Performance
164 /// is the same is isEqual.
165 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
167 /// contains - Returns true if this tree contains a subtree (node) that
168 /// has an data element that matches the specified key. Complexity
169 /// is logarithmic in the size of the tree.
170 bool contains(key_type_ref K) { return (bool) find(K); }
172 /// foreach - A member template the accepts invokes operator() on a functor
173 /// object (specifed by Callback) for every node/subtree in the tree.
174 /// Nodes are visited using an inorder traversal.
175 template <typename Callback>
176 void foreach(Callback& C) {
177 if (ImutAVLTree* L = getLeft())
182 if (ImutAVLTree* R = getRight())
186 /// validateTree - A utility method that checks that the balancing and
187 /// ordering invariants of the tree are satisifed. It is a recursive
188 /// method that returns the height of the tree, which is then consumed
189 /// by the enclosing validateTree call. External callers should ignore the
190 /// return value. An invalid tree will cause an assertion to fire in
192 unsigned validateTree() const {
193 unsigned HL = getLeft() ? getLeft()->validateTree() : 0;
194 unsigned HR = getRight() ? getRight()->validateTree() : 0;
198 assert(getHeight() == ( HL > HR ? HL : HR ) + 1
199 && "Height calculation wrong");
201 assert((HL > HR ? HL-HR : HR-HL) <= 2
202 && "Balancing invariant violated");
204 assert((!getLeft() ||
205 ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
206 ImutInfo::KeyOfValue(getValue()))) &&
207 "Value in left child is not less that current value");
210 assert(!(getRight() ||
211 ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
212 ImutInfo::KeyOfValue(getRight()->getValue()))) &&
213 "Current value is not less that value of right child");
218 //===----------------------------------------------------===//
220 //===----------------------------------------------------===//
226 ImutAVLTree *prev = nullptr;
227 ImutAVLTree *next = nullptr;
229 unsigned height : 28;
231 bool IsDigestCached : 1;
232 bool IsCanonicalized : 1;
236 uint32_t refCount = 0;
238 //===----------------------------------------------------===//
239 // Internal methods (node manipulation; used by Factory).
240 //===----------------------------------------------------===//
243 /// ImutAVLTree - Internal constructor that is only called by
245 ImutAVLTree(Factory *f, ImutAVLTree* l, ImutAVLTree* r, value_type_ref v,
247 : factory(f), left(l), right(r), height(height), IsMutable(true),
248 IsDigestCached(false), IsCanonicalized(false), value(v)
250 if (left) left->retain();
251 if (right) right->retain();
254 /// isMutable - Returns true if the left and right subtree references
255 /// (as well as height) can be changed. If this method returns false,
256 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
257 /// object should always have this method return true. Further, if this
258 /// method returns false for an instance of ImutAVLTree, all subtrees
259 /// will also have this method return false. The converse is not true.
260 bool isMutable() const { return IsMutable; }
262 /// hasCachedDigest - Returns true if the digest for this tree is cached.
263 /// This can only be true if the tree is immutable.
264 bool hasCachedDigest() const { return IsDigestCached; }
266 //===----------------------------------------------------===//
267 // Mutating operations. A tree root can be manipulated as
268 // long as its reference has not "escaped" from internal
269 // methods of a factory object (see below). When a tree
270 // pointer is externally viewable by client code, the
271 // internal "mutable bit" is cleared to mark the tree
272 // immutable. Note that a tree that still has its mutable
273 // bit set may have children (subtrees) that are themselves
275 //===----------------------------------------------------===//
277 /// markImmutable - Clears the mutable flag for a tree. After this happens,
278 /// it is an error to call setLeft(), setRight(), and setHeight().
279 void markImmutable() {
280 assert(isMutable() && "Mutable flag already removed.");
284 /// markedCachedDigest - Clears the NoCachedDigest flag for a tree.
285 void markedCachedDigest() {
286 assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
287 IsDigestCached = true;
290 /// setHeight - Changes the height of the tree. Used internally by
292 void setHeight(unsigned h) {
293 assert(isMutable() && "Only a mutable tree can have its height changed.");
297 static uint32_t computeDigest(ImutAVLTree *L, ImutAVLTree *R,
302 digest += L->computeDigest();
304 // Compute digest of stored data.
306 ImutInfo::Profile(ID,V);
307 digest += ID.ComputeHash();
310 digest += R->computeDigest();
315 uint32_t computeDigest() {
316 // Check the lowest bit to determine if digest has actually been
318 if (hasCachedDigest())
321 uint32_t X = computeDigest(getLeft(), getRight(), getValue());
323 markedCachedDigest();
327 //===----------------------------------------------------===//
328 // Reference count operations.
329 //===----------------------------------------------------===//
332 void retain() { ++refCount; }
335 assert(refCount > 0);
345 if (IsCanonicalized) {
352 factory->Cache[factory->maskCacheIndex(computeDigest())] = next;
355 // We need to clear the mutability bit in case we are
356 // destroying the node as part of a sweep in ImutAVLFactory::recoverNodes().
358 factory->freeNodes.push_back(this);
362 //===----------------------------------------------------------------------===//
363 // Immutable AVL-Tree Factory class.
364 //===----------------------------------------------------------------------===//
366 template <typename ImutInfo >
367 class ImutAVLFactory {
368 friend class ImutAVLTree<ImutInfo>;
370 using TreeTy = ImutAVLTree<ImutInfo>;
371 using value_type_ref = typename TreeTy::value_type_ref;
372 using key_type_ref = typename TreeTy::key_type_ref;
373 using CacheTy = DenseMap<unsigned, TreeTy*>;
377 std::vector<TreeTy*> createdNodes;
378 std::vector<TreeTy*> freeNodes;
380 bool ownsAllocator() const {
381 return (Allocator & 0x1) == 0;
384 BumpPtrAllocator& getAllocator() const {
385 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
388 //===--------------------------------------------------===//
390 //===--------------------------------------------------===//
394 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
396 ImutAVLFactory(BumpPtrAllocator& Alloc)
397 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
400 if (ownsAllocator()) delete &getAllocator();
403 TreeTy* add(TreeTy* T, value_type_ref V) {
404 T = add_internal(V,T);
410 TreeTy* remove(TreeTy* T, key_type_ref V) {
411 T = remove_internal(V,T);
417 TreeTy* getEmptyTree() const { return nullptr; }
420 //===--------------------------------------------------===//
421 // A bunch of quick helper functions used for reasoning
422 // about the properties of trees and their children.
423 // These have succinct names so that the balancing code
424 // is as terse (and readable) as possible.
425 //===--------------------------------------------------===//
427 bool isEmpty(TreeTy* T) const { return !T; }
428 unsigned getHeight(TreeTy* T) const { return T ? T->getHeight() : 0; }
429 TreeTy* getLeft(TreeTy* T) const { return T->getLeft(); }
430 TreeTy* getRight(TreeTy* T) const { return T->getRight(); }
431 value_type_ref getValue(TreeTy* T) const { return T->value; }
433 // Make sure the index is not the Tombstone or Entry key of the DenseMap.
434 static unsigned maskCacheIndex(unsigned I) { return (I & ~0x02); }
436 unsigned incrementHeight(TreeTy* L, TreeTy* R) const {
437 unsigned hl = getHeight(L);
438 unsigned hr = getHeight(R);
439 return (hl > hr ? hl : hr) + 1;
442 static bool compareTreeWithSection(TreeTy* T,
443 typename TreeTy::iterator& TI,
444 typename TreeTy::iterator& TE) {
445 typename TreeTy::iterator I = T->begin(), E = T->end();
446 for ( ; I!=E ; ++I, ++TI) {
447 if (TI == TE || !I->isElementEqual(&*TI))
453 //===--------------------------------------------------===//
454 // "createNode" is used to generate new tree roots that link
455 // to other trees. The functon may also simply move links
456 // in an existing root if that root is still marked mutable.
457 // This is necessary because otherwise our balancing code
458 // would leak memory as it would create nodes that are
459 // then discarded later before the finished tree is
460 // returned to the caller.
461 //===--------------------------------------------------===//
463 TreeTy* createNode(TreeTy* L, value_type_ref V, TreeTy* R) {
464 BumpPtrAllocator& A = getAllocator();
466 if (!freeNodes.empty()) {
467 T = freeNodes.back();
468 freeNodes.pop_back();
472 T = (TreeTy*) A.Allocate<TreeTy>();
474 new (T) TreeTy(this, L, R, V, incrementHeight(L,R));
475 createdNodes.push_back(T);
479 TreeTy* createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
480 return createNode(newLeft, getValue(oldTree), newRight);
483 void recoverNodes() {
484 for (unsigned i = 0, n = createdNodes.size(); i < n; ++i) {
485 TreeTy *N = createdNodes[i];
486 if (N->isMutable() && N->refCount == 0)
489 createdNodes.clear();
492 /// balanceTree - Used by add_internal and remove_internal to
493 /// balance a newly created tree.
494 TreeTy* balanceTree(TreeTy* L, value_type_ref V, TreeTy* R) {
495 unsigned hl = getHeight(L);
496 unsigned hr = getHeight(R);
499 assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
501 TreeTy *LL = getLeft(L);
502 TreeTy *LR = getRight(L);
504 if (getHeight(LL) >= getHeight(LR))
505 return createNode(LL, L, createNode(LR,V,R));
507 assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
509 TreeTy *LRL = getLeft(LR);
510 TreeTy *LRR = getRight(LR);
512 return createNode(createNode(LL,L,LRL), LR, createNode(LRR,V,R));
516 assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
518 TreeTy *RL = getLeft(R);
519 TreeTy *RR = getRight(R);
521 if (getHeight(RR) >= getHeight(RL))
522 return createNode(createNode(L,V,RL), R, RR);
524 assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
526 TreeTy *RLL = getLeft(RL);
527 TreeTy *RLR = getRight(RL);
529 return createNode(createNode(L,V,RLL), RL, createNode(RLR,R,RR));
532 return createNode(L,V,R);
535 /// add_internal - Creates a new tree that includes the specified
536 /// data and the data from the original tree. If the original tree
537 /// already contained the data item, the original tree is returned.
538 TreeTy* add_internal(value_type_ref V, TreeTy* T) {
540 return createNode(T, V, T);
541 assert(!T->isMutable());
543 key_type_ref K = ImutInfo::KeyOfValue(V);
544 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
546 if (ImutInfo::isEqual(K,KCurrent))
547 return createNode(getLeft(T), V, getRight(T));
548 else if (ImutInfo::isLess(K,KCurrent))
549 return balanceTree(add_internal(V, getLeft(T)), getValue(T), getRight(T));
551 return balanceTree(getLeft(T), getValue(T), add_internal(V, getRight(T)));
554 /// remove_internal - Creates a new tree that includes all the data
555 /// from the original tree except the specified data. If the
556 /// specified data did not exist in the original tree, the original
557 /// tree is returned.
558 TreeTy* remove_internal(key_type_ref K, TreeTy* T) {
562 assert(!T->isMutable());
564 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
566 if (ImutInfo::isEqual(K,KCurrent)) {
567 return combineTrees(getLeft(T), getRight(T));
568 } else if (ImutInfo::isLess(K,KCurrent)) {
569 return balanceTree(remove_internal(K, getLeft(T)),
570 getValue(T), getRight(T));
572 return balanceTree(getLeft(T), getValue(T),
573 remove_internal(K, getRight(T)));
577 TreeTy* combineTrees(TreeTy* L, TreeTy* R) {
583 TreeTy* newRight = removeMinBinding(R,OldNode);
584 return balanceTree(L, getValue(OldNode), newRight);
587 TreeTy* removeMinBinding(TreeTy* T, TreeTy*& Noderemoved) {
589 if (isEmpty(getLeft(T))) {
593 return balanceTree(removeMinBinding(getLeft(T), Noderemoved),
594 getValue(T), getRight(T));
597 /// markImmutable - Clears the mutable bits of a root and all of its
599 void markImmutable(TreeTy* T) {
600 if (!T || !T->isMutable())
603 markImmutable(getLeft(T));
604 markImmutable(getRight(T));
608 TreeTy *getCanonicalTree(TreeTy *TNew) {
612 if (TNew->IsCanonicalized)
615 // Search the hashtable for another tree with the same digest, and
616 // if find a collision compare those trees by their contents.
617 unsigned digest = TNew->computeDigest();
618 TreeTy *&entry = Cache[maskCacheIndex(digest)];
622 for (TreeTy *T = entry ; T != nullptr; T = T->next) {
623 // Compare the Contents('T') with Contents('TNew')
624 typename TreeTy::iterator TI = T->begin(), TE = T->end();
625 if (!compareTreeWithSection(TNew, TI, TE))
628 continue; // T has more contents than TNew.
629 // Trees did match! Return 'T'.
630 if (TNew->refCount == 0)
640 TNew->IsCanonicalized = true;
645 //===----------------------------------------------------------------------===//
646 // Immutable AVL-Tree Iterators.
647 //===----------------------------------------------------------------------===//
649 template <typename ImutInfo>
650 class ImutAVLTreeGenericIterator
651 : public std::iterator<std::bidirectional_iterator_tag,
652 ImutAVLTree<ImutInfo>> {
653 SmallVector<uintptr_t,20> stack;
656 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
659 using TreeTy = ImutAVLTree<ImutInfo>;
661 ImutAVLTreeGenericIterator() = default;
662 ImutAVLTreeGenericIterator(const TreeTy *Root) {
663 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
666 TreeTy &operator*() const {
667 assert(!stack.empty());
668 return *reinterpret_cast<TreeTy *>(stack.back() & ~Flags);
670 TreeTy *operator->() const { return &*this; }
672 uintptr_t getVisitState() const {
673 assert(!stack.empty());
674 return stack.back() & Flags;
677 bool atEnd() const { return stack.empty(); }
679 bool atBeginning() const {
680 return stack.size() == 1 && getVisitState() == VisitedNone;
683 void skipToParent() {
684 assert(!stack.empty());
688 switch (getVisitState()) {
690 stack.back() |= VisitedLeft;
693 stack.back() |= VisitedRight;
696 llvm_unreachable("Unreachable.");
700 bool operator==(const ImutAVLTreeGenericIterator &x) const {
701 return stack == x.stack;
704 bool operator!=(const ImutAVLTreeGenericIterator &x) const {
705 return !(*this == x);
708 ImutAVLTreeGenericIterator &operator++() {
709 assert(!stack.empty());
710 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
712 switch (getVisitState()) {
714 if (TreeTy* L = Current->getLeft())
715 stack.push_back(reinterpret_cast<uintptr_t>(L));
717 stack.back() |= VisitedLeft;
720 if (TreeTy* R = Current->getRight())
721 stack.push_back(reinterpret_cast<uintptr_t>(R));
723 stack.back() |= VisitedRight;
729 llvm_unreachable("Unreachable.");
734 ImutAVLTreeGenericIterator &operator--() {
735 assert(!stack.empty());
736 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
738 switch (getVisitState()) {
743 stack.back() &= ~Flags; // Set state to "VisitedNone."
744 if (TreeTy* L = Current->getLeft())
745 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
748 stack.back() &= ~Flags;
749 stack.back() |= VisitedLeft;
750 if (TreeTy* R = Current->getRight())
751 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
754 llvm_unreachable("Unreachable.");
760 template <typename ImutInfo>
761 class ImutAVLTreeInOrderIterator
762 : public std::iterator<std::bidirectional_iterator_tag,
763 ImutAVLTree<ImutInfo>> {
764 using InternalIteratorTy = ImutAVLTreeGenericIterator<ImutInfo>;
766 InternalIteratorTy InternalItr;
769 using TreeTy = ImutAVLTree<ImutInfo>;
771 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
773 ++*this; // Advance to first element.
776 ImutAVLTreeInOrderIterator() : InternalItr() {}
778 bool operator==(const ImutAVLTreeInOrderIterator &x) const {
779 return InternalItr == x.InternalItr;
782 bool operator!=(const ImutAVLTreeInOrderIterator &x) const {
783 return !(*this == x);
786 TreeTy &operator*() const { return *InternalItr; }
787 TreeTy *operator->() const { return &*InternalItr; }
789 ImutAVLTreeInOrderIterator &operator++() {
791 while (!InternalItr.atEnd() &&
792 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
797 ImutAVLTreeInOrderIterator &operator--() {
799 while (!InternalItr.atBeginning() &&
800 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
806 InternalItr.skipToParent();
808 while (!InternalItr.atEnd() &&
809 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
814 /// Generic iterator that wraps a T::TreeTy::iterator and exposes
815 /// iterator::getValue() on dereference.
816 template <typename T>
817 struct ImutAVLValueIterator
818 : iterator_adaptor_base<
819 ImutAVLValueIterator<T>, typename T::TreeTy::iterator,
820 typename std::iterator_traits<
821 typename T::TreeTy::iterator>::iterator_category,
822 const typename T::value_type> {
823 ImutAVLValueIterator() = default;
824 explicit ImutAVLValueIterator(typename T::TreeTy *Tree)
825 : ImutAVLValueIterator::iterator_adaptor_base(Tree) {}
827 typename ImutAVLValueIterator::reference operator*() const {
828 return this->I->getValue();
832 //===----------------------------------------------------------------------===//
833 // Trait classes for Profile information.
834 //===----------------------------------------------------------------------===//
836 /// Generic profile template. The default behavior is to invoke the
837 /// profile method of an object. Specializations for primitive integers
838 /// and generic handling of pointers is done below.
839 template <typename T>
840 struct ImutProfileInfo {
841 using value_type = const T;
842 using value_type_ref = const T&;
844 static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
845 FoldingSetTrait<T>::Profile(X,ID);
849 /// Profile traits for integers.
850 template <typename T>
851 struct ImutProfileInteger {
852 using value_type = const T;
853 using value_type_ref = const T&;
855 static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
860 #define PROFILE_INTEGER_INFO(X)\
861 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
863 PROFILE_INTEGER_INFO(char)
864 PROFILE_INTEGER_INFO(unsigned char)
865 PROFILE_INTEGER_INFO(short)
866 PROFILE_INTEGER_INFO(unsigned short)
867 PROFILE_INTEGER_INFO(unsigned)
868 PROFILE_INTEGER_INFO(signed)
869 PROFILE_INTEGER_INFO(long)
870 PROFILE_INTEGER_INFO(unsigned long)
871 PROFILE_INTEGER_INFO(long long)
872 PROFILE_INTEGER_INFO(unsigned long long)
874 #undef PROFILE_INTEGER_INFO
876 /// Profile traits for booleans.
878 struct ImutProfileInfo<bool> {
879 using value_type = const bool;
880 using value_type_ref = const bool&;
882 static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
887 /// Generic profile trait for pointer types. We treat pointers as
888 /// references to unique objects.
889 template <typename T>
890 struct ImutProfileInfo<T*> {
891 using value_type = const T*;
892 using value_type_ref = value_type;
894 static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
899 //===----------------------------------------------------------------------===//
900 // Trait classes that contain element comparison operators and type
901 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
902 // inherit from the profile traits (ImutProfileInfo) to include operations
903 // for element profiling.
904 //===----------------------------------------------------------------------===//
906 /// ImutContainerInfo - Generic definition of comparison operations for
907 /// elements of immutable containers that defaults to using
908 /// std::equal_to<> and std::less<> to perform comparison of elements.
909 template <typename T>
910 struct ImutContainerInfo : public ImutProfileInfo<T> {
911 using value_type = typename ImutProfileInfo<T>::value_type;
912 using value_type_ref = typename ImutProfileInfo<T>::value_type_ref;
913 using key_type = value_type;
914 using key_type_ref = value_type_ref;
915 using data_type = bool;
916 using data_type_ref = bool;
918 static key_type_ref KeyOfValue(value_type_ref D) { return D; }
919 static data_type_ref DataOfValue(value_type_ref) { return true; }
921 static bool isEqual(key_type_ref LHS, key_type_ref RHS) {
922 return std::equal_to<key_type>()(LHS,RHS);
925 static bool isLess(key_type_ref LHS, key_type_ref RHS) {
926 return std::less<key_type>()(LHS,RHS);
929 static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
932 /// ImutContainerInfo - Specialization for pointer values to treat pointers
933 /// as references to unique objects. Pointers are thus compared by
935 template <typename T>
936 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
937 using value_type = typename ImutProfileInfo<T*>::value_type;
938 using value_type_ref = typename ImutProfileInfo<T*>::value_type_ref;
939 using key_type = value_type;
940 using key_type_ref = value_type_ref;
941 using data_type = bool;
942 using data_type_ref = bool;
944 static key_type_ref KeyOfValue(value_type_ref D) { return D; }
945 static data_type_ref DataOfValue(value_type_ref) { return true; }
947 static bool isEqual(key_type_ref LHS, key_type_ref RHS) { return LHS == RHS; }
949 static bool isLess(key_type_ref LHS, key_type_ref RHS) { return LHS < RHS; }
951 static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
954 //===----------------------------------------------------------------------===//
956 //===----------------------------------------------------------------------===//
958 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT>>
961 using value_type = typename ValInfo::value_type;
962 using value_type_ref = typename ValInfo::value_type_ref;
963 using TreeTy = ImutAVLTree<ValInfo>;
969 /// Constructs a set from a pointer to a tree root. In general one
970 /// should use a Factory object to create sets instead of directly
971 /// invoking the constructor, but there are cases where make this
972 /// constructor public is useful.
973 explicit ImmutableSet(TreeTy* R) : Root(R) {
974 if (Root) { Root->retain(); }
977 ImmutableSet(const ImmutableSet &X) : Root(X.Root) {
978 if (Root) { Root->retain(); }
982 if (Root) { Root->release(); }
985 ImmutableSet &operator=(const ImmutableSet &X) {
986 if (Root != X.Root) {
987 if (X.Root) { X.Root->retain(); }
988 if (Root) { Root->release(); }
995 typename TreeTy::Factory F;
996 const bool Canonicalize;
999 Factory(bool canonicalize = true)
1000 : Canonicalize(canonicalize) {}
1002 Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
1003 : F(Alloc), Canonicalize(canonicalize) {}
1005 Factory(const Factory& RHS) = delete;
1006 void operator=(const Factory& RHS) = delete;
1008 /// getEmptySet - Returns an immutable set that contains no elements.
1009 ImmutableSet getEmptySet() {
1010 return ImmutableSet(F.getEmptyTree());
1013 /// add - Creates a new immutable set that contains all of the values
1014 /// of the original set with the addition of the specified value. If
1015 /// the original set already included the value, then the original set is
1016 /// returned and no memory is allocated. The time and space complexity
1017 /// of this operation is logarithmic in the size of the original set.
1018 /// The memory allocated to represent the set is released when the
1019 /// factory object that created the set is destroyed.
1020 LLVM_NODISCARD ImmutableSet add(ImmutableSet Old, value_type_ref V) {
1021 TreeTy *NewT = F.add(Old.Root, V);
1022 return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
1025 /// remove - Creates a new immutable set that contains all of the values
1026 /// of the original set with the exception of the specified value. If
1027 /// the original set did not contain the value, the original set is
1028 /// returned and no memory is allocated. The time and space complexity
1029 /// of this operation is logarithmic in the size of the original set.
1030 /// The memory allocated to represent the set is released when the
1031 /// factory object that created the set is destroyed.
1032 LLVM_NODISCARD ImmutableSet remove(ImmutableSet Old, value_type_ref V) {
1033 TreeTy *NewT = F.remove(Old.Root, V);
1034 return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
1037 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
1039 typename TreeTy::Factory *getTreeFactory() const {
1040 return const_cast<typename TreeTy::Factory *>(&F);
1044 friend class Factory;
1046 /// Returns true if the set contains the specified value.
1047 bool contains(value_type_ref V) const {
1048 return Root ? Root->contains(V) : false;
1051 bool operator==(const ImmutableSet &RHS) const {
1052 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1055 bool operator!=(const ImmutableSet &RHS) const {
1056 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1060 if (Root) { Root->retain(); }
1064 TreeTy *getRootWithoutRetain() const {
1068 /// isEmpty - Return true if the set contains no elements.
1069 bool isEmpty() const { return !Root; }
1071 /// isSingleton - Return true if the set contains exactly one element.
1072 /// This method runs in constant time.
1073 bool isSingleton() const { return getHeight() == 1; }
1075 template <typename Callback>
1076 void foreach(Callback& C) { if (Root) Root->foreach(C); }
1078 template <typename Callback>
1079 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
1081 //===--------------------------------------------------===//
1083 //===--------------------------------------------------===//
1085 using iterator = ImutAVLValueIterator<ImmutableSet>;
1087 iterator begin() const { return iterator(Root); }
1088 iterator end() const { return iterator(); }
1090 //===--------------------------------------------------===//
1092 //===--------------------------------------------------===//
1094 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1096 static void Profile(FoldingSetNodeID &ID, const ImmutableSet &S) {
1097 ID.AddPointer(S.Root);
1100 void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
1102 //===--------------------------------------------------===//
1104 //===--------------------------------------------------===//
1106 void validateTree() const { if (Root) Root->validateTree(); }
1109 // NOTE: This may some day replace the current ImmutableSet.
1110 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT>>
1111 class ImmutableSetRef {
1113 using value_type = typename ValInfo::value_type;
1114 using value_type_ref = typename ValInfo::value_type_ref;
1115 using TreeTy = ImutAVLTree<ValInfo>;
1116 using FactoryTy = typename TreeTy::Factory;
1123 /// Constructs a set from a pointer to a tree root. In general one
1124 /// should use a Factory object to create sets instead of directly
1125 /// invoking the constructor, but there are cases where make this
1126 /// constructor public is useful.
1127 explicit ImmutableSetRef(TreeTy* R, FactoryTy *F)
1130 if (Root) { Root->retain(); }
1133 ImmutableSetRef(const ImmutableSetRef &X)
1135 Factory(X.Factory) {
1136 if (Root) { Root->retain(); }
1139 ~ImmutableSetRef() {
1140 if (Root) { Root->release(); }
1143 ImmutableSetRef &operator=(const ImmutableSetRef &X) {
1144 if (Root != X.Root) {
1145 if (X.Root) { X.Root->retain(); }
1146 if (Root) { Root->release(); }
1148 Factory = X.Factory;
1153 static ImmutableSetRef getEmptySet(FactoryTy *F) {
1154 return ImmutableSetRef(0, F);
1157 ImmutableSetRef add(value_type_ref V) {
1158 return ImmutableSetRef(Factory->add(Root, V), Factory);
1161 ImmutableSetRef remove(value_type_ref V) {
1162 return ImmutableSetRef(Factory->remove(Root, V), Factory);
1165 /// Returns true if the set contains the specified value.
1166 bool contains(value_type_ref V) const {
1167 return Root ? Root->contains(V) : false;
1170 ImmutableSet<ValT> asImmutableSet(bool canonicalize = true) const {
1171 return ImmutableSet<ValT>(canonicalize ?
1172 Factory->getCanonicalTree(Root) : Root);
1175 TreeTy *getRootWithoutRetain() const {
1179 bool operator==(const ImmutableSetRef &RHS) const {
1180 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1183 bool operator!=(const ImmutableSetRef &RHS) const {
1184 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1187 /// isEmpty - Return true if the set contains no elements.
1188 bool isEmpty() const { return !Root; }
1190 /// isSingleton - Return true if the set contains exactly one element.
1191 /// This method runs in constant time.
1192 bool isSingleton() const { return getHeight() == 1; }
1194 //===--------------------------------------------------===//
1196 //===--------------------------------------------------===//
1198 using iterator = ImutAVLValueIterator<ImmutableSetRef>;
1200 iterator begin() const { return iterator(Root); }
1201 iterator end() const { return iterator(); }
1203 //===--------------------------------------------------===//
1205 //===--------------------------------------------------===//
1207 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1209 static void Profile(FoldingSetNodeID &ID, const ImmutableSetRef &S) {
1210 ID.AddPointer(S.Root);
1213 void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
1215 //===--------------------------------------------------===//
1217 //===--------------------------------------------------===//
1219 void validateTree() const { if (Root) Root->validateTree(); }
1222 } // end namespace llvm
1224 #endif // LLVM_ADT_IMMUTABLESET_H