Optimize BitVector::all().
[oota-llvm.git] / include / llvm / ADT / BitVector.h
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/Compiler.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/MathExtras.h"
20 #include <algorithm>
21 #include <cassert>
22 #include <climits>
23 #include <cstdlib>
24
25 namespace llvm {
26
27 class BitVector {
28   typedef unsigned long BitWord;
29
30   enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * CHAR_BIT };
31
32   BitWord  *Bits;        // Actual bits.
33   unsigned Size;         // Size of bitvector in bits.
34   unsigned Capacity;     // Size of allocated memory in BitWord.
35
36 public:
37   // Encapsulation of a single bit.
38   class reference {
39     friend class BitVector;
40
41     BitWord *WordRef;
42     unsigned BitPos;
43
44     reference();  // Undefined
45
46   public:
47     reference(BitVector &b, unsigned Idx) {
48       WordRef = &b.Bits[Idx / BITWORD_SIZE];
49       BitPos = Idx % BITWORD_SIZE;
50     }
51
52     ~reference() {}
53
54     reference &operator=(reference t) {
55       *this = bool(t);
56       return *this;
57     }
58
59     reference& operator=(bool t) {
60       if (t)
61         *WordRef |= 1L << BitPos;
62       else
63         *WordRef &= ~(1L << BitPos);
64       return *this;
65     }
66
67     operator bool() const {
68       return ((*WordRef) & (1L << BitPos)) ? true : false;
69     }
70   };
71
72
73   /// BitVector default ctor - Creates an empty bitvector.
74   BitVector() : Size(0), Capacity(0) {
75     Bits = 0;
76   }
77
78   /// BitVector ctor - Creates a bitvector of specified number of bits. All
79   /// bits are initialized to the specified value.
80   explicit BitVector(unsigned s, bool t = false) : Size(s) {
81     Capacity = NumBitWords(s);
82     Bits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
83     init_words(Bits, Capacity, t);
84     if (t)
85       clear_unused_bits();
86   }
87
88   /// BitVector copy ctor.
89   BitVector(const BitVector &RHS) : Size(RHS.size()) {
90     if (Size == 0) {
91       Bits = 0;
92       Capacity = 0;
93       return;
94     }
95
96     Capacity = NumBitWords(RHS.size());
97     Bits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
98     std::memcpy(Bits, RHS.Bits, Capacity * sizeof(BitWord));
99   }
100
101 #if LLVM_HAS_RVALUE_REFERENCES
102   BitVector(BitVector &&RHS)
103     : Bits(RHS.Bits), Size(RHS.Size), Capacity(RHS.Capacity) {
104     RHS.Bits = 0;
105   }
106 #endif
107
108   ~BitVector() {
109     std::free(Bits);
110   }
111
112   /// empty - Tests whether there are no bits in this bitvector.
113   bool empty() const { return Size == 0; }
114
115   /// size - Returns the number of bits in this bitvector.
116   unsigned size() const { return Size; }
117
118   /// count - Returns the number of bits which are set.
119   unsigned count() const {
120     unsigned NumBits = 0;
121     for (unsigned i = 0; i < NumBitWords(size()); ++i)
122       if (sizeof(BitWord) == 4)
123         NumBits += CountPopulation_32((uint32_t)Bits[i]);
124       else if (sizeof(BitWord) == 8)
125         NumBits += CountPopulation_64(Bits[i]);
126       else
127         llvm_unreachable("Unsupported!");
128     return NumBits;
129   }
130
131   /// any - Returns true if any bit is set.
132   bool any() const {
133     for (unsigned i = 0; i < NumBitWords(size()); ++i)
134       if (Bits[i] != 0)
135         return true;
136     return false;
137   }
138
139   /// all - Returns true if all bits are set.
140   bool all() const {
141     if (empty())
142       return true;
143
144     for (unsigned i = 0; i < NumBitWords(size()) - 1; ++i)
145       if (Bits[i] != ~0UL)
146         return false;
147
148     // For the last word check that the lower bits are ones. The unused bits are
149     // always zero.
150     return Bits[NumBitWords(size()) - 1] == ~(~0UL << (Size % BITWORD_SIZE));
151   }
152
153   /// none - Returns true if none of the bits are set.
154   bool none() const {
155     return !any();
156   }
157
158   /// find_first - Returns the index of the first set bit, -1 if none
159   /// of the bits are set.
160   int find_first() const {
161     for (unsigned i = 0; i < NumBitWords(size()); ++i)
162       if (Bits[i] != 0) {
163         if (sizeof(BitWord) == 4)
164           return i * BITWORD_SIZE + countTrailingZeros((uint32_t)Bits[i]);
165         if (sizeof(BitWord) == 8)
166           return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
167         llvm_unreachable("Unsupported!");
168       }
169     return -1;
170   }
171
172   /// find_next - Returns the index of the next set bit following the
173   /// "Prev" bit. Returns -1 if the next set bit is not found.
174   int find_next(unsigned Prev) const {
175     ++Prev;
176     if (Prev >= Size)
177       return -1;
178
179     unsigned WordPos = Prev / BITWORD_SIZE;
180     unsigned BitPos = Prev % BITWORD_SIZE;
181     BitWord Copy = Bits[WordPos];
182     // Mask off previous bits.
183     Copy &= ~0UL << BitPos;
184
185     if (Copy != 0) {
186       if (sizeof(BitWord) == 4)
187         return WordPos * BITWORD_SIZE + countTrailingZeros((uint32_t)Copy);
188       if (sizeof(BitWord) == 8)
189         return WordPos * BITWORD_SIZE + countTrailingZeros(Copy);
190       llvm_unreachable("Unsupported!");
191     }
192
193     // Check subsequent words.
194     for (unsigned i = WordPos+1; i < NumBitWords(size()); ++i)
195       if (Bits[i] != 0) {
196         if (sizeof(BitWord) == 4)
197           return i * BITWORD_SIZE + countTrailingZeros((uint32_t)Bits[i]);
198         if (sizeof(BitWord) == 8)
199           return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
200         llvm_unreachable("Unsupported!");
201       }
202     return -1;
203   }
204
205   /// clear - Clear all bits.
206   void clear() {
207     Size = 0;
208   }
209
210   /// resize - Grow or shrink the bitvector.
211   void resize(unsigned N, bool t = false) {
212     if (N > Capacity * BITWORD_SIZE) {
213       unsigned OldCapacity = Capacity;
214       grow(N);
215       init_words(&Bits[OldCapacity], (Capacity-OldCapacity), t);
216     }
217
218     // Set any old unused bits that are now included in the BitVector. This
219     // may set bits that are not included in the new vector, but we will clear
220     // them back out below.
221     if (N > Size)
222       set_unused_bits(t);
223
224     // Update the size, and clear out any bits that are now unused
225     unsigned OldSize = Size;
226     Size = N;
227     if (t || N < OldSize)
228       clear_unused_bits();
229   }
230
231   void reserve(unsigned N) {
232     if (N > Capacity * BITWORD_SIZE)
233       grow(N);
234   }
235
236   // Set, reset, flip
237   BitVector &set() {
238     init_words(Bits, Capacity, true);
239     clear_unused_bits();
240     return *this;
241   }
242
243   BitVector &set(unsigned Idx) {
244     Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
245     return *this;
246   }
247
248   /// set - Efficiently set a range of bits in [I, E)
249   BitVector &set(unsigned I, unsigned E) {
250     assert(I <= E && "Attempted to set backwards range!");
251     assert(E <= size() && "Attempted to set out-of-bounds range!");
252
253     if (I == E) return *this;
254
255     if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
256       BitWord EMask = 1UL << (E % BITWORD_SIZE);
257       BitWord IMask = 1UL << (I % BITWORD_SIZE);
258       BitWord Mask = EMask - IMask;
259       Bits[I / BITWORD_SIZE] |= Mask;
260       return *this;
261     }
262
263     BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
264     Bits[I / BITWORD_SIZE] |= PrefixMask;
265     I = RoundUpToAlignment(I, BITWORD_SIZE);
266
267     for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
268       Bits[I / BITWORD_SIZE] = ~0UL;
269
270     BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
271     Bits[I / BITWORD_SIZE] |= PostfixMask;
272
273     return *this;
274   }
275
276   BitVector &reset() {
277     init_words(Bits, Capacity, false);
278     return *this;
279   }
280
281   BitVector &reset(unsigned Idx) {
282     Bits[Idx / BITWORD_SIZE] &= ~(1L << (Idx % BITWORD_SIZE));
283     return *this;
284   }
285
286   /// reset - Efficiently reset a range of bits in [I, E)
287   BitVector &reset(unsigned I, unsigned E) {
288     assert(I <= E && "Attempted to reset backwards range!");
289     assert(E <= size() && "Attempted to reset out-of-bounds range!");
290
291     if (I == E) return *this;
292
293     if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
294       BitWord EMask = 1UL << (E % BITWORD_SIZE);
295       BitWord IMask = 1UL << (I % BITWORD_SIZE);
296       BitWord Mask = EMask - IMask;
297       Bits[I / BITWORD_SIZE] &= ~Mask;
298       return *this;
299     }
300
301     BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
302     Bits[I / BITWORD_SIZE] &= ~PrefixMask;
303     I = RoundUpToAlignment(I, BITWORD_SIZE);
304
305     for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
306       Bits[I / BITWORD_SIZE] = 0UL;
307
308     BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
309     Bits[I / BITWORD_SIZE] &= ~PostfixMask;
310
311     return *this;
312   }
313
314   BitVector &flip() {
315     for (unsigned i = 0; i < NumBitWords(size()); ++i)
316       Bits[i] = ~Bits[i];
317     clear_unused_bits();
318     return *this;
319   }
320
321   BitVector &flip(unsigned Idx) {
322     Bits[Idx / BITWORD_SIZE] ^= 1L << (Idx % BITWORD_SIZE);
323     return *this;
324   }
325
326   // Indexing.
327   reference operator[](unsigned Idx) {
328     assert (Idx < Size && "Out-of-bounds Bit access.");
329     return reference(*this, Idx);
330   }
331
332   bool operator[](unsigned Idx) const {
333     assert (Idx < Size && "Out-of-bounds Bit access.");
334     BitWord Mask = 1L << (Idx % BITWORD_SIZE);
335     return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
336   }
337
338   bool test(unsigned Idx) const {
339     return (*this)[Idx];
340   }
341
342   /// Test if any common bits are set.
343   bool anyCommon(const BitVector &RHS) const {
344     unsigned ThisWords = NumBitWords(size());
345     unsigned RHSWords  = NumBitWords(RHS.size());
346     for (unsigned i = 0, e = std::min(ThisWords, RHSWords); i != e; ++i)
347       if (Bits[i] & RHS.Bits[i])
348         return true;
349     return false;
350   }
351
352   // Comparison operators.
353   bool operator==(const BitVector &RHS) const {
354     unsigned ThisWords = NumBitWords(size());
355     unsigned RHSWords  = NumBitWords(RHS.size());
356     unsigned i;
357     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
358       if (Bits[i] != RHS.Bits[i])
359         return false;
360
361     // Verify that any extra words are all zeros.
362     if (i != ThisWords) {
363       for (; i != ThisWords; ++i)
364         if (Bits[i])
365           return false;
366     } else if (i != RHSWords) {
367       for (; i != RHSWords; ++i)
368         if (RHS.Bits[i])
369           return false;
370     }
371     return true;
372   }
373
374   bool operator!=(const BitVector &RHS) const {
375     return !(*this == RHS);
376   }
377
378   /// Intersection, union, disjoint union.
379   BitVector &operator&=(const BitVector &RHS) {
380     unsigned ThisWords = NumBitWords(size());
381     unsigned RHSWords  = NumBitWords(RHS.size());
382     unsigned i;
383     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
384       Bits[i] &= RHS.Bits[i];
385
386     // Any bits that are just in this bitvector become zero, because they aren't
387     // in the RHS bit vector.  Any words only in RHS are ignored because they
388     // are already zero in the LHS.
389     for (; i != ThisWords; ++i)
390       Bits[i] = 0;
391
392     return *this;
393   }
394
395   /// reset - Reset bits that are set in RHS. Same as *this &= ~RHS.
396   BitVector &reset(const BitVector &RHS) {
397     unsigned ThisWords = NumBitWords(size());
398     unsigned RHSWords  = NumBitWords(RHS.size());
399     unsigned i;
400     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
401       Bits[i] &= ~RHS.Bits[i];
402     return *this;
403   }
404
405   /// test - Check if (This - RHS) is zero.
406   /// This is the same as reset(RHS) and any().
407   bool test(const BitVector &RHS) const {
408     unsigned ThisWords = NumBitWords(size());
409     unsigned RHSWords  = NumBitWords(RHS.size());
410     unsigned i;
411     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
412       if ((Bits[i] & ~RHS.Bits[i]) != 0)
413         return true;
414
415     for (; i != ThisWords ; ++i)
416       if (Bits[i] != 0)
417         return true;
418
419     return false;
420   }
421
422   BitVector &operator|=(const BitVector &RHS) {
423     if (size() < RHS.size())
424       resize(RHS.size());
425     for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
426       Bits[i] |= RHS.Bits[i];
427     return *this;
428   }
429
430   BitVector &operator^=(const BitVector &RHS) {
431     if (size() < RHS.size())
432       resize(RHS.size());
433     for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
434       Bits[i] ^= RHS.Bits[i];
435     return *this;
436   }
437
438   // Assignment operator.
439   const BitVector &operator=(const BitVector &RHS) {
440     if (this == &RHS) return *this;
441
442     Size = RHS.size();
443     unsigned RHSWords = NumBitWords(Size);
444     if (Size <= Capacity * BITWORD_SIZE) {
445       if (Size)
446         std::memcpy(Bits, RHS.Bits, RHSWords * sizeof(BitWord));
447       clear_unused_bits();
448       return *this;
449     }
450
451     // Grow the bitvector to have enough elements.
452     Capacity = RHSWords;
453     BitWord *NewBits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
454     std::memcpy(NewBits, RHS.Bits, Capacity * sizeof(BitWord));
455
456     // Destroy the old bits.
457     std::free(Bits);
458     Bits = NewBits;
459
460     return *this;
461   }
462
463 #if LLVM_HAS_RVALUE_REFERENCES
464   const BitVector &operator=(BitVector &&RHS) {
465     if (this == &RHS) return *this;
466
467     std::free(Bits);
468     Bits = RHS.Bits;
469     Size = RHS.Size;
470     Capacity = RHS.Capacity;
471
472     RHS.Bits = 0;
473
474     return *this;
475   }
476 #endif
477
478   void swap(BitVector &RHS) {
479     std::swap(Bits, RHS.Bits);
480     std::swap(Size, RHS.Size);
481     std::swap(Capacity, RHS.Capacity);
482   }
483
484   //===--------------------------------------------------------------------===//
485   // Portable bit mask operations.
486   //===--------------------------------------------------------------------===//
487   //
488   // These methods all operate on arrays of uint32_t, each holding 32 bits. The
489   // fixed word size makes it easier to work with literal bit vector constants
490   // in portable code.
491   //
492   // The LSB in each word is the lowest numbered bit.  The size of a portable
493   // bit mask is always a whole multiple of 32 bits.  If no bit mask size is
494   // given, the bit mask is assumed to cover the entire BitVector.
495
496   /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
497   /// This computes "*this |= Mask".
498   void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
499     applyMask<true, false>(Mask, MaskWords);
500   }
501
502   /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
503   /// Don't resize. This computes "*this &= ~Mask".
504   void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
505     applyMask<false, false>(Mask, MaskWords);
506   }
507
508   /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask.
509   /// Don't resize.  This computes "*this |= ~Mask".
510   void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
511     applyMask<true, true>(Mask, MaskWords);
512   }
513
514   /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
515   /// Don't resize.  This computes "*this &= Mask".
516   void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
517     applyMask<false, true>(Mask, MaskWords);
518   }
519
520 private:
521   unsigned NumBitWords(unsigned S) const {
522     return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
523   }
524
525   // Set the unused bits in the high words.
526   void set_unused_bits(bool t = true) {
527     //  Set high words first.
528     unsigned UsedWords = NumBitWords(Size);
529     if (Capacity > UsedWords)
530       init_words(&Bits[UsedWords], (Capacity-UsedWords), t);
531
532     //  Then set any stray high bits of the last used word.
533     unsigned ExtraBits = Size % BITWORD_SIZE;
534     if (ExtraBits) {
535       BitWord ExtraBitMask = ~0UL << ExtraBits;
536       if (t)
537         Bits[UsedWords-1] |= ExtraBitMask;
538       else
539         Bits[UsedWords-1] &= ~ExtraBitMask;
540     }
541   }
542
543   // Clear the unused bits in the high words.
544   void clear_unused_bits() {
545     set_unused_bits(false);
546   }
547
548   void grow(unsigned NewSize) {
549     Capacity = std::max(NumBitWords(NewSize), Capacity * 2);
550     Bits = (BitWord *)std::realloc(Bits, Capacity * sizeof(BitWord));
551
552     clear_unused_bits();
553   }
554
555   void init_words(BitWord *B, unsigned NumWords, bool t) {
556     memset(B, 0 - (int)t, NumWords*sizeof(BitWord));
557   }
558
559   template<bool AddBits, bool InvertMask>
560   void applyMask(const uint32_t *Mask, unsigned MaskWords) {
561     assert(BITWORD_SIZE % 32 == 0 && "Unsupported BitWord size.");
562     MaskWords = std::min(MaskWords, (size() + 31) / 32);
563     const unsigned Scale = BITWORD_SIZE / 32;
564     unsigned i;
565     for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) {
566       BitWord BW = Bits[i];
567       // This inner loop should unroll completely when BITWORD_SIZE > 32.
568       for (unsigned b = 0; b != BITWORD_SIZE; b += 32) {
569         uint32_t M = *Mask++;
570         if (InvertMask) M = ~M;
571         if (AddBits) BW |=   BitWord(M) << b;
572         else         BW &= ~(BitWord(M) << b);
573       }
574       Bits[i] = BW;
575     }
576     for (unsigned b = 0; MaskWords; b += 32, --MaskWords) {
577       uint32_t M = *Mask++;
578       if (InvertMask) M = ~M;
579       if (AddBits) Bits[i] |=   BitWord(M) << b;
580       else         Bits[i] &= ~(BitWord(M) << b);
581     }
582     if (AddBits)
583       clear_unused_bits();
584   }
585 };
586
587 } // End llvm namespace
588
589 namespace std {
590   /// Implement std::swap in terms of BitVector swap.
591   inline void
592   swap(llvm::BitVector &LHS, llvm::BitVector &RHS) {
593     LHS.swap(RHS);
594   }
595 }
596
597 #endif