LLVM 23.0.0git
BitVector.h
Go to the documentation of this file.
1//===- llvm/ADT/BitVector.h - Bit vectors -----------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
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/ADT/ArrayRef.h"
21#include <algorithm>
22#include <cassert>
23#include <climits>
24#include <cstdint>
25#include <cstdlib>
26#include <cstring>
27#include <iterator>
28#include <utility>
29
30namespace llvm {
31
32/// ForwardIterator for the bits that are set.
33/// Iterators get invalidated when resize / reserve is called.
34template <typename BitVectorT> class const_set_bits_iterator_impl {
35 const BitVectorT &Parent;
36 int Current = 0;
37
38 void advance() {
39 assert(Current != -1 && "Trying to advance past end.");
40 Current = Parent.find_next(Current);
41 }
42
43 void retreat() {
44 if (Current == -1) {
45 Current = Parent.find_last();
46 } else {
47 Current = Parent.find_prev(Current);
48 }
49 }
50
51public:
52 using iterator_category = std::bidirectional_iterator_tag;
53 using difference_type = std::ptrdiff_t;
55 using pointer = const value_type *;
57
58 const_set_bits_iterator_impl(const BitVectorT &Parent, int Current)
59 : Parent(Parent), Current(Current) {}
60 explicit const_set_bits_iterator_impl(const BitVectorT &Parent)
61 : const_set_bits_iterator_impl(Parent, Parent.find_first()) {}
63
65 auto Prev = *this;
66 advance();
67 return Prev;
68 }
69
71 advance();
72 return *this;
73 }
74
76 auto Prev = *this;
77 retreat();
78 return Prev;
79 }
80
82 retreat();
83 return *this;
84 }
85
86 unsigned operator*() const { return Current; }
87
89 assert(&Parent == &Other.Parent &&
90 "Comparing iterators from different BitVectors");
91 return Current == Other.Current;
92 }
93
95 assert(&Parent == &Other.Parent &&
96 "Comparing iterators from different BitVectors");
97 return Current != Other.Current;
98 }
99};
100
102 using BitWord = uintptr_t;
103
104 enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * CHAR_BIT };
105
106 static_assert(BITWORD_SIZE == 64 || BITWORD_SIZE == 32,
107 "Unsupported word size");
108
109 using Storage = SmallVector<BitWord>;
110
111 Storage Bits; // Actual bits.
112 unsigned Size = 0; // Size of bitvector in bits.
113
114public:
116
117 // Encapsulation of a single bit.
118 class reference {
119
120 BitWord *WordRef;
121 unsigned BitPos;
122
123 public:
124 reference(BitVector &b, unsigned Idx) {
125 WordRef = &b.Bits[Idx / BITWORD_SIZE];
126 BitPos = Idx % BITWORD_SIZE;
127 }
128
129 reference() = delete;
130 reference(const reference&) = default;
131
133 *this = bool(t);
134 return *this;
135 }
136
138 if (t)
139 *WordRef |= BitWord(1) << BitPos;
140 else
141 *WordRef &= ~(BitWord(1) << BitPos);
142 return *this;
143 }
144
145 operator bool() const {
146 return ((*WordRef) & (BitWord(1) << BitPos)) != 0;
147 }
148 };
149
152
157 return const_set_bits_iterator(*this, -1);
158 }
162
163 /// BitVector default ctor - Creates an empty bitvector.
164 BitVector() = default;
165
166 /// BitVector ctor - Creates a bitvector of specified number of bits. All
167 /// bits are initialized to the specified value.
168 explicit BitVector(unsigned s, bool t = false)
169 : Bits(NumBitWords(s), 0 - (BitWord)t), Size(s) {
170 if (t)
171 clear_unused_bits();
172 }
173
174 /// Returns whether there are no bits in this bitvector.
175 bool empty() const { return Size == 0; }
176
177 /// Returns the number of bits in this bitvector.
178 size_type size() const { return Size; }
179
180 /// Returns the number of bits which are set.
181 size_type count() const {
182 unsigned NumBits = 0;
183 for (auto Bit : Bits)
184 NumBits += llvm::popcount(Bit);
185 return NumBits;
186 }
187
188 /// Returns true if any bit is set.
189 bool any() const {
190 return any_of(Bits, [](BitWord Bit) { return Bit != 0; });
191 }
192
193 /// Returns true if all bits are set.
194 bool all() const {
195 for (unsigned i = 0; i < Size / BITWORD_SIZE; ++i)
196 if (Bits[i] != ~BitWord(0))
197 return false;
198
199 // If bits remain check that they are ones. The unused bits are always zero.
200 if (unsigned Remainder = Size % BITWORD_SIZE)
201 return Bits[Size / BITWORD_SIZE] == (BitWord(1) << Remainder) - 1;
202
203 return true;
204 }
205
206 /// Returns true if none of the bits are set.
207 bool none() const {
208 return !any();
209 }
210
211 /// Returns the index of the first set/unset bit, depending on \p Set, in
212 /// the range [Begin, End). Returns -1 if all bits in the range are unset/set.
213 int find_first_in(unsigned Begin, unsigned End, bool Set = true) const {
214 assert(Begin <= End && End <= Size);
215 if (Begin == End)
216 return -1;
217
218 unsigned FirstWord = Begin / BITWORD_SIZE;
219 unsigned LastWord = (End - 1) / BITWORD_SIZE;
220
221 // Check subsequent words.
222 // The code below is based on search for the first _set_ bit. If
223 // we're searching for the first _unset_, we just take the
224 // complement of each word before we use it and apply
225 // the same method.
226 for (unsigned i = FirstWord; i <= LastWord; ++i) {
227 BitWord Copy = Bits[i];
228 if (!Set)
229 Copy = ~Copy;
230
231 if (i == FirstWord) {
232 unsigned FirstBit = Begin % BITWORD_SIZE;
233 Copy &= maskTrailingZeros<BitWord>(FirstBit);
234 }
235
236 if (i == LastWord) {
237 unsigned LastBit = (End - 1) % BITWORD_SIZE;
238 Copy &= maskTrailingOnes<BitWord>(LastBit + 1);
239 }
240 if (Copy != 0)
241 return i * BITWORD_SIZE + llvm::countr_zero(Copy);
242 }
243 return -1;
244 }
245
246 /// Returns the index of the last set bit in the range [Begin, End).
247 /// Returns -1 if all bits in the range are unset.
248 int find_last_in(unsigned Begin, unsigned End) const {
249 assert(Begin <= End && End <= Size);
250 if (Begin == End)
251 return -1;
252
253 unsigned LastWord = (End - 1) / BITWORD_SIZE;
254 unsigned FirstWord = Begin / BITWORD_SIZE;
255
256 for (unsigned i = LastWord + 1; i >= FirstWord + 1; --i) {
257 unsigned CurrentWord = i - 1;
258
259 BitWord Copy = Bits[CurrentWord];
260 if (CurrentWord == LastWord) {
261 unsigned LastBit = (End - 1) % BITWORD_SIZE;
262 Copy &= maskTrailingOnes<BitWord>(LastBit + 1);
263 }
264
265 if (CurrentWord == FirstWord) {
266 unsigned FirstBit = Begin % BITWORD_SIZE;
267 Copy &= maskTrailingZeros<BitWord>(FirstBit);
268 }
269
270 if (Copy != 0)
271 return (CurrentWord + 1) * BITWORD_SIZE - llvm::countl_zero(Copy) - 1;
272 }
273
274 return -1;
275 }
276
277 /// Returns the index of the first unset bit in the range [Begin, End).
278 /// Returns -1 if all bits in the range are set.
279 int find_first_unset_in(unsigned Begin, unsigned End) const {
280 return find_first_in(Begin, End, /* Set = */ false);
281 }
282
283 /// Returns the index of the last unset bit in the range [Begin, End).
284 /// Returns -1 if all bits in the range are set.
285 int find_last_unset_in(unsigned Begin, unsigned End) const {
286 assert(Begin <= End && End <= Size);
287 if (Begin == End)
288 return -1;
289
290 unsigned LastWord = (End - 1) / BITWORD_SIZE;
291 unsigned FirstWord = Begin / BITWORD_SIZE;
292
293 for (unsigned i = LastWord + 1; i >= FirstWord + 1; --i) {
294 unsigned CurrentWord = i - 1;
295
296 BitWord Copy = Bits[CurrentWord];
297 if (CurrentWord == LastWord) {
298 unsigned LastBit = (End - 1) % BITWORD_SIZE;
299 Copy |= maskTrailingZeros<BitWord>(LastBit + 1);
300 }
301
302 if (CurrentWord == FirstWord) {
303 unsigned FirstBit = Begin % BITWORD_SIZE;
304 Copy |= maskTrailingOnes<BitWord>(FirstBit);
305 }
306
307 if (Copy != ~BitWord(0)) {
308 unsigned Result =
309 (CurrentWord + 1) * BITWORD_SIZE - llvm::countl_one(Copy) - 1;
310 return Result < Size ? Result : -1;
311 }
312 }
313 return -1;
314 }
315
316 /// Returns the index of the first set bit, -1 if none of the bits are set.
317 int find_first() const { return find_first_in(0, Size); }
318
319 /// Returns the index of the last set bit, -1 if none of the bits are set.
320 int find_last() const { return find_last_in(0, Size); }
321
322 /// Returns the index of the next set bit following the "Prev" bit.
323 /// Returns -1 if the next set bit is not found.
324 int find_next(unsigned Prev) const { return find_first_in(Prev + 1, Size); }
325
326 /// Returns the index of the first set bit that precedes the bit at
327 /// \p PriorTo. Returns -1 if all previous bits are unset.
328 int find_prev(unsigned PriorTo) const { return find_last_in(0, PriorTo); }
329
330 /// Returns the index of the first unset bit, -1 if all of the bits are set.
331 int find_first_unset() const { return find_first_unset_in(0, Size); }
332
333 /// Returns the index of the next unset bit following the \p Prev bit.
334 /// Returns -1 if all remaining bits are set.
335 int find_next_unset(unsigned Prev) const {
336 return find_first_unset_in(Prev + 1, Size);
337 }
338
339 /// Returns the index of the last unset bit, -1 if all of the bits are set.
340 int find_last_unset() const { return find_last_unset_in(0, Size); }
341
342 /// Returns the index of the first unset bit that precedes the bit at
343 /// \p PriorTo. Returns -1 if all previous bits are set.
344 int find_prev_unset(unsigned PriorTo) const {
345 return find_last_unset_in(0, PriorTo);
346 }
347
348 /// Removes all bits from the bitvector.
349 void clear() {
350 Size = 0;
351 Bits.clear();
352 }
353
354 /// Grow or shrink the bitvector.
355 void resize(unsigned N, bool t = false) {
356 set_unused_bits(t);
357 Size = N;
358 Bits.resize(NumBitWords(N), 0 - BitWord(t));
359 clear_unused_bits();
360 }
361
362 /// Reserve space for atleast \p N bits in the bitvector.
363 void reserve(unsigned N) { Bits.reserve(NumBitWords(N)); }
364
365 /// Set all bits in the bitvector.
367 init_words(true);
368 clear_unused_bits();
369 return *this;
370 }
371
372 // Set bit \p Idx in the bitvector.
373 BitVector &set(unsigned Idx) {
374 assert(Idx < Size && "access in bound");
375 Bits[Idx / BITWORD_SIZE] |= BitWord(1) << (Idx % BITWORD_SIZE);
376 return *this;
377 }
378
379 /// Efficiently set a range of bits in [I, E)
380 BitVector &set(unsigned I, unsigned E) {
381 assert(I <= E && "Attempted to set backwards range!");
382 assert(E <= size() && "Attempted to set out-of-bounds range!");
383
384 if (I == E) return *this;
385
386 if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
387 BitWord EMask = BitWord(1) << (E % BITWORD_SIZE);
388 BitWord IMask = BitWord(1) << (I % BITWORD_SIZE);
389 BitWord Mask = EMask - IMask;
390 Bits[I / BITWORD_SIZE] |= Mask;
391 return *this;
392 }
393
394 BitWord PrefixMask = ~BitWord(0) << (I % BITWORD_SIZE);
395 Bits[I / BITWORD_SIZE] |= PrefixMask;
396 I = alignTo(I, BITWORD_SIZE);
397
398 for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
399 Bits[I / BITWORD_SIZE] = ~BitWord(0);
400
401 BitWord PostfixMask = (BitWord(1) << (E % BITWORD_SIZE)) - 1;
402 if (I < E)
403 Bits[I / BITWORD_SIZE] |= PostfixMask;
404
405 return *this;
406 }
407
408 /// Reset all bits in the bitvector.
410 init_words(false);
411 return *this;
412 }
413
414 /// Reset bit \p Idx in the bitvector.
415 BitVector &reset(unsigned Idx) {
416 Bits[Idx / BITWORD_SIZE] &= ~(BitWord(1) << (Idx % BITWORD_SIZE));
417 return *this;
418 }
419
420 /// Efficiently reset a range of bits in [I, E)
421 BitVector &reset(unsigned I, unsigned E) {
422 assert(I <= E && "Attempted to reset backwards range!");
423 assert(E <= size() && "Attempted to reset out-of-bounds range!");
424
425 if (I == E) return *this;
426
427 if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
428 BitWord EMask = BitWord(1) << (E % BITWORD_SIZE);
429 BitWord IMask = BitWord(1) << (I % BITWORD_SIZE);
430 BitWord Mask = EMask - IMask;
431 Bits[I / BITWORD_SIZE] &= ~Mask;
432 return *this;
433 }
434
435 BitWord PrefixMask = ~BitWord(0) << (I % BITWORD_SIZE);
436 Bits[I / BITWORD_SIZE] &= ~PrefixMask;
437 I = alignTo(I, BITWORD_SIZE);
438
439 for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
440 Bits[I / BITWORD_SIZE] = BitWord(0);
441
442 BitWord PostfixMask = (BitWord(1) << (E % BITWORD_SIZE)) - 1;
443 if (I < E)
444 Bits[I / BITWORD_SIZE] &= ~PostfixMask;
445
446 return *this;
447 }
448
449 /// Flip all bits in the bitvector.
451 for (auto &Bit : Bits)
452 Bit = ~Bit;
453 clear_unused_bits();
454 return *this;
455 }
456
457 /// Flip bit \p Idx in the bitvector.
458 BitVector &flip(unsigned Idx) {
459 Bits[Idx / BITWORD_SIZE] ^= BitWord(1) << (Idx % BITWORD_SIZE);
460 return *this;
461 }
462
463 // Indexing.
464 reference operator[](unsigned Idx) {
465 assert (Idx < Size && "Out-of-bounds Bit access.");
466 return reference(*this, Idx);
467 }
468
469 bool operator[](unsigned Idx) const {
470 assert (Idx < Size && "Out-of-bounds Bit access.");
471 BitWord Mask = BitWord(1) << (Idx % BITWORD_SIZE);
472 return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
473 }
474
475 /// Return the last element in the bitvector.
476 bool back() const {
477 assert(!empty() && "Getting last element of empty vector.");
478 return (*this)[size() - 1];
479 }
480
481 /// Returns true if bit \p Idx is set.
482 bool test(unsigned Idx) const {
483 return (*this)[Idx];
484 }
485
486 // Push single bit to end of bitvector.
487 void push_back(bool Val) {
488 unsigned OldSize = Size;
489 unsigned NewSize = Size + 1;
490
491 // Resize, which will insert zeros.
492 // If we already fit then the unused bits will be already zero.
493 if (NewSize > getBitCapacity())
494 resize(NewSize, false);
495 else
496 Size = NewSize;
497
498 // If true, set single bit.
499 if (Val)
500 set(OldSize);
501 }
502
503 /// Pop one bit from the end of the vector.
504 void pop_back() {
505 assert(!empty() && "Empty vector has no element to pop.");
506 resize(size() - 1);
507 }
508
509 /// Test if any common bits are set.
510 bool anyCommon(const BitVector &RHS) const {
511 unsigned ThisWords = Bits.size();
512 unsigned RHSWords = RHS.Bits.size();
513 for (unsigned i = 0, e = std::min(ThisWords, RHSWords); i != e; ++i)
514 if (Bits[i] & RHS.Bits[i])
515 return true;
516 return false;
517 }
518
519 // Comparison operators.
520 bool operator==(const BitVector &RHS) const {
521 if (size() != RHS.size())
522 return false;
523 unsigned NumWords = Bits.size();
524 return std::equal(Bits.begin(), Bits.begin() + NumWords, RHS.Bits.begin());
525 }
526
527 bool operator!=(const BitVector &RHS) const { return !(*this == RHS); }
528
529 /// Intersection of this bitvector with \p RHS.
531 unsigned ThisWords = Bits.size();
532 unsigned RHSWords = RHS.Bits.size();
533 unsigned i;
534 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
535 Bits[i] &= RHS.Bits[i];
536
537 // Any bits that are just in this bitvector become zero, because they aren't
538 // in the RHS bit vector. Any words only in RHS are ignored because they
539 // are already zero in the LHS.
540 for (; i != ThisWords; ++i)
541 Bits[i] = 0;
542
543 return *this;
544 }
545
546 /// Reset bits that are set in RHS. Same as *this &= ~RHS.
548 unsigned ThisWords = Bits.size();
549 unsigned RHSWords = RHS.Bits.size();
550 for (unsigned i = 0; i != std::min(ThisWords, RHSWords); ++i)
551 Bits[i] &= ~RHS.Bits[i];
552 return *this;
553 }
554
555 /// Check if (This - RHS) is non-zero.
556 /// This is the same as reset(RHS) and any().
557 bool test(const BitVector &RHS) const {
558 unsigned ThisWords = Bits.size();
559 unsigned RHSWords = RHS.Bits.size();
560 unsigned i;
561 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
562 if ((Bits[i] & ~RHS.Bits[i]) != 0)
563 return true;
564
565 for (; i != ThisWords ; ++i)
566 if (Bits[i] != 0)
567 return true;
568
569 return false;
570 }
571
572 /// Check if This is a subset of RHS.
573 bool subsetOf(const BitVector &RHS) const { return !test(RHS); }
574
575 template <class F, class... ArgTys>
576 static BitVector &apply(F &&f, BitVector &Out, BitVector const &Arg,
577 ArgTys const &...Args) {
578 assert(((Arg.size() == Args.size()) && ...) && "consistent sizes");
579 Out.resize(Arg.size());
580 for (size_type I = 0, E = Arg.Bits.size(); I != E; ++I)
581 Out.Bits[I] = f(Arg.Bits[I], Args.Bits[I]...);
582 Out.clear_unused_bits();
583 return Out;
584 }
585
586 /// Union of this bitvector with \p RHS.
588 if (size() < RHS.size())
589 resize(RHS.size());
590 for (size_type I = 0, E = RHS.Bits.size(); I != E; ++I)
591 Bits[I] |= RHS.Bits[I];
592 return *this;
593 }
594
595 /// Disjoint union of this bitvector with \p RHS.
597 if (size() < RHS.size())
598 resize(RHS.size());
599 for (size_type I = 0, E = RHS.Bits.size(); I != E; ++I)
600 Bits[I] ^= RHS.Bits[I];
601 return *this;
602 }
603
605 assert(N <= Size);
606 if (LLVM_UNLIKELY(empty() || N == 0))
607 return *this;
608
609 unsigned NumWords = Bits.size();
610 assert(NumWords >= 1);
611
612 wordShr(N / BITWORD_SIZE);
613
614 unsigned BitDistance = N % BITWORD_SIZE;
615 if (BitDistance == 0)
616 return *this;
617
618 // When the shift size is not a multiple of the word size, then we have
619 // a tricky situation where each word in succession needs to extract some
620 // of the bits from the next word and or them into this word while
621 // shifting this word to make room for the new bits. This has to be done
622 // for every word in the array.
623
624 // Since we're shifting each word right, some bits will fall off the end
625 // of each word to the right, and empty space will be created on the left.
626 // The final word in the array will lose bits permanently, so starting at
627 // the beginning, work forwards shifting each word to the right, and
628 // OR'ing in the bits from the end of the next word to the beginning of
629 // the current word.
630
631 // Example:
632 // Starting with {0xAABBCCDD, 0xEEFF0011, 0x22334455} and shifting right
633 // by 4 bits.
634 // Step 1: Word[0] >>= 4 ; 0x0ABBCCDD
635 // Step 2: Word[0] |= 0x10000000 ; 0x1ABBCCDD
636 // Step 3: Word[1] >>= 4 ; 0x0EEFF001
637 // Step 4: Word[1] |= 0x50000000 ; 0x5EEFF001
638 // Step 5: Word[2] >>= 4 ; 0x02334455
639 // Result: { 0x1ABBCCDD, 0x5EEFF001, 0x02334455 }
640 const BitWord Mask = maskTrailingOnes<BitWord>(BitDistance);
641 const unsigned LSH = BITWORD_SIZE - BitDistance;
642
643 for (unsigned I = 0; I < NumWords - 1; ++I) {
644 Bits[I] >>= BitDistance;
645 Bits[I] |= (Bits[I + 1] & Mask) << LSH;
646 }
647
648 Bits[NumWords - 1] >>= BitDistance;
649
650 return *this;
651 }
652
654 assert(N <= Size);
655 if (LLVM_UNLIKELY(empty() || N == 0))
656 return *this;
657
658 unsigned NumWords = Bits.size();
659 assert(NumWords >= 1);
660
661 wordShl(N / BITWORD_SIZE);
662
663 unsigned BitDistance = N % BITWORD_SIZE;
664 if (BitDistance == 0)
665 return *this;
666
667 // When the shift size is not a multiple of the word size, then we have
668 // a tricky situation where each word in succession needs to extract some
669 // of the bits from the previous word and or them into this word while
670 // shifting this word to make room for the new bits. This has to be done
671 // for every word in the array. This is similar to the algorithm outlined
672 // in operator>>=, but backwards.
673
674 // Since we're shifting each word left, some bits will fall off the end
675 // of each word to the left, and empty space will be created on the right.
676 // The first word in the array will lose bits permanently, so starting at
677 // the end, work backwards shifting each word to the left, and OR'ing
678 // in the bits from the end of the next word to the beginning of the
679 // current word.
680
681 // Example:
682 // Starting with {0xAABBCCDD, 0xEEFF0011, 0x22334455} and shifting left
683 // by 4 bits.
684 // Step 1: Word[2] <<= 4 ; 0x23344550
685 // Step 2: Word[2] |= 0x0000000E ; 0x2334455E
686 // Step 3: Word[1] <<= 4 ; 0xEFF00110
687 // Step 4: Word[1] |= 0x0000000A ; 0xEFF0011A
688 // Step 5: Word[0] <<= 4 ; 0xABBCCDD0
689 // Result: { 0xABBCCDD0, 0xEFF0011A, 0x2334455E }
690 const BitWord Mask = maskLeadingOnes<BitWord>(BitDistance);
691 const unsigned RSH = BITWORD_SIZE - BitDistance;
692
693 for (int I = NumWords - 1; I > 0; --I) {
694 Bits[I] <<= BitDistance;
695 Bits[I] |= (Bits[I - 1] & Mask) >> RSH;
696 }
697 Bits[0] <<= BitDistance;
698 clear_unused_bits();
699
700 return *this;
701 }
702
704 std::swap(Bits, RHS.Bits);
705 std::swap(Size, RHS.Size);
706 }
707
708 void invalid() {
709 assert(!Size && Bits.empty());
710 Size = (unsigned)-1;
711 }
712 bool isInvalid() const { return Size == (unsigned)-1; }
713
714 ArrayRef<BitWord> getData() const { return {Bits.data(), Bits.size()}; }
715
716 //===--------------------------------------------------------------------===//
717 // Portable bit mask operations.
718 //===--------------------------------------------------------------------===//
719 //
720 // These methods all operate on arrays of uint32_t, each holding 32 bits. The
721 // fixed word size makes it easier to work with literal bit vector constants
722 // in portable code.
723 //
724 // The LSB in each word is the lowest numbered bit. The size of a portable
725 // bit mask is always a whole multiple of 32 bits. If no bit mask size is
726 // given, the bit mask is assumed to cover the entire BitVector.
727
728 /// Add '1' bits from Mask to this vector. Don't resize.
729 /// This computes "*this |= Mask".
730 void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
731 applyMask<true, false>(Mask, MaskWords);
732 }
733
734 /// Clear any bits in this vector that are set in Mask.
735 /// Don't resize. This computes "*this &= ~Mask".
736 void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
737 applyMask<false, false>(Mask, MaskWords);
738 }
739
740 /// Add a bit to this vector for every '0' bit in Mask.
741 /// Don't resize. This computes "*this |= ~Mask".
742 void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
743 applyMask<true, true>(Mask, MaskWords);
744 }
745
746 /// Clear a bit in this vector for every '0' bit in Mask.
747 /// Don't resize. This computes "*this &= Mask".
748 void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
749 applyMask<false, true>(Mask, MaskWords);
750 }
751
752private:
753 /// Perform a logical left shift of \p Count words by moving everything
754 /// \p Count words to the right in memory.
755 ///
756 /// While confusing, words are stored from least significant at Bits[0] to
757 /// most significant at Bits[NumWords-1]. A logical shift left, however,
758 /// moves the current least significant bit to a higher logical index, and
759 /// fills the previous least significant bits with 0. Thus, we actually
760 /// need to move the bytes of the memory to the right, not to the left.
761 /// Example:
762 /// Words = [0xBBBBAAAA, 0xDDDDFFFF, 0x00000000, 0xDDDD0000]
763 /// represents a BitVector where 0xBBBBAAAA contain the least significant
764 /// bits. So if we want to shift the BitVector left by 2 words, we need
765 /// to turn this into 0x00000000 0x00000000 0xBBBBAAAA 0xDDDDFFFF by using a
766 /// memmove which moves right, not left.
767 void wordShl(uint32_t Count) {
768 if (Count == 0)
769 return;
770
771 uint32_t NumWords = Bits.size();
772
773 // Since we always move Word-sized chunks of data with src and dest both
774 // aligned to a word-boundary, we don't need to worry about endianness
775 // here.
776 std::copy(Bits.begin(), Bits.begin() + NumWords - Count,
777 Bits.begin() + Count);
778 std::fill(Bits.begin(), Bits.begin() + Count, 0);
779 clear_unused_bits();
780 }
781
782 /// Perform a logical right shift of \p Count words by moving those
783 /// words to the left in memory. See wordShl for more information.
784 ///
785 void wordShr(uint32_t Count) {
786 if (Count == 0)
787 return;
788
789 uint32_t NumWords = Bits.size();
790
791 std::copy(Bits.begin() + Count, Bits.begin() + NumWords, Bits.begin());
792 std::fill(Bits.begin() + NumWords - Count, Bits.begin() + NumWords, 0);
793 }
794
795 unsigned NumBitWords(unsigned S) const {
796 return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
797 }
798
799 // Set the unused bits in the high words.
800 void set_unused_bits(bool t = true) {
801 // Then set any stray high bits of the last used word.
802 if (unsigned ExtraBits = Size % BITWORD_SIZE) {
803 BitWord ExtraBitMask = ~BitWord(0) << ExtraBits;
804 if (t)
805 Bits.back() |= ExtraBitMask;
806 else
807 Bits.back() &= ~ExtraBitMask;
808 }
809 }
810
811 // Clear the unused bits in the high words.
812 void clear_unused_bits() {
813 set_unused_bits(false);
814 }
815
816 void init_words(bool t) { llvm::fill(Bits, 0 - (BitWord)t); }
817
818 template<bool AddBits, bool InvertMask>
819 void applyMask(const uint32_t *Mask, unsigned MaskWords) {
820 static_assert(BITWORD_SIZE % 32 == 0, "Unsupported BitWord size.");
821 MaskWords = std::min(MaskWords, (size() + 31) / 32);
822 const unsigned Scale = BITWORD_SIZE / 32;
823 unsigned i;
824 for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) {
825 BitWord BW = Bits[i];
826 // This inner loop should unroll completely when BITWORD_SIZE > 32.
827 for (unsigned b = 0; b != BITWORD_SIZE; b += 32) {
828 uint32_t M = *Mask++;
829 if (InvertMask) M = ~M;
830 if (AddBits) BW |= BitWord(M) << b;
831 else BW &= ~(BitWord(M) << b);
832 }
833 Bits[i] = BW;
834 }
835 for (unsigned b = 0; MaskWords; b += 32, --MaskWords) {
836 uint32_t M = *Mask++;
837 if (InvertMask) M = ~M;
838 if (AddBits) Bits[i] |= BitWord(M) << b;
839 else Bits[i] &= ~(BitWord(M) << b);
840 }
841 if (AddBits)
842 clear_unused_bits();
843 }
844
845public:
846 /// Return the size (in bytes) of the bit vector.
847 size_type getMemorySize() const { return Bits.size() * sizeof(BitWord); }
848 size_type getBitCapacity() const { return Bits.size() * BITWORD_SIZE; }
849};
850
852 return X.getMemorySize();
853}
854
855template <> struct DenseMapInfo<BitVector> {
856 static inline BitVector getEmptyKey() { return {}; }
857 static inline BitVector getTombstoneKey() {
858 BitVector V;
859 V.invalid();
860 return V;
861 }
862 static unsigned getHashValue(const BitVector &V) {
864 getHashValue(std::make_pair(V.size(), V.getData()));
865 }
866 static bool isEqual(const BitVector &LHS, const BitVector &RHS) {
867 if (LHS.isInvalid() || RHS.isInvalid())
868 return LHS.isInvalid() == RHS.isInvalid();
869 return LHS == RHS;
870 }
871};
872} // end namespace llvm
873
874namespace std {
875 /// Implement std::swap in terms of BitVector swap.
877} // end namespace std
878
879#endif // LLVM_ADT_BITVECTOR_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:336
This file defines DenseMapInfo traits for DenseMap.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
modulo schedule test
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:39
reference & operator=(bool t)
Definition BitVector.h:137
reference(BitVector &b, unsigned Idx)
Definition BitVector.h:124
reference & operator=(reference t)
Definition BitVector.h:132
reference(const reference &)=default
BitVector & operator>>=(unsigned N)
Definition BitVector.h:604
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
void swap(BitVector &RHS)
Definition BitVector.h:703
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
Definition BitVector.h:317
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:355
bool anyCommon(const BitVector &RHS) const
Test if any common bits are set.
Definition BitVector.h:510
void clear()
Removes all bits from the bitvector.
Definition BitVector.h:349
bool test(const BitVector &RHS) const
Check if (This - RHS) is non-zero.
Definition BitVector.h:557
BitVector()=default
BitVector default ctor - Creates an empty bitvector.
bool back() const
Return the last element in the bitvector.
Definition BitVector.h:476
bool operator!=(const BitVector &RHS) const
Definition BitVector.h:527
void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Clear a bit in this vector for every '0' bit in Mask.
Definition BitVector.h:748
int find_last() const
Returns the index of the last set bit, -1 if none of the bits are set.
Definition BitVector.h:320
int find_first_unset_in(unsigned Begin, unsigned End) const
Returns the index of the first unset bit in the range [Begin, End).
Definition BitVector.h:279
size_type count() const
Returns the number of bits which are set.
Definition BitVector.h:181
BitVector & operator<<=(unsigned N)
Definition BitVector.h:653
ArrayRef< BitWord > getData() const
Definition BitVector.h:714
const_set_bits_iterator set_bits_end() const
Definition BitVector.h:156
BitVector & reset(unsigned Idx)
Reset bit Idx in the bitvector.
Definition BitVector.h:415
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
int find_last_unset() const
Returns the index of the last unset bit, -1 if all of the bits are set.
Definition BitVector.h:340
void reserve(unsigned N)
Reserve space for atleast N bits in the bitvector.
Definition BitVector.h:363
void setBitsInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Add '1' bits from Mask to this vector.
Definition BitVector.h:730
const_set_bits_iterator set_iterator
Definition BitVector.h:151
bool any() const
Returns true if any bit is set.
Definition BitVector.h:189
bool all() const
Returns true if all bits are set.
Definition BitVector.h:194
void push_back(bool Val)
Definition BitVector.h:487
BitVector(unsigned s, bool t=false)
BitVector ctor - Creates a bitvector of specified number of bits.
Definition BitVector.h:168
BitVector & reset(const BitVector &RHS)
Reset bits that are set in RHS. Same as *this &= ~RHS.
Definition BitVector.h:547
BitVector & operator|=(const BitVector &RHS)
Union of this bitvector with RHS.
Definition BitVector.h:587
void pop_back()
Pop one bit from the end of the vector.
Definition BitVector.h:504
void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Clear any bits in this vector that are set in Mask.
Definition BitVector.h:736
int find_prev(unsigned PriorTo) const
Returns the index of the first set bit that precedes the bit at PriorTo.
Definition BitVector.h:328
const_set_bits_iterator_impl< BitVector > const_set_bits_iterator
Definition BitVector.h:150
int find_last_in(unsigned Begin, unsigned End) const
Returns the index of the last set bit in the range [Begin, End).
Definition BitVector.h:248
void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Add a bit to this vector for every '0' bit in Mask.
Definition BitVector.h:742
BitVector & flip()
Flip all bits in the bitvector.
Definition BitVector.h:450
BitVector & reset(unsigned I, unsigned E)
Efficiently reset a range of bits in [I, E)
Definition BitVector.h:421
bool operator==(const BitVector &RHS) const
Definition BitVector.h:520
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
Definition BitVector.h:324
bool none() const
Returns true if none of the bits are set.
Definition BitVector.h:207
const_set_bits_iterator set_bits_begin() const
Definition BitVector.h:153
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:159
BitVector & set(unsigned I, unsigned E)
Efficiently set a range of bits in [I, E)
Definition BitVector.h:380
size_type getBitCapacity() const
Definition BitVector.h:848
int find_first_in(unsigned Begin, unsigned End, bool Set=true) const
Returns the index of the first set/unset bit, depending on Set, in the range [Begin,...
Definition BitVector.h:213
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:178
BitVector & operator^=(const BitVector &RHS)
Disjoint union of this bitvector with RHS.
Definition BitVector.h:596
BitVector & flip(unsigned Idx)
Flip bit Idx in the bitvector.
Definition BitVector.h:458
size_type getMemorySize() const
Return the size (in bytes) of the bit vector.
Definition BitVector.h:847
static BitVector & apply(F &&f, BitVector &Out, BitVector const &Arg, ArgTys const &...Args)
Definition BitVector.h:576
unsigned size_type
Definition BitVector.h:115
bool empty() const
Returns whether there are no bits in this bitvector.
Definition BitVector.h:175
int find_next_unset(unsigned Prev) const
Returns the index of the next unset bit following the Prev bit.
Definition BitVector.h:335
BitVector & set(unsigned Idx)
Definition BitVector.h:373
int find_prev_unset(unsigned PriorTo) const
Returns the index of the first unset bit that precedes the bit at PriorTo.
Definition BitVector.h:344
BitVector & operator&=(const BitVector &RHS)
Intersection of this bitvector with RHS.
Definition BitVector.h:530
int find_first_unset() const
Returns the index of the first unset bit, -1 if all of the bits are set.
Definition BitVector.h:331
bool isInvalid() const
Definition BitVector.h:712
bool subsetOf(const BitVector &RHS) const
Check if This is a subset of RHS.
Definition BitVector.h:573
int find_last_unset_in(unsigned Begin, unsigned End) const
Returns the index of the last unset bit in the range [Begin, End).
Definition BitVector.h:285
bool operator[](unsigned Idx) const
Definition BitVector.h:469
reference operator[](unsigned Idx)
Definition BitVector.h:464
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
ForwardIterator for the bits that are set.
Definition BitVector.h:34
const_set_bits_iterator_impl operator--(int)
Definition BitVector.h:75
const_set_bits_iterator_impl(const BitVectorT &Parent)
Definition BitVector.h:60
std::bidirectional_iterator_tag iterator_category
Definition BitVector.h:52
bool operator==(const const_set_bits_iterator_impl &Other) const
Definition BitVector.h:88
const_set_bits_iterator_impl(const const_set_bits_iterator_impl &)=default
const_set_bits_iterator_impl & operator++()
Definition BitVector.h:70
const_set_bits_iterator_impl & operator--()
Definition BitVector.h:81
const_set_bits_iterator_impl operator++(int)
Definition BitVector.h:64
const_set_bits_iterator_impl(const BitVectorT &Parent, int Current)
Definition BitVector.h:58
bool operator!=(const const_set_bits_iterator_impl &Other) const
Definition BitVector.h:94
A range adaptor for a pair of iterators.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
This is an optimization pass for GlobalISel generic memory operations.
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1758
BitVector::size_type capacity_in_bytes(const BitVector &X)
Definition BitVector.h:851
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr T maskLeadingOnes(unsigned N)
Create a bitmask with the N left-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:88
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1745
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
int countl_one(T Value)
Count the number of ones from the most significant bit to the first zero bit.
Definition bit.h:302
@ Other
Any other memory.
Definition ModRef.h:68
constexpr T maskTrailingZeros(unsigned N)
Create a bitmask with the N right-most bits set to 0, and all other bits set to 1.
Definition MathExtras.h:94
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:77
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:874
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:876
#define N
static BitVector getEmptyKey()
Definition BitVector.h:856
static bool isEqual(const BitVector &LHS, const BitVector &RHS)
Definition BitVector.h:866
static unsigned getHashValue(const BitVector &V)
Definition BitVector.h:862
static BitVector getTombstoneKey()
Definition BitVector.h:857
An information struct used to provide DenseMap with the various necessary components for a given valu...