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