Fix a buffer overrun detected by AddressSanitizer.
[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     for (unsigned i = 0; i < Size / BITWORD_SIZE; ++i)
142       if (Bits[i] != ~0UL)
143         return false;
144
145     // If bits remain check that they are ones. The unused bits are always zero.
146     if (unsigned Remainder = Size % BITWORD_SIZE)
147       return Bits[Size / BITWORD_SIZE] == (1UL << Remainder) - 1;
148
149     return true;
150   }
151
152   /// none - Returns true if none of the bits are set.
153   bool none() const {
154     return !any();
155   }
156
157   /// find_first - Returns the index of the first set bit, -1 if none
158   /// of the bits are set.
159   int find_first() const {
160     for (unsigned i = 0; i < NumBitWords(size()); ++i)
161       if (Bits[i] != 0) {
162         if (sizeof(BitWord) == 4)
163           return i * BITWORD_SIZE + countTrailingZeros((uint32_t)Bits[i]);
164         if (sizeof(BitWord) == 8)
165           return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
166         llvm_unreachable("Unsupported!");
167       }
168     return -1;
169   }
170
171   /// find_next - Returns the index of the next set bit following the
172   /// "Prev" bit. Returns -1 if the next set bit is not found.
173   int find_next(unsigned Prev) const {
174     ++Prev;
175     if (Prev >= Size)
176       return -1;
177
178     unsigned WordPos = Prev / BITWORD_SIZE;
179     unsigned BitPos = Prev % BITWORD_SIZE;
180     BitWord Copy = Bits[WordPos];
181     // Mask off previous bits.
182     Copy &= ~0UL << BitPos;
183
184     if (Copy != 0) {
185       if (sizeof(BitWord) == 4)
186         return WordPos * BITWORD_SIZE + countTrailingZeros((uint32_t)Copy);
187       if (sizeof(BitWord) == 8)
188         return WordPos * BITWORD_SIZE + countTrailingZeros(Copy);
189       llvm_unreachable("Unsupported!");
190     }
191
192     // Check subsequent words.
193     for (unsigned i = WordPos+1; i < NumBitWords(size()); ++i)
194       if (Bits[i] != 0) {
195         if (sizeof(BitWord) == 4)
196           return i * BITWORD_SIZE + countTrailingZeros((uint32_t)Bits[i]);
197         if (sizeof(BitWord) == 8)
198           return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
199         llvm_unreachable("Unsupported!");
200       }
201     return -1;
202   }
203
204   /// clear - Clear all bits.
205   void clear() {
206     Size = 0;
207   }
208
209   /// resize - Grow or shrink the bitvector.
210   void resize(unsigned N, bool t = false) {
211     if (N > Capacity * BITWORD_SIZE) {
212       unsigned OldCapacity = Capacity;
213       grow(N);
214       init_words(&Bits[OldCapacity], (Capacity-OldCapacity), t);
215     }
216
217     // Set any old unused bits that are now included in the BitVector. This
218     // may set bits that are not included in the new vector, but we will clear
219     // them back out below.
220     if (N > Size)
221       set_unused_bits(t);
222
223     // Update the size, and clear out any bits that are now unused
224     unsigned OldSize = Size;
225     Size = N;
226     if (t || N < OldSize)
227       clear_unused_bits();
228   }
229
230   void reserve(unsigned N) {
231     if (N > Capacity * BITWORD_SIZE)
232       grow(N);
233   }
234
235   // Set, reset, flip
236   BitVector &set() {
237     init_words(Bits, Capacity, true);
238     clear_unused_bits();
239     return *this;
240   }
241
242   BitVector &set(unsigned Idx) {
243     Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
244     return *this;
245   }
246
247   /// set - Efficiently set a range of bits in [I, E)
248   BitVector &set(unsigned I, unsigned E) {
249     assert(I <= E && "Attempted to set backwards range!");
250     assert(E <= size() && "Attempted to set out-of-bounds range!");
251
252     if (I == E) return *this;
253
254     if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
255       BitWord EMask = 1UL << (E % BITWORD_SIZE);
256       BitWord IMask = 1UL << (I % BITWORD_SIZE);
257       BitWord Mask = EMask - IMask;
258       Bits[I / BITWORD_SIZE] |= Mask;
259       return *this;
260     }
261
262     BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
263     Bits[I / BITWORD_SIZE] |= PrefixMask;
264     I = RoundUpToAlignment(I, BITWORD_SIZE);
265
266     for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
267       Bits[I / BITWORD_SIZE] = ~0UL;
268
269     BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
270     if (I < E)
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     if (I < E)
310       Bits[I / BITWORD_SIZE] &= ~PostfixMask;
311
312     return *this;
313   }
314
315   BitVector &flip() {
316     for (unsigned i = 0; i < NumBitWords(size()); ++i)
317       Bits[i] = ~Bits[i];
318     clear_unused_bits();
319     return *this;
320   }
321
322   BitVector &flip(unsigned Idx) {
323     Bits[Idx / BITWORD_SIZE] ^= 1L << (Idx % BITWORD_SIZE);
324     return *this;
325   }
326
327   // Indexing.
328   reference operator[](unsigned Idx) {
329     assert (Idx < Size && "Out-of-bounds Bit access.");
330     return reference(*this, Idx);
331   }
332
333   bool operator[](unsigned Idx) const {
334     assert (Idx < Size && "Out-of-bounds Bit access.");
335     BitWord Mask = 1L << (Idx % BITWORD_SIZE);
336     return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
337   }
338
339   bool test(unsigned Idx) const {
340     return (*this)[Idx];
341   }
342
343   /// Test if any common bits are set.
344   bool anyCommon(const BitVector &RHS) const {
345     unsigned ThisWords = NumBitWords(size());
346     unsigned RHSWords  = NumBitWords(RHS.size());
347     for (unsigned i = 0, e = std::min(ThisWords, RHSWords); i != e; ++i)
348       if (Bits[i] & RHS.Bits[i])
349         return true;
350     return false;
351   }
352
353   // Comparison operators.
354   bool operator==(const BitVector &RHS) const {
355     unsigned ThisWords = NumBitWords(size());
356     unsigned RHSWords  = NumBitWords(RHS.size());
357     unsigned i;
358     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
359       if (Bits[i] != RHS.Bits[i])
360         return false;
361
362     // Verify that any extra words are all zeros.
363     if (i != ThisWords) {
364       for (; i != ThisWords; ++i)
365         if (Bits[i])
366           return false;
367     } else if (i != RHSWords) {
368       for (; i != RHSWords; ++i)
369         if (RHS.Bits[i])
370           return false;
371     }
372     return true;
373   }
374
375   bool operator!=(const BitVector &RHS) const {
376     return !(*this == RHS);
377   }
378
379   /// Intersection, union, disjoint union.
380   BitVector &operator&=(const BitVector &RHS) {
381     unsigned ThisWords = NumBitWords(size());
382     unsigned RHSWords  = NumBitWords(RHS.size());
383     unsigned i;
384     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
385       Bits[i] &= RHS.Bits[i];
386
387     // Any bits that are just in this bitvector become zero, because they aren't
388     // in the RHS bit vector.  Any words only in RHS are ignored because they
389     // are already zero in the LHS.
390     for (; i != ThisWords; ++i)
391       Bits[i] = 0;
392
393     return *this;
394   }
395
396   /// reset - Reset bits that are set in RHS. Same as *this &= ~RHS.
397   BitVector &reset(const BitVector &RHS) {
398     unsigned ThisWords = NumBitWords(size());
399     unsigned RHSWords  = NumBitWords(RHS.size());
400     unsigned i;
401     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
402       Bits[i] &= ~RHS.Bits[i];
403     return *this;
404   }
405
406   /// test - Check if (This - RHS) is zero.
407   /// This is the same as reset(RHS) and any().
408   bool test(const BitVector &RHS) const {
409     unsigned ThisWords = NumBitWords(size());
410     unsigned RHSWords  = NumBitWords(RHS.size());
411     unsigned i;
412     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
413       if ((Bits[i] & ~RHS.Bits[i]) != 0)
414         return true;
415
416     for (; i != ThisWords ; ++i)
417       if (Bits[i] != 0)
418         return true;
419
420     return false;
421   }
422
423   BitVector &operator|=(const BitVector &RHS) {
424     if (size() < RHS.size())
425       resize(RHS.size());
426     for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
427       Bits[i] |= RHS.Bits[i];
428     return *this;
429   }
430
431   BitVector &operator^=(const BitVector &RHS) {
432     if (size() < RHS.size())
433       resize(RHS.size());
434     for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
435       Bits[i] ^= RHS.Bits[i];
436     return *this;
437   }
438
439   // Assignment operator.
440   const BitVector &operator=(const BitVector &RHS) {
441     if (this == &RHS) return *this;
442
443     Size = RHS.size();
444     unsigned RHSWords = NumBitWords(Size);
445     if (Size <= Capacity * BITWORD_SIZE) {
446       if (Size)
447         std::memcpy(Bits, RHS.Bits, RHSWords * sizeof(BitWord));
448       clear_unused_bits();
449       return *this;
450     }
451
452     // Grow the bitvector to have enough elements.
453     Capacity = RHSWords;
454     BitWord *NewBits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
455     std::memcpy(NewBits, RHS.Bits, Capacity * sizeof(BitWord));
456
457     // Destroy the old bits.
458     std::free(Bits);
459     Bits = NewBits;
460
461     return *this;
462   }
463
464 #if LLVM_HAS_RVALUE_REFERENCES
465   const BitVector &operator=(BitVector &&RHS) {
466     if (this == &RHS) return *this;
467
468     std::free(Bits);
469     Bits = RHS.Bits;
470     Size = RHS.Size;
471     Capacity = RHS.Capacity;
472
473     RHS.Bits = 0;
474
475     return *this;
476   }
477 #endif
478
479   void swap(BitVector &RHS) {
480     std::swap(Bits, RHS.Bits);
481     std::swap(Size, RHS.Size);
482     std::swap(Capacity, RHS.Capacity);
483   }
484
485   //===--------------------------------------------------------------------===//
486   // Portable bit mask operations.
487   //===--------------------------------------------------------------------===//
488   //
489   // These methods all operate on arrays of uint32_t, each holding 32 bits. The
490   // fixed word size makes it easier to work with literal bit vector constants
491   // in portable code.
492   //
493   // The LSB in each word is the lowest numbered bit.  The size of a portable
494   // bit mask is always a whole multiple of 32 bits.  If no bit mask size is
495   // given, the bit mask is assumed to cover the entire BitVector.
496
497   /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
498   /// This computes "*this |= Mask".
499   void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
500     applyMask<true, false>(Mask, MaskWords);
501   }
502
503   /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
504   /// Don't resize. This computes "*this &= ~Mask".
505   void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
506     applyMask<false, false>(Mask, MaskWords);
507   }
508
509   /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask.
510   /// Don't resize.  This computes "*this |= ~Mask".
511   void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
512     applyMask<true, true>(Mask, MaskWords);
513   }
514
515   /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
516   /// Don't resize.  This computes "*this &= Mask".
517   void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
518     applyMask<false, true>(Mask, MaskWords);
519   }
520
521 private:
522   unsigned NumBitWords(unsigned S) const {
523     return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
524   }
525
526   // Set the unused bits in the high words.
527   void set_unused_bits(bool t = true) {
528     //  Set high words first.
529     unsigned UsedWords = NumBitWords(Size);
530     if (Capacity > UsedWords)
531       init_words(&Bits[UsedWords], (Capacity-UsedWords), t);
532
533     //  Then set any stray high bits of the last used word.
534     unsigned ExtraBits = Size % BITWORD_SIZE;
535     if (ExtraBits) {
536       BitWord ExtraBitMask = ~0UL << ExtraBits;
537       if (t)
538         Bits[UsedWords-1] |= ExtraBitMask;
539       else
540         Bits[UsedWords-1] &= ~ExtraBitMask;
541     }
542   }
543
544   // Clear the unused bits in the high words.
545   void clear_unused_bits() {
546     set_unused_bits(false);
547   }
548
549   void grow(unsigned NewSize) {
550     Capacity = std::max(NumBitWords(NewSize), Capacity * 2);
551     Bits = (BitWord *)std::realloc(Bits, Capacity * sizeof(BitWord));
552
553     clear_unused_bits();
554   }
555
556   void init_words(BitWord *B, unsigned NumWords, bool t) {
557     memset(B, 0 - (int)t, NumWords*sizeof(BitWord));
558   }
559
560   template<bool AddBits, bool InvertMask>
561   void applyMask(const uint32_t *Mask, unsigned MaskWords) {
562     assert(BITWORD_SIZE % 32 == 0 && "Unsupported BitWord size.");
563     MaskWords = std::min(MaskWords, (size() + 31) / 32);
564     const unsigned Scale = BITWORD_SIZE / 32;
565     unsigned i;
566     for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) {
567       BitWord BW = Bits[i];
568       // This inner loop should unroll completely when BITWORD_SIZE > 32.
569       for (unsigned b = 0; b != BITWORD_SIZE; b += 32) {
570         uint32_t M = *Mask++;
571         if (InvertMask) M = ~M;
572         if (AddBits) BW |=   BitWord(M) << b;
573         else         BW &= ~(BitWord(M) << b);
574       }
575       Bits[i] = BW;
576     }
577     for (unsigned b = 0; MaskWords; b += 32, --MaskWords) {
578       uint32_t M = *Mask++;
579       if (InvertMask) M = ~M;
580       if (AddBits) Bits[i] |=   BitWord(M) << b;
581       else         Bits[i] &= ~(BitWord(M) << b);
582     }
583     if (AddBits)
584       clear_unused_bits();
585   }
586 };
587
588 } // End llvm namespace
589
590 namespace std {
591   /// Implement std::swap in terms of BitVector swap.
592   inline void
593   swap(llvm::BitVector &LHS, llvm::BitVector &RHS) {
594     LHS.swap(RHS);
595   }
596 }
597
598 #endif