SparseBitVector.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. //===- llvm/ADT/SparseBitVector.h - Efficient Sparse BitVector --*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the SparseBitVector class. See the doxygen comment for
  10. // SparseBitVector for more details on the algorithm used.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_ADT_SPARSEBITVECTOR_H
  14. #define LLVM_ADT_SPARSEBITVECTOR_H
  15. #include "llvm/Support/ErrorHandling.h"
  16. #include "llvm/Support/MathExtras.h"
  17. #include "llvm/Support/raw_ostream.h"
  18. #include <cassert>
  19. #include <climits>
  20. #include <cstring>
  21. #include <iterator>
  22. #include <list>
  23. namespace llvm {
  24. /// SparseBitVector is an implementation of a bitvector that is sparse by only
  25. /// storing the elements that have non-zero bits set. In order to make this
  26. /// fast for the most common cases, SparseBitVector is implemented as a linked
  27. /// list of SparseBitVectorElements. We maintain a pointer to the last
  28. /// SparseBitVectorElement accessed (in the form of a list iterator), in order
  29. /// to make multiple in-order test/set constant time after the first one is
  30. /// executed. Note that using vectors to store SparseBitVectorElement's does
  31. /// not work out very well because it causes insertion in the middle to take
  32. /// enormous amounts of time with a large amount of bits. Other structures that
  33. /// have better worst cases for insertion in the middle (various balanced trees,
  34. /// etc) do not perform as well in practice as a linked list with this iterator
  35. /// kept up to date. They are also significantly more memory intensive.
  36. template <unsigned ElementSize = 128> struct SparseBitVectorElement {
  37. public:
  38. using BitWord = unsigned long;
  39. using size_type = unsigned;
  40. enum {
  41. BITWORD_SIZE = sizeof(BitWord) * CHAR_BIT,
  42. BITWORDS_PER_ELEMENT = (ElementSize + BITWORD_SIZE - 1) / BITWORD_SIZE,
  43. BITS_PER_ELEMENT = ElementSize
  44. };
  45. private:
  46. // Index of Element in terms of where first bit starts.
  47. unsigned ElementIndex;
  48. BitWord Bits[BITWORDS_PER_ELEMENT];
  49. SparseBitVectorElement() {
  50. ElementIndex = ~0U;
  51. memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
  52. }
  53. public:
  54. explicit SparseBitVectorElement(unsigned Idx) {
  55. ElementIndex = Idx;
  56. memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
  57. }
  58. // Comparison.
  59. bool operator==(const SparseBitVectorElement &RHS) const {
  60. if (ElementIndex != RHS.ElementIndex)
  61. return false;
  62. for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
  63. if (Bits[i] != RHS.Bits[i])
  64. return false;
  65. return true;
  66. }
  67. bool operator!=(const SparseBitVectorElement &RHS) const {
  68. return !(*this == RHS);
  69. }
  70. // Return the bits that make up word Idx in our element.
  71. BitWord word(unsigned Idx) const {
  72. assert(Idx < BITWORDS_PER_ELEMENT);
  73. return Bits[Idx];
  74. }
  75. unsigned index() const {
  76. return ElementIndex;
  77. }
  78. bool empty() const {
  79. for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
  80. if (Bits[i])
  81. return false;
  82. return true;
  83. }
  84. void set(unsigned Idx) {
  85. Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
  86. }
  87. bool test_and_set(unsigned Idx) {
  88. bool old = test(Idx);
  89. if (!old) {
  90. set(Idx);
  91. return true;
  92. }
  93. return false;
  94. }
  95. void reset(unsigned Idx) {
  96. Bits[Idx / BITWORD_SIZE] &= ~(1L << (Idx % BITWORD_SIZE));
  97. }
  98. bool test(unsigned Idx) const {
  99. return Bits[Idx / BITWORD_SIZE] & (1L << (Idx % BITWORD_SIZE));
  100. }
  101. size_type count() const {
  102. unsigned NumBits = 0;
  103. for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
  104. NumBits += countPopulation(Bits[i]);
  105. return NumBits;
  106. }
  107. /// find_first - Returns the index of the first set bit.
  108. int find_first() const {
  109. for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
  110. if (Bits[i] != 0)
  111. return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
  112. llvm_unreachable("Illegal empty element");
  113. }
  114. /// find_last - Returns the index of the last set bit.
  115. int find_last() const {
  116. for (unsigned I = 0; I < BITWORDS_PER_ELEMENT; ++I) {
  117. unsigned Idx = BITWORDS_PER_ELEMENT - I - 1;
  118. if (Bits[Idx] != 0)
  119. return Idx * BITWORD_SIZE + BITWORD_SIZE -
  120. countLeadingZeros(Bits[Idx]) - 1;
  121. }
  122. llvm_unreachable("Illegal empty element");
  123. }
  124. /// find_next - Returns the index of the next set bit starting from the
  125. /// "Curr" bit. Returns -1 if the next set bit is not found.
  126. int find_next(unsigned Curr) const {
  127. if (Curr >= BITS_PER_ELEMENT)
  128. return -1;
  129. unsigned WordPos = Curr / BITWORD_SIZE;
  130. unsigned BitPos = Curr % BITWORD_SIZE;
  131. BitWord Copy = Bits[WordPos];
  132. assert(WordPos <= BITWORDS_PER_ELEMENT
  133. && "Word Position outside of element");
  134. // Mask off previous bits.
  135. Copy &= ~0UL << BitPos;
  136. if (Copy != 0)
  137. return WordPos * BITWORD_SIZE + countTrailingZeros(Copy);
  138. // Check subsequent words.
  139. for (unsigned i = WordPos+1; i < BITWORDS_PER_ELEMENT; ++i)
  140. if (Bits[i] != 0)
  141. return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
  142. return -1;
  143. }
  144. // Union this element with RHS and return true if this one changed.
  145. bool unionWith(const SparseBitVectorElement &RHS) {
  146. bool changed = false;
  147. for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
  148. BitWord old = changed ? 0 : Bits[i];
  149. Bits[i] |= RHS.Bits[i];
  150. if (!changed && old != Bits[i])
  151. changed = true;
  152. }
  153. return changed;
  154. }
  155. // Return true if we have any bits in common with RHS
  156. bool intersects(const SparseBitVectorElement &RHS) const {
  157. for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
  158. if (RHS.Bits[i] & Bits[i])
  159. return true;
  160. }
  161. return false;
  162. }
  163. // Intersect this Element with RHS and return true if this one changed.
  164. // BecameZero is set to true if this element became all-zero bits.
  165. bool intersectWith(const SparseBitVectorElement &RHS,
  166. bool &BecameZero) {
  167. bool changed = false;
  168. bool allzero = true;
  169. BecameZero = false;
  170. for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
  171. BitWord old = changed ? 0 : Bits[i];
  172. Bits[i] &= RHS.Bits[i];
  173. if (Bits[i] != 0)
  174. allzero = false;
  175. if (!changed && old != Bits[i])
  176. changed = true;
  177. }
  178. BecameZero = allzero;
  179. return changed;
  180. }
  181. // Intersect this Element with the complement of RHS and return true if this
  182. // one changed. BecameZero is set to true if this element became all-zero
  183. // bits.
  184. bool intersectWithComplement(const SparseBitVectorElement &RHS,
  185. bool &BecameZero) {
  186. bool changed = false;
  187. bool allzero = true;
  188. BecameZero = false;
  189. for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
  190. BitWord old = changed ? 0 : Bits[i];
  191. Bits[i] &= ~RHS.Bits[i];
  192. if (Bits[i] != 0)
  193. allzero = false;
  194. if (!changed && old != Bits[i])
  195. changed = true;
  196. }
  197. BecameZero = allzero;
  198. return changed;
  199. }
  200. // Three argument version of intersectWithComplement that intersects
  201. // RHS1 & ~RHS2 into this element
  202. void intersectWithComplement(const SparseBitVectorElement &RHS1,
  203. const SparseBitVectorElement &RHS2,
  204. bool &BecameZero) {
  205. bool allzero = true;
  206. BecameZero = false;
  207. for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
  208. Bits[i] = RHS1.Bits[i] & ~RHS2.Bits[i];
  209. if (Bits[i] != 0)
  210. allzero = false;
  211. }
  212. BecameZero = allzero;
  213. }
  214. };
  215. template <unsigned ElementSize = 128>
  216. class SparseBitVector {
  217. using ElementList = std::list<SparseBitVectorElement<ElementSize>>;
  218. using ElementListIter = typename ElementList::iterator;
  219. using ElementListConstIter = typename ElementList::const_iterator;
  220. enum {
  221. BITWORD_SIZE = SparseBitVectorElement<ElementSize>::BITWORD_SIZE
  222. };
  223. ElementList Elements;
  224. // Pointer to our current Element. This has no visible effect on the external
  225. // state of a SparseBitVector, it's just used to improve performance in the
  226. // common case of testing/modifying bits with similar indices.
  227. mutable ElementListIter CurrElementIter;
  228. // This is like std::lower_bound, except we do linear searching from the
  229. // current position.
  230. ElementListIter FindLowerBoundImpl(unsigned ElementIndex) const {
  231. // We cache a non-const iterator so we're forced to resort to const_cast to
  232. // get the begin/end in the case where 'this' is const. To avoid duplication
  233. // of code with the only difference being whether the const cast is present
  234. // 'this' is always const in this particular function and we sort out the
  235. // difference in FindLowerBound and FindLowerBoundConst.
  236. ElementListIter Begin =
  237. const_cast<SparseBitVector<ElementSize> *>(this)->Elements.begin();
  238. ElementListIter End =
  239. const_cast<SparseBitVector<ElementSize> *>(this)->Elements.end();
  240. if (Elements.empty()) {
  241. CurrElementIter = Begin;
  242. return CurrElementIter;
  243. }
  244. // Make sure our current iterator is valid.
  245. if (CurrElementIter == End)
  246. --CurrElementIter;
  247. // Search from our current iterator, either backwards or forwards,
  248. // depending on what element we are looking for.
  249. ElementListIter ElementIter = CurrElementIter;
  250. if (CurrElementIter->index() == ElementIndex) {
  251. return ElementIter;
  252. } else if (CurrElementIter->index() > ElementIndex) {
  253. while (ElementIter != Begin
  254. && ElementIter->index() > ElementIndex)
  255. --ElementIter;
  256. } else {
  257. while (ElementIter != End &&
  258. ElementIter->index() < ElementIndex)
  259. ++ElementIter;
  260. }
  261. CurrElementIter = ElementIter;
  262. return ElementIter;
  263. }
  264. ElementListConstIter FindLowerBoundConst(unsigned ElementIndex) const {
  265. return FindLowerBoundImpl(ElementIndex);
  266. }
  267. ElementListIter FindLowerBound(unsigned ElementIndex) {
  268. return FindLowerBoundImpl(ElementIndex);
  269. }
  270. // Iterator to walk set bits in the bitmap. This iterator is a lot uglier
  271. // than it would be, in order to be efficient.
  272. class SparseBitVectorIterator {
  273. private:
  274. bool AtEnd;
  275. const SparseBitVector<ElementSize> *BitVector = nullptr;
  276. // Current element inside of bitmap.
  277. ElementListConstIter Iter;
  278. // Current bit number inside of our bitmap.
  279. unsigned BitNumber;
  280. // Current word number inside of our element.
  281. unsigned WordNumber;
  282. // Current bits from the element.
  283. typename SparseBitVectorElement<ElementSize>::BitWord Bits;
  284. // Move our iterator to the first non-zero bit in the bitmap.
  285. void AdvanceToFirstNonZero() {
  286. if (AtEnd)
  287. return;
  288. if (BitVector->Elements.empty()) {
  289. AtEnd = true;
  290. return;
  291. }
  292. Iter = BitVector->Elements.begin();
  293. BitNumber = Iter->index() * ElementSize;
  294. unsigned BitPos = Iter->find_first();
  295. BitNumber += BitPos;
  296. WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
  297. Bits = Iter->word(WordNumber);
  298. Bits >>= BitPos % BITWORD_SIZE;
  299. }
  300. // Move our iterator to the next non-zero bit.
  301. void AdvanceToNextNonZero() {
  302. if (AtEnd)
  303. return;
  304. while (Bits && !(Bits & 1)) {
  305. Bits >>= 1;
  306. BitNumber += 1;
  307. }
  308. // See if we ran out of Bits in this word.
  309. if (!Bits) {
  310. int NextSetBitNumber = Iter->find_next(BitNumber % ElementSize) ;
  311. // If we ran out of set bits in this element, move to next element.
  312. if (NextSetBitNumber == -1 || (BitNumber % ElementSize == 0)) {
  313. ++Iter;
  314. WordNumber = 0;
  315. // We may run out of elements in the bitmap.
  316. if (Iter == BitVector->Elements.end()) {
  317. AtEnd = true;
  318. return;
  319. }
  320. // Set up for next non-zero word in bitmap.
  321. BitNumber = Iter->index() * ElementSize;
  322. NextSetBitNumber = Iter->find_first();
  323. BitNumber += NextSetBitNumber;
  324. WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
  325. Bits = Iter->word(WordNumber);
  326. Bits >>= NextSetBitNumber % BITWORD_SIZE;
  327. } else {
  328. WordNumber = (NextSetBitNumber % ElementSize) / BITWORD_SIZE;
  329. Bits = Iter->word(WordNumber);
  330. Bits >>= NextSetBitNumber % BITWORD_SIZE;
  331. BitNumber = Iter->index() * ElementSize;
  332. BitNumber += NextSetBitNumber;
  333. }
  334. }
  335. }
  336. public:
  337. SparseBitVectorIterator() = default;
  338. SparseBitVectorIterator(const SparseBitVector<ElementSize> *RHS,
  339. bool end = false):BitVector(RHS) {
  340. Iter = BitVector->Elements.begin();
  341. BitNumber = 0;
  342. Bits = 0;
  343. WordNumber = ~0;
  344. AtEnd = end;
  345. AdvanceToFirstNonZero();
  346. }
  347. // Preincrement.
  348. inline SparseBitVectorIterator& operator++() {
  349. ++BitNumber;
  350. Bits >>= 1;
  351. AdvanceToNextNonZero();
  352. return *this;
  353. }
  354. // Postincrement.
  355. inline SparseBitVectorIterator operator++(int) {
  356. SparseBitVectorIterator tmp = *this;
  357. ++*this;
  358. return tmp;
  359. }
  360. // Return the current set bit number.
  361. unsigned operator*() const {
  362. return BitNumber;
  363. }
  364. bool operator==(const SparseBitVectorIterator &RHS) const {
  365. // If they are both at the end, ignore the rest of the fields.
  366. if (AtEnd && RHS.AtEnd)
  367. return true;
  368. // Otherwise they are the same if they have the same bit number and
  369. // bitmap.
  370. return AtEnd == RHS.AtEnd && RHS.BitNumber == BitNumber;
  371. }
  372. bool operator!=(const SparseBitVectorIterator &RHS) const {
  373. return !(*this == RHS);
  374. }
  375. };
  376. public:
  377. using iterator = SparseBitVectorIterator;
  378. SparseBitVector() : Elements(), CurrElementIter(Elements.begin()) {}
  379. SparseBitVector(const SparseBitVector &RHS)
  380. : Elements(RHS.Elements), CurrElementIter(Elements.begin()) {}
  381. SparseBitVector(SparseBitVector &&RHS)
  382. : Elements(std::move(RHS.Elements)), CurrElementIter(Elements.begin()) {}
  383. // Clear.
  384. void clear() {
  385. Elements.clear();
  386. }
  387. // Assignment
  388. SparseBitVector& operator=(const SparseBitVector& RHS) {
  389. if (this == &RHS)
  390. return *this;
  391. Elements = RHS.Elements;
  392. CurrElementIter = Elements.begin();
  393. return *this;
  394. }
  395. SparseBitVector &operator=(SparseBitVector &&RHS) {
  396. Elements = std::move(RHS.Elements);
  397. CurrElementIter = Elements.begin();
  398. return *this;
  399. }
  400. // Test, Reset, and Set a bit in the bitmap.
  401. bool test(unsigned Idx) const {
  402. if (Elements.empty())
  403. return false;
  404. unsigned ElementIndex = Idx / ElementSize;
  405. ElementListConstIter ElementIter = FindLowerBoundConst(ElementIndex);
  406. // If we can't find an element that is supposed to contain this bit, there
  407. // is nothing more to do.
  408. if (ElementIter == Elements.end() ||
  409. ElementIter->index() != ElementIndex)
  410. return false;
  411. return ElementIter->test(Idx % ElementSize);
  412. }
  413. void reset(unsigned Idx) {
  414. if (Elements.empty())
  415. return;
  416. unsigned ElementIndex = Idx / ElementSize;
  417. ElementListIter ElementIter = FindLowerBound(ElementIndex);
  418. // If we can't find an element that is supposed to contain this bit, there
  419. // is nothing more to do.
  420. if (ElementIter == Elements.end() ||
  421. ElementIter->index() != ElementIndex)
  422. return;
  423. ElementIter->reset(Idx % ElementSize);
  424. // When the element is zeroed out, delete it.
  425. if (ElementIter->empty()) {
  426. ++CurrElementIter;
  427. Elements.erase(ElementIter);
  428. }
  429. }
  430. void set(unsigned Idx) {
  431. unsigned ElementIndex = Idx / ElementSize;
  432. ElementListIter ElementIter;
  433. if (Elements.empty()) {
  434. ElementIter = Elements.emplace(Elements.end(), ElementIndex);
  435. } else {
  436. ElementIter = FindLowerBound(ElementIndex);
  437. if (ElementIter == Elements.end() ||
  438. ElementIter->index() != ElementIndex) {
  439. // We may have hit the beginning of our SparseBitVector, in which case,
  440. // we may need to insert right after this element, which requires moving
  441. // the current iterator forward one, because insert does insert before.
  442. if (ElementIter != Elements.end() &&
  443. ElementIter->index() < ElementIndex)
  444. ++ElementIter;
  445. ElementIter = Elements.emplace(ElementIter, ElementIndex);
  446. }
  447. }
  448. CurrElementIter = ElementIter;
  449. ElementIter->set(Idx % ElementSize);
  450. }
  451. bool test_and_set(unsigned Idx) {
  452. bool old = test(Idx);
  453. if (!old) {
  454. set(Idx);
  455. return true;
  456. }
  457. return false;
  458. }
  459. bool operator!=(const SparseBitVector &RHS) const {
  460. return !(*this == RHS);
  461. }
  462. bool operator==(const SparseBitVector &RHS) const {
  463. ElementListConstIter Iter1 = Elements.begin();
  464. ElementListConstIter Iter2 = RHS.Elements.begin();
  465. for (; Iter1 != Elements.end() && Iter2 != RHS.Elements.end();
  466. ++Iter1, ++Iter2) {
  467. if (*Iter1 != *Iter2)
  468. return false;
  469. }
  470. return Iter1 == Elements.end() && Iter2 == RHS.Elements.end();
  471. }
  472. // Union our bitmap with the RHS and return true if we changed.
  473. bool operator|=(const SparseBitVector &RHS) {
  474. if (this == &RHS)
  475. return false;
  476. bool changed = false;
  477. ElementListIter Iter1 = Elements.begin();
  478. ElementListConstIter Iter2 = RHS.Elements.begin();
  479. // If RHS is empty, we are done
  480. if (RHS.Elements.empty())
  481. return false;
  482. while (Iter2 != RHS.Elements.end()) {
  483. if (Iter1 == Elements.end() || Iter1->index() > Iter2->index()) {
  484. Elements.insert(Iter1, *Iter2);
  485. ++Iter2;
  486. changed = true;
  487. } else if (Iter1->index() == Iter2->index()) {
  488. changed |= Iter1->unionWith(*Iter2);
  489. ++Iter1;
  490. ++Iter2;
  491. } else {
  492. ++Iter1;
  493. }
  494. }
  495. CurrElementIter = Elements.begin();
  496. return changed;
  497. }
  498. // Intersect our bitmap with the RHS and return true if ours changed.
  499. bool operator&=(const SparseBitVector &RHS) {
  500. if (this == &RHS)
  501. return false;
  502. bool changed = false;
  503. ElementListIter Iter1 = Elements.begin();
  504. ElementListConstIter Iter2 = RHS.Elements.begin();
  505. // Check if both bitmaps are empty.
  506. if (Elements.empty() && RHS.Elements.empty())
  507. return false;
  508. // Loop through, intersecting as we go, erasing elements when necessary.
  509. while (Iter2 != RHS.Elements.end()) {
  510. if (Iter1 == Elements.end()) {
  511. CurrElementIter = Elements.begin();
  512. return changed;
  513. }
  514. if (Iter1->index() > Iter2->index()) {
  515. ++Iter2;
  516. } else if (Iter1->index() == Iter2->index()) {
  517. bool BecameZero;
  518. changed |= Iter1->intersectWith(*Iter2, BecameZero);
  519. if (BecameZero) {
  520. ElementListIter IterTmp = Iter1;
  521. ++Iter1;
  522. Elements.erase(IterTmp);
  523. } else {
  524. ++Iter1;
  525. }
  526. ++Iter2;
  527. } else {
  528. ElementListIter IterTmp = Iter1;
  529. ++Iter1;
  530. Elements.erase(IterTmp);
  531. changed = true;
  532. }
  533. }
  534. if (Iter1 != Elements.end()) {
  535. Elements.erase(Iter1, Elements.end());
  536. changed = true;
  537. }
  538. CurrElementIter = Elements.begin();
  539. return changed;
  540. }
  541. // Intersect our bitmap with the complement of the RHS and return true
  542. // if ours changed.
  543. bool intersectWithComplement(const SparseBitVector &RHS) {
  544. if (this == &RHS) {
  545. if (!empty()) {
  546. clear();
  547. return true;
  548. }
  549. return false;
  550. }
  551. bool changed = false;
  552. ElementListIter Iter1 = Elements.begin();
  553. ElementListConstIter Iter2 = RHS.Elements.begin();
  554. // If either our bitmap or RHS is empty, we are done
  555. if (Elements.empty() || RHS.Elements.empty())
  556. return false;
  557. // Loop through, intersecting as we go, erasing elements when necessary.
  558. while (Iter2 != RHS.Elements.end()) {
  559. if (Iter1 == Elements.end()) {
  560. CurrElementIter = Elements.begin();
  561. return changed;
  562. }
  563. if (Iter1->index() > Iter2->index()) {
  564. ++Iter2;
  565. } else if (Iter1->index() == Iter2->index()) {
  566. bool BecameZero;
  567. changed |= Iter1->intersectWithComplement(*Iter2, BecameZero);
  568. if (BecameZero) {
  569. ElementListIter IterTmp = Iter1;
  570. ++Iter1;
  571. Elements.erase(IterTmp);
  572. } else {
  573. ++Iter1;
  574. }
  575. ++Iter2;
  576. } else {
  577. ++Iter1;
  578. }
  579. }
  580. CurrElementIter = Elements.begin();
  581. return changed;
  582. }
  583. bool intersectWithComplement(const SparseBitVector<ElementSize> *RHS) const {
  584. return intersectWithComplement(*RHS);
  585. }
  586. // Three argument version of intersectWithComplement.
  587. // Result of RHS1 & ~RHS2 is stored into this bitmap.
  588. void intersectWithComplement(const SparseBitVector<ElementSize> &RHS1,
  589. const SparseBitVector<ElementSize> &RHS2)
  590. {
  591. if (this == &RHS1) {
  592. intersectWithComplement(RHS2);
  593. return;
  594. } else if (this == &RHS2) {
  595. SparseBitVector RHS2Copy(RHS2);
  596. intersectWithComplement(RHS1, RHS2Copy);
  597. return;
  598. }
  599. Elements.clear();
  600. CurrElementIter = Elements.begin();
  601. ElementListConstIter Iter1 = RHS1.Elements.begin();
  602. ElementListConstIter Iter2 = RHS2.Elements.begin();
  603. // If RHS1 is empty, we are done
  604. // If RHS2 is empty, we still have to copy RHS1
  605. if (RHS1.Elements.empty())
  606. return;
  607. // Loop through, intersecting as we go, erasing elements when necessary.
  608. while (Iter2 != RHS2.Elements.end()) {
  609. if (Iter1 == RHS1.Elements.end())
  610. return;
  611. if (Iter1->index() > Iter2->index()) {
  612. ++Iter2;
  613. } else if (Iter1->index() == Iter2->index()) {
  614. bool BecameZero = false;
  615. Elements.emplace_back(Iter1->index());
  616. Elements.back().intersectWithComplement(*Iter1, *Iter2, BecameZero);
  617. if (BecameZero)
  618. Elements.pop_back();
  619. ++Iter1;
  620. ++Iter2;
  621. } else {
  622. Elements.push_back(*Iter1++);
  623. }
  624. }
  625. // copy the remaining elements
  626. std::copy(Iter1, RHS1.Elements.end(), std::back_inserter(Elements));
  627. }
  628. void intersectWithComplement(const SparseBitVector<ElementSize> *RHS1,
  629. const SparseBitVector<ElementSize> *RHS2) {
  630. intersectWithComplement(*RHS1, *RHS2);
  631. }
  632. bool intersects(const SparseBitVector<ElementSize> *RHS) const {
  633. return intersects(*RHS);
  634. }
  635. // Return true if we share any bits in common with RHS
  636. bool intersects(const SparseBitVector<ElementSize> &RHS) const {
  637. ElementListConstIter Iter1 = Elements.begin();
  638. ElementListConstIter Iter2 = RHS.Elements.begin();
  639. // Check if both bitmaps are empty.
  640. if (Elements.empty() && RHS.Elements.empty())
  641. return false;
  642. // Loop through, intersecting stopping when we hit bits in common.
  643. while (Iter2 != RHS.Elements.end()) {
  644. if (Iter1 == Elements.end())
  645. return false;
  646. if (Iter1->index() > Iter2->index()) {
  647. ++Iter2;
  648. } else if (Iter1->index() == Iter2->index()) {
  649. if (Iter1->intersects(*Iter2))
  650. return true;
  651. ++Iter1;
  652. ++Iter2;
  653. } else {
  654. ++Iter1;
  655. }
  656. }
  657. return false;
  658. }
  659. // Return true iff all bits set in this SparseBitVector are
  660. // also set in RHS.
  661. bool contains(const SparseBitVector<ElementSize> &RHS) const {
  662. SparseBitVector<ElementSize> Result(*this);
  663. Result &= RHS;
  664. return (Result == RHS);
  665. }
  666. // Return the first set bit in the bitmap. Return -1 if no bits are set.
  667. int find_first() const {
  668. if (Elements.empty())
  669. return -1;
  670. const SparseBitVectorElement<ElementSize> &First = *(Elements.begin());
  671. return (First.index() * ElementSize) + First.find_first();
  672. }
  673. // Return the last set bit in the bitmap. Return -1 if no bits are set.
  674. int find_last() const {
  675. if (Elements.empty())
  676. return -1;
  677. const SparseBitVectorElement<ElementSize> &Last = *(Elements.rbegin());
  678. return (Last.index() * ElementSize) + Last.find_last();
  679. }
  680. // Return true if the SparseBitVector is empty
  681. bool empty() const {
  682. return Elements.empty();
  683. }
  684. unsigned count() const {
  685. unsigned BitCount = 0;
  686. for (ElementListConstIter Iter = Elements.begin();
  687. Iter != Elements.end();
  688. ++Iter)
  689. BitCount += Iter->count();
  690. return BitCount;
  691. }
  692. iterator begin() const {
  693. return iterator(this);
  694. }
  695. iterator end() const {
  696. return iterator(this, true);
  697. }
  698. };
  699. // Convenience functions to allow Or and And without dereferencing in the user
  700. // code.
  701. template <unsigned ElementSize>
  702. inline bool operator |=(SparseBitVector<ElementSize> &LHS,
  703. const SparseBitVector<ElementSize> *RHS) {
  704. return LHS |= *RHS;
  705. }
  706. template <unsigned ElementSize>
  707. inline bool operator |=(SparseBitVector<ElementSize> *LHS,
  708. const SparseBitVector<ElementSize> &RHS) {
  709. return LHS->operator|=(RHS);
  710. }
  711. template <unsigned ElementSize>
  712. inline bool operator &=(SparseBitVector<ElementSize> *LHS,
  713. const SparseBitVector<ElementSize> &RHS) {
  714. return LHS->operator&=(RHS);
  715. }
  716. template <unsigned ElementSize>
  717. inline bool operator &=(SparseBitVector<ElementSize> &LHS,
  718. const SparseBitVector<ElementSize> *RHS) {
  719. return LHS &= *RHS;
  720. }
  721. // Convenience functions for infix union, intersection, difference operators.
  722. template <unsigned ElementSize>
  723. inline SparseBitVector<ElementSize>
  724. operator|(const SparseBitVector<ElementSize> &LHS,
  725. const SparseBitVector<ElementSize> &RHS) {
  726. SparseBitVector<ElementSize> Result(LHS);
  727. Result |= RHS;
  728. return Result;
  729. }
  730. template <unsigned ElementSize>
  731. inline SparseBitVector<ElementSize>
  732. operator&(const SparseBitVector<ElementSize> &LHS,
  733. const SparseBitVector<ElementSize> &RHS) {
  734. SparseBitVector<ElementSize> Result(LHS);
  735. Result &= RHS;
  736. return Result;
  737. }
  738. template <unsigned ElementSize>
  739. inline SparseBitVector<ElementSize>
  740. operator-(const SparseBitVector<ElementSize> &LHS,
  741. const SparseBitVector<ElementSize> &RHS) {
  742. SparseBitVector<ElementSize> Result;
  743. Result.intersectWithComplement(LHS, RHS);
  744. return Result;
  745. }
  746. // Dump a SparseBitVector to a stream
  747. template <unsigned ElementSize>
  748. void dump(const SparseBitVector<ElementSize> &LHS, raw_ostream &out) {
  749. out << "[";
  750. typename SparseBitVector<ElementSize>::iterator bi = LHS.begin(),
  751. be = LHS.end();
  752. if (bi != be) {
  753. out << *bi;
  754. for (++bi; bi != be; ++bi) {
  755. out << " " << *bi;
  756. }
  757. }
  758. out << "]\n";
  759. }
  760. } // end namespace llvm
  761. #endif // LLVM_ADT_SPARSEBITVECTOR_H