1 //===- llvm/ADT/SparseBitVector.h - Efficient Sparse BitVector -*- C++ -*- ===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the SparseBitVector class. See the doxygen comment for
11 // SparseBitVector for more details on the algorithm used.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ADT_SPARSEBITVECTOR_H
16 #define LLVM_ADT_SPARSEBITVECTOR_H
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/Support/DataTypes.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/raw_ostream.h"
29 /// SparseBitVector is an implementation of a bitvector that is sparse by only
30 /// storing the elements that have non-zero bits set. In order to make this
31 /// fast for the most common cases, SparseBitVector is implemented as a linked
32 /// list of SparseBitVectorElements. We maintain a pointer to the last
33 /// SparseBitVectorElement accessed (in the form of a list iterator), in order
34 /// to make multiple in-order test/set constant time after the first one is
35 /// executed. Note that using vectors to store SparseBitVectorElement's does
36 /// not work out very well because it causes insertion in the middle to take
37 /// enormous amounts of time with a large amount of bits. Other structures that
38 /// have better worst cases for insertion in the middle (various balanced trees,
39 /// etc) do not perform as well in practice as a linked list with this iterator
40 /// kept up to date. They are also significantly more memory intensive.
43 template <unsigned ElementSize = 128>
44 struct SparseBitVectorElement
45 : public ilist_node<SparseBitVectorElement<ElementSize> > {
47 typedef unsigned long BitWord;
48 typedef unsigned size_type;
50 BITWORD_SIZE = sizeof(BitWord) * CHAR_BIT,
51 BITWORDS_PER_ELEMENT = (ElementSize + BITWORD_SIZE - 1) / BITWORD_SIZE,
52 BITS_PER_ELEMENT = ElementSize
56 // Index of Element in terms of where first bit starts.
57 unsigned ElementIndex;
58 BitWord Bits[BITWORDS_PER_ELEMENT];
59 // Needed for sentinels
60 friend struct ilist_sentinel_traits<SparseBitVectorElement>;
61 SparseBitVectorElement() {
63 memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
67 explicit SparseBitVectorElement(unsigned Idx) {
69 memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
73 bool operator==(const SparseBitVectorElement &RHS) const {
74 if (ElementIndex != RHS.ElementIndex)
76 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
77 if (Bits[i] != RHS.Bits[i])
82 bool operator!=(const SparseBitVectorElement &RHS) const {
83 return !(*this == RHS);
86 // Return the bits that make up word Idx in our element.
87 BitWord word(unsigned Idx) const {
88 assert (Idx < BITWORDS_PER_ELEMENT);
92 unsigned index() const {
97 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
103 void set(unsigned Idx) {
104 Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
107 bool test_and_set (unsigned Idx) {
108 bool old = test(Idx);
116 void reset(unsigned Idx) {
117 Bits[Idx / BITWORD_SIZE] &= ~(1L << (Idx % BITWORD_SIZE));
120 bool test(unsigned Idx) const {
121 return Bits[Idx / BITWORD_SIZE] & (1L << (Idx % BITWORD_SIZE));
124 size_type count() const {
125 unsigned NumBits = 0;
126 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
127 NumBits += countPopulation(Bits[i]);
131 /// find_first - Returns the index of the first set bit.
132 int find_first() const {
133 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
135 return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
136 llvm_unreachable("Illegal empty element");
139 /// find_next - Returns the index of the next set bit starting from the
140 /// "Curr" bit. Returns -1 if the next set bit is not found.
141 int find_next(unsigned Curr) const {
142 if (Curr >= BITS_PER_ELEMENT)
145 unsigned WordPos = Curr / BITWORD_SIZE;
146 unsigned BitPos = Curr % BITWORD_SIZE;
147 BitWord Copy = Bits[WordPos];
148 assert (WordPos <= BITWORDS_PER_ELEMENT
149 && "Word Position outside of element");
151 // Mask off previous bits.
152 Copy &= ~0UL << BitPos;
155 return WordPos * BITWORD_SIZE + countTrailingZeros(Copy);
157 // Check subsequent words.
158 for (unsigned i = WordPos+1; i < BITWORDS_PER_ELEMENT; ++i)
160 return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
164 // Union this element with RHS and return true if this one changed.
165 bool unionWith(const SparseBitVectorElement &RHS) {
166 bool changed = false;
167 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
168 BitWord old = changed ? 0 : Bits[i];
170 Bits[i] |= RHS.Bits[i];
171 if (!changed && old != Bits[i])
177 // Return true if we have any bits in common with RHS
178 bool intersects(const SparseBitVectorElement &RHS) const {
179 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
180 if (RHS.Bits[i] & Bits[i])
186 // Intersect this Element with RHS and return true if this one changed.
187 // BecameZero is set to true if this element became all-zero bits.
188 bool intersectWith(const SparseBitVectorElement &RHS,
190 bool changed = false;
194 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
195 BitWord old = changed ? 0 : Bits[i];
197 Bits[i] &= RHS.Bits[i];
201 if (!changed && old != Bits[i])
204 BecameZero = allzero;
207 // Intersect this Element with the complement of RHS and return true if this
208 // one changed. BecameZero is set to true if this element became all-zero
210 bool intersectWithComplement(const SparseBitVectorElement &RHS,
212 bool changed = false;
216 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
217 BitWord old = changed ? 0 : Bits[i];
219 Bits[i] &= ~RHS.Bits[i];
223 if (!changed && old != Bits[i])
226 BecameZero = allzero;
229 // Three argument version of intersectWithComplement that intersects
230 // RHS1 & ~RHS2 into this element
231 void intersectWithComplement(const SparseBitVectorElement &RHS1,
232 const SparseBitVectorElement &RHS2,
237 for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
238 Bits[i] = RHS1.Bits[i] & ~RHS2.Bits[i];
242 BecameZero = allzero;
246 template <unsigned ElementSize>
247 struct ilist_traits<SparseBitVectorElement<ElementSize> >
248 : public ilist_default_traits<SparseBitVectorElement<ElementSize> > {
249 typedef SparseBitVectorElement<ElementSize> Element;
251 Element *createSentinel() const { return static_cast<Element *>(&Sentinel); }
252 static void destroySentinel(Element *) {}
254 Element *provideInitialHead() const { return createSentinel(); }
255 Element *ensureHead(Element *) const { return createSentinel(); }
256 static void noteHead(Element *, Element *) {}
259 mutable ilist_half_node<Element> Sentinel;
262 template <unsigned ElementSize = 128>
263 class SparseBitVector {
264 typedef ilist<SparseBitVectorElement<ElementSize> > ElementList;
265 typedef typename ElementList::iterator ElementListIter;
266 typedef typename ElementList::const_iterator ElementListConstIter;
268 BITWORD_SIZE = SparseBitVectorElement<ElementSize>::BITWORD_SIZE
271 // Pointer to our current Element.
272 ElementListIter CurrElementIter;
273 ElementList Elements;
275 // This is like std::lower_bound, except we do linear searching from the
277 ElementListIter FindLowerBound(unsigned ElementIndex) {
279 if (Elements.empty()) {
280 CurrElementIter = Elements.begin();
281 return Elements.begin();
284 // Make sure our current iterator is valid.
285 if (CurrElementIter == Elements.end())
288 // Search from our current iterator, either backwards or forwards,
289 // depending on what element we are looking for.
290 ElementListIter ElementIter = CurrElementIter;
291 if (CurrElementIter->index() == ElementIndex) {
293 } else if (CurrElementIter->index() > ElementIndex) {
294 while (ElementIter != Elements.begin()
295 && ElementIter->index() > ElementIndex)
298 while (ElementIter != Elements.end() &&
299 ElementIter->index() < ElementIndex)
302 CurrElementIter = ElementIter;
306 // Iterator to walk set bits in the bitmap. This iterator is a lot uglier
307 // than it would be, in order to be efficient.
308 class SparseBitVectorIterator {
312 const SparseBitVector<ElementSize> *BitVector;
314 // Current element inside of bitmap.
315 ElementListConstIter Iter;
317 // Current bit number inside of our bitmap.
320 // Current word number inside of our element.
323 // Current bits from the element.
324 typename SparseBitVectorElement<ElementSize>::BitWord Bits;
326 // Move our iterator to the first non-zero bit in the bitmap.
327 void AdvanceToFirstNonZero() {
330 if (BitVector->Elements.empty()) {
334 Iter = BitVector->Elements.begin();
335 BitNumber = Iter->index() * ElementSize;
336 unsigned BitPos = Iter->find_first();
338 WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
339 Bits = Iter->word(WordNumber);
340 Bits >>= BitPos % BITWORD_SIZE;
343 // Move our iterator to the next non-zero bit.
344 void AdvanceToNextNonZero() {
348 while (Bits && !(Bits & 1)) {
353 // See if we ran out of Bits in this word.
355 int NextSetBitNumber = Iter->find_next(BitNumber % ElementSize) ;
356 // If we ran out of set bits in this element, move to next element.
357 if (NextSetBitNumber == -1 || (BitNumber % ElementSize == 0)) {
361 // We may run out of elements in the bitmap.
362 if (Iter == BitVector->Elements.end()) {
366 // Set up for next non-zero word in bitmap.
367 BitNumber = Iter->index() * ElementSize;
368 NextSetBitNumber = Iter->find_first();
369 BitNumber += NextSetBitNumber;
370 WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
371 Bits = Iter->word(WordNumber);
372 Bits >>= NextSetBitNumber % BITWORD_SIZE;
374 WordNumber = (NextSetBitNumber % ElementSize) / BITWORD_SIZE;
375 Bits = Iter->word(WordNumber);
376 Bits >>= NextSetBitNumber % BITWORD_SIZE;
377 BitNumber = Iter->index() * ElementSize;
378 BitNumber += NextSetBitNumber;
384 inline SparseBitVectorIterator& operator++() {
387 AdvanceToNextNonZero();
392 inline SparseBitVectorIterator operator++(int) {
393 SparseBitVectorIterator tmp = *this;
398 // Return the current set bit number.
399 unsigned operator*() const {
403 bool operator==(const SparseBitVectorIterator &RHS) const {
404 // If they are both at the end, ignore the rest of the fields.
405 if (AtEnd && RHS.AtEnd)
407 // Otherwise they are the same if they have the same bit number and
409 return AtEnd == RHS.AtEnd && RHS.BitNumber == BitNumber;
411 bool operator!=(const SparseBitVectorIterator &RHS) const {
412 return !(*this == RHS);
414 SparseBitVectorIterator(): BitVector(NULL) {
418 SparseBitVectorIterator(const SparseBitVector<ElementSize> *RHS,
419 bool end = false):BitVector(RHS) {
420 Iter = BitVector->Elements.begin();
425 AdvanceToFirstNonZero();
429 typedef SparseBitVectorIterator iterator;
432 CurrElementIter = Elements.begin ();
438 // SparseBitVector copy ctor.
439 SparseBitVector(const SparseBitVector &RHS) {
440 ElementListConstIter ElementIter = RHS.Elements.begin();
441 while (ElementIter != RHS.Elements.end()) {
442 Elements.push_back(SparseBitVectorElement<ElementSize>(*ElementIter));
446 CurrElementIter = Elements.begin ();
455 SparseBitVector& operator=(const SparseBitVector& RHS) {
461 ElementListConstIter ElementIter = RHS.Elements.begin();
462 while (ElementIter != RHS.Elements.end()) {
463 Elements.push_back(SparseBitVectorElement<ElementSize>(*ElementIter));
467 CurrElementIter = Elements.begin ();
472 // Test, Reset, and Set a bit in the bitmap.
473 bool test(unsigned Idx) {
474 if (Elements.empty())
477 unsigned ElementIndex = Idx / ElementSize;
478 ElementListIter ElementIter = FindLowerBound(ElementIndex);
480 // If we can't find an element that is supposed to contain this bit, there
481 // is nothing more to do.
482 if (ElementIter == Elements.end() ||
483 ElementIter->index() != ElementIndex)
485 return ElementIter->test(Idx % ElementSize);
488 void reset(unsigned Idx) {
489 if (Elements.empty())
492 unsigned ElementIndex = Idx / ElementSize;
493 ElementListIter ElementIter = FindLowerBound(ElementIndex);
495 // If we can't find an element that is supposed to contain this bit, there
496 // is nothing more to do.
497 if (ElementIter == Elements.end() ||
498 ElementIter->index() != ElementIndex)
500 ElementIter->reset(Idx % ElementSize);
502 // When the element is zeroed out, delete it.
503 if (ElementIter->empty()) {
505 Elements.erase(ElementIter);
509 void set(unsigned Idx) {
510 unsigned ElementIndex = Idx / ElementSize;
511 SparseBitVectorElement<ElementSize> *Element;
512 ElementListIter ElementIter;
513 if (Elements.empty()) {
514 Element = new SparseBitVectorElement<ElementSize>(ElementIndex);
515 ElementIter = Elements.insert(Elements.end(), Element);
518 ElementIter = FindLowerBound(ElementIndex);
520 if (ElementIter == Elements.end() ||
521 ElementIter->index() != ElementIndex) {
522 Element = new SparseBitVectorElement<ElementSize>(ElementIndex);
523 // We may have hit the beginning of our SparseBitVector, in which case,
524 // we may need to insert right after this element, which requires moving
525 // the current iterator forward one, because insert does insert before.
526 if (ElementIter != Elements.end() &&
527 ElementIter->index() < ElementIndex)
528 ElementIter = Elements.insert(++ElementIter, Element);
530 ElementIter = Elements.insert(ElementIter, Element);
533 CurrElementIter = ElementIter;
535 ElementIter->set(Idx % ElementSize);
538 bool test_and_set (unsigned Idx) {
539 bool old = test(Idx);
547 bool operator!=(const SparseBitVector &RHS) const {
548 return !(*this == RHS);
551 bool operator==(const SparseBitVector &RHS) const {
552 ElementListConstIter Iter1 = Elements.begin();
553 ElementListConstIter Iter2 = RHS.Elements.begin();
555 for (; Iter1 != Elements.end() && Iter2 != RHS.Elements.end();
557 if (*Iter1 != *Iter2)
560 return Iter1 == Elements.end() && Iter2 == RHS.Elements.end();
563 // Union our bitmap with the RHS and return true if we changed.
564 bool operator|=(const SparseBitVector &RHS) {
568 bool changed = false;
569 ElementListIter Iter1 = Elements.begin();
570 ElementListConstIter Iter2 = RHS.Elements.begin();
572 // If RHS is empty, we are done
573 if (RHS.Elements.empty())
576 while (Iter2 != RHS.Elements.end()) {
577 if (Iter1 == Elements.end() || Iter1->index() > Iter2->index()) {
578 Elements.insert(Iter1,
579 new SparseBitVectorElement<ElementSize>(*Iter2));
582 } else if (Iter1->index() == Iter2->index()) {
583 changed |= Iter1->unionWith(*Iter2);
590 CurrElementIter = Elements.begin();
594 // Intersect our bitmap with the RHS and return true if ours changed.
595 bool operator&=(const SparseBitVector &RHS) {
599 bool changed = false;
600 ElementListIter Iter1 = Elements.begin();
601 ElementListConstIter Iter2 = RHS.Elements.begin();
603 // Check if both bitmaps are empty.
604 if (Elements.empty() && RHS.Elements.empty())
607 // Loop through, intersecting as we go, erasing elements when necessary.
608 while (Iter2 != RHS.Elements.end()) {
609 if (Iter1 == Elements.end()) {
610 CurrElementIter = Elements.begin();
614 if (Iter1->index() > Iter2->index()) {
616 } else if (Iter1->index() == Iter2->index()) {
618 changed |= Iter1->intersectWith(*Iter2, BecameZero);
620 ElementListIter IterTmp = Iter1;
622 Elements.erase(IterTmp);
628 ElementListIter IterTmp = Iter1;
630 Elements.erase(IterTmp);
634 if (Iter1 != Elements.end()) {
635 Elements.erase(Iter1, Elements.end());
638 CurrElementIter = Elements.begin();
642 // Intersect our bitmap with the complement of the RHS and return true
644 bool intersectWithComplement(const SparseBitVector &RHS) {
653 bool changed = false;
654 ElementListIter Iter1 = Elements.begin();
655 ElementListConstIter Iter2 = RHS.Elements.begin();
657 // If either our bitmap or RHS is empty, we are done
658 if (Elements.empty() || RHS.Elements.empty())
661 // Loop through, intersecting as we go, erasing elements when necessary.
662 while (Iter2 != RHS.Elements.end()) {
663 if (Iter1 == Elements.end()) {
664 CurrElementIter = Elements.begin();
668 if (Iter1->index() > Iter2->index()) {
670 } else if (Iter1->index() == Iter2->index()) {
672 changed |= Iter1->intersectWithComplement(*Iter2, BecameZero);
674 ElementListIter IterTmp = Iter1;
676 Elements.erase(IterTmp);
685 CurrElementIter = Elements.begin();
689 bool intersectWithComplement(const SparseBitVector<ElementSize> *RHS) const {
690 return intersectWithComplement(*RHS);
694 // Three argument version of intersectWithComplement.
695 // Result of RHS1 & ~RHS2 is stored into this bitmap.
696 void intersectWithComplement(const SparseBitVector<ElementSize> &RHS1,
697 const SparseBitVector<ElementSize> &RHS2)
700 intersectWithComplement(RHS2);
702 } else if (this == &RHS2) {
703 SparseBitVector RHS2Copy(RHS2);
704 intersectWithComplement(RHS1, RHS2Copy);
709 CurrElementIter = Elements.begin();
710 ElementListConstIter Iter1 = RHS1.Elements.begin();
711 ElementListConstIter Iter2 = RHS2.Elements.begin();
713 // If RHS1 is empty, we are done
714 // If RHS2 is empty, we still have to copy RHS1
715 if (RHS1.Elements.empty())
718 // Loop through, intersecting as we go, erasing elements when necessary.
719 while (Iter2 != RHS2.Elements.end()) {
720 if (Iter1 == RHS1.Elements.end())
723 if (Iter1->index() > Iter2->index()) {
725 } else if (Iter1->index() == Iter2->index()) {
726 bool BecameZero = false;
727 SparseBitVectorElement<ElementSize> *NewElement =
728 new SparseBitVectorElement<ElementSize>(Iter1->index());
729 NewElement->intersectWithComplement(*Iter1, *Iter2, BecameZero);
731 Elements.push_back(NewElement);
738 SparseBitVectorElement<ElementSize> *NewElement =
739 new SparseBitVectorElement<ElementSize>(*Iter1);
740 Elements.push_back(NewElement);
745 // copy the remaining elements
746 while (Iter1 != RHS1.Elements.end()) {
747 SparseBitVectorElement<ElementSize> *NewElement =
748 new SparseBitVectorElement<ElementSize>(*Iter1);
749 Elements.push_back(NewElement);
756 void intersectWithComplement(const SparseBitVector<ElementSize> *RHS1,
757 const SparseBitVector<ElementSize> *RHS2) {
758 intersectWithComplement(*RHS1, *RHS2);
761 bool intersects(const SparseBitVector<ElementSize> *RHS) const {
762 return intersects(*RHS);
765 // Return true if we share any bits in common with RHS
766 bool intersects(const SparseBitVector<ElementSize> &RHS) const {
767 ElementListConstIter Iter1 = Elements.begin();
768 ElementListConstIter Iter2 = RHS.Elements.begin();
770 // Check if both bitmaps are empty.
771 if (Elements.empty() && RHS.Elements.empty())
774 // Loop through, intersecting stopping when we hit bits in common.
775 while (Iter2 != RHS.Elements.end()) {
776 if (Iter1 == Elements.end())
779 if (Iter1->index() > Iter2->index()) {
781 } else if (Iter1->index() == Iter2->index()) {
782 if (Iter1->intersects(*Iter2))
793 // Return true iff all bits set in this SparseBitVector are
795 bool contains(const SparseBitVector<ElementSize> &RHS) const {
796 SparseBitVector<ElementSize> Result(*this);
798 return (Result == RHS);
801 // Return the first set bit in the bitmap. Return -1 if no bits are set.
802 int find_first() const {
803 if (Elements.empty())
805 const SparseBitVectorElement<ElementSize> &First = *(Elements.begin());
806 return (First.index() * ElementSize) + First.find_first();
809 // Return true if the SparseBitVector is empty
811 return Elements.empty();
814 unsigned count() const {
815 unsigned BitCount = 0;
816 for (ElementListConstIter Iter = Elements.begin();
817 Iter != Elements.end();
819 BitCount += Iter->count();
823 iterator begin() const {
824 return iterator(this);
827 iterator end() const {
828 return iterator(this, true);
832 // Convenience functions to allow Or and And without dereferencing in the user
835 template <unsigned ElementSize>
836 inline bool operator |=(SparseBitVector<ElementSize> &LHS,
837 const SparseBitVector<ElementSize> *RHS) {
841 template <unsigned ElementSize>
842 inline bool operator |=(SparseBitVector<ElementSize> *LHS,
843 const SparseBitVector<ElementSize> &RHS) {
844 return LHS->operator|=(RHS);
847 template <unsigned ElementSize>
848 inline bool operator &=(SparseBitVector<ElementSize> *LHS,
849 const SparseBitVector<ElementSize> &RHS) {
850 return LHS->operator&=(RHS);
853 template <unsigned ElementSize>
854 inline bool operator &=(SparseBitVector<ElementSize> &LHS,
855 const SparseBitVector<ElementSize> *RHS) {
859 // Convenience functions for infix union, intersection, difference operators.
861 template <unsigned ElementSize>
862 inline SparseBitVector<ElementSize>
863 operator|(const SparseBitVector<ElementSize> &LHS,
864 const SparseBitVector<ElementSize> &RHS) {
865 SparseBitVector<ElementSize> Result(LHS);
870 template <unsigned ElementSize>
871 inline SparseBitVector<ElementSize>
872 operator&(const SparseBitVector<ElementSize> &LHS,
873 const SparseBitVector<ElementSize> &RHS) {
874 SparseBitVector<ElementSize> Result(LHS);
879 template <unsigned ElementSize>
880 inline SparseBitVector<ElementSize>
881 operator-(const SparseBitVector<ElementSize> &LHS,
882 const SparseBitVector<ElementSize> &RHS) {
883 SparseBitVector<ElementSize> Result;
884 Result.intersectWithComplement(LHS, RHS);
891 // Dump a SparseBitVector to a stream
892 template <unsigned ElementSize>
893 void dump(const SparseBitVector<ElementSize> &LHS, raw_ostream &out) {
896 typename SparseBitVector<ElementSize>::iterator bi = LHS.begin(),
900 for (++bi; bi != be; ++bi) {
906 } // end namespace llvm