• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_LIBARTBASE_BASE_BIT_VECTOR_H_
18 #define ART_LIBARTBASE_BASE_BIT_VECTOR_H_
19 
20 #include <stdint.h>
21 
22 #include <iterator>
23 
24 #include "bit_utils.h"
25 #include "globals.h"
26 
27 namespace art {
28 
29 class Allocator;
30 class ArenaBitVector;
31 
32 /*
33  * Expanding bitmap. Bits are numbered starting from zero. All operations on a BitVector are
34  * unsynchronized. New BitVectors are not necessarily zeroed out. If the used allocator doesn't do
35  * clear the vector (e.g. ScopedArenaAllocator), the responsibility of clearing it relies on the
36  * caller (e.g. ArenaBitVector).
37  */
38 class BitVector {
39  public:
40   static constexpr uint32_t kWordBytes = sizeof(uint32_t);
41   static constexpr uint32_t kWordBits = kWordBytes * 8;
42 
43   class IndexContainer;
44 
45   /**
46    * @brief Convenient iterator across the indexes of the BitVector's set bits.
47    *
48    * @details IndexIterator is a Forward iterator (C++11: 24.2.5) from the lowest
49    * to the highest index of the BitVector's set bits. Instances can be retrieved
50    * only through BitVector::Indexes() which returns an IndexContainer wrapper
51    * object with begin() and end() suitable for range-based loops:
52    *   for (uint32_t idx : bit_vector.Indexes()) {
53    *     // Use idx.
54    *   }
55    */
56   class IndexIterator {
57    public:
58     using iterator_category = std::forward_iterator_tag;
59     using value_type = uint32_t;
60     using difference_type = ptrdiff_t;
61     using pointer = void;
62     using reference = void;
63 
64     bool operator==(const IndexIterator& other) const;
65 
66     bool operator!=(const IndexIterator& other) const {
67       return !(*this == other);
68     }
69 
70     uint32_t operator*() const;
71 
72     IndexIterator& operator++();
73 
74     IndexIterator operator++(int);
75 
76     // Helper function to check for end without comparing with bit_vector.Indexes().end().
Done()77     bool Done() const {
78       return bit_index_ == BitSize();
79     }
80 
81    private:
82     struct begin_tag { };
83     struct end_tag { };
84 
85     IndexIterator(const BitVector* bit_vector, begin_tag);
86     IndexIterator(const BitVector* bit_vector, end_tag);
87 
BitSize()88     uint32_t BitSize() const {
89       return storage_size_ * kWordBits;
90     }
91 
92     uint32_t FindIndex(uint32_t start_index) const;
93     const uint32_t* const bit_storage_;
94     const uint32_t storage_size_;  // Size of vector in words.
95     uint32_t bit_index_;           // Current index (size in bits).
96 
97     friend class BitVector::IndexContainer;
98   };
99 
100   /**
101    * @brief BitVector wrapper class for iteration across indexes of set bits.
102    */
103   class IndexContainer {
104    public:
IndexContainer(const BitVector * bit_vector)105     explicit IndexContainer(const BitVector* bit_vector) : bit_vector_(bit_vector) { }
106 
107     IndexIterator begin() const;
108     IndexIterator end() const;
109 
110    private:
111     const BitVector* const bit_vector_;
112   };
113 
114   // MoveConstructible but not MoveAssignable, CopyConstructible or CopyAssignable.
115 
116   BitVector(const BitVector& other) = delete;
117   BitVector& operator=(const BitVector& other) = delete;
118 
BitVector(BitVector && other)119   BitVector(BitVector&& other) noexcept
120       : storage_(other.storage_),
121         storage_size_(other.storage_size_),
122         allocator_(other.allocator_),
123         expandable_(other.expandable_) {
124     other.storage_ = nullptr;
125     other.storage_size_ = 0u;
126   }
127 
128   BitVector(uint32_t start_bits,
129             bool expandable,
130             Allocator* allocator);
131 
132   BitVector(bool expandable,
133             Allocator* allocator,
134             uint32_t storage_size,
135             uint32_t* storage);
136 
137   BitVector(const BitVector& src,
138             bool expandable,
139             Allocator* allocator);
140 
141   virtual ~BitVector();
142 
143   // The number of words necessary to encode bits.
BitsToWords(uint32_t bits)144   static constexpr uint32_t BitsToWords(uint32_t bits) {
145     return RoundUp(bits, kWordBits) / kWordBits;
146   }
147 
148   // Mark the specified bit as "set".
SetBit(uint32_t idx)149   void SetBit(uint32_t idx) {
150     /*
151      * TUNING: this could have pathologically bad growth/expand behavior.  Make sure we're
152      * not using it badly or change resize mechanism.
153      */
154     if (idx >= storage_size_ * kWordBits) {
155       EnsureSize(idx);
156     }
157     storage_[WordIndex(idx)] |= BitMask(idx);
158   }
159 
160   // Mark the specified bit as "unset".
ClearBit(uint32_t idx)161   void ClearBit(uint32_t idx) {
162     // If the index is over the size, we don't have to do anything, it is cleared.
163     if (idx < storage_size_ * kWordBits) {
164       // Otherwise, go ahead and clear it.
165       storage_[WordIndex(idx)] &= ~BitMask(idx);
166     }
167   }
168 
169   // Determine whether or not the specified bit is set.
IsBitSet(uint32_t idx)170   bool IsBitSet(uint32_t idx) const {
171     // If the index is over the size, whether it is expandable or not, this bit does not exist:
172     // thus it is not set.
173     return (idx < (storage_size_ * kWordBits)) && IsBitSet(storage_, idx);
174   }
175 
176   // Mark all bits bit as "clear".
177   void ClearAllBits();
178 
179   // Mark specified number of bits as "set". Cannot set all bits like ClearAll since there might
180   // be unused bits - setting those to one will confuse the iterator.
181   void SetInitialBits(uint32_t num_bits);
182 
183   void Copy(const BitVector* src);
184 
185   // Intersect with another bit vector.
186   void Intersect(const BitVector* src2);
187 
188   // Union with another bit vector.
189   bool Union(const BitVector* src);
190 
191   // Set bits of union_with that are not in not_in.
192   bool UnionIfNotIn(const BitVector* union_with, const BitVector* not_in);
193 
194   void Subtract(const BitVector* src);
195 
196   // Are we equal to another bit vector?  Note: expandability attributes must also match.
197   bool Equal(const BitVector* src) const;
198 
199   /**
200    * @brief Are all the bits set the same?
201    * @details expandability and size can differ as long as the same bits are set.
202    */
203   bool SameBitsSet(const BitVector *src) const;
204 
205   bool IsSubsetOf(const BitVector *other) const;
206 
207   // Count the number of bits that are set.
208   uint32_t NumSetBits() const;
209 
210   // Count the number of bits that are set in range [0, end).
211   uint32_t NumSetBits(uint32_t end) const;
212 
Indexes()213   IndexContainer Indexes() const {
214     return IndexContainer(this);
215   }
216 
GetStorageSize()217   uint32_t GetStorageSize() const {
218     return storage_size_;
219   }
220 
IsExpandable()221   bool IsExpandable() const {
222     return expandable_;
223   }
224 
GetRawStorageWord(size_t idx)225   uint32_t GetRawStorageWord(size_t idx) const {
226     return storage_[idx];
227   }
228 
GetRawStorage()229   uint32_t* GetRawStorage() {
230     return storage_;
231   }
232 
GetRawStorage()233   const uint32_t* GetRawStorage() const {
234     return storage_;
235   }
236 
GetSizeOf()237   size_t GetSizeOf() const {
238     return storage_size_ * kWordBytes;
239   }
240 
GetBitSizeOf()241   size_t GetBitSizeOf() const {
242     return storage_size_ * kWordBits;
243   }
244 
245   /**
246    * @return the highest bit set, -1 if none are set
247    */
248   int GetHighestBitSet() const;
249 
250   /**
251    * @return true if there are any bits set, false otherwise.
252    */
IsAnyBitSet()253   bool IsAnyBitSet() const {
254     return GetHighestBitSet() != -1;
255   }
256 
257   // Minimum number of bits required to store this vector, 0 if none are set.
GetNumberOfBits()258   size_t GetNumberOfBits() const {
259     return GetHighestBitSet() + 1;
260   }
261 
262   // Is bit set in storage. (No range check.)
IsBitSet(const uint32_t * storage,uint32_t idx)263   static bool IsBitSet(const uint32_t* storage, uint32_t idx) {
264     return (storage[WordIndex(idx)] & BitMask(idx)) != 0;
265   }
266 
267   // Number of bits set in range [0, end) in storage. (No range check.)
268   static uint32_t NumSetBits(const uint32_t* storage, uint32_t end);
269 
270   // Fill given memory region with the contents of the vector and zero padding.
CopyTo(void * dst,size_t len)271   void CopyTo(void* dst, size_t len) const {
272     DCHECK_LE(static_cast<size_t>(GetHighestBitSet() + 1), len * kBitsPerByte);
273     size_t vec_len = GetSizeOf();
274     if (vec_len < len) {
275       void* dst_padding = reinterpret_cast<uint8_t*>(dst) + vec_len;
276       memcpy(dst, storage_, vec_len);
277       memset(dst_padding, 0, len - vec_len);
278     } else {
279       memcpy(dst, storage_, len);
280     }
281   }
282 
283   void Dump(std::ostream& os, const char* prefix) const;
284 
285   Allocator* GetAllocator() const;
286 
287  private:
288   /**
289    * @brief Dump the bitvector into buffer in a 00101..01 format.
290    * @param buffer the ostringstream used to dump the bitvector into.
291    */
292   void DumpHelper(const char* prefix, std::ostringstream& buffer) const;
293 
294   // Ensure there is space for a bit at idx.
295   void EnsureSize(uint32_t idx);
296 
297   // The index of the word within storage.
WordIndex(uint32_t idx)298   static constexpr uint32_t WordIndex(uint32_t idx) {
299     return idx >> 5;
300   }
301 
302   // A bit mask to extract the bit for the given index.
BitMask(uint32_t idx)303   static constexpr uint32_t BitMask(uint32_t idx) {
304     return 1 << (idx & 0x1f);
305   }
306 
307   uint32_t*  storage_;            // The storage for the bit vector.
308   uint32_t   storage_size_;       // Current size, in 32-bit words.
309   Allocator* const allocator_;    // Allocator if expandable.
310   const bool expandable_;         // Should the bitmap expand if too small?
311 };
312 
313 }  // namespace art
314 
315 #endif  // ART_LIBARTBASE_BASE_BIT_VECTOR_H_
316