BitVector.h revision e7962c9897cf3ac5fc731702d5e5d8963fc5c723
1//===- llvm/ADT/BitVector.h - Bit vectors -----------------------*- 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 implements the BitVector class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_BITVECTOR_H
15#define LLVM_ADT_BITVECTOR_H
16
17#include "llvm/Support/MathExtras.h"
18#include <algorithm>
19#include <cassert>
20#include <climits>
21#include <cstring>
22
23namespace llvm {
24
25class BitVector {
26  typedef unsigned long BitWord;
27
28  enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * CHAR_BIT };
29
30  BitWord  *Bits;        // Actual bits.
31  unsigned Size;         // Size of bitvector in bits.
32  unsigned Capacity;     // Size of allocated memory in BitWord.
33
34public:
35  // Encapsulation of a single bit.
36  class reference {
37    friend class BitVector;
38
39    BitWord *WordRef;
40    unsigned BitPos;
41
42    reference();  // Undefined
43
44  public:
45    reference(BitVector &b, unsigned Idx) {
46      WordRef = &b.Bits[Idx / BITWORD_SIZE];
47      BitPos = Idx % BITWORD_SIZE;
48    }
49
50    ~reference() {}
51
52    reference& operator=(bool t) {
53      if (t)
54        *WordRef |= 1L << BitPos;
55      else
56        *WordRef &= ~(1L << BitPos);
57      return *this;
58    }
59
60    operator bool() const {
61      return ((*WordRef) & (1L << BitPos)) ? true : false;
62    }
63  };
64
65
66  /// BitVector default ctor - Creates an empty bitvector.
67  BitVector() : Size(0), Capacity(0) {
68    Bits = 0;
69  }
70
71  /// BitVector ctor - Creates a bitvector of specified number of bits. All
72  /// bits are initialized to the specified value.
73  explicit BitVector(unsigned s, bool t = false) : Size(s) {
74    Capacity = NumBitWords(s);
75    Bits = new BitWord[Capacity];
76    init_words(Bits, Capacity, t);
77    if (t)
78      clear_unused_bits();
79  }
80
81  /// BitVector copy ctor.
82  BitVector(const BitVector &RHS) : Size(RHS.size()) {
83    if (Size == 0) {
84      Bits = 0;
85      Capacity = 0;
86      return;
87    }
88
89    Capacity = NumBitWords(RHS.size());
90    Bits = new BitWord[Capacity];
91    std::copy(RHS.Bits, &RHS.Bits[Capacity], Bits);
92  }
93
94  ~BitVector() {
95    delete[] Bits;
96  }
97
98  /// empty - Tests whether there are no bits in this bitvector.
99  bool empty() const { return Size == 0; }
100
101  /// size - Returns the number of bits in this bitvector.
102  unsigned size() const { return Size; }
103
104  /// count - Returns the number of bits which are set.
105  unsigned count() const {
106    unsigned NumBits = 0;
107    for (unsigned i = 0; i < NumBitWords(size()); ++i)
108      if (sizeof(BitWord) == 4)
109        NumBits += CountPopulation_32((uint32_t)Bits[i]);
110      else if (sizeof(BitWord) == 8)
111        NumBits += CountPopulation_64(Bits[i]);
112      else
113        assert(0 && "Unsupported!");
114    return NumBits;
115  }
116
117  /// any - Returns true if any bit is set.
118  bool any() const {
119    for (unsigned i = 0; i < NumBitWords(size()); ++i)
120      if (Bits[i] != 0)
121        return true;
122    return false;
123  }
124
125  /// none - Returns true if none of the bits are set.
126  bool none() const {
127    return !any();
128  }
129
130  /// find_first - Returns the index of the first set bit, -1 if none
131  /// of the bits are set.
132  int find_first() const {
133    for (unsigned i = 0; i < NumBitWords(size()); ++i)
134      if (Bits[i] != 0) {
135        if (sizeof(BitWord) == 4)
136          return i * BITWORD_SIZE + CountTrailingZeros_32((uint32_t)Bits[i]);
137        else if (sizeof(BitWord) == 8)
138          return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
139        else
140          assert(0 && "Unsupported!");
141      }
142    return -1;
143  }
144
145  /// find_next - Returns the index of the next set bit following the
146  /// "Prev" bit. Returns -1 if the next set bit is not found.
147  int find_next(unsigned Prev) const {
148    ++Prev;
149    if (Prev >= Size)
150      return -1;
151
152    unsigned WordPos = Prev / BITWORD_SIZE;
153    unsigned BitPos = Prev % BITWORD_SIZE;
154    BitWord Copy = Bits[WordPos];
155    // Mask off previous bits.
156    Copy &= ~0L << BitPos;
157
158    if (Copy != 0) {
159      if (sizeof(BitWord) == 4)
160        return WordPos * BITWORD_SIZE + CountTrailingZeros_32((uint32_t)Copy);
161      else if (sizeof(BitWord) == 8)
162        return WordPos * BITWORD_SIZE + CountTrailingZeros_64(Copy);
163      else
164        assert(0 && "Unsupported!");
165    }
166
167    // Check subsequent words.
168    for (unsigned i = WordPos+1; i < NumBitWords(size()); ++i)
169      if (Bits[i] != 0) {
170        if (sizeof(BitWord) == 4)
171          return i * BITWORD_SIZE + CountTrailingZeros_32((uint32_t)Bits[i]);
172        else if (sizeof(BitWord) == 8)
173          return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
174        else
175          assert(0 && "Unsupported!");
176      }
177    return -1;
178  }
179
180  /// clear - Clear all bits.
181  void clear() {
182    Size = 0;
183  }
184
185  /// resize - Grow or shrink the bitvector.
186  void resize(unsigned N, bool t = false) {
187    if (N > Capacity * BITWORD_SIZE) {
188      unsigned OldCapacity = Capacity;
189      grow(N);
190      init_words(&Bits[OldCapacity], (Capacity-OldCapacity), t);
191    }
192
193    // Set any old unused bits that are now included in the BitVector. This
194    // may set bits that are not included in the new vector, but we will clear
195    // them back out below.
196    if (N > Size)
197      set_unused_bits(t);
198
199    // Update the size, and clear out any bits that are now unused
200    unsigned OldSize = Size;
201    Size = N;
202    if (t || N < OldSize)
203      clear_unused_bits();
204  }
205
206  void reserve(unsigned N) {
207    if (N > Capacity * BITWORD_SIZE)
208      grow(N);
209  }
210
211  // Set, reset, flip
212  BitVector &set() {
213    init_words(Bits, Capacity, true);
214    clear_unused_bits();
215    return *this;
216  }
217
218  BitVector &set(unsigned Idx) {
219    Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
220    return *this;
221  }
222
223  BitVector &reset() {
224    init_words(Bits, Capacity, false);
225    return *this;
226  }
227
228  BitVector &reset(unsigned Idx) {
229    Bits[Idx / BITWORD_SIZE] &= ~(1L << (Idx % BITWORD_SIZE));
230    return *this;
231  }
232
233  BitVector &flip() {
234    for (unsigned i = 0; i < NumBitWords(size()); ++i)
235      Bits[i] = ~Bits[i];
236    clear_unused_bits();
237    return *this;
238  }
239
240  BitVector &flip(unsigned Idx) {
241    Bits[Idx / BITWORD_SIZE] ^= 1L << (Idx % BITWORD_SIZE);
242    return *this;
243  }
244
245  // No argument flip.
246  BitVector operator~() const {
247    return BitVector(*this).flip();
248  }
249
250  // Indexing.
251  reference operator[](unsigned Idx) {
252    assert (Idx < Size && "Out-of-bounds Bit access.");
253    return reference(*this, Idx);
254  }
255
256  bool operator[](unsigned Idx) const {
257    assert (Idx < Size && "Out-of-bounds Bit access.");
258    BitWord Mask = 1L << (Idx % BITWORD_SIZE);
259    return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
260  }
261
262  bool test(unsigned Idx) const {
263    return (*this)[Idx];
264  }
265
266  // Comparison operators.
267  bool operator==(const BitVector &RHS) const {
268    unsigned ThisWords = NumBitWords(size());
269    unsigned RHSWords  = NumBitWords(RHS.size());
270    unsigned i;
271    for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
272      if (Bits[i] != RHS.Bits[i])
273        return false;
274
275    // Verify that any extra words are all zeros.
276    if (i != ThisWords) {
277      for (; i != ThisWords; ++i)
278        if (Bits[i])
279          return false;
280    } else if (i != RHSWords) {
281      for (; i != RHSWords; ++i)
282        if (RHS.Bits[i])
283          return false;
284    }
285    return true;
286  }
287
288  bool operator!=(const BitVector &RHS) const {
289    return !(*this == RHS);
290  }
291
292  // Intersection, union, disjoint union.
293  BitVector &operator&=(const BitVector &RHS) {
294    unsigned ThisWords = NumBitWords(size());
295    unsigned RHSWords  = NumBitWords(RHS.size());
296    unsigned i;
297    for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
298      Bits[i] &= RHS.Bits[i];
299
300    // Any bits that are just in this bitvector become zero, because they aren't
301    // in the RHS bit vector.  Any words only in RHS are ignored because they
302    // are already zero in the LHS.
303    for (; i != ThisWords; ++i)
304      Bits[i] = 0;
305
306    return *this;
307  }
308
309  BitVector &operator|=(const BitVector &RHS) {
310    if (size() < RHS.size())
311      resize(RHS.size());
312    for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
313      Bits[i] |= RHS.Bits[i];
314    return *this;
315  }
316
317  BitVector &operator^=(const BitVector &RHS) {
318    if (size() < RHS.size())
319      resize(RHS.size());
320    for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
321      Bits[i] ^= RHS.Bits[i];
322    return *this;
323  }
324
325  // Assignment operator.
326  const BitVector &operator=(const BitVector &RHS) {
327    if (this == &RHS) return *this;
328
329    Size = RHS.size();
330    unsigned RHSWords = NumBitWords(Size);
331    if (Size <= Capacity * BITWORD_SIZE) {
332      std::copy(RHS.Bits, &RHS.Bits[RHSWords], Bits);
333      clear_unused_bits();
334      return *this;
335    }
336
337    // Grow the bitvector to have enough elements.
338    Capacity = RHSWords;
339    BitWord *NewBits = new BitWord[Capacity];
340    std::copy(RHS.Bits, &RHS.Bits[RHSWords], NewBits);
341
342    // Destroy the old bits.
343    delete[] Bits;
344    Bits = NewBits;
345
346    return *this;
347  }
348
349  void swap(BitVector &RHS) {
350    std::swap(Bits, RHS.Bits);
351    std::swap(Size, RHS.Size);
352    std::swap(Capacity, RHS.Capacity);
353  }
354
355private:
356  unsigned NumBitWords(unsigned S) const {
357    return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
358  }
359
360  // Set the unused bits in the high words.
361  void set_unused_bits(bool t = true) {
362    //  Set high words first.
363    unsigned UsedWords = NumBitWords(Size);
364    if (Capacity > UsedWords)
365      init_words(&Bits[UsedWords], (Capacity-UsedWords), t);
366
367    //  Then set any stray high bits of the last used word.
368    unsigned ExtraBits = Size % BITWORD_SIZE;
369    if (ExtraBits) {
370      Bits[UsedWords-1] &= ~(~0L << ExtraBits);
371      Bits[UsedWords-1] |= (0 - (BitWord)t) << ExtraBits;
372    }
373  }
374
375  // Clear the unused bits in the high words.
376  void clear_unused_bits() {
377    set_unused_bits(false);
378  }
379
380  void grow(unsigned NewSize) {
381    unsigned OldCapacity = Capacity;
382    Capacity = NumBitWords(NewSize);
383    BitWord *NewBits = new BitWord[Capacity];
384
385    // Copy the old bits over.
386    if (OldCapacity != 0)
387      std::copy(Bits, &Bits[OldCapacity], NewBits);
388
389    // Destroy the old bits.
390    delete[] Bits;
391    Bits = NewBits;
392
393    clear_unused_bits();
394  }
395
396  void init_words(BitWord *B, unsigned NumWords, bool t) {
397    memset(B, 0 - (int)t, NumWords*sizeof(BitWord));
398  }
399};
400
401inline BitVector operator&(const BitVector &LHS, const BitVector &RHS) {
402  BitVector Result(LHS);
403  Result &= RHS;
404  return Result;
405}
406
407inline BitVector operator|(const BitVector &LHS, const BitVector &RHS) {
408  BitVector Result(LHS);
409  Result |= RHS;
410  return Result;
411}
412
413inline BitVector operator^(const BitVector &LHS, const BitVector &RHS) {
414  BitVector Result(LHS);
415  Result ^= RHS;
416  return Result;
417}
418
419} // End llvm namespace
420
421namespace std {
422  /// Implement std::swap in terms of BitVector swap.
423  inline void
424  swap(llvm::BitVector &LHS, llvm::BitVector &RHS) {
425    LHS.swap(RHS);
426  }
427}
428
429#endif
430