ImmutableSet.h 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===--- ImmutableSet.h - Immutable (functional) set interface --*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file defines the ImutAVLTree and ImmutableSet classes.
  16. ///
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_ADT_IMMUTABLESET_H
  19. #define LLVM_ADT_IMMUTABLESET_H
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/FoldingSet.h"
  22. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/iterator.h"
  25. #include "llvm/Support/Allocator.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include <cassert>
  28. #include <cstdint>
  29. #include <functional>
  30. #include <iterator>
  31. #include <new>
  32. #include <vector>
  33. namespace llvm {
  34. //===----------------------------------------------------------------------===//
  35. // Immutable AVL-Tree Definition.
  36. //===----------------------------------------------------------------------===//
  37. template <typename ImutInfo> class ImutAVLFactory;
  38. template <typename ImutInfo> class ImutIntervalAVLFactory;
  39. template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
  40. template <typename ImutInfo> class ImutAVLTreeGenericIterator;
  41. template <typename ImutInfo >
  42. class ImutAVLTree {
  43. public:
  44. using key_type_ref = typename ImutInfo::key_type_ref;
  45. using value_type = typename ImutInfo::value_type;
  46. using value_type_ref = typename ImutInfo::value_type_ref;
  47. using Factory = ImutAVLFactory<ImutInfo>;
  48. using iterator = ImutAVLTreeInOrderIterator<ImutInfo>;
  49. friend class ImutAVLFactory<ImutInfo>;
  50. friend class ImutIntervalAVLFactory<ImutInfo>;
  51. friend class ImutAVLTreeGenericIterator<ImutInfo>;
  52. //===----------------------------------------------------===//
  53. // Public Interface.
  54. //===----------------------------------------------------===//
  55. /// Return a pointer to the left subtree. This value
  56. /// is NULL if there is no left subtree.
  57. ImutAVLTree *getLeft() const { return left; }
  58. /// Return a pointer to the right subtree. This value is
  59. /// NULL if there is no right subtree.
  60. ImutAVLTree *getRight() const { return right; }
  61. /// getHeight - Returns the height of the tree. A tree with no subtrees
  62. /// has a height of 1.
  63. unsigned getHeight() const { return height; }
  64. /// getValue - Returns the data value associated with the tree node.
  65. const value_type& getValue() const { return value; }
  66. /// find - Finds the subtree associated with the specified key value.
  67. /// This method returns NULL if no matching subtree is found.
  68. ImutAVLTree* find(key_type_ref K) {
  69. ImutAVLTree *T = this;
  70. while (T) {
  71. key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
  72. if (ImutInfo::isEqual(K,CurrentKey))
  73. return T;
  74. else if (ImutInfo::isLess(K,CurrentKey))
  75. T = T->getLeft();
  76. else
  77. T = T->getRight();
  78. }
  79. return nullptr;
  80. }
  81. /// getMaxElement - Find the subtree associated with the highest ranged
  82. /// key value.
  83. ImutAVLTree* getMaxElement() {
  84. ImutAVLTree *T = this;
  85. ImutAVLTree *Right = T->getRight();
  86. while (Right) { T = Right; Right = T->getRight(); }
  87. return T;
  88. }
  89. /// size - Returns the number of nodes in the tree, which includes
  90. /// both leaves and non-leaf nodes.
  91. unsigned size() const {
  92. unsigned n = 1;
  93. if (const ImutAVLTree* L = getLeft())
  94. n += L->size();
  95. if (const ImutAVLTree* R = getRight())
  96. n += R->size();
  97. return n;
  98. }
  99. /// begin - Returns an iterator that iterates over the nodes of the tree
  100. /// in an inorder traversal. The returned iterator thus refers to the
  101. /// the tree node with the minimum data element.
  102. iterator begin() const { return iterator(this); }
  103. /// end - Returns an iterator for the tree that denotes the end of an
  104. /// inorder traversal.
  105. iterator end() const { return iterator(); }
  106. bool isElementEqual(value_type_ref V) const {
  107. // Compare the keys.
  108. if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
  109. ImutInfo::KeyOfValue(V)))
  110. return false;
  111. // Also compare the data values.
  112. if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
  113. ImutInfo::DataOfValue(V)))
  114. return false;
  115. return true;
  116. }
  117. bool isElementEqual(const ImutAVLTree* RHS) const {
  118. return isElementEqual(RHS->getValue());
  119. }
  120. /// isEqual - Compares two trees for structural equality and returns true
  121. /// if they are equal. This worst case performance of this operation is
  122. // linear in the sizes of the trees.
  123. bool isEqual(const ImutAVLTree& RHS) const {
  124. if (&RHS == this)
  125. return true;
  126. iterator LItr = begin(), LEnd = end();
  127. iterator RItr = RHS.begin(), REnd = RHS.end();
  128. while (LItr != LEnd && RItr != REnd) {
  129. if (&*LItr == &*RItr) {
  130. LItr.skipSubTree();
  131. RItr.skipSubTree();
  132. continue;
  133. }
  134. if (!LItr->isElementEqual(&*RItr))
  135. return false;
  136. ++LItr;
  137. ++RItr;
  138. }
  139. return LItr == LEnd && RItr == REnd;
  140. }
  141. /// isNotEqual - Compares two trees for structural inequality. Performance
  142. /// is the same is isEqual.
  143. bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
  144. /// contains - Returns true if this tree contains a subtree (node) that
  145. /// has an data element that matches the specified key. Complexity
  146. /// is logarithmic in the size of the tree.
  147. bool contains(key_type_ref K) { return (bool) find(K); }
  148. /// validateTree - A utility method that checks that the balancing and
  149. /// ordering invariants of the tree are satisfied. It is a recursive
  150. /// method that returns the height of the tree, which is then consumed
  151. /// by the enclosing validateTree call. External callers should ignore the
  152. /// return value. An invalid tree will cause an assertion to fire in
  153. /// a debug build.
  154. unsigned validateTree() const {
  155. unsigned HL = getLeft() ? getLeft()->validateTree() : 0;
  156. unsigned HR = getRight() ? getRight()->validateTree() : 0;
  157. (void) HL;
  158. (void) HR;
  159. assert(getHeight() == ( HL > HR ? HL : HR ) + 1
  160. && "Height calculation wrong");
  161. assert((HL > HR ? HL-HR : HR-HL) <= 2
  162. && "Balancing invariant violated");
  163. assert((!getLeft() ||
  164. ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
  165. ImutInfo::KeyOfValue(getValue()))) &&
  166. "Value in left child is not less that current value");
  167. assert((!getRight() ||
  168. ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
  169. ImutInfo::KeyOfValue(getRight()->getValue()))) &&
  170. "Current value is not less that value of right child");
  171. return getHeight();
  172. }
  173. //===----------------------------------------------------===//
  174. // Internal values.
  175. //===----------------------------------------------------===//
  176. private:
  177. Factory *factory;
  178. ImutAVLTree *left;
  179. ImutAVLTree *right;
  180. ImutAVLTree *prev = nullptr;
  181. ImutAVLTree *next = nullptr;
  182. unsigned height : 28;
  183. bool IsMutable : 1;
  184. bool IsDigestCached : 1;
  185. bool IsCanonicalized : 1;
  186. value_type value;
  187. uint32_t digest = 0;
  188. uint32_t refCount = 0;
  189. //===----------------------------------------------------===//
  190. // Internal methods (node manipulation; used by Factory).
  191. //===----------------------------------------------------===//
  192. private:
  193. /// ImutAVLTree - Internal constructor that is only called by
  194. /// ImutAVLFactory.
  195. ImutAVLTree(Factory *f, ImutAVLTree* l, ImutAVLTree* r, value_type_ref v,
  196. unsigned height)
  197. : factory(f), left(l), right(r), height(height), IsMutable(true),
  198. IsDigestCached(false), IsCanonicalized(false), value(v)
  199. {
  200. if (left) left->retain();
  201. if (right) right->retain();
  202. }
  203. /// isMutable - Returns true if the left and right subtree references
  204. /// (as well as height) can be changed. If this method returns false,
  205. /// the tree is truly immutable. Trees returned from an ImutAVLFactory
  206. /// object should always have this method return true. Further, if this
  207. /// method returns false for an instance of ImutAVLTree, all subtrees
  208. /// will also have this method return false. The converse is not true.
  209. bool isMutable() const { return IsMutable; }
  210. /// hasCachedDigest - Returns true if the digest for this tree is cached.
  211. /// This can only be true if the tree is immutable.
  212. bool hasCachedDigest() const { return IsDigestCached; }
  213. //===----------------------------------------------------===//
  214. // Mutating operations. A tree root can be manipulated as
  215. // long as its reference has not "escaped" from internal
  216. // methods of a factory object (see below). When a tree
  217. // pointer is externally viewable by client code, the
  218. // internal "mutable bit" is cleared to mark the tree
  219. // immutable. Note that a tree that still has its mutable
  220. // bit set may have children (subtrees) that are themselves
  221. // immutable.
  222. //===----------------------------------------------------===//
  223. /// markImmutable - Clears the mutable flag for a tree. After this happens,
  224. /// it is an error to call setLeft(), setRight(), and setHeight().
  225. void markImmutable() {
  226. assert(isMutable() && "Mutable flag already removed.");
  227. IsMutable = false;
  228. }
  229. /// markedCachedDigest - Clears the NoCachedDigest flag for a tree.
  230. void markedCachedDigest() {
  231. assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
  232. IsDigestCached = true;
  233. }
  234. /// setHeight - Changes the height of the tree. Used internally by
  235. /// ImutAVLFactory.
  236. void setHeight(unsigned h) {
  237. assert(isMutable() && "Only a mutable tree can have its height changed.");
  238. height = h;
  239. }
  240. static uint32_t computeDigest(ImutAVLTree *L, ImutAVLTree *R,
  241. value_type_ref V) {
  242. uint32_t digest = 0;
  243. if (L)
  244. digest += L->computeDigest();
  245. // Compute digest of stored data.
  246. FoldingSetNodeID ID;
  247. ImutInfo::Profile(ID,V);
  248. digest += ID.ComputeHash();
  249. if (R)
  250. digest += R->computeDigest();
  251. return digest;
  252. }
  253. uint32_t computeDigest() {
  254. // Check the lowest bit to determine if digest has actually been
  255. // pre-computed.
  256. if (hasCachedDigest())
  257. return digest;
  258. uint32_t X = computeDigest(getLeft(), getRight(), getValue());
  259. digest = X;
  260. markedCachedDigest();
  261. return X;
  262. }
  263. //===----------------------------------------------------===//
  264. // Reference count operations.
  265. //===----------------------------------------------------===//
  266. public:
  267. void retain() { ++refCount; }
  268. void release() {
  269. assert(refCount > 0);
  270. if (--refCount == 0)
  271. destroy();
  272. }
  273. void destroy() {
  274. if (left)
  275. left->release();
  276. if (right)
  277. right->release();
  278. if (IsCanonicalized) {
  279. if (next)
  280. next->prev = prev;
  281. if (prev)
  282. prev->next = next;
  283. else
  284. factory->Cache[factory->maskCacheIndex(computeDigest())] = next;
  285. }
  286. // We need to clear the mutability bit in case we are
  287. // destroying the node as part of a sweep in ImutAVLFactory::recoverNodes().
  288. IsMutable = false;
  289. factory->freeNodes.push_back(this);
  290. }
  291. };
  292. template <typename ImutInfo>
  293. struct IntrusiveRefCntPtrInfo<ImutAVLTree<ImutInfo>> {
  294. static void retain(ImutAVLTree<ImutInfo> *Tree) { Tree->retain(); }
  295. static void release(ImutAVLTree<ImutInfo> *Tree) { Tree->release(); }
  296. };
  297. //===----------------------------------------------------------------------===//
  298. // Immutable AVL-Tree Factory class.
  299. //===----------------------------------------------------------------------===//
  300. template <typename ImutInfo >
  301. class ImutAVLFactory {
  302. friend class ImutAVLTree<ImutInfo>;
  303. using TreeTy = ImutAVLTree<ImutInfo>;
  304. using value_type_ref = typename TreeTy::value_type_ref;
  305. using key_type_ref = typename TreeTy::key_type_ref;
  306. using CacheTy = DenseMap<unsigned, TreeTy*>;
  307. CacheTy Cache;
  308. uintptr_t Allocator;
  309. std::vector<TreeTy*> createdNodes;
  310. std::vector<TreeTy*> freeNodes;
  311. bool ownsAllocator() const {
  312. return (Allocator & 0x1) == 0;
  313. }
  314. BumpPtrAllocator& getAllocator() const {
  315. return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
  316. }
  317. //===--------------------------------------------------===//
  318. // Public interface.
  319. //===--------------------------------------------------===//
  320. public:
  321. ImutAVLFactory()
  322. : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
  323. ImutAVLFactory(BumpPtrAllocator& Alloc)
  324. : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
  325. ~ImutAVLFactory() {
  326. if (ownsAllocator()) delete &getAllocator();
  327. }
  328. TreeTy* add(TreeTy* T, value_type_ref V) {
  329. T = add_internal(V,T);
  330. markImmutable(T);
  331. recoverNodes();
  332. return T;
  333. }
  334. TreeTy* remove(TreeTy* T, key_type_ref V) {
  335. T = remove_internal(V,T);
  336. markImmutable(T);
  337. recoverNodes();
  338. return T;
  339. }
  340. TreeTy* getEmptyTree() const { return nullptr; }
  341. protected:
  342. //===--------------------------------------------------===//
  343. // A bunch of quick helper functions used for reasoning
  344. // about the properties of trees and their children.
  345. // These have succinct names so that the balancing code
  346. // is as terse (and readable) as possible.
  347. //===--------------------------------------------------===//
  348. bool isEmpty(TreeTy* T) const { return !T; }
  349. unsigned getHeight(TreeTy* T) const { return T ? T->getHeight() : 0; }
  350. TreeTy* getLeft(TreeTy* T) const { return T->getLeft(); }
  351. TreeTy* getRight(TreeTy* T) const { return T->getRight(); }
  352. value_type_ref getValue(TreeTy* T) const { return T->value; }
  353. // Make sure the index is not the Tombstone or Entry key of the DenseMap.
  354. static unsigned maskCacheIndex(unsigned I) { return (I & ~0x02); }
  355. unsigned incrementHeight(TreeTy* L, TreeTy* R) const {
  356. unsigned hl = getHeight(L);
  357. unsigned hr = getHeight(R);
  358. return (hl > hr ? hl : hr) + 1;
  359. }
  360. static bool compareTreeWithSection(TreeTy* T,
  361. typename TreeTy::iterator& TI,
  362. typename TreeTy::iterator& TE) {
  363. typename TreeTy::iterator I = T->begin(), E = T->end();
  364. for ( ; I!=E ; ++I, ++TI) {
  365. if (TI == TE || !I->isElementEqual(&*TI))
  366. return false;
  367. }
  368. return true;
  369. }
  370. //===--------------------------------------------------===//
  371. // "createNode" is used to generate new tree roots that link
  372. // to other trees. The function may also simply move links
  373. // in an existing root if that root is still marked mutable.
  374. // This is necessary because otherwise our balancing code
  375. // would leak memory as it would create nodes that are
  376. // then discarded later before the finished tree is
  377. // returned to the caller.
  378. //===--------------------------------------------------===//
  379. TreeTy* createNode(TreeTy* L, value_type_ref V, TreeTy* R) {
  380. BumpPtrAllocator& A = getAllocator();
  381. TreeTy* T;
  382. if (!freeNodes.empty()) {
  383. T = freeNodes.back();
  384. freeNodes.pop_back();
  385. assert(T != L);
  386. assert(T != R);
  387. } else {
  388. T = (TreeTy*) A.Allocate<TreeTy>();
  389. }
  390. new (T) TreeTy(this, L, R, V, incrementHeight(L,R));
  391. createdNodes.push_back(T);
  392. return T;
  393. }
  394. TreeTy* createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
  395. return createNode(newLeft, getValue(oldTree), newRight);
  396. }
  397. void recoverNodes() {
  398. for (unsigned i = 0, n = createdNodes.size(); i < n; ++i) {
  399. TreeTy *N = createdNodes[i];
  400. if (N->isMutable() && N->refCount == 0)
  401. N->destroy();
  402. }
  403. createdNodes.clear();
  404. }
  405. /// balanceTree - Used by add_internal and remove_internal to
  406. /// balance a newly created tree.
  407. TreeTy* balanceTree(TreeTy* L, value_type_ref V, TreeTy* R) {
  408. unsigned hl = getHeight(L);
  409. unsigned hr = getHeight(R);
  410. if (hl > hr + 2) {
  411. assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
  412. TreeTy *LL = getLeft(L);
  413. TreeTy *LR = getRight(L);
  414. if (getHeight(LL) >= getHeight(LR))
  415. return createNode(LL, L, createNode(LR,V,R));
  416. assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
  417. TreeTy *LRL = getLeft(LR);
  418. TreeTy *LRR = getRight(LR);
  419. return createNode(createNode(LL,L,LRL), LR, createNode(LRR,V,R));
  420. }
  421. if (hr > hl + 2) {
  422. assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
  423. TreeTy *RL = getLeft(R);
  424. TreeTy *RR = getRight(R);
  425. if (getHeight(RR) >= getHeight(RL))
  426. return createNode(createNode(L,V,RL), R, RR);
  427. assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
  428. TreeTy *RLL = getLeft(RL);
  429. TreeTy *RLR = getRight(RL);
  430. return createNode(createNode(L,V,RLL), RL, createNode(RLR,R,RR));
  431. }
  432. return createNode(L,V,R);
  433. }
  434. /// add_internal - Creates a new tree that includes the specified
  435. /// data and the data from the original tree. If the original tree
  436. /// already contained the data item, the original tree is returned.
  437. TreeTy* add_internal(value_type_ref V, TreeTy* T) {
  438. if (isEmpty(T))
  439. return createNode(T, V, T);
  440. assert(!T->isMutable());
  441. key_type_ref K = ImutInfo::KeyOfValue(V);
  442. key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
  443. if (ImutInfo::isEqual(K,KCurrent))
  444. return createNode(getLeft(T), V, getRight(T));
  445. else if (ImutInfo::isLess(K,KCurrent))
  446. return balanceTree(add_internal(V, getLeft(T)), getValue(T), getRight(T));
  447. else
  448. return balanceTree(getLeft(T), getValue(T), add_internal(V, getRight(T)));
  449. }
  450. /// remove_internal - Creates a new tree that includes all the data
  451. /// from the original tree except the specified data. If the
  452. /// specified data did not exist in the original tree, the original
  453. /// tree is returned.
  454. TreeTy* remove_internal(key_type_ref K, TreeTy* T) {
  455. if (isEmpty(T))
  456. return T;
  457. assert(!T->isMutable());
  458. key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
  459. if (ImutInfo::isEqual(K,KCurrent)) {
  460. return combineTrees(getLeft(T), getRight(T));
  461. } else if (ImutInfo::isLess(K,KCurrent)) {
  462. return balanceTree(remove_internal(K, getLeft(T)),
  463. getValue(T), getRight(T));
  464. } else {
  465. return balanceTree(getLeft(T), getValue(T),
  466. remove_internal(K, getRight(T)));
  467. }
  468. }
  469. TreeTy* combineTrees(TreeTy* L, TreeTy* R) {
  470. if (isEmpty(L))
  471. return R;
  472. if (isEmpty(R))
  473. return L;
  474. TreeTy* OldNode;
  475. TreeTy* newRight = removeMinBinding(R,OldNode);
  476. return balanceTree(L, getValue(OldNode), newRight);
  477. }
  478. TreeTy* removeMinBinding(TreeTy* T, TreeTy*& Noderemoved) {
  479. assert(!isEmpty(T));
  480. if (isEmpty(getLeft(T))) {
  481. Noderemoved = T;
  482. return getRight(T);
  483. }
  484. return balanceTree(removeMinBinding(getLeft(T), Noderemoved),
  485. getValue(T), getRight(T));
  486. }
  487. /// markImmutable - Clears the mutable bits of a root and all of its
  488. /// descendants.
  489. void markImmutable(TreeTy* T) {
  490. if (!T || !T->isMutable())
  491. return;
  492. T->markImmutable();
  493. markImmutable(getLeft(T));
  494. markImmutable(getRight(T));
  495. }
  496. public:
  497. TreeTy *getCanonicalTree(TreeTy *TNew) {
  498. if (!TNew)
  499. return nullptr;
  500. if (TNew->IsCanonicalized)
  501. return TNew;
  502. // Search the hashtable for another tree with the same digest, and
  503. // if find a collision compare those trees by their contents.
  504. unsigned digest = TNew->computeDigest();
  505. TreeTy *&entry = Cache[maskCacheIndex(digest)];
  506. do {
  507. if (!entry)
  508. break;
  509. for (TreeTy *T = entry ; T != nullptr; T = T->next) {
  510. // Compare the Contents('T') with Contents('TNew')
  511. typename TreeTy::iterator TI = T->begin(), TE = T->end();
  512. if (!compareTreeWithSection(TNew, TI, TE))
  513. continue;
  514. if (TI != TE)
  515. continue; // T has more contents than TNew.
  516. // Trees did match! Return 'T'.
  517. if (TNew->refCount == 0)
  518. TNew->destroy();
  519. return T;
  520. }
  521. entry->prev = TNew;
  522. TNew->next = entry;
  523. }
  524. while (false);
  525. entry = TNew;
  526. TNew->IsCanonicalized = true;
  527. return TNew;
  528. }
  529. };
  530. //===----------------------------------------------------------------------===//
  531. // Immutable AVL-Tree Iterators.
  532. //===----------------------------------------------------------------------===//
  533. template <typename ImutInfo> class ImutAVLTreeGenericIterator {
  534. SmallVector<uintptr_t,20> stack;
  535. public:
  536. using iterator_category = std::bidirectional_iterator_tag;
  537. using value_type = ImutAVLTree<ImutInfo>;
  538. using difference_type = std::ptrdiff_t;
  539. using pointer = value_type *;
  540. using reference = value_type &;
  541. enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
  542. Flags=0x3 };
  543. using TreeTy = ImutAVLTree<ImutInfo>;
  544. ImutAVLTreeGenericIterator() = default;
  545. ImutAVLTreeGenericIterator(const TreeTy *Root) {
  546. if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
  547. }
  548. TreeTy &operator*() const {
  549. assert(!stack.empty());
  550. return *reinterpret_cast<TreeTy *>(stack.back() & ~Flags);
  551. }
  552. TreeTy *operator->() const { return &*this; }
  553. uintptr_t getVisitState() const {
  554. assert(!stack.empty());
  555. return stack.back() & Flags;
  556. }
  557. bool atEnd() const { return stack.empty(); }
  558. bool atBeginning() const {
  559. return stack.size() == 1 && getVisitState() == VisitedNone;
  560. }
  561. void skipToParent() {
  562. assert(!stack.empty());
  563. stack.pop_back();
  564. if (stack.empty())
  565. return;
  566. switch (getVisitState()) {
  567. case VisitedNone:
  568. stack.back() |= VisitedLeft;
  569. break;
  570. case VisitedLeft:
  571. stack.back() |= VisitedRight;
  572. break;
  573. default:
  574. llvm_unreachable("Unreachable.");
  575. }
  576. }
  577. bool operator==(const ImutAVLTreeGenericIterator &x) const {
  578. return stack == x.stack;
  579. }
  580. bool operator!=(const ImutAVLTreeGenericIterator &x) const {
  581. return !(*this == x);
  582. }
  583. ImutAVLTreeGenericIterator &operator++() {
  584. assert(!stack.empty());
  585. TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
  586. assert(Current);
  587. switch (getVisitState()) {
  588. case VisitedNone:
  589. if (TreeTy* L = Current->getLeft())
  590. stack.push_back(reinterpret_cast<uintptr_t>(L));
  591. else
  592. stack.back() |= VisitedLeft;
  593. break;
  594. case VisitedLeft:
  595. if (TreeTy* R = Current->getRight())
  596. stack.push_back(reinterpret_cast<uintptr_t>(R));
  597. else
  598. stack.back() |= VisitedRight;
  599. break;
  600. case VisitedRight:
  601. skipToParent();
  602. break;
  603. default:
  604. llvm_unreachable("Unreachable.");
  605. }
  606. return *this;
  607. }
  608. ImutAVLTreeGenericIterator &operator--() {
  609. assert(!stack.empty());
  610. TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
  611. assert(Current);
  612. switch (getVisitState()) {
  613. case VisitedNone:
  614. stack.pop_back();
  615. break;
  616. case VisitedLeft:
  617. stack.back() &= ~Flags; // Set state to "VisitedNone."
  618. if (TreeTy* L = Current->getLeft())
  619. stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
  620. break;
  621. case VisitedRight:
  622. stack.back() &= ~Flags;
  623. stack.back() |= VisitedLeft;
  624. if (TreeTy* R = Current->getRight())
  625. stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
  626. break;
  627. default:
  628. llvm_unreachable("Unreachable.");
  629. }
  630. return *this;
  631. }
  632. };
  633. template <typename ImutInfo> class ImutAVLTreeInOrderIterator {
  634. using InternalIteratorTy = ImutAVLTreeGenericIterator<ImutInfo>;
  635. InternalIteratorTy InternalItr;
  636. public:
  637. using iterator_category = std::bidirectional_iterator_tag;
  638. using value_type = ImutAVLTree<ImutInfo>;
  639. using difference_type = std::ptrdiff_t;
  640. using pointer = value_type *;
  641. using reference = value_type &;
  642. using TreeTy = ImutAVLTree<ImutInfo>;
  643. ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
  644. if (Root)
  645. ++*this; // Advance to first element.
  646. }
  647. ImutAVLTreeInOrderIterator() : InternalItr() {}
  648. bool operator==(const ImutAVLTreeInOrderIterator &x) const {
  649. return InternalItr == x.InternalItr;
  650. }
  651. bool operator!=(const ImutAVLTreeInOrderIterator &x) const {
  652. return !(*this == x);
  653. }
  654. TreeTy &operator*() const { return *InternalItr; }
  655. TreeTy *operator->() const { return &*InternalItr; }
  656. ImutAVLTreeInOrderIterator &operator++() {
  657. do ++InternalItr;
  658. while (!InternalItr.atEnd() &&
  659. InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
  660. return *this;
  661. }
  662. ImutAVLTreeInOrderIterator &operator--() {
  663. do --InternalItr;
  664. while (!InternalItr.atBeginning() &&
  665. InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
  666. return *this;
  667. }
  668. void skipSubTree() {
  669. InternalItr.skipToParent();
  670. while (!InternalItr.atEnd() &&
  671. InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
  672. ++InternalItr;
  673. }
  674. };
  675. /// Generic iterator that wraps a T::TreeTy::iterator and exposes
  676. /// iterator::getValue() on dereference.
  677. template <typename T>
  678. struct ImutAVLValueIterator
  679. : iterator_adaptor_base<
  680. ImutAVLValueIterator<T>, typename T::TreeTy::iterator,
  681. typename std::iterator_traits<
  682. typename T::TreeTy::iterator>::iterator_category,
  683. const typename T::value_type> {
  684. ImutAVLValueIterator() = default;
  685. explicit ImutAVLValueIterator(typename T::TreeTy *Tree)
  686. : ImutAVLValueIterator::iterator_adaptor_base(Tree) {}
  687. typename ImutAVLValueIterator::reference operator*() const {
  688. return this->I->getValue();
  689. }
  690. };
  691. //===----------------------------------------------------------------------===//
  692. // Trait classes for Profile information.
  693. //===----------------------------------------------------------------------===//
  694. /// Generic profile template. The default behavior is to invoke the
  695. /// profile method of an object. Specializations for primitive integers
  696. /// and generic handling of pointers is done below.
  697. template <typename T>
  698. struct ImutProfileInfo {
  699. using value_type = const T;
  700. using value_type_ref = const T&;
  701. static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
  702. FoldingSetTrait<T>::Profile(X,ID);
  703. }
  704. };
  705. /// Profile traits for integers.
  706. template <typename T>
  707. struct ImutProfileInteger {
  708. using value_type = const T;
  709. using value_type_ref = const T&;
  710. static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
  711. ID.AddInteger(X);
  712. }
  713. };
  714. #define PROFILE_INTEGER_INFO(X)\
  715. template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
  716. PROFILE_INTEGER_INFO(char)
  717. PROFILE_INTEGER_INFO(unsigned char)
  718. PROFILE_INTEGER_INFO(short)
  719. PROFILE_INTEGER_INFO(unsigned short)
  720. PROFILE_INTEGER_INFO(unsigned)
  721. PROFILE_INTEGER_INFO(signed)
  722. PROFILE_INTEGER_INFO(long)
  723. PROFILE_INTEGER_INFO(unsigned long)
  724. PROFILE_INTEGER_INFO(long long)
  725. PROFILE_INTEGER_INFO(unsigned long long)
  726. #undef PROFILE_INTEGER_INFO
  727. /// Profile traits for booleans.
  728. template <>
  729. struct ImutProfileInfo<bool> {
  730. using value_type = const bool;
  731. using value_type_ref = const bool&;
  732. static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
  733. ID.AddBoolean(X);
  734. }
  735. };
  736. /// Generic profile trait for pointer types. We treat pointers as
  737. /// references to unique objects.
  738. template <typename T>
  739. struct ImutProfileInfo<T*> {
  740. using value_type = const T*;
  741. using value_type_ref = value_type;
  742. static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
  743. ID.AddPointer(X);
  744. }
  745. };
  746. //===----------------------------------------------------------------------===//
  747. // Trait classes that contain element comparison operators and type
  748. // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
  749. // inherit from the profile traits (ImutProfileInfo) to include operations
  750. // for element profiling.
  751. //===----------------------------------------------------------------------===//
  752. /// ImutContainerInfo - Generic definition of comparison operations for
  753. /// elements of immutable containers that defaults to using
  754. /// std::equal_to<> and std::less<> to perform comparison of elements.
  755. template <typename T>
  756. struct ImutContainerInfo : public ImutProfileInfo<T> {
  757. using value_type = typename ImutProfileInfo<T>::value_type;
  758. using value_type_ref = typename ImutProfileInfo<T>::value_type_ref;
  759. using key_type = value_type;
  760. using key_type_ref = value_type_ref;
  761. using data_type = bool;
  762. using data_type_ref = bool;
  763. static key_type_ref KeyOfValue(value_type_ref D) { return D; }
  764. static data_type_ref DataOfValue(value_type_ref) { return true; }
  765. static bool isEqual(key_type_ref LHS, key_type_ref RHS) {
  766. return std::equal_to<key_type>()(LHS,RHS);
  767. }
  768. static bool isLess(key_type_ref LHS, key_type_ref RHS) {
  769. return std::less<key_type>()(LHS,RHS);
  770. }
  771. static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
  772. };
  773. /// ImutContainerInfo - Specialization for pointer values to treat pointers
  774. /// as references to unique objects. Pointers are thus compared by
  775. /// their addresses.
  776. template <typename T>
  777. struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
  778. using value_type = typename ImutProfileInfo<T*>::value_type;
  779. using value_type_ref = typename ImutProfileInfo<T*>::value_type_ref;
  780. using key_type = value_type;
  781. using key_type_ref = value_type_ref;
  782. using data_type = bool;
  783. using data_type_ref = bool;
  784. static key_type_ref KeyOfValue(value_type_ref D) { return D; }
  785. static data_type_ref DataOfValue(value_type_ref) { return true; }
  786. static bool isEqual(key_type_ref LHS, key_type_ref RHS) { return LHS == RHS; }
  787. static bool isLess(key_type_ref LHS, key_type_ref RHS) { return LHS < RHS; }
  788. static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
  789. };
  790. //===----------------------------------------------------------------------===//
  791. // Immutable Set
  792. //===----------------------------------------------------------------------===//
  793. template <typename ValT, typename ValInfo = ImutContainerInfo<ValT>>
  794. class ImmutableSet {
  795. public:
  796. using value_type = typename ValInfo::value_type;
  797. using value_type_ref = typename ValInfo::value_type_ref;
  798. using TreeTy = ImutAVLTree<ValInfo>;
  799. private:
  800. IntrusiveRefCntPtr<TreeTy> Root;
  801. public:
  802. /// Constructs a set from a pointer to a tree root. In general one
  803. /// should use a Factory object to create sets instead of directly
  804. /// invoking the constructor, but there are cases where make this
  805. /// constructor public is useful.
  806. explicit ImmutableSet(TreeTy *R) : Root(R) {}
  807. class Factory {
  808. typename TreeTy::Factory F;
  809. const bool Canonicalize;
  810. public:
  811. Factory(bool canonicalize = true)
  812. : Canonicalize(canonicalize) {}
  813. Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
  814. : F(Alloc), Canonicalize(canonicalize) {}
  815. Factory(const Factory& RHS) = delete;
  816. void operator=(const Factory& RHS) = delete;
  817. /// getEmptySet - Returns an immutable set that contains no elements.
  818. ImmutableSet getEmptySet() {
  819. return ImmutableSet(F.getEmptyTree());
  820. }
  821. /// add - Creates a new immutable set that contains all of the values
  822. /// of the original set with the addition of the specified value. If
  823. /// the original set already included the value, then the original set is
  824. /// returned and no memory is allocated. The time and space complexity
  825. /// of this operation is logarithmic in the size of the original set.
  826. /// The memory allocated to represent the set is released when the
  827. /// factory object that created the set is destroyed.
  828. [[nodiscard]] ImmutableSet add(ImmutableSet Old, value_type_ref V) {
  829. TreeTy *NewT = F.add(Old.Root.get(), V);
  830. return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
  831. }
  832. /// remove - Creates a new immutable set that contains all of the values
  833. /// of the original set with the exception of the specified value. If
  834. /// the original set did not contain the value, the original set is
  835. /// returned and no memory is allocated. The time and space complexity
  836. /// of this operation is logarithmic in the size of the original set.
  837. /// The memory allocated to represent the set is released when the
  838. /// factory object that created the set is destroyed.
  839. [[nodiscard]] ImmutableSet remove(ImmutableSet Old, value_type_ref V) {
  840. TreeTy *NewT = F.remove(Old.Root.get(), V);
  841. return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
  842. }
  843. BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
  844. typename TreeTy::Factory *getTreeFactory() const {
  845. return const_cast<typename TreeTy::Factory *>(&F);
  846. }
  847. };
  848. friend class Factory;
  849. /// Returns true if the set contains the specified value.
  850. bool contains(value_type_ref V) const {
  851. return Root ? Root->contains(V) : false;
  852. }
  853. bool operator==(const ImmutableSet &RHS) const {
  854. return Root && RHS.Root ? Root->isEqual(*RHS.Root.get()) : Root == RHS.Root;
  855. }
  856. bool operator!=(const ImmutableSet &RHS) const {
  857. return Root && RHS.Root ? Root->isNotEqual(*RHS.Root.get())
  858. : Root != RHS.Root;
  859. }
  860. TreeTy *getRoot() {
  861. if (Root) { Root->retain(); }
  862. return Root.get();
  863. }
  864. TreeTy *getRootWithoutRetain() const { return Root.get(); }
  865. /// isEmpty - Return true if the set contains no elements.
  866. bool isEmpty() const { return !Root; }
  867. /// isSingleton - Return true if the set contains exactly one element.
  868. /// This method runs in constant time.
  869. bool isSingleton() const { return getHeight() == 1; }
  870. //===--------------------------------------------------===//
  871. // Iterators.
  872. //===--------------------------------------------------===//
  873. using iterator = ImutAVLValueIterator<ImmutableSet>;
  874. iterator begin() const { return iterator(Root.get()); }
  875. iterator end() const { return iterator(); }
  876. //===--------------------------------------------------===//
  877. // Utility methods.
  878. //===--------------------------------------------------===//
  879. unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
  880. static void Profile(FoldingSetNodeID &ID, const ImmutableSet &S) {
  881. ID.AddPointer(S.Root.get());
  882. }
  883. void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
  884. //===--------------------------------------------------===//
  885. // For testing.
  886. //===--------------------------------------------------===//
  887. void validateTree() const { if (Root) Root->validateTree(); }
  888. };
  889. // NOTE: This may some day replace the current ImmutableSet.
  890. template <typename ValT, typename ValInfo = ImutContainerInfo<ValT>>
  891. class ImmutableSetRef {
  892. public:
  893. using value_type = typename ValInfo::value_type;
  894. using value_type_ref = typename ValInfo::value_type_ref;
  895. using TreeTy = ImutAVLTree<ValInfo>;
  896. using FactoryTy = typename TreeTy::Factory;
  897. private:
  898. IntrusiveRefCntPtr<TreeTy> Root;
  899. FactoryTy *Factory;
  900. public:
  901. /// Constructs a set from a pointer to a tree root. In general one
  902. /// should use a Factory object to create sets instead of directly
  903. /// invoking the constructor, but there are cases where make this
  904. /// constructor public is useful.
  905. ImmutableSetRef(TreeTy *R, FactoryTy *F) : Root(R), Factory(F) {}
  906. static ImmutableSetRef getEmptySet(FactoryTy *F) {
  907. return ImmutableSetRef(0, F);
  908. }
  909. ImmutableSetRef add(value_type_ref V) {
  910. return ImmutableSetRef(Factory->add(Root.get(), V), Factory);
  911. }
  912. ImmutableSetRef remove(value_type_ref V) {
  913. return ImmutableSetRef(Factory->remove(Root.get(), V), Factory);
  914. }
  915. /// Returns true if the set contains the specified value.
  916. bool contains(value_type_ref V) const {
  917. return Root ? Root->contains(V) : false;
  918. }
  919. ImmutableSet<ValT> asImmutableSet(bool canonicalize = true) const {
  920. return ImmutableSet<ValT>(
  921. canonicalize ? Factory->getCanonicalTree(Root.get()) : Root.get());
  922. }
  923. TreeTy *getRootWithoutRetain() const { return Root.get(); }
  924. bool operator==(const ImmutableSetRef &RHS) const {
  925. return Root && RHS.Root ? Root->isEqual(*RHS.Root.get()) : Root == RHS.Root;
  926. }
  927. bool operator!=(const ImmutableSetRef &RHS) const {
  928. return Root && RHS.Root ? Root->isNotEqual(*RHS.Root.get())
  929. : Root != RHS.Root;
  930. }
  931. /// isEmpty - Return true if the set contains no elements.
  932. bool isEmpty() const { return !Root; }
  933. /// isSingleton - Return true if the set contains exactly one element.
  934. /// This method runs in constant time.
  935. bool isSingleton() const { return getHeight() == 1; }
  936. //===--------------------------------------------------===//
  937. // Iterators.
  938. //===--------------------------------------------------===//
  939. using iterator = ImutAVLValueIterator<ImmutableSetRef>;
  940. iterator begin() const { return iterator(Root.get()); }
  941. iterator end() const { return iterator(); }
  942. //===--------------------------------------------------===//
  943. // Utility methods.
  944. //===--------------------------------------------------===//
  945. unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
  946. static void Profile(FoldingSetNodeID &ID, const ImmutableSetRef &S) {
  947. ID.AddPointer(S.Root.get());
  948. }
  949. void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
  950. //===--------------------------------------------------===//
  951. // For testing.
  952. //===--------------------------------------------------===//
  953. void validateTree() const { if (Root) Root->validateTree(); }
  954. };
  955. } // end namespace llvm
  956. #endif // LLVM_ADT_IMMUTABLESET_H
  957. #ifdef __GNUC__
  958. #pragma GCC diagnostic pop
  959. #endif