1 //===- llvm/ADT/BitVector.h - 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 BitVector class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_BITVECTOR_H
15 #define LLVM_ADT_BITVECTOR_H
17 #include "llvm/Support/Compiler.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/MathExtras.h"
28 typedef unsigned long BitWord;
30 enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * CHAR_BIT };
32 static_assert(BITWORD_SIZE == 64 || BITWORD_SIZE == 32,
33 "Unsupported word size");
35 BitWord *Bits; // Actual bits.
36 unsigned Size; // Size of bitvector in bits.
37 unsigned Capacity; // Size of allocated memory in BitWord.
40 typedef unsigned size_type;
41 // Encapsulation of a single bit.
43 friend class BitVector;
48 reference(); // Undefined
51 reference(BitVector &b, unsigned Idx) {
52 WordRef = &b.Bits[Idx / BITWORD_SIZE];
53 BitPos = Idx % BITWORD_SIZE;
58 reference &operator=(reference t) {
63 reference& operator=(bool t) {
65 *WordRef |= BitWord(1) << BitPos;
67 *WordRef &= ~(BitWord(1) << BitPos);
71 operator bool() const {
72 return ((*WordRef) & (BitWord(1) << BitPos)) ? true : false;
77 /// BitVector default ctor - Creates an empty bitvector.
78 BitVector() : Size(0), Capacity(0) {
82 /// BitVector ctor - Creates a bitvector of specified number of bits. All
83 /// bits are initialized to the specified value.
84 explicit BitVector(unsigned s, bool t = false) : Size(s) {
85 Capacity = NumBitWords(s);
86 Bits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
87 init_words(Bits, Capacity, t);
92 /// BitVector copy ctor.
93 BitVector(const BitVector &RHS) : Size(RHS.size()) {
100 Capacity = NumBitWords(RHS.size());
101 Bits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
102 std::memcpy(Bits, RHS.Bits, Capacity * sizeof(BitWord));
105 BitVector(BitVector &&RHS)
106 : Bits(RHS.Bits), Size(RHS.Size), Capacity(RHS.Capacity) {
114 /// empty - Tests whether there are no bits in this bitvector.
115 bool empty() const { return Size == 0; }
117 /// size - Returns the number of bits in this bitvector.
118 size_type size() const { return Size; }
120 /// count - Returns the number of bits which are set.
121 size_type count() const {
122 unsigned NumBits = 0;
123 for (unsigned i = 0; i < NumBitWords(size()); ++i)
124 if (sizeof(BitWord) == 4)
125 NumBits += CountPopulation_32((uint32_t)Bits[i]);
126 else if (sizeof(BitWord) == 8)
127 NumBits += CountPopulation_64(Bits[i]);
129 llvm_unreachable("Unsupported!");
133 /// any - Returns true if any bit is set.
135 for (unsigned i = 0; i < NumBitWords(size()); ++i)
141 /// all - Returns true if all bits are set.
143 for (unsigned i = 0; i < Size / BITWORD_SIZE; ++i)
147 // If bits remain check that they are ones. The unused bits are always zero.
148 if (unsigned Remainder = Size % BITWORD_SIZE)
149 return Bits[Size / BITWORD_SIZE] == (1UL << Remainder) - 1;
154 /// none - Returns true if none of the bits are set.
159 /// find_first - Returns the index of the first set bit, -1 if none
160 /// of the bits are set.
161 int find_first() const {
162 for (unsigned i = 0; i < NumBitWords(size()); ++i)
164 return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
168 /// find_next - Returns the index of the next set bit following the
169 /// "Prev" bit. Returns -1 if the next set bit is not found.
170 int find_next(unsigned Prev) const {
175 unsigned WordPos = Prev / BITWORD_SIZE;
176 unsigned BitPos = Prev % BITWORD_SIZE;
177 BitWord Copy = Bits[WordPos];
178 // Mask off previous bits.
179 Copy &= ~0UL << BitPos;
182 return WordPos * BITWORD_SIZE + countTrailingZeros(Copy);
184 // Check subsequent words.
185 for (unsigned i = WordPos+1; i < NumBitWords(size()); ++i)
187 return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
191 /// clear - Clear all bits.
196 /// resize - Grow or shrink the bitvector.
197 void resize(unsigned N, bool t = false) {
198 if (N > Capacity * BITWORD_SIZE) {
199 unsigned OldCapacity = Capacity;
201 init_words(&Bits[OldCapacity], (Capacity-OldCapacity), t);
204 // Set any old unused bits that are now included in the BitVector. This
205 // may set bits that are not included in the new vector, but we will clear
206 // them back out below.
210 // Update the size, and clear out any bits that are now unused
211 unsigned OldSize = Size;
213 if (t || N < OldSize)
217 void reserve(unsigned N) {
218 if (N > Capacity * BITWORD_SIZE)
224 init_words(Bits, Capacity, true);
229 BitVector &set(unsigned Idx) {
230 assert(Bits && "Bits never allocated");
231 Bits[Idx / BITWORD_SIZE] |= BitWord(1) << (Idx % BITWORD_SIZE);
235 /// set - Efficiently set a range of bits in [I, E)
236 BitVector &set(unsigned I, unsigned E) {
237 assert(I <= E && "Attempted to set backwards range!");
238 assert(E <= size() && "Attempted to set out-of-bounds range!");
240 if (I == E) return *this;
242 if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
243 BitWord EMask = 1UL << (E % BITWORD_SIZE);
244 BitWord IMask = 1UL << (I % BITWORD_SIZE);
245 BitWord Mask = EMask - IMask;
246 Bits[I / BITWORD_SIZE] |= Mask;
250 BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
251 Bits[I / BITWORD_SIZE] |= PrefixMask;
252 I = RoundUpToAlignment(I, BITWORD_SIZE);
254 for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
255 Bits[I / BITWORD_SIZE] = ~0UL;
257 BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
259 Bits[I / BITWORD_SIZE] |= PostfixMask;
265 init_words(Bits, Capacity, false);
269 BitVector &reset(unsigned Idx) {
270 Bits[Idx / BITWORD_SIZE] &= ~(BitWord(1) << (Idx % BITWORD_SIZE));
274 /// reset - Efficiently reset a range of bits in [I, E)
275 BitVector &reset(unsigned I, unsigned E) {
276 assert(I <= E && "Attempted to reset backwards range!");
277 assert(E <= size() && "Attempted to reset out-of-bounds range!");
279 if (I == E) return *this;
281 if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
282 BitWord EMask = 1UL << (E % BITWORD_SIZE);
283 BitWord IMask = 1UL << (I % BITWORD_SIZE);
284 BitWord Mask = EMask - IMask;
285 Bits[I / BITWORD_SIZE] &= ~Mask;
289 BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
290 Bits[I / BITWORD_SIZE] &= ~PrefixMask;
291 I = RoundUpToAlignment(I, BITWORD_SIZE);
293 for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
294 Bits[I / BITWORD_SIZE] = 0UL;
296 BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
298 Bits[I / BITWORD_SIZE] &= ~PostfixMask;
304 for (unsigned i = 0; i < NumBitWords(size()); ++i)
310 BitVector &flip(unsigned Idx) {
311 Bits[Idx / BITWORD_SIZE] ^= BitWord(1) << (Idx % BITWORD_SIZE);
316 reference operator[](unsigned Idx) {
317 assert (Idx < Size && "Out-of-bounds Bit access.");
318 return reference(*this, Idx);
321 bool operator[](unsigned Idx) const {
322 assert (Idx < Size && "Out-of-bounds Bit access.");
323 BitWord Mask = BitWord(1) << (Idx % BITWORD_SIZE);
324 return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
327 bool test(unsigned Idx) const {
331 /// Test if any common bits are set.
332 bool anyCommon(const BitVector &RHS) const {
333 unsigned ThisWords = NumBitWords(size());
334 unsigned RHSWords = NumBitWords(RHS.size());
335 for (unsigned i = 0, e = std::min(ThisWords, RHSWords); i != e; ++i)
336 if (Bits[i] & RHS.Bits[i])
341 // Comparison operators.
342 bool operator==(const BitVector &RHS) const {
343 unsigned ThisWords = NumBitWords(size());
344 unsigned RHSWords = NumBitWords(RHS.size());
346 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
347 if (Bits[i] != RHS.Bits[i])
350 // Verify that any extra words are all zeros.
351 if (i != ThisWords) {
352 for (; i != ThisWords; ++i)
355 } else if (i != RHSWords) {
356 for (; i != RHSWords; ++i)
363 bool operator!=(const BitVector &RHS) const {
364 return !(*this == RHS);
367 /// Intersection, union, disjoint union.
368 BitVector &operator&=(const BitVector &RHS) {
369 unsigned ThisWords = NumBitWords(size());
370 unsigned RHSWords = NumBitWords(RHS.size());
372 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
373 Bits[i] &= RHS.Bits[i];
375 // Any bits that are just in this bitvector become zero, because they aren't
376 // in the RHS bit vector. Any words only in RHS are ignored because they
377 // are already zero in the LHS.
378 for (; i != ThisWords; ++i)
384 /// reset - Reset bits that are set in RHS. Same as *this &= ~RHS.
385 BitVector &reset(const BitVector &RHS) {
386 unsigned ThisWords = NumBitWords(size());
387 unsigned RHSWords = NumBitWords(RHS.size());
389 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
390 Bits[i] &= ~RHS.Bits[i];
394 /// test - Check if (This - RHS) is zero.
395 /// This is the same as reset(RHS) and any().
396 bool test(const BitVector &RHS) const {
397 unsigned ThisWords = NumBitWords(size());
398 unsigned RHSWords = NumBitWords(RHS.size());
400 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
401 if ((Bits[i] & ~RHS.Bits[i]) != 0)
404 for (; i != ThisWords ; ++i)
411 BitVector &operator|=(const BitVector &RHS) {
412 if (size() < RHS.size())
414 for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
415 Bits[i] |= RHS.Bits[i];
419 BitVector &operator^=(const BitVector &RHS) {
420 if (size() < RHS.size())
422 for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
423 Bits[i] ^= RHS.Bits[i];
427 // Assignment operator.
428 const BitVector &operator=(const BitVector &RHS) {
429 if (this == &RHS) return *this;
432 unsigned RHSWords = NumBitWords(Size);
433 if (Size <= Capacity * BITWORD_SIZE) {
435 std::memcpy(Bits, RHS.Bits, RHSWords * sizeof(BitWord));
440 // Grow the bitvector to have enough elements.
442 assert(Capacity > 0 && "negative capacity?");
443 BitWord *NewBits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
444 std::memcpy(NewBits, RHS.Bits, Capacity * sizeof(BitWord));
446 // Destroy the old bits.
453 const BitVector &operator=(BitVector &&RHS) {
454 if (this == &RHS) return *this;
459 Capacity = RHS.Capacity;
466 void swap(BitVector &RHS) {
467 std::swap(Bits, RHS.Bits);
468 std::swap(Size, RHS.Size);
469 std::swap(Capacity, RHS.Capacity);
472 //===--------------------------------------------------------------------===//
473 // Portable bit mask operations.
474 //===--------------------------------------------------------------------===//
476 // These methods all operate on arrays of uint32_t, each holding 32 bits. The
477 // fixed word size makes it easier to work with literal bit vector constants
480 // The LSB in each word is the lowest numbered bit. The size of a portable
481 // bit mask is always a whole multiple of 32 bits. If no bit mask size is
482 // given, the bit mask is assumed to cover the entire BitVector.
484 /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
485 /// This computes "*this |= Mask".
486 void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
487 applyMask<true, false>(Mask, MaskWords);
490 /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
491 /// Don't resize. This computes "*this &= ~Mask".
492 void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
493 applyMask<false, false>(Mask, MaskWords);
496 /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask.
497 /// Don't resize. This computes "*this |= ~Mask".
498 void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
499 applyMask<true, true>(Mask, MaskWords);
502 /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
503 /// Don't resize. This computes "*this &= Mask".
504 void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
505 applyMask<false, true>(Mask, MaskWords);
509 unsigned NumBitWords(unsigned S) const {
510 return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
513 // Set the unused bits in the high words.
514 void set_unused_bits(bool t = true) {
515 // Set high words first.
516 unsigned UsedWords = NumBitWords(Size);
517 if (Capacity > UsedWords)
518 init_words(&Bits[UsedWords], (Capacity-UsedWords), t);
520 // Then set any stray high bits of the last used word.
521 unsigned ExtraBits = Size % BITWORD_SIZE;
523 BitWord ExtraBitMask = ~0UL << ExtraBits;
525 Bits[UsedWords-1] |= ExtraBitMask;
527 Bits[UsedWords-1] &= ~ExtraBitMask;
531 // Clear the unused bits in the high words.
532 void clear_unused_bits() {
533 set_unused_bits(false);
536 void grow(unsigned NewSize) {
537 Capacity = std::max(NumBitWords(NewSize), Capacity * 2);
538 assert(Capacity > 0 && "realloc-ing zero space");
539 Bits = (BitWord *)std::realloc(Bits, Capacity * sizeof(BitWord));
544 void init_words(BitWord *B, unsigned NumWords, bool t) {
545 memset(B, 0 - (int)t, NumWords*sizeof(BitWord));
548 template<bool AddBits, bool InvertMask>
549 void applyMask(const uint32_t *Mask, unsigned MaskWords) {
550 static_assert(BITWORD_SIZE % 32 == 0, "Unsupported BitWord size.");
551 MaskWords = std::min(MaskWords, (size() + 31) / 32);
552 const unsigned Scale = BITWORD_SIZE / 32;
554 for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) {
555 BitWord BW = Bits[i];
556 // This inner loop should unroll completely when BITWORD_SIZE > 32.
557 for (unsigned b = 0; b != BITWORD_SIZE; b += 32) {
558 uint32_t M = *Mask++;
559 if (InvertMask) M = ~M;
560 if (AddBits) BW |= BitWord(M) << b;
561 else BW &= ~(BitWord(M) << b);
565 for (unsigned b = 0; MaskWords; b += 32, --MaskWords) {
566 uint32_t M = *Mask++;
567 if (InvertMask) M = ~M;
568 if (AddBits) Bits[i] |= BitWord(M) << b;
569 else Bits[i] &= ~(BitWord(M) << b);
576 } // End llvm namespace
579 /// Implement std::swap in terms of BitVector swap.
581 swap(llvm::BitVector &LHS, llvm::BitVector &RHS) {