14#ifndef LLVM_ADT_IMMUTABLESET_H
15#define LLVM_ADT_IMMUTABLESET_H
41template <
typename ImutInfo,
bool Canonicalize = true>
class ImutAVLFactory;
42template <
typename ImutInfo,
bool Canonicalize = true>
74template <
typename ImutInfo,
bool Canonicalize = true>
94 ImutAVLTree *
getLeft()
const {
return left; }
98 ImutAVLTree *
getRight()
const {
return right; }
109 ImutAVLTree *
T =
this;
111 key_type_ref CurrentKey = ImutInfo::KeyOfValue(
T->getValue());
112 if (ImutInfo::isEqual(
K,CurrentKey))
114 else if (ImutInfo::isLess(
K,CurrentKey))
124 ImutAVLTree *
T =
this;
125 ImutAVLTree *
Right =
T->getRight();
134 if (
const ImutAVLTree* L =
getLeft())
136 if (
const ImutAVLTree* R =
getRight())
152 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(
getValue()),
153 ImutInfo::KeyOfValue(
V)))
157 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(
getValue()),
158 ImutInfo::DataOfValue(
V)))
178 while (LItr != LEnd && RItr != REnd) {
179 if (&*LItr == &*RItr) {
192 return LItr == LEnd && RItr == REnd;
216 &&
"Height calculation wrong");
218 assert((HL > HR ? HL-HR : HR-HL) <= 2
219 &&
"Balancing invariant violated");
223 ImutInfo::KeyOfValue(
getValue()))) &&
224 "Value in left child is not less that current value");
227 ImutInfo::isLess(ImutInfo::KeyOfValue(
getValue()),
229 "Current value is not less that value of right child");
245 unsigned height : 28;
247 unsigned IsMutable : 1;
249 unsigned IsDigestCached : 1;
251 unsigned IsCanonicalized : 1;
266 : left(l), right(r), height(height), IsMutable(
true),
267 IsDigestCached(
false), IsCanonicalized(
false), value(v), factory(f) {
278 bool isMutable()
const {
return IsMutable; }
282 bool hasCachedDigest()
const {
return IsDigestCached; }
297 void markImmutable() {
298 assert(isMutable() &&
"Mutable flag already removed.");
303 void markedCachedDigest() {
304 assert(!hasCachedDigest() &&
"NoCachedDigest flag already removed.");
305 IsDigestCached =
true;
309 void setHeight(
unsigned h) {
310 assert(isMutable() &&
"Only a mutable tree can have its height changed.");
314 static uint32_t computeDigest(ImutAVLTree *L, ImutAVLTree *R,
319 digest +=
L->computeDigest();
323 ImutInfo::Profile(ID,
V);
324 digest +=
ID.computeHash();
327 digest +=
R->computeDigest();
332 uint32_t computeDigest() {
335 if (hasCachedDigest())
336 return digest.Digest;
340 markedCachedDigest();
362 if constexpr (Canonicalize) {
363 if (IsCanonicalized) {
370 factory->Cache[factory->maskCacheIndex(computeDigest())] = this->
Next;
377 factory->freeNodes.push_back(
this);
381template <
typename ImutInfo,
bool Canonicalize>
395template <
typename ImutInfo,
bool Canonicalize>
407 std::vector<TreeTy*> createdNodes;
408 std::vector<TreeTy*> freeNodes;
410 bool ownsAllocator()
const {
411 return (Allocator & 0x1) == 0;
430 if (ownsAllocator())
delete &getAllocator();
433 TreeTy*
add(TreeTy*
T, value_type_ref
V) {
449 template <
typename CombineFn>
451 bool KeepUnmatched,
bool SkipShared =
false) {
462 auto KeepFirst = [](
const value_type *L,
463 const value_type *R) ->
const value_type & {
490 TreeTy*
getLeft(TreeTy*
T)
const {
return T->getLeft(); }
492 value_type_ref
getValue(TreeTy*
T)
const {
return T->value; }
500 return (hl > hr ? hl : hr) + 1;
516 if (!freeNodes.empty()) {
517 T = freeNodes.back();
518 freeNodes.pop_back();
522 T = (TreeTy*)
A.Allocate<TreeTy>();
525 createdNodes.push_back(
T);
529 TreeTy*
createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
543 if (
N != Result &&
N->refCount == 0)
548 createdNodes.clear();
557 assert(!
isEmpty(L) &&
"Left tree cannot be empty to have a height >= 2");
565 assert(!
isEmpty(LR) &&
"LR cannot be empty because it has a height >= 1");
574 assert(!
isEmpty(R) &&
"Right tree cannot be empty to have a height >= 2");
582 assert(!
isEmpty(RL) &&
"RL cannot be empty because it has a height >= 1");
610 const value_type *&Match, TreeTy *&R) {
616 key_type_ref KCurrent = ImutInfo::KeyOfValue(
getValue(
T));
617 if (ImutInfo::isEqual(
K, KCurrent)) {
623 Match = &
T->getValue();
624 }
else if (ImutInfo::isLess(
K, KCurrent)) {
638 template <
typename CombineFn>
658 template <
typename CombineFn>
660 bool KeepUnmatched,
bool SkipShared) {
665 if (SkipShared &&
A ==
B)
674 const value_type *BMatch;
675 splitLookup(
B, ImutInfo::KeyOfValue(AElem), BL, BMatch, BR);
694 auto NewElem =
Combine(&AElem, BMatch);
696 ImutInfo::isDataEqual(ImutInfo::DataOfValue(NewElem),
697 ImutInfo::DataOfValue(AElem)))
710 key_type_ref
K = ImutInfo::KeyOfValue(
V);
711 key_type_ref KCurrent = ImutInfo::KeyOfValue(
getValue(
T));
713 if (ImutInfo::isEqual(
K, KCurrent)) {
715 if (ImutInfo::isDataEqual(ImutInfo::DataOfValue(
V),
724 if (ImutInfo::isLess(
K, KCurrent))
746 key_type_ref KCurrent = ImutInfo::KeyOfValue(
getValue(
T));
748 if (ImutInfo::isEqual(
K, KCurrent))
753 if (ImutInfo::isLess(
K, KCurrent))
787 static_assert(Canonicalize,
788 "getCanonicalTree requires a canonicalizing factory");
792 if (TNew->IsCanonicalized)
797 unsigned digest = TNew->computeDigest();
800 for (TreeTy *
T = entry;
T !=
nullptr;
T =
T->Next) {
808 if (TNew->refCount == 0)
817 TNew->IsCanonicalized =
true;
840template <
typename ImutInfo,
bool Canonicalize>
860 for (;
T;
T =
T->getLeft())
867 for (;
T;
T =
T->getRight())
877 void ascendFromRightChild() {
878 TreeTy *Child = Path.pop_back_val();
879 while (!Path.empty() && Path.back()->getRight() == Child)
880 Child = Path.pop_back_val();
884 void ascendFromLeftChild() {
885 TreeTy *Child = Path.pop_back_val();
886 while (!Path.empty() && Path.back()->getLeft() == Child)
887 Child = Path.pop_back_val();
893 descendToMin(
const_cast<TreeTy *
>(Root));
902 if (Path.empty() || x.Path.empty())
903 return Path.empty() == x.Path.empty();
904 return Path.back() == x.Path.back();
907 return !(*
this == x);
914 assert(!Path.empty() &&
"Incrementing the end iterator");
915 if (
TreeTy *R = Path.back()->getRight())
921 ascendFromRightChild();
926 assert(!Path.empty() &&
"Decrementing the end iterator");
927 if (
TreeTy *L = Path.back()->getLeft())
932 ascendFromLeftChild();
940 assert(!Path.empty() &&
"Skipping past the end iterator");
941 ascendFromRightChild();
950 ImutAVLValueIterator<T>, typename T::TreeTy::iterator,
951 typename std::iterator_traits<
952 typename T::TreeTy::iterator>::iterator_category,
953 const typename T::value_type> {
959 return this->
I->getValue();
991#define PROFILE_INTEGER_INFO(X)\
992template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
1005#undef PROFILE_INTEGER_INFO
1020template <
typename T>
1052 return std::equal_to<key_type>()(
LHS,
RHS);
1056 return std::less<key_type>()(
LHS,
RHS);
1086template <
typename ValT,
typename ValInfo = ImutContainerInfo<ValT>,
1087 bool Canonicalize = true>
1128 TreeTy *NewT = F.add(Old.Root.get(),
V);
1129 if constexpr (Canonicalize)
1140 if (
A.Root.get() ==
B.Root.get() ||
B.isEmpty())
1146 if (
A.getHeight() <
B.getHeight())
1148 if constexpr (Canonicalize) {
1167 TreeTy *NewT = F.remove(Old.Root.get(),
V);
1168 if constexpr (Canonicalize)
1185 return Root ? Root->contains(
V) :
false;
1193 if constexpr (Canonicalize)
1194 return Root ==
RHS.Root;
1196 return Root &&
RHS.Root ? Root->isEqual(*
RHS.Root.get())
1201 if constexpr (Canonicalize)
1202 return Root !=
RHS.Root;
1204 return Root &&
RHS.Root ? Root->isNotEqual(*
RHS.Root.get())
1209 if (Root) { Root->retain(); }
1235 unsigned getHeight()
const {
return Root ? Root->getHeight() : 0; }
1238 ID.AddPointer(S.Root.get());
1251template <
typename ValT,
typename ValInfo = ImutContainerInfo<ValT>,
1252 bool Canonicalize = true>
1285 return Root ? Root->contains(
V) :
false;
1290 if constexpr (Canonicalize)
1291 return SetTy(Factory->getCanonicalTree(Root.get()));
1293 return SetTy(Root.get());
1299 return Root &&
RHS.Root ? Root->isEqual(*
RHS.Root.get()) : Root ==
RHS.Root;
1303 return Root &&
RHS.Root ? Root->isNotEqual(*
RHS.Root.get())
1327 unsigned getHeight()
const {
return Root ? Root->getHeight() : 0; }
1330 ID.AddPointer(S.Root.get());
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")
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.
#define LLVM_NO_UNIQUE_ADDRESS
#define LLVM_ATTRIBUTE_NOINLINE
LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, mark a method "not for inl...
#define LLVM_ATTRIBUTE_WARN_UNUSED
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.
This file defines the SmallVector class.
This class is used to gather all the unique data bits of a node.
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.
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
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.
ImutAVLTree< ValInfo, Canonicalize > TreeTy
ImmutableSet(TreeTy *R)
Constructs a set from a pointer to a tree root.
bool operator!=(const ImmutableSet &RHS) 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)
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 * 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++()
TreeTy & operator*() const
void skipSubTree()
Move to the in-order successor of the entire subtree rooted at the current node, i....
ImutAVLTreeInOrderIterator & operator--()
ImutAVLTreeInOrderIterator()=default
std::ptrdiff_t difference_type
TreeTy * operator->() const
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.
iterator_adaptor_base()=default
This is an optimization pass for GlobalISel generic memory operations.
auto reverse(ContainerTy &&C)
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static void Profile(const T &X, FoldingSetNodeID &ID)
The factory-side canonicalization cache: digest -> tree chain.
DenseMap< unsigned, Tree * > Cache
The cached structural digest, used only for canonicalization.
The intrusive doubly-linked chain of same-digest trees in the factory's canonicalization cache.
Generic iterator that wraps a T::TreeTy::iterator and exposes iterator::getValue() on dereference.
ImutAVLValueIterator()=default
ImutAVLValueIterator::reference operator*() const
ImutAVLValueIterator(typename T::TreeTy *Tree)
static bool isDataEqual(data_type_ref, data_type_ref)
value_type_ref key_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)
value_type value_type_ref
const bool & value_type_ref
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.