LLVM 24.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"
20#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/iterator.h"
25#include "llvm/Support/Debug.h"
28#include <cassert>
29#include <cstdint>
30#include <functional>
31#include <iterator>
32#include <new>
33#include <vector>
34
35namespace llvm {
36
37//===----------------------------------------------------------------------===//
38// Immutable AVL-Tree Definition.
39//===----------------------------------------------------------------------===//
40
41template <typename ImutInfo, bool Canonicalize = true> class ImutAVLFactory;
42template <typename ImutInfo, bool Canonicalize = true>
44
45namespace ImutAVLDetail {
46/// The intrusive doubly-linked chain of same-digest trees in the factory's
47/// canonicalization cache. Held as an (empty) base so that, when
48/// canonicalization is disabled, the empty base optimization removes it
49/// entirely. Kept separate from the cached digest below so that the two
50/// pointers pack without the tail padding that grouping a trailing 32-bit field
51/// with them would introduce.
52template <typename Tree, bool Canonicalize> struct CanonicalLinks {
53 Tree *Prev = nullptr;
54 Tree *Next = nullptr;
55};
56template <typename Tree> struct CanonicalLinks<Tree, false> {};
57
58/// The cached structural digest, used only for canonicalization. Stored as an
59/// LLVM_NO_UNIQUE_ADDRESS member so it occupies no space when disabled and
60/// packs alongside the adjacent 32-bit fields when enabled.
61template <bool Canonicalize> struct CanonicalDigest {
63};
64template <> struct CanonicalDigest<false> {};
65
66/// The factory-side canonicalization cache: digest -> tree chain.
67/// Empty when canonicalization is disabled.
68template <typename Tree, bool Canonicalize> struct CanonicalCache {
70};
71template <typename Tree> struct CanonicalCache<Tree, false> {};
72} // namespace ImutAVLDetail
73
74template <typename ImutInfo, bool Canonicalize = true>
75class ImutAVLTree
76 : private ImutAVLDetail::CanonicalLinks<ImutAVLTree<ImutInfo, Canonicalize>,
77 Canonicalize> {
78public:
79 using key_type_ref = typename ImutInfo::key_type_ref;
80 using value_type = typename ImutInfo::value_type;
81 using value_type_ref = typename ImutInfo::value_type_ref;
84
85 friend class ImutAVLFactory<ImutInfo, Canonicalize>;
86
87public:
88 //===----------------------------------------------------===//
89 // Public Interface.
90 //===----------------------------------------------------===//
91
92 /// Return a pointer to the left subtree. This value
93 /// is NULL if there is no left subtree.
94 ImutAVLTree *getLeft() const { return left; }
95
96 /// Return a pointer to the right subtree. This value is
97 /// NULL if there is no right subtree.
98 ImutAVLTree *getRight() const { return right; }
99
100 /// Returns the height of the tree. A tree with no subtrees has a height of 1.
101 unsigned getHeight() const { return height; }
102
103 /// Returns the data value associated with the tree node.
104 const value_type& getValue() const { return value; }
105
106 /// Finds the subtree associated with the specified key value. This method
107 /// returns NULL if no matching subtree is found.
108 ImutAVLTree* find(key_type_ref K) {
109 ImutAVLTree *T = this;
110 while (T) {
111 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
112 if (ImutInfo::isEqual(K,CurrentKey))
113 return T;
114 else if (ImutInfo::isLess(K,CurrentKey))
115 T = T->getLeft();
116 else
117 T = T->getRight();
118 }
119 return nullptr;
120 }
121
122 /// Find the subtree associated with the highest ranged key value.
123 ImutAVLTree* getMaxElement() {
124 ImutAVLTree *T = this;
125 ImutAVLTree *Right = T->getRight();
126 while (Right) { T = Right; Right = T->getRight(); }
127 return T;
128 }
129
130 /// Returns the number of nodes in the tree, which includes both leaves and
131 // non-leaf nodes.
132 unsigned size() const {
133 unsigned n = 1;
134 if (const ImutAVLTree* L = getLeft())
135 n += L->size();
136 if (const ImutAVLTree* R = getRight())
137 n += R->size();
138 return n;
139 }
140
141 /// Returns an iterator that iterates over the nodes of the tree in an inorder
142 /// traversal. The returned iterator thus refers to the tree node with the
143 /// minimum data element.
144 iterator begin() const { return iterator(this); }
145
146 /// Returns an iterator for the tree that denotes the end of an inorder
147 /// traversal.
148 iterator end() const { return iterator(); }
149
151 // Compare the keys.
152 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
153 ImutInfo::KeyOfValue(V)))
154 return false;
155
156 // Also compare the data values.
157 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
158 ImutInfo::DataOfValue(V)))
159 return false;
160
161 return true;
162 }
163
164 bool isElementEqual(const ImutAVLTree* RHS) const {
165 return isElementEqual(RHS->getValue());
166 }
167
168 /// Compares two trees for structural equality and returns true if they are
169 /// equal. The worst case performance of this operation is linear in the sizes
170 /// of the trees.
171 bool isEqual(const ImutAVLTree& RHS) const {
172 if (&RHS == this)
173 return true;
174
175 iterator LItr = begin(), LEnd = end();
176 iterator RItr = RHS.begin(), REnd = RHS.end();
177
178 while (LItr != LEnd && RItr != REnd) {
179 if (&*LItr == &*RItr) {
180 LItr.skipSubTree();
181 RItr.skipSubTree();
182 continue;
183 }
184
185 if (!LItr->isElementEqual(&*RItr))
186 return false;
187
188 ++LItr;
189 ++RItr;
190 }
191
192 return LItr == LEnd && RItr == REnd;
193 }
194
195 /// Compares two trees for structural inequality. Performance is the same as
196 /// isEqual.
197 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
198
199 /// Returns true if this tree contains a subtree (node) that has an data
200 /// element that matches the specified key. Complexity is logarithmic in the
201 /// size of the tree.
202 bool contains(key_type_ref K) { return (bool) find(K); }
203
204 /// A utility method that checks that the balancing and ordering invariants of
205 /// the tree are satisfied. It is a recursive method that returns the height
206 /// of the tree, which is then consumed by the enclosing validateTree call.
207 /// External callers should ignore the return value. An invalid tree will
208 /// cause an assertion to fire in a debug build.
209 unsigned validateTree() const {
210 unsigned HL = getLeft() ? getLeft()->validateTree() : 0;
211 unsigned HR = getRight() ? getRight()->validateTree() : 0;
212 (void) HL;
213 (void) HR;
214
215 assert(getHeight() == ( HL > HR ? HL : HR ) + 1
216 && "Height calculation wrong");
217
218 assert((HL > HR ? HL-HR : HR-HL) <= 2
219 && "Balancing invariant violated");
220
221 assert((!getLeft() ||
222 ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
223 ImutInfo::KeyOfValue(getValue()))) &&
224 "Value in left child is not less that current value");
225
226 assert((!getRight() ||
227 ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
228 ImutInfo::KeyOfValue(getRight()->getValue()))) &&
229 "Current value is not less that value of right child");
230
231 return getHeight();
232 }
233
234 //===----------------------------------------------------===//
235 // Internal values.
236 //===----------------------------------------------------===//
237
238private:
239 // Field order places the traversal-hot fields (left, right, value) first so
240 // that in a node that straddles a cache line they land in the earlier line;
241 // the cold factory back-pointer (only touched on create/destroy) goes last.
242 // The reference count shares a word with the bit-fields so that it adds no
243 // padding before a pointer-aligned value.
244 ImutAVLTree *left;
245 ImutAVLTree *right;
246
247 unsigned height : 28;
249 unsigned IsMutable : 1;
251 unsigned IsDigestCached : 1;
253 unsigned IsCanonicalized : 1;
254 uint32_t refCount = 0;
255
256 value_type value;
258 Factory *factory;
259
260 //===----------------------------------------------------===//
261 // Internal methods (node manipulation; used by Factory).
262 //===----------------------------------------------------===//
263
264private:
265 /// Internal constructor that is only called by ImutAVLFactory.
267 unsigned height)
268 : left(l), right(r), height(height), IsMutable(true),
269 IsDigestCached(false), IsCanonicalized(false), value(v), factory(f) {
270 if (left) left->retain();
271 if (right) right->retain();
272 }
273
274 /// Returns true if the left and right subtree references
275 /// (as well as height) can be changed. If this method returns false,
276 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
277 /// object should always have this method return true. Further, if this
278 /// method returns false for an instance of ImutAVLTree, all subtrees
279 /// will also have this method return false. The converse is not true.
280 bool isMutable() const { return IsMutable; }
281
282 /// Returns true if the digest for this tree is cached. This can only be true
283 /// if the tree is immutable.
284 bool hasCachedDigest() const { return IsDigestCached; }
285
286 //===----------------------------------------------------===//
287 // Mutating operations. A tree root can be manipulated as
288 // long as its reference has not "escaped" from internal
289 // methods of a factory object (see below). When a tree
290 // pointer is externally viewable by client code, the
291 // internal "mutable bit" is cleared to mark the tree
292 // immutable. Note that a tree that still has its mutable
293 // bit set may have children (subtrees) that are themselves
294 // immutable.
295 //===----------------------------------------------------===//
296
297 /// Clears the mutable flag for a tree. After this happens,
298 /// it is an error to call setLeft(), setRight(), and setHeight().
299 void markImmutable() {
300 assert(isMutable() && "Mutable flag already removed.");
301 IsMutable = false;
302 }
303
304 /// Clears the NoCachedDigest flag for a tree.
305 void markedCachedDigest() {
306 assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
307 IsDigestCached = true;
308 }
309
310 /// Changes the height of the tree. Used internally by ImutAVLFactory.
311 void setHeight(unsigned h) {
312 assert(isMutable() && "Only a mutable tree can have its height changed.");
313 height = h;
314 }
315
316 static uint32_t computeDigest(ImutAVLTree *L, ImutAVLTree *R,
318 uint32_t digest = 0;
319
320 if (L)
321 digest += L->computeDigest();
322
323 // Compute digest of stored data.
324 FoldingSetNodeID ID;
325 ImutInfo::Profile(ID,V);
326 digest += ID.computeHash();
327
328 if (R)
329 digest += R->computeDigest();
330
331 return digest;
332 }
333
334 uint32_t computeDigest() {
335 // Check the lowest bit to determine if digest has actually been
336 // pre-computed.
337 if (hasCachedDigest())
338 return digest.Digest;
339
340 uint32_t X = computeDigest(getLeft(), getRight(), getValue());
341 digest.Digest = X;
342 markedCachedDigest();
343 return X;
344 }
345
346 //===----------------------------------------------------===//
347 // Reference count operations.
348 //===----------------------------------------------------===//
349
350public:
351 void retain() { ++refCount; }
352
353 void release() {
354 assert(refCount > 0);
355 if (--refCount == 0)
356 destroy();
357 }
358
360 if (left)
361 left->release();
362 if (right)
363 right->release();
364 if constexpr (Canonicalize) {
365 if (IsCanonicalized) {
366 if (this->Next)
367 this->Next->Prev = this->Prev;
368
369 if (this->Prev)
370 this->Prev->Next = this->Next;
371 else
372 factory->Cache[factory->maskCacheIndex(computeDigest())] = this->Next;
373 }
374 }
375
376 // We need to clear the mutability bit in case we are
377 // destroying the node as part of a sweep in ImutAVLFactory::recoverNodes().
378 IsMutable = false;
379 // The children were released above, so reuse the left pointer to link
380 // this node into the factory's free list.
381 left = factory->freeNodes;
382 factory->freeNodes = this;
383 }
384};
385
386template <typename ImutInfo, bool Canonicalize>
387struct IntrusiveRefCntPtrInfo<ImutAVLTree<ImutInfo, Canonicalize>> {
389 Tree->retain();
390 }
392 Tree->release();
393 }
394};
395
396//===----------------------------------------------------------------------===//
397// Immutable AVL-Tree Factory class.
398//===----------------------------------------------------------------------===//
399
400template <typename ImutInfo, bool Canonicalize>
402 : private ImutAVLDetail::CanonicalCache<ImutAVLTree<ImutInfo, Canonicalize>,
403 Canonicalize> {
404 friend class ImutAVLTree<ImutInfo, Canonicalize>;
405
407 using value_type = typename TreeTy::value_type;
408 using value_type_ref = typename TreeTy::value_type_ref;
409 using key_type_ref = typename TreeTy::key_type_ref;
410
411 uintptr_t Allocator;
412 std::vector<TreeTy*> createdNodes;
413 // Destroyed nodes, linked through their left pointers.
414 TreeTy *freeNodes = nullptr;
415
416 bool ownsAllocator() const {
417 return (Allocator & 0x1) == 0;
418 }
419
420 BumpPtrAllocator& getAllocator() const {
421 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
422 }
423
424 //===--------------------------------------------------===//
425 // Public interface.
426 //===--------------------------------------------------===//
427
428public:
430 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
431
433 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
434
436 if (ownsAllocator()) delete &getAllocator();
437 }
438
439 TreeTy* add(TreeTy* T, value_type_ref V) {
440 T = add_internal(V,T);
442 return T;
443 }
444
445 /// Merges \p A and \p B in a single traversal, sharing every subtree that the
446 /// two operands do not overlap. \p Combine(AElem, BElem) produces the element
447 /// stored for a key present in both; \p KeepUnmatched governs keys unique to
448 /// one side (see merge_internal). For merging |B| entries into |A|
449 /// (|B| <= |A|) this costs O(|B| * log(|A|/|B| + 1)) and copies each spine
450 /// node at most once, versus O(|B| * log|A|) repeated \ref add descents.
451 /// \p A and \p B must be immutable. This does not short-circuit equal or
452 /// empty operands (merge_internal handles them correctly but not specially);
453 /// callers that want those fast paths, or size-driven operand ordering,
454 /// should apply them first (see ImmutableSet::Factory::unionSets).
455 template <typename CombineFn>
456 TreeTy *mergeTrees(TreeTy *A, TreeTy *B, CombineFn Combine,
457 bool KeepUnmatched, bool SkipShared = false) {
458 TreeTy *T = merge_internal(A, B, Combine, KeepUnmatched, SkipShared);
460 return T;
461 }
462
463 /// Returns the set union of \p A and \p B (keeping \p A's element on matching
464 /// keys). Shorthand for the fully sharing \ref mergeTrees.
465 TreeTy *unionTrees(TreeTy *A, TreeTy *B) {
466 // With KeepUnmatched=true, unmatched elements are shared as-is and Combine
467 // is invoked only for keys present in both, where it keeps A's element.
468 auto KeepFirst = [](const value_type *L,
469 const value_type *R) -> const value_type & {
470 return L ? *L : *R;
471 };
472 // Set union is idempotent, so identical (pointer-equal) subtrees -- common
473 // once one operand is derived from the other -- can be shared in O(1).
474 return mergeTrees(A, B, KeepFirst, /*KeepUnmatched=*/true,
475 /*SkipShared=*/true);
476 }
477
478 TreeTy* remove(TreeTy* T, key_type_ref V) {
479 T = remove_internal(V,T);
481 return T;
482 }
483
484 /// Returns the tree of the elements of \p T for which \p Pred holds. \p Pred
485 /// is called on the elements in order and must not use this factory.
486 /// Subtrees that keep all of their elements are shared rather than rebuilt.
487 template <typename PredFn> TreeTy *filterTree(TreeTy *T, PredFn Pred) {
490 return T;
491 }
492
493 TreeTy* getEmptyTree() const { return nullptr; }
494
495protected:
496 //===--------------------------------------------------===//
497 // A bunch of quick helper functions used for reasoning
498 // about the properties of trees and their children.
499 // These have succinct names so that the balancing code
500 // is as terse (and readable) as possible.
501 //===--------------------------------------------------===//
502
503 bool isEmpty(TreeTy* T) const { return !T; }
504 unsigned getHeight(TreeTy* T) const { return T ? T->getHeight() : 0; }
505 TreeTy* getLeft(TreeTy* T) const { return T->getLeft(); }
506 TreeTy* getRight(TreeTy* T) const { return T->getRight(); }
507 value_type_ref getValue(TreeTy* T) const { return T->value; }
508
509 // Make sure the index is not the Tombstone or Entry key of the DenseMap.
510 static unsigned maskCacheIndex(unsigned I) { return (I & ~0x02); }
511
512 unsigned incrementHeight(TreeTy* L, TreeTy* R) const {
513 unsigned hl = getHeight(L);
514 unsigned hr = getHeight(R);
515 return (hl > hr ? hl : hr) + 1;
516 }
517
518 //===--------------------------------------------------===//
519 // "createNode" is used to generate new tree roots that link
520 // to other trees. The function may also simply move links
521 // in an existing root if that root is still marked mutable.
522 // This is necessary because otherwise our balancing code
523 // would leak memory as it would create nodes that are
524 // then discarded later before the finished tree is
525 // returned to the caller.
526 //===--------------------------------------------------===//
527
528 TreeTy* createNode(TreeTy* L, value_type_ref V, TreeTy* R) {
529 BumpPtrAllocator& A = getAllocator();
530 TreeTy* T;
531 if (freeNodes) {
532 T = freeNodes;
533 freeNodes = T->getLeft();
534 assert(!T->isMutable() && "free-list node must have been destroyed");
535 assert(T != L);
536 assert(T != R);
537 } else {
538 T = (TreeTy*) A.Allocate<TreeTy>();
539 }
540 new (T) TreeTy(this, L, R, V, incrementHeight(L,R));
541 createdNodes.push_back(T);
542 return T;
543 }
544
545 TreeTy* createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
546 return createNode(newLeft, getValue(oldTree), newRight);
547 }
548
549 void recoverNodes(TreeTy *Result) {
550 // Mark Result's nodes immutable and reclaim the intermediates discarded
551 // during balancing, in one pass. Nodes are built bottom-up, so a node
552 // precedes its parents in createdNodes; visiting in reverse thus reaches
553 // each node only once its reference count is final. Unreferenced nodes are
554 // unreachable and destroyed; the rest belong to Result. Result is kept
555 // despite its zero count -- the caller has not taken ownership yet.
556 for (TreeTy *N : llvm::reverse(createdNodes)) {
557 if (!N->isMutable())
558 continue; // Already reclaimed while destroying an unreachable parent.
559 if (N != Result && N->refCount == 0)
560 N->destroy();
561 else
562 N->markImmutable();
563 }
564 createdNodes.clear();
565 }
566
567 /// Used by add_internal and remove_internal to balance a newly created tree.
568 TreeTy* balanceTree(TreeTy* L, value_type_ref V, TreeTy* R) {
569 unsigned hl = getHeight(L);
570 unsigned hr = getHeight(R);
571
572 if (hl > hr + 2) {
573 assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
574
575 TreeTy *LL = getLeft(L);
576 TreeTy *LR = getRight(L);
577
578 if (getHeight(LL) >= getHeight(LR))
579 return createNode(LL, L, createNode(LR,V,R));
580
581 assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
582
583 TreeTy *LRL = getLeft(LR);
584 TreeTy *LRR = getRight(LR);
585
586 return createNode(createNode(LL,L,LRL), LR, createNode(LRR,V,R));
587 }
588
589 if (hr > hl + 2) {
590 assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
591
592 TreeTy *RL = getLeft(R);
593 TreeTy *RR = getRight(R);
594
595 if (getHeight(RR) >= getHeight(RL))
596 return createNode(createNode(L,V,RL), R, RR);
597
598 assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
599
600 TreeTy *RLL = getLeft(RL);
601 TreeTy *RLR = getRight(RL);
602
603 return createNode(createNode(L,V,RLL), RL, createNode(RLR,R,RR));
604 }
605
606 return createNode(L,V,R);
607 }
608
609 /// Combines \p L and \p R with the value \p V (every key in \p L less than
610 /// \p V, every key in \p R greater) into one balanced tree. Unlike
611 /// balanceTree this tolerates an arbitrary height difference between \p L and
612 /// \p R: it descends the taller side's spine and rebalances on the way back
613 /// up, exactly as an insertion would.
614 TreeTy *joinTrees(TreeTy *L, value_type_ref V, TreeTy *R) {
615 if (getHeight(L) > getHeight(R) + 2)
616 return balanceTree(getLeft(L), getValue(L), joinTrees(getRight(L), V, R));
617 if (getHeight(R) > getHeight(L) + 2)
618 return balanceTree(joinTrees(L, V, getLeft(R)), getValue(R), getRight(R));
619 return createNode(L, V, R);
620 }
621
622 /// Splits \p T into \p L (all keys less than \p K) and \p R (all keys greater
623 /// than \p K). If \p K is present in \p T, \p Match is set to point at its
624 /// element (which is dropped from \p L and \p R); otherwise \p Match is null.
625 void splitLookup(TreeTy *T, key_type_ref K, TreeTy *&L,
626 const value_type *&Match, TreeTy *&R) {
627 if (isEmpty(T)) {
628 L = R = getEmptyTree();
629 Match = nullptr;
630 return;
631 }
632 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
633 if (ImutInfo::isEqual(K, KCurrent)) {
634 L = getLeft(T);
635 R = getRight(T);
636 // Use the tree accessor, which returns a reference to the stored element
637 // (the factory's getValue returns value_type_ref, which is by value for
638 // pointer-like element types).
639 Match = &T->getValue();
640 } else if (ImutInfo::isLess(K, KCurrent)) {
641 TreeTy *LR;
642 splitLookup(getLeft(T), K, L, Match, LR);
643 R = joinTrees(LR, getValue(T), getRight(T));
644 } else {
645 TreeTy *RL;
646 splitLookup(getRight(T), K, RL, Match, R);
647 L = joinTrees(getLeft(T), getValue(T), RL);
648 }
649 }
650
651 /// Rebuilds \p T with the same shape but each element replaced by
652 /// \p Combine applied to it. \p FromB selects which side of \p Combine the
653 /// element is passed on (it is the sole non-null argument).
654 /// Subtrees that \p Combine leaves unchanged are shared.
655 template <typename CombineFn>
656 TreeTy *transformTree(TreeTy *T, CombineFn &Combine, bool FromB) {
657 if (isEmpty(T))
658 return T;
659 TreeTy *L = transformTree(getLeft(T), Combine, FromB);
660 TreeTy *R = transformTree(getRight(T), Combine, FromB);
661 const value_type &E = getValue(T);
662 auto NewElem = FromB ? Combine(nullptr, &E) : Combine(&E, nullptr);
663 if (L == getLeft(T) && R == getRight(T) &&
664 ImutInfo::isDataEqual(ImutInfo::DataOfValue(NewElem),
665 ImutInfo::DataOfValue(E))) {
666 return T;
667 }
668 return createNode(L, NewElem, R);
669 }
670
671 /// Merges \p A and \p B by recursing over \p A's structure and splitting \p B
672 /// at each of \p A's keys. For a key in both, the stored element is
673 /// Combine(AElem, BElem). \p KeepUnmatched controls keys unique to one side:
674 /// when true, such elements (and whole non-overlapping subtrees) are taken
675 /// unchanged and shared, and \p Combine is invoked only on keys present in
676 /// both (valid when \p Combine is an identity for a missing side, e.g. a set
677 /// union or a lattice join with an identity element); when false every key is
678 /// passed through \p Combine with the absent side null (needed for a join
679 /// that transforms unmatched keys, e.g. liveness downgrading Must to Maybe).
680 template <typename CombineFn>
681 TreeTy *merge_internal(TreeTy *A, TreeTy *B, CombineFn &Combine,
682 bool KeepUnmatched, bool SkipShared) {
683 // When A and B are the same tree (which happens all the time once B is
684 // derived from A by a small edit, since the untouched side is shared by
685 // pointer), an idempotent merge returns it unchanged in O(1). Only valid
686 // when merge(x, x) == x, so the caller opts in via SkipShared.
687 if (SkipShared && A == B)
688 return A;
689 if (isEmpty(A))
690 return KeepUnmatched ? B : transformTree(B, Combine, /*FromB=*/true);
691 if (isEmpty(B))
692 return KeepUnmatched ? A : transformTree(A, Combine, /*FromB=*/false);
693
694 const value_type &AElem = getValue(A);
695 TreeTy *BL, *BR;
696 const value_type *BMatch;
697 splitLookup(B, ImutInfo::KeyOfValue(AElem), BL, BMatch, BR);
698
699 TreeTy *NewL =
700 merge_internal(getLeft(A), BL, Combine, KeepUnmatched, SkipShared);
701 TreeTy *NewR =
702 merge_internal(getRight(A), BR, Combine, KeepUnmatched, SkipShared);
703
704 if (!BMatch && KeepUnmatched) {
705 // Key present only in A.
706 if (NewL == getLeft(A) && NewR == getRight(A))
707 return A;
708 return joinTrees(NewL, AElem, NewR);
709 }
710 // Combine the elements (BMatch is null for a key present only in A).
711 // Preserve sharing when the combined value is unchanged and neither
712 // subtree moved, so that a join that only touches a few keys does not
713 // rebuild the whole spine.
714 auto NewElem = Combine(&AElem, BMatch);
715 if (NewL == getLeft(A) && NewR == getRight(A) &&
716 ImutInfo::isDataEqual(ImutInfo::DataOfValue(NewElem),
717 ImutInfo::DataOfValue(AElem)))
718 return A;
719 return joinTrees(NewL, NewElem, NewR);
720 }
721
722 /// add_internal - Creates a new tree that includes the specified
723 /// data and the data from the original tree. If the original tree
724 /// already contained the data item, the original tree is returned.
725 TreeTy *add_internal(value_type_ref V, TreeTy *T) {
726 if (isEmpty(T))
727 return createNode(T, V, T);
728 assert(!T->isMutable());
729
730 key_type_ref K = ImutInfo::KeyOfValue(V);
731 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
732
733 if (ImutInfo::isEqual(K, KCurrent)) {
734 // If both key and value are same, return the original tree.
735 if (ImutInfo::isDataEqual(ImutInfo::DataOfValue(V),
736 ImutInfo::DataOfValue(getValue(T))))
737 return T;
738 // Otherwise create a new node with the new value.
739 return createNode(getLeft(T), V, getRight(T));
740 }
741
742 TreeTy *NewL = getLeft(T);
743 TreeTy *NewR = getRight(T);
744 if (ImutInfo::isLess(K, KCurrent))
745 NewL = add_internal(V, NewL);
746 else
747 NewR = add_internal(V, NewR);
748
749 // If no changes were made, return the original tree. Otherwise, balance the
750 // tree and return the new root.
751 return NewL == getLeft(T) && NewR == getRight(T)
752 ? T
753 : balanceTree(NewL, getValue(T), NewR);
754 }
755
756 /// remove_internal - Creates a new tree that includes all the data
757 /// from the original tree except the specified data. If the
758 /// specified data did not exist in the original tree, the original
759 /// tree is returned.
760 TreeTy *remove_internal(key_type_ref K, TreeTy *T) {
761 if (isEmpty(T))
762 return T;
763
764 assert(!T->isMutable());
765
766 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
767
768 if (ImutInfo::isEqual(K, KCurrent))
769 return combineTrees(getLeft(T), getRight(T));
770
771 TreeTy *NewL = getLeft(T);
772 TreeTy *NewR = getRight(T);
773 if (ImutInfo::isLess(K, KCurrent))
774 NewL = remove_internal(K, NewL);
775 else
776 NewR = remove_internal(K, NewR);
777
778 // If no changes were made, return the original tree. Otherwise, balance the
779 // tree and return the new root.
780 return NewL == getLeft(T) && NewR == getRight(T)
781 ? T
782 : balanceTree(NewL, getValue(T), NewR);
783 }
784
785 TreeTy* combineTrees(TreeTy* L, TreeTy* R) {
786 if (isEmpty(L))
787 return R;
788 if (isEmpty(R))
789 return L;
790 TreeTy* OldNode;
791 TreeTy* newRight = removeMinBinding(R,OldNode);
792 return balanceTree(L, getValue(OldNode), newRight);
793 }
794
795 TreeTy* removeMinBinding(TreeTy* T, TreeTy*& Noderemoved) {
796 assert(!isEmpty(T));
797 if (isEmpty(getLeft(T))) {
798 Noderemoved = T;
799 return getRight(T);
800 }
801 return balanceTree(removeMinBinding(getLeft(T), Noderemoved),
802 getValue(T), getRight(T));
803 }
804
805 template <typename PredFn> TreeTy *filter_internal(TreeTy *T, PredFn &Pred) {
806 if (isEmpty(T))
807 return T;
808 TreeTy *L = filter_internal(getLeft(T), Pred);
809 bool Keep = Pred(getValue(T));
810 TreeTy *R = filter_internal(getRight(T), Pred);
811 if (Keep)
812 return L == getLeft(T) && R == getRight(T) ? T
813 : joinTrees(L, getValue(T), R);
814 if (isEmpty(R))
815 return L;
816 TreeTy *Min;
817 R = removeMinBinding(R, Min);
818 return joinTrees(L, getValue(Min), R);
819 }
820
821public:
822 TreeTy *getCanonicalTree(TreeTy *TNew) {
823 static_assert(Canonicalize,
824 "getCanonicalTree requires a canonicalizing factory");
825 if (!TNew)
826 return nullptr;
827
828 if (TNew->IsCanonicalized)
829 return TNew;
830
831 // Search the hashtable for another tree with the same digest, and
832 // if find a collision compare those trees by their contents.
833 unsigned digest = TNew->computeDigest();
834 TreeTy *&entry = this->Cache[maskCacheIndex(digest)];
835 if (entry) {
836 for (TreeTy *T = entry; T != nullptr; T = T->Next) {
837 // Compare the contents of 'T' with 'TNew'. isEqual skips subtrees that
838 // are shared by pointer, so for structurally-shared persistent trees
839 // (the common case, e.g. one derived from the other) this is linear in
840 // the number of differing nodes rather than in the tree size.
841 if (!TNew->isEqual(*T))
842 continue;
843 // Trees did match! Return 'T'.
844 if (TNew->refCount == 0)
845 TNew->destroy();
846 return T;
847 }
848 entry->Prev = TNew;
849 TNew->Next = entry;
850 }
851
852 entry = TNew;
853 TNew->IsCanonicalized = true;
854 return TNew;
855 }
856};
857
858//===----------------------------------------------------------------------===//
859// Immutable AVL-Tree Iterator.
860//===----------------------------------------------------------------------===//
861
862/// Bidirectional in-order iterator over the nodes of an ImutAVLTree.
863///
864/// The iterator keeps the chain of ancestors from the root down to the current
865/// node on an explicit stack of plain node pointers, and decides which way to
866/// move next by inspecting whether it is ascending from a node's left or right
867/// child. This avoids storing any per-node visit-state: there is no need to
868/// remember "have I already visited this node's left/right subtree", because
869/// that is recovered by comparing the child we just left against the parent's
870/// left and right pointers.
871///
872/// A node's parent cannot be cached in the node itself, because these trees are
873/// persistent and structurally shared: a single node may appear as the child of
874/// different parents across different tree versions. The ancestor stack is
875/// therefore the per-traversal parent chain.
876template <typename ImutInfo, bool Canonicalize>
878public:
879 using iterator_category = std::bidirectional_iterator_tag;
881 using difference_type = std::ptrdiff_t;
884
886
887private:
888 // Path[0] is the root and Path.back() is the current node. An empty path is
889 // the end iterator. The invariant is that Path always holds the exact chain
890 // of ancestors of the current node, root-most first.
892
893 // Descend along left children, pushing each node; lands on the minimum of the
894 // subtree rooted at T (i.e. the first node in an in-order traversal of T).
895 void descendToMin(TreeTy *T) {
896 for (; T; T = T->getLeft())
897 Path.push_back(T);
898 }
899
900 // Descend along right children, pushing each node; lands on the maximum of
901 // the subtree rooted at T (i.e. the last node in an in-order traversal of T).
902 void descendToMax(TreeTy *T) {
903 for (; T; T = T->getRight())
904 Path.push_back(T);
905 }
906
907 // Pop the current node and ascend until we reach an ancestor from its *left*
908 // child, i.e. the first ancestor whose subtree is not yet fully visited. That
909 // ancestor is the in-order successor of the subtree we just left; if there is
910 // none, Path is emptied (the end iterator). Shared by operator++ and
911 // skipSubTree, whose only difference is whether the current node's right
912 // subtree is descended into first.
913 void ascendFromRightChild() {
914 TreeTy *Child = Path.pop_back_val();
915 while (!Path.empty() && Path.back()->getRight() == Child)
916 Child = Path.pop_back_val();
917 }
918
919 // Mirror of ascendFromRightChild for reverse traversal (operator--).
920 void ascendFromLeftChild() {
921 TreeTy *Child = Path.pop_back_val();
922 while (!Path.empty() && Path.back()->getLeft() == Child)
923 Child = Path.pop_back_val();
924 }
925
926public:
927 ImutAVLTreeInOrderIterator() = default; // end() iterator.
929 descendToMin(const_cast<TreeTy *>(Root));
930 }
931
932 // Two iterators are equal iff they sit on the same node (or are both end()).
933 // Within a single tree a node has a unique root-to-node path, so the current
934 // node alone identifies the position; comparing the whole path is therefore
935 // unnecessary. Comparing iterators from different trees is not meaningful, as
936 // for any standard container.
938 if (Path.empty() || x.Path.empty())
939 return Path.empty() == x.Path.empty();
940 return Path.back() == x.Path.back();
941 }
943 return !(*this == x);
944 }
945
946 TreeTy &operator*() const { return *Path.back(); }
947 TreeTy *operator->() const { return Path.back(); }
948
950 assert(!Path.empty() && "Incrementing the end iterator");
951 if (TreeTy *R = Path.back()->getRight())
952 // The in-order successor is the minimum of the right subtree.
953 descendToMin(R);
954 else
955 // No right subtree: the successor is the nearest ancestor reached from a
956 // left child.
957 ascendFromRightChild();
958 return *this;
959 }
960
962 assert(!Path.empty() && "Decrementing the end iterator");
963 if (TreeTy *L = Path.back()->getLeft())
964 // The in-order predecessor is the maximum of the left subtree.
965 descendToMax(L);
966 else
967 // Mirror of operator++.
968 ascendFromLeftChild();
969 return *this;
970 }
971
972 /// Move to the in-order successor of the entire subtree rooted at the current
973 /// node, i.e. skip the current node together with its right subtree. This is
974 /// exactly the ascent half of operator++.
975 void skipSubTree() {
976 assert(!Path.empty() && "Skipping past the end iterator");
977 ascendFromRightChild();
978 }
979};
980
981/// Generic iterator that wraps a T::TreeTy::iterator and exposes
982/// iterator::getValue() on dereference.
983template <typename T>
986 ImutAVLValueIterator<T>, typename T::TreeTy::iterator,
987 typename std::iterator_traits<
988 typename T::TreeTy::iterator>::iterator_category,
989 const typename T::value_type> {
993
995 return this->I->getValue();
996 }
997};
998
999//===----------------------------------------------------------------------===//
1000// Trait classes for Profile information.
1001//===----------------------------------------------------------------------===//
1002
1003/// Generic profile template. The default behavior is to invoke the
1004/// profile method of an object. Specializations for primitive integers
1005/// and generic handling of pointers is done below.
1006template <typename T>
1008 using value_type = const T;
1009 using value_type_ref = const T&;
1010
1014};
1015
1016/// Profile traits for integers.
1017template <typename T>
1019 using value_type = const T;
1020 using value_type_ref = const T&;
1021
1023 ID.AddInteger(X);
1024 }
1025};
1026
1027#define PROFILE_INTEGER_INFO(X)\
1028template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
1029
1031PROFILE_INTEGER_INFO(unsigned char)
1033PROFILE_INTEGER_INFO(unsigned short)
1034PROFILE_INTEGER_INFO(unsigned)
1037PROFILE_INTEGER_INFO(unsigned long)
1038PROFILE_INTEGER_INFO(long long)
1039PROFILE_INTEGER_INFO(unsigned long long)
1040
1041#undef PROFILE_INTEGER_INFO
1042
1043/// Profile traits for booleans.
1044template <>
1046 using value_type = const bool;
1047 using value_type_ref = const bool&;
1048
1050 ID.AddBoolean(X);
1051 }
1052};
1053
1054/// Generic profile trait for pointer types. We treat pointers as
1055/// references to unique objects.
1056template <typename T>
1058 using value_type = const T*;
1060
1062 ID.AddPointer(X);
1063 }
1064};
1065
1066//===----------------------------------------------------------------------===//
1067// Trait classes that contain element comparison operators and type
1068// definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
1069// inherit from the profile traits (ImutProfileInfo) to include operations
1070// for element profiling.
1071//===----------------------------------------------------------------------===//
1072
1073/// Generic definition of comparison operations for elements of immutable
1074/// containers that defaults to using std::equal_to<> and std::less<> to perform
1075/// comparison of elements.
1076template <typename T> struct ImutContainerInfo : ImutProfileInfo<T> {
1083
1086
1088 return std::equal_to<key_type>()(LHS,RHS);
1089 }
1090
1092 return std::less<key_type>()(LHS,RHS);
1093 }
1094
1095 static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
1096};
1097
1098/// Specialization for pointer values to treat pointers as references to unique
1099/// objects. Pointers are thus compared by their addresses.
1100template <typename T> struct ImutContainerInfo<T *> : ImutProfileInfo<T *> {
1107
1110
1111 static bool isEqual(key_type_ref LHS, key_type_ref RHS) { return LHS == RHS; }
1112
1113 static bool isLess(key_type_ref LHS, key_type_ref RHS) { return LHS < RHS; }
1114
1115 static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
1116};
1117
1118//===----------------------------------------------------------------------===//
1119// Immutable Set
1120//===----------------------------------------------------------------------===//
1121
1122template <typename ValT, typename ValInfo = ImutContainerInfo<ValT>,
1123 bool Canonicalize = true>
1125public:
1126 using value_type = typename ValInfo::value_type;
1127 using value_type_ref = typename ValInfo::value_type_ref;
1129
1130private:
1132
1133public:
1134 /// Constructs a set from a pointer to a tree root. In general one
1135 /// should use a Factory object to create sets instead of directly
1136 /// invoking the constructor, but there are cases where make this
1137 /// constructor public is useful.
1138 explicit ImmutableSet(TreeTy *R) : Root(R) {}
1139
1140 class Factory {
1141 typename TreeTy::Factory F;
1142
1143 public:
1144 Factory() = default;
1145
1147
1148 Factory(const Factory& RHS) = delete;
1149 void operator=(const Factory& RHS) = delete;
1150
1151 /// Returns an immutable set that contains no elements.
1153 return ImmutableSet(F.getEmptyTree());
1154 }
1155
1156 /// Creates a new immutable set that contains all of the values
1157 /// of the original set with the addition of the specified value. If
1158 /// the original set already included the value, then the original set is
1159 /// returned and no memory is allocated. The time and space complexity
1160 /// of this operation is logarithmic in the size of the original set.
1161 /// The memory allocated to represent the set is released when the
1162 /// factory object that created the set is destroyed.
1164 TreeTy *NewT = F.add(Old.Root.get(), V);
1165 if constexpr (Canonicalize)
1166 return ImmutableSet(F.getCanonicalTree(NewT));
1167 else
1168 return ImmutableSet(NewT);
1169 }
1170
1171 /// Returns the union of \p A and \p B, computed in a single traversal that
1172 /// shares subtrees of both operands wherever possible (see
1173 /// ImutAVLFactory::unionTrees). This is more efficient than repeatedly
1174 /// adding \p B's elements to \p A when \p B is large.
1176 if (A.Root.get() == B.Root.get() || B.isEmpty())
1177 return A;
1178 if (A.isEmpty())
1179 return B;
1180 // Drive the recursion with the taller tree so the shorter one is the one
1181 // being split.
1182 if (A.getHeight() < B.getHeight())
1183 std::swap(A, B);
1184 if constexpr (Canonicalize) {
1185 // The bulk path does not canonicalize the nodes it creates, so fall
1186 // back to per-element insertion for canonicalizing factories.
1187 for (value_type_ref V : B)
1188 A = add(A, V);
1189 return A;
1190 } else {
1191 return ImmutableSet(F.unionTrees(A.Root.get(), B.Root.get()));
1192 }
1193 }
1194
1195 /// Creates a new immutable set that contains all of the values
1196 /// of the original set with the exception of the specified value. If
1197 /// the original set did not contain the value, the original set is
1198 /// returned and no memory is allocated. The time and space complexity
1199 /// of this operation is logarithmic in the size of the original set.
1200 /// The memory allocated to represent the set is released when the
1201 /// factory object that created the set is destroyed.
1203 TreeTy *NewT = F.remove(Old.Root.get(), V);
1204 if constexpr (Canonicalize)
1205 return ImmutableSet(F.getCanonicalTree(NewT));
1206 else
1207 return ImmutableSet(NewT);
1208 }
1209
1210 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
1211
1213 return const_cast<typename TreeTy::Factory *>(&F);
1214 }
1215 };
1216
1217 friend class Factory;
1218
1219 /// Returns true if the set contains the specified value.
1221 return Root ? Root->contains(V) : false;
1222 }
1223
1224 /// Compares two sets for equality. For a canonicalizing factory, sets with
1225 /// equal contents share the same tree, so this is an O(1) pointer comparison
1226 /// (like ImmutableList); only sets created by the same factory may be
1227 /// compared. Otherwise it is a structural comparison.
1228 bool operator==(const ImmutableSet &RHS) const {
1229 if constexpr (Canonicalize)
1230 return Root == RHS.Root;
1231 else
1232 return Root && RHS.Root ? Root->isEqual(*RHS.Root.get())
1233 : Root == RHS.Root;
1234 }
1235
1236 bool operator!=(const ImmutableSet &RHS) const {
1237 if constexpr (Canonicalize)
1238 return Root != RHS.Root;
1239 else
1240 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root.get())
1241 : Root != RHS.Root;
1242 }
1243
1245 if (Root) { Root->retain(); }
1246 return Root.get();
1247 }
1248
1249 TreeTy *getRootWithoutRetain() const { return Root.get(); }
1250
1251 /// Return true if the set contains no elements.
1252 bool isEmpty() const { return !Root; }
1253
1254 /// Return true if the set contains exactly one element.
1255 /// This method runs in constant time.
1256 bool isSingleton() const { return getHeight() == 1; }
1257
1258 //===--------------------------------------------------===//
1259 // Iterators.
1260 //===--------------------------------------------------===//
1261
1263
1264 iterator begin() const { return iterator(Root.get()); }
1265 iterator end() const { return iterator(); }
1266
1267 //===--------------------------------------------------===//
1268 // Utility methods.
1269 //===--------------------------------------------------===//
1270
1271 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1272
1273 static void Profile(FoldingSetNodeID &ID, const ImmutableSet &S) {
1274 ID.AddPointer(S.Root.get());
1275 }
1276
1277 void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
1278
1279 //===--------------------------------------------------===//
1280 // For testing.
1281 //===--------------------------------------------------===//
1282
1283 void validateTree() const { if (Root) Root->validateTree(); }
1284};
1285
1286// NOTE: This may some day replace the current ImmutableSet.
1287template <typename ValT, typename ValInfo = ImutContainerInfo<ValT>,
1288 bool Canonicalize = true>
1290public:
1291 using value_type = typename ValInfo::value_type;
1292 using value_type_ref = typename ValInfo::value_type_ref;
1294 using FactoryTy = typename TreeTy::Factory;
1295
1296private:
1298 FactoryTy *Factory;
1299
1300public:
1301 /// Constructs a set from a pointer to a tree root. In general one
1302 /// should use a Factory object to create sets instead of directly
1303 /// invoking the constructor, but there are cases where make this
1304 /// constructor public is useful.
1305 ImmutableSetRef(TreeTy *R, FactoryTy *F) : Root(R), Factory(F) {}
1306
1308 return ImmutableSetRef(0, F);
1309 }
1310
1312 return ImmutableSetRef(Factory->add(Root.get(), V), Factory);
1313 }
1314
1316 return ImmutableSetRef(Factory->remove(Root.get(), V), Factory);
1317 }
1318
1319 /// Returns true if the set contains the specified value.
1321 return Root ? Root->contains(V) : false;
1322 }
1323
1326 if constexpr (Canonicalize)
1327 return SetTy(Factory->getCanonicalTree(Root.get()));
1328 else
1329 return SetTy(Root.get());
1330 }
1331
1332 TreeTy *getRootWithoutRetain() const { return Root.get(); }
1333
1334 bool operator==(const ImmutableSetRef &RHS) const {
1335 return Root && RHS.Root ? Root->isEqual(*RHS.Root.get()) : Root == RHS.Root;
1336 }
1337
1338 bool operator!=(const ImmutableSetRef &RHS) const {
1339 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root.get())
1340 : Root != RHS.Root;
1341 }
1342
1343 /// Return true if the set contains no elements.
1344 bool isEmpty() const { return !Root; }
1345
1346 /// Return true if the set contains exactly one element.
1347 /// This method runs in constant time.
1348 bool isSingleton() const { return getHeight() == 1; }
1349
1350 //===--------------------------------------------------===//
1351 // Iterators.
1352 //===--------------------------------------------------===//
1353
1355
1356 iterator begin() const { return iterator(Root.get()); }
1357 iterator end() const { return iterator(); }
1358
1359 //===--------------------------------------------------===//
1360 // Utility methods.
1361 //===--------------------------------------------------===//
1362
1363 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1364
1365 static void Profile(FoldingSetNodeID &ID, const ImmutableSetRef &S) {
1366 ID.AddPointer(S.Root.get());
1367 }
1368
1369 void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
1370
1371 //===--------------------------------------------------===//
1372 // For testing.
1373 //===--------------------------------------------------===//
1374
1375 void validateTree() const { if (Root) Root->validateTree(); }
1376};
1377
1378} // end namespace llvm
1379
1380#endif // LLVM_ADT_IMMUTABLESET_H
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Uniform Intrinsic Combine
This file defines the BumpPtrAllocator interface.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
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")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_PREFERRED_TYPE(T)
\macro LLVM_PREFERRED_TYPE Adjust type of bit-field in debug info.
Definition Compiler.h:770
#define LLVM_NO_UNIQUE_ADDRESS
Definition Compiler.h:493
#define LLVM_ATTRIBUTE_NOINLINE
LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, mark a method "not for inl...
Definition Compiler.h:366
#define LLVM_ATTRIBUTE_WARN_UNUSED
Definition Compiler.h:240
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:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
if(PassOpts->AAPipeline)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
Value * RHS
Value * LHS
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
unsigned getHeight() const
bool operator==(const ImmutableSetRef &RHS) const
ImmutableSet< ValT, ValInfo, Canonicalize > asImmutableSet() const
ImutAVLTree< ValInfo, Canonicalize > TreeTy
bool contains(value_type_ref V) const
Returns true if the set contains the specified value.
bool operator!=(const ImmutableSetRef &RHS) const
typename ValInfo::value_type_ref value_type_ref
ImmutableSetRef(TreeTy *R, FactoryTy *F)
Constructs a set from a pointer to a tree root.
void Profile(FoldingSetNodeID &ID) const
bool isEmpty() const
Return true if the set contains no elements.
iterator end() const
TreeTy * getRootWithoutRetain() const
void validateTree() const
typename TreeTy::Factory FactoryTy
static ImmutableSetRef getEmptySet(FactoryTy *F)
ImmutableSetRef remove(value_type_ref V)
typename ValInfo::value_type value_type
iterator begin() const
ImutAVLValueIterator< ImmutableSetRef > iterator
static void Profile(FoldingSetNodeID &ID, const ImmutableSetRef &S)
bool isSingleton() const
Return true if the set contains exactly one element.
ImmutableSetRef add(value_type_ref V)
ImmutableSet unionSets(ImmutableSet A, ImmutableSet B)
Returns the union of A and B, computed in a single traversal that shares subtrees of both operands wh...
Factory(BumpPtrAllocator &Alloc)
void operator=(const Factory &RHS)=delete
ImmutableSet add(ImmutableSet Old, value_type_ref V)
Creates a new immutable set that contains all of the values of the original set with the addition of ...
BumpPtrAllocator & getAllocator()
Factory(const Factory &RHS)=delete
ImmutableSet remove(ImmutableSet Old, value_type_ref V)
Creates a new immutable set that contains all of the values of the original set with the exception of...
ImmutableSet getEmptySet()
Returns an immutable set that contains no elements.
TreeTy::Factory * getTreeFactory() const
TreeTy * getRootWithoutRetain() const
bool isEmpty() const
Return true if the set contains no elements.
bool isSingleton() const
Return true if the set contains exactly one element.
static void Profile(FoldingSetNodeID &ID, const ImmutableSet &S)
bool contains(value_type_ref V) const
Returns true if the set contains the specified value.
iterator end() const
ImutAVLTree< ValInfo, Canonicalize > TreeTy
ImmutableSet(TreeTy *R)
Constructs a set from a pointer to a tree root.
bool operator!=(const ImmutableSet &RHS) const
iterator begin() const
typename ValInfo::value_type_ref value_type_ref
unsigned getHeight() const
ImutAVLValueIterator< ImmutableSet > iterator
bool operator==(const ImmutableSet &RHS) const
Compares two sets for equality.
void validateTree() const
void Profile(FoldingSetNodeID &ID) const
typename ValInfo::value_type value_type
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...
ImutAVLFactory(BumpPtrAllocator &Alloc)
TreeTy * filter_internal(TreeTy *T, PredFn &Pred)
unsigned incrementHeight(TreeTy *L, TreeTy *R) const
TreeTy * remove(TreeTy *T, key_type_ref V)
TreeTy * getLeft(TreeTy *T) const
TreeTy * transformTree(TreeTy *T, CombineFn &Combine, bool FromB)
Rebuilds T with the same shape but each element replaced by Combine applied to it.
TreeTy * mergeTrees(TreeTy *A, TreeTy *B, CombineFn Combine, bool KeepUnmatched, bool SkipShared=false)
Merges A and B in a single traversal, sharing every subtree that the two operands do not overlap.
TreeTy * getEmptyTree() const
TreeTy * createNode(TreeTy *newLeft, TreeTy *oldTree, TreeTy *newRight)
unsigned getHeight(TreeTy *T) const
value_type_ref getValue(TreeTy *T) const
TreeTy * joinTrees(TreeTy *L, value_type_ref V, TreeTy *R)
Combines L and R with the value V (every key in L less than V, every key in R greater) into one balan...
bool isEmpty(TreeTy *T) const
TreeTy * combineTrees(TreeTy *L, TreeTy *R)
TreeTy * filterTree(TreeTy *T, PredFn Pred)
Returns the tree of the elements of T for which Pred holds.
TreeTy * balanceTree(TreeTy *L, value_type_ref V, TreeTy *R)
Used by add_internal and remove_internal to balance a newly created tree.
void recoverNodes(TreeTy *Result)
TreeTy * add(TreeTy *T, value_type_ref V)
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 * getCanonicalTree(TreeTy *TNew)
TreeTy * removeMinBinding(TreeTy *T, TreeTy *&Noderemoved)
TreeTy * unionTrees(TreeTy *A, TreeTy *B)
Returns the set union of A and B (keeping A's element on matching keys).
void splitLookup(TreeTy *T, key_type_ref K, TreeTy *&L, const value_type *&Match, TreeTy *&R)
Splits T into L (all keys less than K) and R (all keys greater than K).
TreeTy * getRight(TreeTy *T) const
TreeTy * merge_internal(TreeTy *A, TreeTy *B, CombineFn &Combine, bool KeepUnmatched, bool SkipShared)
Merges A and B by recursing over A's structure and splitting B at each of A's keys.
TreeTy * createNode(TreeTy *L, value_type_ref V, TreeTy *R)
static unsigned maskCacheIndex(unsigned I)
Bidirectional in-order iterator over the nodes of an ImutAVLTree.
bool operator!=(const ImutAVLTreeInOrderIterator &x) const
ImutAVLTree< ImutInfo, Canonicalize > value_type
ImutAVLTree< ImutInfo, Canonicalize > TreeTy
ImutAVLTreeInOrderIterator & operator++()
void skipSubTree()
Move to the in-order successor of the entire subtree rooted at the current node, i....
ImutAVLTreeInOrderIterator & operator--()
std::bidirectional_iterator_tag iterator_category
bool operator==(const ImutAVLTreeInOrderIterator &x) const
ImutAVLTreeInOrderIterator(const TreeTy *Root)
unsigned getHeight() const
Returns the height of the tree. A tree with no subtrees has a height of 1.
iterator end() const
Returns an iterator for the tree that denotes the end of an inorder traversal.
typename ValInfo::key_type_ref key_type_ref
ImutAVLTreeInOrderIterator< ValInfo, Canonicalize > iterator
ImutAVLTree * find(key_type_ref K)
Finds the subtree associated with the specified key value.
typename ValInfo::value_type value_type
bool isNotEqual(const ImutAVLTree &RHS) const
Compares two trees for structural inequality.
bool contains(key_type_ref K)
Returns true if this tree contains a subtree (node) that has an data element that matches the specifi...
unsigned size() const
Returns the number of nodes in the tree, which includes both leaves and.
ImutAVLTree * getRight() const
Return a pointer to the right subtree.
ImutAVLTree * getMaxElement()
Find the subtree associated with the highest ranged key value.
ImutAVLFactory< ValInfo, Canonicalize > Factory
bool isElementEqual(const ImutAVLTree *RHS) const
LLVM_ATTRIBUTE_NOINLINE void destroy()
bool isEqual(const ImutAVLTree &RHS) const
Compares two trees for structural equality and returns true if they are equal.
unsigned validateTree() const
A utility method that checks that the balancing and ordering invariants of the tree are satisfied.
const value_type & getValue() const
Returns the data value associated with the tree node.
bool isElementEqual(value_type_ref V) const
typename ValInfo::value_type_ref value_type_ref
iterator begin() const
Returns an iterator that iterates over the nodes of the tree in an inorder traversal.
ImutAVLTree * getLeft() const
Return a pointer to the left subtree.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This is an optimization pass for GlobalISel generic memory operations.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
@ Keep
No function return thunk.
Definition CodeGen.h:370
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
static void Profile(const T &X, FoldingSetNodeID &ID)
Definition FoldingSet.h:235
The factory-side canonicalization cache: digest -> tree chain.
DenseMap< unsigned, Tree * > Cache
The cached structural digest, used only for canonicalization.
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)
Generic definition of comparison operations for elements of immutable containers that defaults to usi...
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, Canonicalize > *Tree)
Class you can specialize to provide custom retain/release functionality for a type.