LLVM 22.0.0git
ImmutableSet.h
Go to the documentation of this file.
1//===--- ImmutableSet.h - Immutable (functional) set interface --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file defines the ImutAVLTree and ImmutableSet classes.
11///
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_IMMUTABLESET_H
15#define LLVM_ADT_IMMUTABLESET_H
16
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/FoldingSet.h"
21#include "llvm/ADT/iterator.h"
24#include "llvm/Support/Debug.h"
27#include <cassert>
28#include <cstdint>
29#include <functional>
30#include <iterator>
31#include <new>
32#include <vector>
33
34namespace llvm {
35
36//===----------------------------------------------------------------------===//
37// Immutable AVL-Tree Definition.
38//===----------------------------------------------------------------------===//
39
40template <typename ImutInfo> class ImutAVLFactory;
41template <typename ImutInfo> class ImutIntervalAVLFactory;
42template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
43template <typename ImutInfo> class ImutAVLTreeGenericIterator;
44
45template <typename ImutInfo >
46class ImutAVLTree {
47public:
48 using key_type_ref = typename ImutInfo::key_type_ref;
49 using value_type = typename ImutInfo::value_type;
50 using value_type_ref = typename ImutInfo::value_type_ref;
53
54 friend class ImutAVLFactory<ImutInfo>;
55 friend class ImutIntervalAVLFactory<ImutInfo>;
56 friend class ImutAVLTreeGenericIterator<ImutInfo>;
57
58 //===----------------------------------------------------===//
59 // Public Interface.
60 //===----------------------------------------------------===//
61
62 /// Return a pointer to the left subtree. This value
63 /// is NULL if there is no left subtree.
64 ImutAVLTree *getLeft() const { return left; }
65
66 /// Return a pointer to the right subtree. This value is
67 /// NULL if there is no right subtree.
68 ImutAVLTree *getRight() const { return right; }
69
70 /// getHeight - Returns the height of the tree. A tree with no subtrees
71 /// has a height of 1.
72 unsigned getHeight() const { return height; }
73
74 /// getValue - Returns the data value associated with the tree node.
75 const value_type& getValue() const { return value; }
76
77 /// find - Finds the subtree associated with the specified key value.
78 /// This method returns NULL if no matching subtree is found.
79 ImutAVLTree* find(key_type_ref K) {
80 ImutAVLTree *T = this;
81 while (T) {
82 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
83 if (ImutInfo::isEqual(K,CurrentKey))
84 return T;
85 else if (ImutInfo::isLess(K,CurrentKey))
86 T = T->getLeft();
87 else
88 T = T->getRight();
89 }
90 return nullptr;
91 }
92
93 /// getMaxElement - Find the subtree associated with the highest ranged
94 /// key value.
95 ImutAVLTree* getMaxElement() {
96 ImutAVLTree *T = this;
97 ImutAVLTree *Right = T->getRight();
98 while (Right) { T = Right; Right = T->getRight(); }
99 return T;
100 }
101
102 /// size - Returns the number of nodes in the tree, which includes
103 /// both leaves and non-leaf nodes.
104 unsigned size() const {
105 unsigned n = 1;
106 if (const ImutAVLTree* L = getLeft())
107 n += L->size();
108 if (const ImutAVLTree* R = getRight())
109 n += R->size();
110 return n;
111 }
112
113 /// begin - Returns an iterator that iterates over the nodes of the tree
114 /// in an inorder traversal. The returned iterator thus refers to the
115 /// the tree node with the minimum data element.
116 iterator begin() const { return iterator(this); }
117
118 /// end - Returns an iterator for the tree that denotes the end of an
119 /// inorder traversal.
120 iterator end() const { return iterator(); }
121
123 // Compare the keys.
124 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
125 ImutInfo::KeyOfValue(V)))
126 return false;
127
128 // Also compare the data values.
129 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
130 ImutInfo::DataOfValue(V)))
131 return false;
132
133 return true;
134 }
135
136 bool isElementEqual(const ImutAVLTree* RHS) const {
137 return isElementEqual(RHS->getValue());
138 }
139
140 /// isEqual - Compares two trees for structural equality and returns true
141 /// if they are equal. This worst case performance of this operation is
142 // linear in the sizes of the trees.
143 bool isEqual(const ImutAVLTree& RHS) const {
144 if (&RHS == this)
145 return true;
146
147 iterator LItr = begin(), LEnd = end();
148 iterator RItr = RHS.begin(), REnd = RHS.end();
149
150 while (LItr != LEnd && RItr != REnd) {
151 if (&*LItr == &*RItr) {
152 LItr.skipSubTree();
153 RItr.skipSubTree();
154 continue;
155 }
156
157 if (!LItr->isElementEqual(&*RItr))
158 return false;
159
160 ++LItr;
161 ++RItr;
162 }
163
164 return LItr == LEnd && RItr == REnd;
165 }
166
167 /// isNotEqual - Compares two trees for structural inequality. Performance
168 /// is the same is isEqual.
169 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
170
171 /// contains - Returns true if this tree contains a subtree (node) that
172 /// has an data element that matches the specified key. Complexity
173 /// is logarithmic in the size of the tree.
174 bool contains(key_type_ref K) { return (bool) find(K); }
175
176 /// validateTree - A utility method that checks that the balancing and
177 /// ordering invariants of the tree are satisfied. It is a recursive
178 /// method that returns the height of the tree, which is then consumed
179 /// by the enclosing validateTree call. External callers should ignore the
180 /// return value. An invalid tree will cause an assertion to fire in
181 /// a debug build.
182 unsigned validateTree() const {
183 unsigned HL = getLeft() ? getLeft()->validateTree() : 0;
184 unsigned HR = getRight() ? getRight()->validateTree() : 0;
185 (void) HL;
186 (void) HR;
187
188 assert(getHeight() == ( HL > HR ? HL : HR ) + 1
189 && "Height calculation wrong");
190
191 assert((HL > HR ? HL-HR : HR-HL) <= 2
192 && "Balancing invariant violated");
193
194 assert((!getLeft() ||
195 ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
196 ImutInfo::KeyOfValue(getValue()))) &&
197 "Value in left child is not less that current value");
198
199 assert((!getRight() ||
200 ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
201 ImutInfo::KeyOfValue(getRight()->getValue()))) &&
202 "Current value is not less that value of right child");
203
204 return getHeight();
205 }
206
207 //===----------------------------------------------------===//
208 // Internal values.
209 //===----------------------------------------------------===//
210
211private:
212 Factory *factory;
213 ImutAVLTree *left;
214 ImutAVLTree *right;
215 ImutAVLTree *prev = nullptr;
216 ImutAVLTree *next = nullptr;
217
218 unsigned height : 28;
220 unsigned IsMutable : 1;
222 unsigned IsDigestCached : 1;
224 unsigned IsCanonicalized : 1;
225
226 value_type value;
227 uint32_t digest = 0;
228 uint32_t refCount = 0;
229
230 //===----------------------------------------------------===//
231 // Internal methods (node manipulation; used by Factory).
232 //===----------------------------------------------------===//
233
234private:
235 /// ImutAVLTree - Internal constructor that is only called by
236 /// ImutAVLFactory.
238 unsigned height)
239 : factory(f), left(l), right(r), height(height), IsMutable(true),
240 IsDigestCached(false), IsCanonicalized(false), value(v)
241 {
242 if (left) left->retain();
243 if (right) right->retain();
244 }
245
246 /// isMutable - Returns true if the left and right subtree references
247 /// (as well as height) can be changed. If this method returns false,
248 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
249 /// object should always have this method return true. Further, if this
250 /// method returns false for an instance of ImutAVLTree, all subtrees
251 /// will also have this method return false. The converse is not true.
252 bool isMutable() const { return IsMutable; }
253
254 /// hasCachedDigest - Returns true if the digest for this tree is cached.
255 /// This can only be true if the tree is immutable.
256 bool hasCachedDigest() const { return IsDigestCached; }
257
258 //===----------------------------------------------------===//
259 // Mutating operations. A tree root can be manipulated as
260 // long as its reference has not "escaped" from internal
261 // methods of a factory object (see below). When a tree
262 // pointer is externally viewable by client code, the
263 // internal "mutable bit" is cleared to mark the tree
264 // immutable. Note that a tree that still has its mutable
265 // bit set may have children (subtrees) that are themselves
266 // immutable.
267 //===----------------------------------------------------===//
268
269 /// markImmutable - Clears the mutable flag for a tree. After this happens,
270 /// it is an error to call setLeft(), setRight(), and setHeight().
271 void markImmutable() {
272 assert(isMutable() && "Mutable flag already removed.");
273 IsMutable = false;
274 }
275
276 /// markedCachedDigest - Clears the NoCachedDigest flag for a tree.
277 void markedCachedDigest() {
278 assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
279 IsDigestCached = true;
280 }
281
282 /// setHeight - Changes the height of the tree. Used internally by
283 /// ImutAVLFactory.
284 void setHeight(unsigned h) {
285 assert(isMutable() && "Only a mutable tree can have its height changed.");
286 height = h;
287 }
288
289 static uint32_t computeDigest(ImutAVLTree *L, ImutAVLTree *R,
290 value_type_ref V) {
291 uint32_t digest = 0;
292
293 if (L)
294 digest += L->computeDigest();
295
296 // Compute digest of stored data.
297 FoldingSetNodeID ID;
298 ImutInfo::Profile(ID,V);
299 digest += ID.ComputeHash();
300
301 if (R)
302 digest += R->computeDigest();
303
304 return digest;
305 }
306
307 uint32_t computeDigest() {
308 // Check the lowest bit to determine if digest has actually been
309 // pre-computed.
310 if (hasCachedDigest())
311 return digest;
312
313 uint32_t X = computeDigest(getLeft(), getRight(), getValue());
314 digest = X;
315 markedCachedDigest();
316 return X;
317 }
318
319 //===----------------------------------------------------===//
320 // Reference count operations.
321 //===----------------------------------------------------===//
322
323public:
324 void retain() { ++refCount; }
325
326 void release() {
327 assert(refCount > 0);
328 if (--refCount == 0)
329 destroy();
330 }
331
332 void destroy() {
333 if (left)
334 left->release();
335 if (right)
336 right->release();
337 if (IsCanonicalized) {
338 if (next)
339 next->prev = prev;
340
341 if (prev)
342 prev->next = next;
343 else
344 factory->Cache[factory->maskCacheIndex(computeDigest())] = next;
345 }
346
347 // We need to clear the mutability bit in case we are
348 // destroying the node as part of a sweep in ImutAVLFactory::recoverNodes().
349 IsMutable = false;
350 factory->freeNodes.push_back(this);
351 }
352};
353
354template <typename ImutInfo>
356 static void retain(ImutAVLTree<ImutInfo> *Tree) { Tree->retain(); }
357 static void release(ImutAVLTree<ImutInfo> *Tree) { Tree->release(); }
358};
359
360//===----------------------------------------------------------------------===//
361// Immutable AVL-Tree Factory class.
362//===----------------------------------------------------------------------===//
363
364template <typename ImutInfo >
366 friend class ImutAVLTree<ImutInfo>;
367
368 using TreeTy = ImutAVLTree<ImutInfo>;
369 using value_type_ref = typename TreeTy::value_type_ref;
370 using key_type_ref = typename TreeTy::key_type_ref;
371 using CacheTy = DenseMap<unsigned, TreeTy*>;
372
373 CacheTy Cache;
374 uintptr_t Allocator;
375 std::vector<TreeTy*> createdNodes;
376 std::vector<TreeTy*> freeNodes;
377
378 bool ownsAllocator() const {
379 return (Allocator & 0x1) == 0;
380 }
381
382 BumpPtrAllocator& getAllocator() const {
383 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
384 }
385
386 //===--------------------------------------------------===//
387 // Public interface.
388 //===--------------------------------------------------===//
389
390public:
392 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
393
395 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
396
398 if (ownsAllocator()) delete &getAllocator();
399 }
400
401 TreeTy* add(TreeTy* T, value_type_ref V) {
402 T = add_internal(V,T);
404 recoverNodes();
405 return T;
406 }
407
408 TreeTy* remove(TreeTy* T, key_type_ref V) {
409 T = remove_internal(V,T);
411 recoverNodes();
412 return T;
413 }
414
415 TreeTy* getEmptyTree() const { return nullptr; }
416
417protected:
418 //===--------------------------------------------------===//
419 // A bunch of quick helper functions used for reasoning
420 // about the properties of trees and their children.
421 // These have succinct names so that the balancing code
422 // is as terse (and readable) as possible.
423 //===--------------------------------------------------===//
424
425 bool isEmpty(TreeTy* T) const { return !T; }
426 unsigned getHeight(TreeTy* T) const { return T ? T->getHeight() : 0; }
427 TreeTy* getLeft(TreeTy* T) const { return T->getLeft(); }
428 TreeTy* getRight(TreeTy* T) const { return T->getRight(); }
429 value_type_ref getValue(TreeTy* T) const { return T->value; }
430
431 // Make sure the index is not the Tombstone or Entry key of the DenseMap.
432 static unsigned maskCacheIndex(unsigned I) { return (I & ~0x02); }
433
434 unsigned incrementHeight(TreeTy* L, TreeTy* R) const {
435 unsigned hl = getHeight(L);
436 unsigned hr = getHeight(R);
437 return (hl > hr ? hl : hr) + 1;
438 }
439
440 static bool compareTreeWithSection(TreeTy* T,
441 typename TreeTy::iterator& TI,
442 typename TreeTy::iterator& TE) {
443 typename TreeTy::iterator I = T->begin(), E = T->end();
444 for ( ; I!=E ; ++I, ++TI) {
445 if (TI == TE || !I->isElementEqual(&*TI))
446 return false;
447 }
448 return true;
449 }
450
451 //===--------------------------------------------------===//
452 // "createNode" is used to generate new tree roots that link
453 // to other trees. The function may also simply move links
454 // in an existing root if that root is still marked mutable.
455 // This is necessary because otherwise our balancing code
456 // would leak memory as it would create nodes that are
457 // then discarded later before the finished tree is
458 // returned to the caller.
459 //===--------------------------------------------------===//
460
461 TreeTy* createNode(TreeTy* L, value_type_ref V, TreeTy* R) {
462 BumpPtrAllocator& A = getAllocator();
463 TreeTy* T;
464 if (!freeNodes.empty()) {
465 T = freeNodes.back();
466 freeNodes.pop_back();
467 assert(T != L);
468 assert(T != R);
469 } else {
470 T = (TreeTy*) A.Allocate<TreeTy>();
471 }
472 new (T) TreeTy(this, L, R, V, incrementHeight(L,R));
473 createdNodes.push_back(T);
474 return T;
475 }
476
477 TreeTy* createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
478 return createNode(newLeft, getValue(oldTree), newRight);
479 }
480
482 for (unsigned i = 0, n = createdNodes.size(); i < n; ++i) {
483 TreeTy *N = createdNodes[i];
484 if (N->isMutable() && N->refCount == 0)
485 N->destroy();
486 }
487 createdNodes.clear();
488 }
489
490 /// balanceTree - Used by add_internal and remove_internal to
491 /// balance a newly created tree.
492 TreeTy* balanceTree(TreeTy* L, value_type_ref V, TreeTy* R) {
493 unsigned hl = getHeight(L);
494 unsigned hr = getHeight(R);
495
496 if (hl > hr + 2) {
497 assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
498
499 TreeTy *LL = getLeft(L);
500 TreeTy *LR = getRight(L);
501
502 if (getHeight(LL) >= getHeight(LR))
503 return createNode(LL, L, createNode(LR,V,R));
504
505 assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
506
507 TreeTy *LRL = getLeft(LR);
508 TreeTy *LRR = getRight(LR);
509
510 return createNode(createNode(LL,L,LRL), LR, createNode(LRR,V,R));
511 }
512
513 if (hr > hl + 2) {
514 assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
515
516 TreeTy *RL = getLeft(R);
517 TreeTy *RR = getRight(R);
518
519 if (getHeight(RR) >= getHeight(RL))
520 return createNode(createNode(L,V,RL), R, RR);
521
522 assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
523
524 TreeTy *RLL = getLeft(RL);
525 TreeTy *RLR = getRight(RL);
526
527 return createNode(createNode(L,V,RLL), RL, createNode(RLR,R,RR));
528 }
529
530 return createNode(L,V,R);
531 }
532
533 /// add_internal - Creates a new tree that includes the specified
534 /// data and the data from the original tree. If the original tree
535 /// already contained the data item, the original tree is returned.
536 TreeTy *add_internal(value_type_ref V, TreeTy *T) {
537 if (isEmpty(T))
538 return createNode(T, V, T);
539 assert(!T->isMutable());
540
541 key_type_ref K = ImutInfo::KeyOfValue(V);
542 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
543
544 if (ImutInfo::isEqual(K, KCurrent)) {
545 // If both key and value are same, return the original tree.
546 if (ImutInfo::isDataEqual(ImutInfo::DataOfValue(V),
547 ImutInfo::DataOfValue(getValue(T))))
548 return T;
549 // Otherwise create a new node with the new value.
550 return createNode(getLeft(T), V, getRight(T));
551 }
552
553 TreeTy *NewL = getLeft(T);
554 TreeTy *NewR = getRight(T);
555 if (ImutInfo::isLess(K, KCurrent))
556 NewL = add_internal(V, NewL);
557 else
558 NewR = add_internal(V, NewR);
559
560 // If no changes were made, return the original tree. Otherwise, balance the
561 // tree and return the new root.
562 return NewL == getLeft(T) && NewR == getRight(T)
563 ? T
564 : balanceTree(NewL, getValue(T), NewR);
565 }
566
567 /// remove_internal - Creates a new tree that includes all the data
568 /// from the original tree except the specified data. If the
569 /// specified data did not exist in the original tree, the original
570 /// tree is returned.
571 TreeTy *remove_internal(key_type_ref K, TreeTy *T) {
572 if (isEmpty(T))
573 return T;
574
575 assert(!T->isMutable());
576
577 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
578
579 if (ImutInfo::isEqual(K, KCurrent))
580 return combineTrees(getLeft(T), getRight(T));
581
582 TreeTy *NewL = getLeft(T);
583 TreeTy *NewR = getRight(T);
584 if (ImutInfo::isLess(K, KCurrent))
585 NewL = remove_internal(K, NewL);
586 else
587 NewR = remove_internal(K, NewR);
588
589 // If no changes were made, return the original tree. Otherwise, balance the
590 // tree and return the new root.
591 return NewL == getLeft(T) && NewR == getRight(T)
592 ? T
593 : balanceTree(NewL, getValue(T), NewR);
594 }
595
596 TreeTy* combineTrees(TreeTy* L, TreeTy* R) {
597 if (isEmpty(L))
598 return R;
599 if (isEmpty(R))
600 return L;
601 TreeTy* OldNode;
602 TreeTy* newRight = removeMinBinding(R,OldNode);
603 return balanceTree(L, getValue(OldNode), newRight);
604 }
605
606 TreeTy* removeMinBinding(TreeTy* T, TreeTy*& Noderemoved) {
607 assert(!isEmpty(T));
608 if (isEmpty(getLeft(T))) {
609 Noderemoved = T;
610 return getRight(T);
611 }
612 return balanceTree(removeMinBinding(getLeft(T), Noderemoved),
613 getValue(T), getRight(T));
614 }
615
616 /// markImmutable - Clears the mutable bits of a root and all of its
617 /// descendants.
618 void markImmutable(TreeTy* T) {
619 if (!T || !T->isMutable())
620 return;
621 T->markImmutable();
624 }
625
626public:
627 TreeTy *getCanonicalTree(TreeTy *TNew) {
628 if (!TNew)
629 return nullptr;
630
631 if (TNew->IsCanonicalized)
632 return TNew;
633
634 // Search the hashtable for another tree with the same digest, and
635 // if find a collision compare those trees by their contents.
636 unsigned digest = TNew->computeDigest();
637 TreeTy *&entry = Cache[maskCacheIndex(digest)];
638 do {
639 if (!entry)
640 break;
641 for (TreeTy *T = entry ; T != nullptr; T = T->next) {
642 // Compare the Contents('T') with Contents('TNew')
643 typename TreeTy::iterator TI = T->begin(), TE = T->end();
644 if (!compareTreeWithSection(TNew, TI, TE))
645 continue;
646 if (TI != TE)
647 continue; // T has more contents than TNew.
648 // Trees did match! Return 'T'.
649 if (TNew->refCount == 0)
650 TNew->destroy();
651 return T;
652 }
653 entry->prev = TNew;
654 TNew->next = entry;
655 }
656 while (false);
657
658 entry = TNew;
659 TNew->IsCanonicalized = true;
660 return TNew;
661 }
662};
663
664//===----------------------------------------------------------------------===//
665// Immutable AVL-Tree Iterators.
666//===----------------------------------------------------------------------===//
667
668template <typename ImutInfo> class ImutAVLTreeGenericIterator {
670
671public:
672 using iterator_category = std::bidirectional_iterator_tag;
674 using difference_type = std::ptrdiff_t;
677
679 Flags=0x3 };
680
682
685 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
686 }
687
688 TreeTy &operator*() const {
689 assert(!stack.empty());
690 return *reinterpret_cast<TreeTy *>(stack.back() & ~Flags);
691 }
692 TreeTy *operator->() const { return &*this; }
693
694 uintptr_t getVisitState() const {
695 assert(!stack.empty());
696 return stack.back() & Flags;
697 }
698
699 bool atEnd() const { return stack.empty(); }
700
701 bool atBeginning() const {
702 return stack.size() == 1 && getVisitState() == VisitedNone;
703 }
704
706 assert(!stack.empty());
707 stack.pop_back();
708 if (stack.empty())
709 return;
710 switch (getVisitState()) {
711 case VisitedNone:
712 stack.back() |= VisitedLeft;
713 break;
714 case VisitedLeft:
715 stack.back() |= VisitedRight;
716 break;
717 default:
718 llvm_unreachable("Unreachable.");
719 }
720 }
721
723 return stack == x.stack;
724 }
725
727 return !(*this == x);
728 }
729
731 assert(!stack.empty());
732 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
733 assert(Current);
734 switch (getVisitState()) {
735 case VisitedNone:
736 if (TreeTy* L = Current->getLeft())
737 stack.push_back(reinterpret_cast<uintptr_t>(L));
738 else
739 stack.back() |= VisitedLeft;
740 break;
741 case VisitedLeft:
742 if (TreeTy* R = Current->getRight())
743 stack.push_back(reinterpret_cast<uintptr_t>(R));
744 else
745 stack.back() |= VisitedRight;
746 break;
747 case VisitedRight:
748 skipToParent();
749 break;
750 default:
751 llvm_unreachable("Unreachable.");
752 }
753 return *this;
754 }
755
757 assert(!stack.empty());
758 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
759 assert(Current);
760 switch (getVisitState()) {
761 case VisitedNone:
762 stack.pop_back();
763 break;
764 case VisitedLeft:
765 stack.back() &= ~Flags; // Set state to "VisitedNone."
766 if (TreeTy* L = Current->getLeft())
767 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
768 break;
769 case VisitedRight:
770 stack.back() &= ~Flags;
771 stack.back() |= VisitedLeft;
772 if (TreeTy* R = Current->getRight())
773 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
774 break;
775 default:
776 llvm_unreachable("Unreachable.");
777 }
778 return *this;
779 }
780};
781
782template <typename ImutInfo> class ImutAVLTreeInOrderIterator {
783 using InternalIteratorTy = ImutAVLTreeGenericIterator<ImutInfo>;
784
785 InternalIteratorTy InternalItr;
786
787public:
788 using iterator_category = std::bidirectional_iterator_tag;
790 using difference_type = std::ptrdiff_t;
793
795
796 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
797 if (Root)
798 ++*this; // Advance to first element.
799 }
800
801 ImutAVLTreeInOrderIterator() : InternalItr() {}
802
804 return InternalItr == x.InternalItr;
805 }
806
808 return !(*this == x);
809 }
810
811 TreeTy &operator*() const { return *InternalItr; }
812 TreeTy *operator->() const { return &*InternalItr; }
813
815 do ++InternalItr;
816 while (!InternalItr.atEnd() &&
817 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
818
819 return *this;
820 }
821
823 do --InternalItr;
824 while (!InternalItr.atBeginning() &&
825 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
826
827 return *this;
828 }
829
830 void skipSubTree() {
831 InternalItr.skipToParent();
832
833 while (!InternalItr.atEnd() &&
834 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
835 ++InternalItr;
836 }
837};
838
839/// Generic iterator that wraps a T::TreeTy::iterator and exposes
840/// iterator::getValue() on dereference.
841template <typename T>
844 ImutAVLValueIterator<T>, typename T::TreeTy::iterator,
845 typename std::iterator_traits<
846 typename T::TreeTy::iterator>::iterator_category,
847 const typename T::value_type> {
849 explicit ImutAVLValueIterator(typename T::TreeTy *Tree)
851
853 return this->I->getValue();
854 }
855};
856
857//===----------------------------------------------------------------------===//
858// Trait classes for Profile information.
859//===----------------------------------------------------------------------===//
860
861/// Generic profile template. The default behavior is to invoke the
862/// profile method of an object. Specializations for primitive integers
863/// and generic handling of pointers is done below.
864template <typename T>
866 using value_type = const T;
867 using value_type_ref = const T&;
868
872};
873
874/// Profile traits for integers.
875template <typename T>
877 using value_type = const T;
878 using value_type_ref = const T&;
879
881 ID.AddInteger(X);
882 }
883};
884
885#define PROFILE_INTEGER_INFO(X)\
886template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
887
889PROFILE_INTEGER_INFO(unsigned char)
891PROFILE_INTEGER_INFO(unsigned short)
892PROFILE_INTEGER_INFO(unsigned)
895PROFILE_INTEGER_INFO(unsigned long)
896PROFILE_INTEGER_INFO(long long)
897PROFILE_INTEGER_INFO(unsigned long long)
898
899#undef PROFILE_INTEGER_INFO
900
901/// Profile traits for booleans.
902template <>
904 using value_type = const bool;
905 using value_type_ref = const bool&;
906
908 ID.AddBoolean(X);
909 }
910};
911
912/// Generic profile trait for pointer types. We treat pointers as
913/// references to unique objects.
914template <typename T>
916 using value_type = const T*;
918
920 ID.AddPointer(X);
921 }
922};
923
924//===----------------------------------------------------------------------===//
925// Trait classes that contain element comparison operators and type
926// definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
927// inherit from the profile traits (ImutProfileInfo) to include operations
928// for element profiling.
929//===----------------------------------------------------------------------===//
930
931/// ImutContainerInfo - Generic definition of comparison operations for
932/// elements of immutable containers that defaults to using
933/// std::equal_to<> and std::less<> to perform comparison of elements.
934template <typename T>
942
944 static data_type_ref DataOfValue(value_type_ref) { return true; }
945
947 return std::equal_to<key_type>()(LHS,RHS);
948 }
949
951 return std::less<key_type>()(LHS,RHS);
952 }
953
954 static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
955};
956
957/// ImutContainerInfo - Specialization for pointer values to treat pointers
958/// as references to unique objects. Pointers are thus compared by
959/// their addresses.
960template <typename T>
978
979//===----------------------------------------------------------------------===//
980// Immutable Set
981//===----------------------------------------------------------------------===//
982
983template <typename ValT, typename ValInfo = ImutContainerInfo<ValT>>
985public:
986 using value_type = typename ValInfo::value_type;
987 using value_type_ref = typename ValInfo::value_type_ref;
989
990private:
992
993public:
994 /// Constructs a set from a pointer to a tree root. In general one
995 /// should use a Factory object to create sets instead of directly
996 /// invoking the constructor, but there are cases where make this
997 /// constructor public is useful.
998 explicit ImmutableSet(TreeTy *R) : Root(R) {}
999
1000 class Factory {
1001 typename TreeTy::Factory F;
1002 const bool Canonicalize;
1003
1004 public:
1005 Factory(bool canonicalize = true)
1006 : Canonicalize(canonicalize) {}
1007
1008 Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
1009 : F(Alloc), Canonicalize(canonicalize) {}
1010
1011 Factory(const Factory& RHS) = delete;
1012 void operator=(const Factory& RHS) = delete;
1013
1014 /// getEmptySet - Returns an immutable set that contains no elements.
1016 return ImmutableSet(F.getEmptyTree());
1017 }
1018
1019 /// add - Creates a new immutable set that contains all of the values
1020 /// of the original set with the addition of the specified value. If
1021 /// the original set already included the value, then the original set is
1022 /// returned and no memory is allocated. The time and space complexity
1023 /// of this operation is logarithmic in the size of the original set.
1024 /// The memory allocated to represent the set is released when the
1025 /// factory object that created the set is destroyed.
1027 TreeTy *NewT = F.add(Old.Root.get(), V);
1028 return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
1029 }
1030
1031 /// remove - Creates a new immutable set that contains all of the values
1032 /// of the original set with the exception of the specified value. If
1033 /// the original set did not contain the value, the original set is
1034 /// returned and no memory is allocated. The time and space complexity
1035 /// of this operation is logarithmic in the size of the original set.
1036 /// The memory allocated to represent the set is released when the
1037 /// factory object that created the set is destroyed.
1039 TreeTy *NewT = F.remove(Old.Root.get(), V);
1040 return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
1041 }
1042
1043 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
1044
1046 return const_cast<typename TreeTy::Factory *>(&F);
1047 }
1048 };
1049
1050 friend class Factory;
1051
1052 /// Returns true if the set contains the specified value.
1053 bool contains(value_type_ref V) const {
1054 return Root ? Root->contains(V) : false;
1055 }
1056
1057 bool operator==(const ImmutableSet &RHS) const {
1058 return Root && RHS.Root ? Root->isEqual(*RHS.Root.get()) : Root == RHS.Root;
1059 }
1060
1061 bool operator!=(const ImmutableSet &RHS) const {
1062 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root.get())
1063 : Root != RHS.Root;
1064 }
1065
1067 if (Root) { Root->retain(); }
1068 return Root.get();
1069 }
1070
1071 TreeTy *getRootWithoutRetain() const { return Root.get(); }
1072
1073 /// isEmpty - Return true if the set contains no elements.
1074 bool isEmpty() const { return !Root; }
1075
1076 /// isSingleton - Return true if the set contains exactly one element.
1077 /// This method runs in constant time.
1078 bool isSingleton() const { return getHeight() == 1; }
1079
1080 //===--------------------------------------------------===//
1081 // Iterators.
1082 //===--------------------------------------------------===//
1083
1085
1086 iterator begin() const { return iterator(Root.get()); }
1087 iterator end() const { return iterator(); }
1088
1089 //===--------------------------------------------------===//
1090 // Utility methods.
1091 //===--------------------------------------------------===//
1092
1093 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1094
1095 static void Profile(FoldingSetNodeID &ID, const ImmutableSet &S) {
1096 ID.AddPointer(S.Root.get());
1097 }
1098
1099 void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
1100
1101 //===--------------------------------------------------===//
1102 // For testing.
1103 //===--------------------------------------------------===//
1104
1105 void validateTree() const { if (Root) Root->validateTree(); }
1106};
1107
1108// NOTE: This may some day replace the current ImmutableSet.
1109template <typename ValT, typename ValInfo = ImutContainerInfo<ValT>>
1111public:
1112 using value_type = typename ValInfo::value_type;
1113 using value_type_ref = typename ValInfo::value_type_ref;
1115 using FactoryTy = typename TreeTy::Factory;
1116
1117private:
1119 FactoryTy *Factory;
1120
1121public:
1122 /// Constructs a set from a pointer to a tree root. In general one
1123 /// should use a Factory object to create sets instead of directly
1124 /// invoking the constructor, but there are cases where make this
1125 /// constructor public is useful.
1126 ImmutableSetRef(TreeTy *R, FactoryTy *F) : Root(R), Factory(F) {}
1127
1129 return ImmutableSetRef(0, F);
1130 }
1131
1133 return ImmutableSetRef(Factory->add(Root.get(), V), Factory);
1134 }
1135
1137 return ImmutableSetRef(Factory->remove(Root.get(), V), Factory);
1138 }
1139
1140 /// Returns true if the set contains the specified value.
1141 bool contains(value_type_ref V) const {
1142 return Root ? Root->contains(V) : false;
1143 }
1144
1145 ImmutableSet<ValT> asImmutableSet(bool canonicalize = true) const {
1146 return ImmutableSet<ValT>(
1147 canonicalize ? Factory->getCanonicalTree(Root.get()) : Root.get());
1148 }
1149
1150 TreeTy *getRootWithoutRetain() const { return Root.get(); }
1151
1152 bool operator==(const ImmutableSetRef &RHS) const {
1153 return Root && RHS.Root ? Root->isEqual(*RHS.Root.get()) : Root == RHS.Root;
1154 }
1155
1156 bool operator!=(const ImmutableSetRef &RHS) const {
1157 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root.get())
1158 : Root != RHS.Root;
1159 }
1160
1161 /// isEmpty - Return true if the set contains no elements.
1162 bool isEmpty() const { return !Root; }
1163
1164 /// isSingleton - Return true if the set contains exactly one element.
1165 /// This method runs in constant time.
1166 bool isSingleton() const { return getHeight() == 1; }
1167
1168 //===--------------------------------------------------===//
1169 // Iterators.
1170 //===--------------------------------------------------===//
1171
1173
1174 iterator begin() const { return iterator(Root.get()); }
1175 iterator end() const { return iterator(); }
1176
1177 //===--------------------------------------------------===//
1178 // Utility methods.
1179 //===--------------------------------------------------===//
1180
1181 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1182
1183 static void Profile(FoldingSetNodeID &ID, const ImmutableSetRef &S) {
1184 ID.AddPointer(S.Root.get());
1185 }
1186
1187 void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
1188
1189 //===--------------------------------------------------===//
1190 // For testing.
1191 //===--------------------------------------------------===//
1192
1193 void validateTree() const { if (Root) Root->validateTree(); }
1194};
1195
1196} // end namespace llvm
1197
1198#endif // LLVM_ADT_IMMUTABLESET_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_PREFERRED_TYPE(T)
\macro LLVM_PREFERRED_TYPE Adjust type of bit-field in debug info.
Definition Compiler.h:706
This file defines the DenseMap class.
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define PROFILE_INTEGER_INFO(X)
This file defines the RefCountedBase, ThreadSafeRefCountedBase, and IntrusiveRefCntPtr classes.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
#define T
if(PassOpts->AAPipeline)
This file defines the SmallVector class.
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
Value * RHS
Value * LHS
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:330
static void Profile(FoldingSetNodeID &ID, const ImmutableSetRef &S)
void Profile(FoldingSetNodeID &ID) const
ImmutableSetRef add(value_type_ref V)
ImutAVLTree< ValInfo > TreeTy
bool contains(value_type_ref V) const
Returns true if the set contains the specified value.
bool operator!=(const ImmutableSetRef &RHS) const
ImmutableSetRef remove(value_type_ref V)
ImutAVLValueIterator< ImmutableSetRef > iterator
bool isSingleton() const
isSingleton - Return true if the set contains exactly one element.
iterator begin() const
bool isEmpty() const
isEmpty - Return true if the set contains no elements.
typename ValInfo::value_type value_type
ImmutableSetRef(TreeTy *R, FactoryTy *F)
Constructs a set from a pointer to a tree root.
typename ValInfo::value_type_ref value_type_ref
iterator end() const
unsigned getHeight() const
ImmutableSet< ValT > asImmutableSet(bool canonicalize=true) const
typename TreeTy::Factory FactoryTy
static ImmutableSetRef getEmptySet(FactoryTy *F)
void validateTree() const
bool operator==(const ImmutableSetRef &RHS) const
TreeTy * getRootWithoutRetain() const
Factory(const Factory &RHS)=delete
void operator=(const Factory &RHS)=delete
TreeTy::Factory * getTreeFactory() const
BumpPtrAllocator & getAllocator()
Factory(BumpPtrAllocator &Alloc, bool canonicalize=true)
ImmutableSet getEmptySet()
getEmptySet - Returns an immutable set that contains no elements.
Factory(bool canonicalize=true)
ImmutableSet remove(ImmutableSet Old, value_type_ref V)
remove - Creates a new immutable set that contains all of the values of the original set with the exc...
ImmutableSet add(ImmutableSet Old, value_type_ref V)
add - Creates a new immutable set that contains all of the values of the original set with the additi...
bool operator!=(const ImmutableSet &RHS) const
typename ValInfo::value_type value_type
bool operator==(const ImmutableSet &RHS) const
iterator end() const
bool isEmpty() const
isEmpty - Return true if the set contains no elements.
ImmutableSet(TreeTy *R)
Constructs a set from a pointer to a tree root.
bool isSingleton() const
isSingleton - Return true if the set contains exactly one element.
TreeTy * getRootWithoutRetain() const
ImutAVLTree< ValInfo > TreeTy
void validateTree() const
bool contains(value_type_ref V) const
Returns true if the set contains the specified value.
void Profile(FoldingSetNodeID &ID) const
iterator begin() const
unsigned getHeight() const
static void Profile(FoldingSetNodeID &ID, const ImmutableSet &S)
ImutAVLValueIterator< ImmutableSet > iterator
typename ValInfo::value_type_ref value_type_ref
static unsigned maskCacheIndex(unsigned I)
TreeTy * balanceTree(TreeTy *L, value_type_ref V, TreeTy *R)
balanceTree - Used by add_internal and remove_internal to balance a newly created tree.
unsigned getHeight(TreeTy *T) const
ImutAVLFactory(BumpPtrAllocator &Alloc)
TreeTy * add_internal(value_type_ref V, TreeTy *T)
add_internal - Creates a new tree that includes the specified data and the data from the original tre...
value_type_ref getValue(TreeTy *T) const
static bool compareTreeWithSection(TreeTy *T, typename TreeTy::iterator &TI, typename TreeTy::iterator &TE)
TreeTy * getLeft(TreeTy *T) const
TreeTy * getCanonicalTree(TreeTy *TNew)
TreeTy * add(TreeTy *T, value_type_ref V)
TreeTy * getRight(TreeTy *T) const
TreeTy * getEmptyTree() const
TreeTy * removeMinBinding(TreeTy *T, TreeTy *&Noderemoved)
TreeTy * createNode(TreeTy *newLeft, TreeTy *oldTree, TreeTy *newRight)
TreeTy * combineTrees(TreeTy *L, TreeTy *R)
TreeTy * remove_internal(key_type_ref K, TreeTy *T)
remove_internal - Creates a new tree that includes all the data from the original tree except the spe...
TreeTy * createNode(TreeTy *L, value_type_ref V, TreeTy *R)
unsigned incrementHeight(TreeTy *L, TreeTy *R) const
TreeTy * remove(TreeTy *T, key_type_ref V)
void markImmutable(TreeTy *T)
markImmutable - Clears the mutable bits of a root and all of its descendants.
bool isEmpty(TreeTy *T) const
ImutAVLTree< ImutInfo > value_type
bool operator==(const ImutAVLTreeGenericIterator &x) const
std::bidirectional_iterator_tag iterator_category
ImutAVLTreeGenericIterator(const TreeTy *Root)
ImutAVLTree< ImutInfo > TreeTy
ImutAVLTreeGenericIterator & operator--()
bool operator!=(const ImutAVLTreeGenericIterator &x) const
ImutAVLTreeGenericIterator & operator++()
bool operator!=(const ImutAVLTreeInOrderIterator &x) const
ImutAVLTreeInOrderIterator & operator++()
ImutAVLTree< ImutInfo > TreeTy
ImutAVLTreeInOrderIterator & operator--()
std::bidirectional_iterator_tag iterator_category
ImutAVLTreeInOrderIterator(const TreeTy *Root)
bool operator==(const ImutAVLTreeInOrderIterator &x) const
ImutAVLTree< ImutInfo > value_type
unsigned size() const
size - Returns the number of nodes in the tree, which includes both leaves and non-leaf nodes.
iterator end() const
end - Returns an iterator for the tree that denotes the end of an inorder traversal.
const value_type & getValue() const
getValue - Returns the data value associated with the tree node.
unsigned getHeight() const
getHeight - Returns the height of the tree.
typename ValInfo::key_type_ref key_type_ref
ImutAVLFactory< ValInfo > Factory
ImutAVLTree * find(key_type_ref K)
find - Finds the subtree associated with the specified key value.
typename ValInfo::value_type_ref value_type_ref
unsigned validateTree() const
validateTree - A utility method that checks that the balancing and ordering invariants of the tree ar...
bool isNotEqual(const ImutAVLTree &RHS) const
isNotEqual - Compares two trees for structural inequality.
bool isEqual(const ImutAVLTree &RHS) const
isEqual - Compares two trees for structural equality and returns true if they are equal.
ImutAVLTree * getLeft() const
Return a pointer to the left subtree.
ImutAVLTreeInOrderIterator< ValInfo > iterator
typename ValInfo::value_type value_type
ImutAVLTree * getRight() const
Return a pointer to the right subtree.
bool isElementEqual(const ImutAVLTree *RHS) const
bool contains(key_type_ref K)
contains - Returns true if this tree contains a subtree (node) that has an data element that matches ...
ImutAVLTree * getMaxElement()
getMaxElement - Find the subtree associated with the highest ranged key value.
iterator begin() const
begin - Returns an iterator that iterates over the nodes of the tree in an inorder traversal.
bool isElementEqual(value_type_ref V) const
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
#define N
static void Profile(const T &X, FoldingSetNodeID &ID)
Definition FoldingSet.h:237
Generic iterator that wraps a T::TreeTy::iterator and exposes iterator::getValue() on dereference.
ImutAVLValueIterator::reference operator*() const
ImutAVLValueIterator(typename T::TreeTy *Tree)
static bool isDataEqual(data_type_ref, data_type_ref)
static key_type_ref KeyOfValue(value_type_ref D)
static bool isEqual(key_type_ref LHS, key_type_ref RHS)
typename ImutProfileInfo< T * >::value_type_ref value_type_ref
typename ImutProfileInfo< T * >::value_type value_type
static data_type_ref DataOfValue(value_type_ref)
static bool isLess(key_type_ref LHS, key_type_ref RHS)
ImutContainerInfo - Generic definition of comparison operations for elements of immutable containers ...
static bool isLess(key_type_ref LHS, key_type_ref RHS)
typename ImutProfileInfo< T >::value_type value_type
static bool isEqual(key_type_ref LHS, key_type_ref RHS)
static bool isDataEqual(data_type_ref, data_type_ref)
static data_type_ref DataOfValue(value_type_ref)
static key_type_ref KeyOfValue(value_type_ref D)
value_type_ref key_type_ref
typename ImutProfileInfo< T >::value_type_ref value_type_ref
static void Profile(FoldingSetNodeID &ID, value_type_ref X)
static void Profile(FoldingSetNodeID &ID, value_type_ref X)
Generic profile template.
static void Profile(FoldingSetNodeID &ID, value_type_ref X)
Profile traits for integers.
static void Profile(FoldingSetNodeID &ID, value_type_ref X)
static void retain(ImutAVLTree< ImutInfo > *Tree)
Class you can specialize to provide custom retain/release functionality for a type.