Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1232 lines
39 KiB

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