1 //===- llvm/ADT/SmallBitVector.h - 'Normally small' bit vectors -*- 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 implements the SmallBitVector class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_SMALLBITVECTOR_H
15 #define LLVM_ADT_SMALLBITVECTOR_H
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/Support/MathExtras.h"
23 /// This is a 'bitvector' (really, a variable-sized bit array), optimized for
24 /// the case when the array is small. It contains one pointer-sized field, which
25 /// is directly used as a plain collection of bits when possible, or as a
26 /// pointer to a larger heap-allocated array when necessary. This allows normal
27 /// "small" cases to be fast without losing generality for large inputs.
28 class SmallBitVector {
29 // TODO: In "large" mode, a pointer to a BitVector is used, leading to an
30 // unnecessary level of indirection. It would be more efficient to use a
31 // pointer to memory containing size, allocation size, and the array of bits.
35 // The number of bits in this class.
36 NumBaseBits = sizeof(uintptr_t) * CHAR_BIT,
38 // One bit is used to discriminate between small and large mode. The
39 // remaining bits are used for the small-mode representation.
40 SmallNumRawBits = NumBaseBits - 1,
42 // A few more bits are used to store the size of the bit set in small mode.
43 // Theoretically this is a ceil-log2. These bits are encoded in the most
44 // significant bits of the raw bits.
45 SmallNumSizeBits = (NumBaseBits == 32 ? 5 :
46 NumBaseBits == 64 ? 6 :
49 // The remaining bits are used to store the actual set in small mode.
50 SmallNumDataBits = SmallNumRawBits - SmallNumSizeBits
53 static_assert(NumBaseBits == 64 || NumBaseBits == 32,
54 "Unsupported word size");
57 typedef unsigned size_type;
58 // Encapsulation of a single bit.
60 SmallBitVector &TheVector;
64 reference(SmallBitVector &b, unsigned Idx) : TheVector(b), BitPos(Idx) {}
66 reference(const reference&) = default;
68 reference& operator=(reference t) {
73 reference& operator=(bool t) {
75 TheVector.set(BitPos);
77 TheVector.reset(BitPos);
81 operator bool() const {
82 return const_cast<const SmallBitVector &>(TheVector).operator[](BitPos);
87 bool isSmall() const {
88 return X & uintptr_t(1);
91 BitVector *getPointer() const {
93 return reinterpret_cast<BitVector *>(X);
96 void switchToSmall(uintptr_t NewSmallBits, size_t NewSize) {
98 setSmallSize(NewSize);
99 setSmallBits(NewSmallBits);
102 void switchToLarge(BitVector *BV) {
103 X = reinterpret_cast<uintptr_t>(BV);
104 assert(!isSmall() && "Tried to use an unaligned pointer");
107 // Return all the bits used for the "small" representation; this includes
108 // bits for the size as well as the element bits.
109 uintptr_t getSmallRawBits() const {
114 void setSmallRawBits(uintptr_t NewRawBits) {
116 X = (NewRawBits << 1) | uintptr_t(1);
120 size_t getSmallSize() const { return getSmallRawBits() >> SmallNumDataBits; }
122 void setSmallSize(size_t Size) {
123 setSmallRawBits(getSmallBits() | (Size << SmallNumDataBits));
126 // Return the element bits.
127 uintptr_t getSmallBits() const {
128 return getSmallRawBits() & ~(~uintptr_t(0) << getSmallSize());
131 void setSmallBits(uintptr_t NewBits) {
132 setSmallRawBits((NewBits & ~(~uintptr_t(0) << getSmallSize())) |
133 (getSmallSize() << SmallNumDataBits));
137 /// Creates an empty bitvector.
138 SmallBitVector() : X(1) {}
140 /// Creates a bitvector of specified number of bits. All bits are initialized
141 /// to the specified value.
142 explicit SmallBitVector(unsigned s, bool t = false) {
143 if (s <= SmallNumDataBits)
144 switchToSmall(t ? ~uintptr_t(0) : 0, s);
146 switchToLarge(new BitVector(s, t));
149 /// SmallBitVector copy ctor.
150 SmallBitVector(const SmallBitVector &RHS) {
154 switchToLarge(new BitVector(*RHS.getPointer()));
157 SmallBitVector(SmallBitVector &&RHS) : X(RHS.X) {
166 /// Tests whether there are no bits in this bitvector.
168 return isSmall() ? getSmallSize() == 0 : getPointer()->empty();
171 /// Returns the number of bits in this bitvector.
172 size_t size() const {
173 return isSmall() ? getSmallSize() : getPointer()->size();
176 /// Returns the number of bits which are set.
177 size_type count() const {
179 uintptr_t Bits = getSmallBits();
180 return countPopulation(Bits);
182 return getPointer()->count();
185 /// Returns true if any bit is set.
188 return getSmallBits() != 0;
189 return getPointer()->any();
192 /// Returns true if all bits are set.
195 return getSmallBits() == (uintptr_t(1) << getSmallSize()) - 1;
196 return getPointer()->all();
199 /// Returns true if none of the bits are set.
202 return getSmallBits() == 0;
203 return getPointer()->none();
206 /// Returns the index of the first set bit, -1 if none of the bits are set.
207 int find_first() const {
209 uintptr_t Bits = getSmallBits();
212 return countTrailingZeros(Bits);
214 return getPointer()->find_first();
217 int find_last() const {
219 uintptr_t Bits = getSmallBits();
222 return NumBaseBits - countLeadingZeros(Bits);
224 return getPointer()->find_last();
227 /// Returns the index of the first unset bit, -1 if all of the bits are set.
228 int find_first_unset() const {
230 if (count() == getSmallSize())
233 uintptr_t Bits = getSmallBits();
234 return countTrailingOnes(Bits);
236 return getPointer()->find_first_unset();
239 int find_last_unset() const {
241 if (count() == getSmallSize())
244 uintptr_t Bits = getSmallBits();
245 return NumBaseBits - countLeadingOnes(Bits);
247 return getPointer()->find_last_unset();
250 /// Returns the index of the next set bit following the "Prev" bit.
251 /// Returns -1 if the next set bit is not found.
252 int find_next(unsigned Prev) const {
254 uintptr_t Bits = getSmallBits();
255 // Mask off previous bits.
256 Bits &= ~uintptr_t(0) << (Prev + 1);
257 if (Bits == 0 || Prev + 1 >= getSmallSize())
259 return countTrailingZeros(Bits);
261 return getPointer()->find_next(Prev);
264 /// Returns the index of the next unset bit following the "Prev" bit.
265 /// Returns -1 if the next unset bit is not found.
266 int find_next_unset(unsigned Prev) const {
269 uintptr_t Bits = getSmallBits();
270 // Mask in previous bits.
271 uintptr_t Mask = (1 << Prev) - 1;
274 if (Bits == ~uintptr_t(0) || Prev + 1 >= getSmallSize())
276 return countTrailingOnes(Bits);
278 return getPointer()->find_next_unset(Prev);
281 /// find_prev - Returns the index of the first set bit that precedes the
282 /// the bit at \p PriorTo. Returns -1 if all previous bits are unset.
283 int find_prev(unsigned PriorTo) const {
289 uintptr_t Bits = getSmallBits();
290 Bits &= maskTrailingOnes<uintptr_t>(PriorTo + 1);
294 return NumBaseBits - countLeadingZeros(Bits) - 1;
296 return getPointer()->find_prev(PriorTo);
306 /// Grow or shrink the bitvector.
307 void resize(unsigned N, bool t = false) {
309 getPointer()->resize(N, t);
310 } else if (SmallNumDataBits >= N) {
311 uintptr_t NewBits = t ? ~uintptr_t(0) << getSmallSize() : 0;
313 setSmallBits(NewBits | getSmallBits());
315 BitVector *BV = new BitVector(N, t);
316 uintptr_t OldBits = getSmallBits();
317 for (size_t i = 0, e = getSmallSize(); i != e; ++i)
318 (*BV)[i] = (OldBits >> i) & 1;
323 void reserve(unsigned N) {
325 if (N > SmallNumDataBits) {
326 uintptr_t OldBits = getSmallRawBits();
327 size_t SmallSize = getSmallSize();
328 BitVector *BV = new BitVector(SmallSize);
329 for (size_t i = 0; i < SmallSize; ++i)
330 if ((OldBits >> i) & 1)
336 getPointer()->reserve(N);
341 SmallBitVector &set() {
343 setSmallBits(~uintptr_t(0));
349 SmallBitVector &set(unsigned Idx) {
351 assert(Idx <= static_cast<unsigned>(
352 std::numeric_limits<uintptr_t>::digits) &&
353 "undefined behavior");
354 setSmallBits(getSmallBits() | (uintptr_t(1) << Idx));
357 getPointer()->set(Idx);
361 /// Efficiently set a range of bits in [I, E)
362 SmallBitVector &set(unsigned I, unsigned E) {
363 assert(I <= E && "Attempted to set backwards range!");
364 assert(E <= size() && "Attempted to set out-of-bounds range!");
365 if (I == E) return *this;
367 uintptr_t EMask = ((uintptr_t)1) << E;
368 uintptr_t IMask = ((uintptr_t)1) << I;
369 uintptr_t Mask = EMask - IMask;
370 setSmallBits(getSmallBits() | Mask);
372 getPointer()->set(I, E);
376 SmallBitVector &reset() {
380 getPointer()->reset();
384 SmallBitVector &reset(unsigned Idx) {
386 setSmallBits(getSmallBits() & ~(uintptr_t(1) << Idx));
388 getPointer()->reset(Idx);
392 /// Efficiently reset a range of bits in [I, E)
393 SmallBitVector &reset(unsigned I, unsigned E) {
394 assert(I <= E && "Attempted to reset backwards range!");
395 assert(E <= size() && "Attempted to reset out-of-bounds range!");
396 if (I == E) return *this;
398 uintptr_t EMask = ((uintptr_t)1) << E;
399 uintptr_t IMask = ((uintptr_t)1) << I;
400 uintptr_t Mask = EMask - IMask;
401 setSmallBits(getSmallBits() & ~Mask);
403 getPointer()->reset(I, E);
407 SmallBitVector &flip() {
409 setSmallBits(~getSmallBits());
411 getPointer()->flip();
415 SmallBitVector &flip(unsigned Idx) {
417 setSmallBits(getSmallBits() ^ (uintptr_t(1) << Idx));
419 getPointer()->flip(Idx);
424 SmallBitVector operator~() const {
425 return SmallBitVector(*this).flip();
429 reference operator[](unsigned Idx) {
430 assert(Idx < size() && "Out-of-bounds Bit access.");
431 return reference(*this, Idx);
434 bool operator[](unsigned Idx) const {
435 assert(Idx < size() && "Out-of-bounds Bit access.");
437 return ((getSmallBits() >> Idx) & 1) != 0;
438 return getPointer()->operator[](Idx);
441 bool test(unsigned Idx) const {
445 /// Test if any common bits are set.
446 bool anyCommon(const SmallBitVector &RHS) const {
447 if (isSmall() && RHS.isSmall())
448 return (getSmallBits() & RHS.getSmallBits()) != 0;
449 if (!isSmall() && !RHS.isSmall())
450 return getPointer()->anyCommon(*RHS.getPointer());
452 for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
453 if (test(i) && RHS.test(i))
458 // Comparison operators.
459 bool operator==(const SmallBitVector &RHS) const {
460 if (size() != RHS.size())
463 return getSmallBits() == RHS.getSmallBits();
465 return *getPointer() == *RHS.getPointer();
468 bool operator!=(const SmallBitVector &RHS) const {
469 return !(*this == RHS);
472 // Intersection, union, disjoint union.
473 SmallBitVector &operator&=(const SmallBitVector &RHS) {
474 resize(std::max(size(), RHS.size()));
476 setSmallBits(getSmallBits() & RHS.getSmallBits());
477 else if (!RHS.isSmall())
478 getPointer()->operator&=(*RHS.getPointer());
480 SmallBitVector Copy = RHS;
482 getPointer()->operator&=(*Copy.getPointer());
487 /// Reset bits that are set in RHS. Same as *this &= ~RHS.
488 SmallBitVector &reset(const SmallBitVector &RHS) {
489 if (isSmall() && RHS.isSmall())
490 setSmallBits(getSmallBits() & ~RHS.getSmallBits());
491 else if (!isSmall() && !RHS.isSmall())
492 getPointer()->reset(*RHS.getPointer());
494 for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
501 /// Check if (This - RHS) is zero. This is the same as reset(RHS) and any().
502 bool test(const SmallBitVector &RHS) const {
503 if (isSmall() && RHS.isSmall())
504 return (getSmallBits() & ~RHS.getSmallBits()) != 0;
505 if (!isSmall() && !RHS.isSmall())
506 return getPointer()->test(*RHS.getPointer());
509 for (i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
510 if (test(i) && !RHS.test(i))
513 for (e = size(); i != e; ++i)
520 SmallBitVector &operator|=(const SmallBitVector &RHS) {
521 resize(std::max(size(), RHS.size()));
523 setSmallBits(getSmallBits() | RHS.getSmallBits());
524 else if (!RHS.isSmall())
525 getPointer()->operator|=(*RHS.getPointer());
527 SmallBitVector Copy = RHS;
529 getPointer()->operator|=(*Copy.getPointer());
534 SmallBitVector &operator^=(const SmallBitVector &RHS) {
535 resize(std::max(size(), RHS.size()));
537 setSmallBits(getSmallBits() ^ RHS.getSmallBits());
538 else if (!RHS.isSmall())
539 getPointer()->operator^=(*RHS.getPointer());
541 SmallBitVector Copy = RHS;
543 getPointer()->operator^=(*Copy.getPointer());
548 SmallBitVector &operator<<=(unsigned N) {
550 setSmallBits(getSmallBits() << N);
552 getPointer()->operator<<=(N);
556 SmallBitVector &operator>>=(unsigned N) {
558 setSmallBits(getSmallBits() >> N);
560 getPointer()->operator>>=(N);
564 // Assignment operator.
565 const SmallBitVector &operator=(const SmallBitVector &RHS) {
570 switchToLarge(new BitVector(*RHS.getPointer()));
573 *getPointer() = *RHS.getPointer();
582 const SmallBitVector &operator=(SmallBitVector &&RHS) {
590 void swap(SmallBitVector &RHS) {
594 /// Add '1' bits from Mask to this vector. Don't resize.
595 /// This computes "*this |= Mask".
596 void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
598 applyMask<true, false>(Mask, MaskWords);
600 getPointer()->setBitsInMask(Mask, MaskWords);
603 /// Clear any bits in this vector that are set in Mask. Don't resize.
604 /// This computes "*this &= ~Mask".
605 void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
607 applyMask<false, false>(Mask, MaskWords);
609 getPointer()->clearBitsInMask(Mask, MaskWords);
612 /// Add a bit to this vector for every '0' bit in Mask. Don't resize.
613 /// This computes "*this |= ~Mask".
614 void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
616 applyMask<true, true>(Mask, MaskWords);
618 getPointer()->setBitsNotInMask(Mask, MaskWords);
621 /// Clear a bit in this vector for every '0' bit in Mask. Don't resize.
622 /// This computes "*this &= Mask".
623 void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
625 applyMask<false, true>(Mask, MaskWords);
627 getPointer()->clearBitsNotInMask(Mask, MaskWords);
631 template <bool AddBits, bool InvertMask>
632 void applyMask(const uint32_t *Mask, unsigned MaskWords) {
633 assert(MaskWords <= sizeof(uintptr_t) && "Mask is larger than base!");
634 uintptr_t M = Mask[0];
635 if (NumBaseBits == 64)
636 M |= uint64_t(Mask[1]) << 32;
640 setSmallBits(getSmallBits() | M);
642 setSmallBits(getSmallBits() & ~M);
646 inline SmallBitVector
647 operator&(const SmallBitVector &LHS, const SmallBitVector &RHS) {
648 SmallBitVector Result(LHS);
653 inline SmallBitVector
654 operator|(const SmallBitVector &LHS, const SmallBitVector &RHS) {
655 SmallBitVector Result(LHS);
660 inline SmallBitVector
661 operator^(const SmallBitVector &LHS, const SmallBitVector &RHS) {
662 SmallBitVector Result(LHS);
667 } // End llvm namespace
670 /// Implement std::swap in terms of BitVector swap.
672 swap(llvm::SmallBitVector &LHS, llvm::SmallBitVector &RHS) {