blob: d6a44f72932487ab30acccdc623d5e949c6bff42 [file] [log] [blame]
Vladimir Marko80afd022015-05-19 18:08:00 +01001/*
2 * Copyright (C) 2015 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_UTILS_H_
18#define ART_RUNTIME_BASE_BIT_UTILS_H_
19
20#include <iterator>
21#include <limits>
22#include <type_traits>
23
24#include "base/logging.h"
25#include "base/iteration_range.h"
26
27namespace art {
28
29template<typename T>
30static constexpr int CLZ(T x) {
31 static_assert(std::is_integral<T>::value, "T must be integral");
Andreas Gampe151ab8d2015-08-14 23:01:49 +000032 static_assert(std::is_unsigned<T>::value, "T must be unsigned");
Vladimir Marko80afd022015-05-19 18:08:00 +010033 static_assert(sizeof(T) <= sizeof(long long), // NOLINT [runtime/int] [4]
34 "T too large, must be smaller than long long");
Andreas Gampe151ab8d2015-08-14 23:01:49 +000035 return
36 DCHECK_CONSTEXPR(x != 0, "x must not be zero", T(0))
37 (sizeof(T) == sizeof(uint32_t))
38 ? __builtin_clz(x)
39 : __builtin_clzll(x);
Vladimir Marko80afd022015-05-19 18:08:00 +010040}
41
42template<typename T>
43static constexpr int CTZ(T x) {
44 static_assert(std::is_integral<T>::value, "T must be integral");
Andreas Gampe151ab8d2015-08-14 23:01:49 +000045 // It is not unreasonable to ask for trailing zeros in a negative number. As such, do not check
46 // that T is an unsigned type.
47 static_assert(sizeof(T) <= sizeof(long long), // NOLINT [runtime/int] [4]
48 "T too large, must be smaller than long long");
49 return
50 DCHECK_CONSTEXPR(x != 0, "x must not be zero", T(0))
51 (sizeof(T) == sizeof(uint32_t))
52 ? __builtin_ctz(x)
53 : __builtin_ctzll(x);
Vladimir Marko80afd022015-05-19 18:08:00 +010054}
55
Roland Levillain0d5a2812015-11-13 10:07:31 +000056// Return the number of 1-bits in `x`.
Vladimir Marko80afd022015-05-19 18:08:00 +010057template<typename T>
58static constexpr int POPCOUNT(T x) {
59 return (sizeof(T) == sizeof(uint32_t))
60 ? __builtin_popcount(x)
61 : __builtin_popcountll(x);
62}
63
64// Find the bit position of the most significant bit (0-based), or -1 if there were no bits set.
65template <typename T>
66static constexpr ssize_t MostSignificantBit(T value) {
67 static_assert(std::is_integral<T>::value, "T must be integral");
68 static_assert(std::is_unsigned<T>::value, "T must be unsigned");
69 static_assert(std::numeric_limits<T>::radix == 2, "Unexpected radix!");
70 return (value == 0) ? -1 : std::numeric_limits<T>::digits - 1 - CLZ(value);
71}
72
73// Find the bit position of the least significant bit (0-based), or -1 if there were no bits set.
74template <typename T>
75static constexpr ssize_t LeastSignificantBit(T value) {
76 static_assert(std::is_integral<T>::value, "T must be integral");
77 static_assert(std::is_unsigned<T>::value, "T must be unsigned");
78 return (value == 0) ? -1 : CTZ(value);
79}
80
81// How many bits (minimally) does it take to store the constant 'value'? i.e. 1 for 1, 3 for 5, etc.
82template <typename T>
83static constexpr size_t MinimumBitsToStore(T value) {
84 return static_cast<size_t>(MostSignificantBit(value) + 1);
85}
86
87template <typename T>
88static constexpr inline T RoundUpToPowerOfTwo(T x) {
89 static_assert(std::is_integral<T>::value, "T must be integral");
90 static_assert(std::is_unsigned<T>::value, "T must be unsigned");
91 // NOTE: Undefined if x > (1 << (std::numeric_limits<T>::digits - 1)).
92 return (x < 2u) ? x : static_cast<T>(1u) << (std::numeric_limits<T>::digits - CLZ(x - 1u));
93}
94
95template<typename T>
96static constexpr bool IsPowerOfTwo(T x) {
97 static_assert(std::is_integral<T>::value, "T must be integral");
98 // TODO: assert unsigned. There is currently many uses with signed values.
99 return (x & (x - 1)) == 0;
100}
101
102template<typename T>
103static inline int WhichPowerOf2(T x) {
104 static_assert(std::is_integral<T>::value, "T must be integral");
105 // TODO: assert unsigned. There is currently many uses with signed values.
106 DCHECK((x != 0) && IsPowerOfTwo(x));
107 return CTZ(x);
108}
109
110// For rounding integers.
111// NOTE: In the absence of std::omit_from_type_deduction<T> or std::identity<T>, use std::decay<T>.
112template<typename T>
113static constexpr T RoundDown(T x, typename std::decay<T>::type n) WARN_UNUSED;
114
115template<typename T>
116static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
117 return
118 DCHECK_CONSTEXPR(IsPowerOfTwo(n), , T(0))
119 (x & -n);
120}
121
122template<typename T>
123static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) WARN_UNUSED;
124
125template<typename T>
126static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
127 return RoundDown(x + n - 1, n);
128}
129
130// For aligning pointers.
131template<typename T>
132static inline T* AlignDown(T* x, uintptr_t n) WARN_UNUSED;
133
134template<typename T>
135static inline T* AlignDown(T* x, uintptr_t n) {
136 return reinterpret_cast<T*>(RoundDown(reinterpret_cast<uintptr_t>(x), n));
137}
138
139template<typename T>
140static inline T* AlignUp(T* x, uintptr_t n) WARN_UNUSED;
141
142template<typename T>
143static inline T* AlignUp(T* x, uintptr_t n) {
144 return reinterpret_cast<T*>(RoundUp(reinterpret_cast<uintptr_t>(x), n));
145}
146
147template<int n, typename T>
Nicolas Geoffray7bf2b4f2015-07-08 10:11:59 +0000148static constexpr bool IsAligned(T x) {
Vladimir Marko80afd022015-05-19 18:08:00 +0100149 static_assert((n & (n - 1)) == 0, "n is not a power of two");
150 return (x & (n - 1)) == 0;
151}
152
153template<int n, typename T>
154static inline bool IsAligned(T* x) {
155 return IsAligned<n>(reinterpret_cast<const uintptr_t>(x));
156}
157
158template<typename T>
159static inline bool IsAlignedParam(T x, int n) {
160 return (x & (n - 1)) == 0;
161}
162
163#define CHECK_ALIGNED(value, alignment) \
164 CHECK(::art::IsAligned<alignment>(value)) << reinterpret_cast<const void*>(value)
165
166#define DCHECK_ALIGNED(value, alignment) \
167 DCHECK(::art::IsAligned<alignment>(value)) << reinterpret_cast<const void*>(value)
168
Vladimir Markocf36d492015-08-12 19:27:26 +0100169#define CHECK_ALIGNED_PARAM(value, alignment) \
170 CHECK(::art::IsAlignedParam(value, alignment)) << reinterpret_cast<const void*>(value)
171
Vladimir Marko80afd022015-05-19 18:08:00 +0100172#define DCHECK_ALIGNED_PARAM(value, alignment) \
173 DCHECK(::art::IsAlignedParam(value, alignment)) << reinterpret_cast<const void*>(value)
174
175// Like sizeof, but count how many bits a type takes. Pass type explicitly.
176template <typename T>
177static constexpr size_t BitSizeOf() {
178 static_assert(std::is_integral<T>::value, "T must be integral");
179 typedef typename std::make_unsigned<T>::type unsigned_type;
180 static_assert(sizeof(T) == sizeof(unsigned_type), "Unexpected type size mismatch!");
181 static_assert(std::numeric_limits<unsigned_type>::radix == 2, "Unexpected radix!");
182 return std::numeric_limits<unsigned_type>::digits;
183}
184
185// Like sizeof, but count how many bits a type takes. Infers type from parameter.
186template <typename T>
187static constexpr size_t BitSizeOf(T /*x*/) {
188 return BitSizeOf<T>();
189}
190
191static inline uint16_t Low16Bits(uint32_t value) {
192 return static_cast<uint16_t>(value);
193}
194
195static inline uint16_t High16Bits(uint32_t value) {
196 return static_cast<uint16_t>(value >> 16);
197}
198
199static inline uint32_t Low32Bits(uint64_t value) {
200 return static_cast<uint32_t>(value);
201}
202
203static inline uint32_t High32Bits(uint64_t value) {
204 return static_cast<uint32_t>(value >> 32);
205}
206
207// Check whether an N-bit two's-complement representation can hold value.
208template <typename T>
209static inline bool IsInt(size_t N, T value) {
210 if (N == BitSizeOf<T>()) {
211 return true;
212 } else {
213 CHECK_LT(0u, N);
214 CHECK_LT(N, BitSizeOf<T>());
215 T limit = static_cast<T>(1) << (N - 1u);
216 return (-limit <= value) && (value < limit);
217 }
218}
219
220template <typename T>
221static constexpr T GetIntLimit(size_t bits) {
222 return
223 DCHECK_CONSTEXPR(bits > 0, "bits cannot be zero", 0)
224 DCHECK_CONSTEXPR(bits < BitSizeOf<T>(), "kBits must be < max.", 0)
225 static_cast<T>(1) << (bits - 1);
226}
227
228template <size_t kBits, typename T>
229static constexpr bool IsInt(T value) {
230 static_assert(kBits > 0, "kBits cannot be zero.");
231 static_assert(kBits <= BitSizeOf<T>(), "kBits must be <= max.");
232 static_assert(std::is_signed<T>::value, "Needs a signed type.");
233 // Corner case for "use all bits." Can't use the limits, as they would overflow, but it is
234 // trivially true.
235 return (kBits == BitSizeOf<T>()) ?
236 true :
237 (-GetIntLimit<T>(kBits) <= value) && (value < GetIntLimit<T>(kBits));
238}
239
240template <size_t kBits, typename T>
241static constexpr bool IsUint(T value) {
242 static_assert(kBits > 0, "kBits cannot be zero.");
243 static_assert(kBits <= BitSizeOf<T>(), "kBits must be <= max.");
244 static_assert(std::is_integral<T>::value, "Needs an integral type.");
245 // Corner case for "use all bits." Can't use the limits, as they would overflow, but it is
246 // trivially true.
247 // NOTE: To avoid triggering assertion in GetIntLimit(kBits+1) if kBits+1==BitSizeOf<T>(),
248 // use GetIntLimit(kBits)*2u. The unsigned arithmetic works well for us if it overflows.
249 return (0 <= value) &&
250 (kBits == BitSizeOf<T>() ||
251 (static_cast<typename std::make_unsigned<T>::type>(value) <=
252 GetIntLimit<typename std::make_unsigned<T>::type>(kBits) * 2u - 1u));
253}
254
255template <size_t kBits, typename T>
256static constexpr bool IsAbsoluteUint(T value) {
257 static_assert(kBits <= BitSizeOf<T>(), "kBits must be <= max.");
258 static_assert(std::is_integral<T>::value, "Needs an integral type.");
259 typedef typename std::make_unsigned<T>::type unsigned_type;
260 return (kBits == BitSizeOf<T>())
261 ? true
262 : IsUint<kBits>(value < 0
263 ? static_cast<unsigned_type>(-1 - value) + 1u // Avoid overflow.
264 : static_cast<unsigned_type>(value));
265}
266
Chris Larsendbce0d72015-09-17 13:34:00 -0700267// Generate maximum/minimum values for signed/unsigned n-bit integers
268template <typename T>
269static constexpr T MaxInt(size_t bits) {
270 return
271 DCHECK_CONSTEXPR(bits > 0, "bits cannot be zero", 0)
272 DCHECK_CONSTEXPR(bits <= BitSizeOf<T>(), "kBits must be < max.", 0)
273 bits == BitSizeOf<T>()
274 ? std::numeric_limits<T>::max()
275 : std::is_signed<T>::value
276 ? (bits == 1
277 ? 0
278 : static_cast<T>(MaxInt<typename std::make_unsigned<T>::type>(bits - 1)))
279 : static_cast<T>(UINT64_C(1) << bits) - static_cast<T>(1);
280}
281
282template <typename T>
283static constexpr T MinInt(size_t bits) {
284 return
285 DCHECK_CONSTEXPR(bits > 0, "bits cannot be zero", 0)
286 DCHECK_CONSTEXPR(bits <= BitSizeOf<T>(), "kBits must be < max.", 0)
287 bits == BitSizeOf<T>()
288 ? std::numeric_limits<T>::min()
289 : std::is_signed<T>::value
290 ? (bits == 1 ? -1 : static_cast<T>(-1) - MaxInt<T>(bits))
291 : static_cast<T>(0);
292}
293
Vladimir Marko80afd022015-05-19 18:08:00 +0100294// Using the Curiously Recurring Template Pattern to implement everything shared
295// by LowToHighBitIterator and HighToLowBitIterator, i.e. everything but operator*().
296template <typename T, typename Iter>
297class BitIteratorBase
298 : public std::iterator<std::forward_iterator_tag, uint32_t, ptrdiff_t, void, void> {
299 static_assert(std::is_integral<T>::value, "T must be integral");
300 static_assert(std::is_unsigned<T>::value, "T must be unsigned");
301
302 static_assert(sizeof(T) == sizeof(uint32_t) || sizeof(T) == sizeof(uint64_t), "Unsupported size");
303
304 public:
305 BitIteratorBase() : bits_(0u) { }
306 explicit BitIteratorBase(T bits) : bits_(bits) { }
307
308 Iter& operator++() {
309 DCHECK_NE(bits_, 0u);
310 uint32_t bit = *static_cast<Iter&>(*this);
311 bits_ &= ~(static_cast<T>(1u) << bit);
312 return static_cast<Iter&>(*this);
313 }
314
315 Iter& operator++(int) {
316 Iter tmp(static_cast<Iter&>(*this));
317 ++*this;
318 return tmp;
319 }
320
321 protected:
322 T bits_;
323
324 template <typename U, typename I>
325 friend bool operator==(const BitIteratorBase<U, I>& lhs, const BitIteratorBase<U, I>& rhs);
326};
327
328template <typename T, typename Iter>
329bool operator==(const BitIteratorBase<T, Iter>& lhs, const BitIteratorBase<T, Iter>& rhs) {
330 return lhs.bits_ == rhs.bits_;
331}
332
333template <typename T, typename Iter>
334bool operator!=(const BitIteratorBase<T, Iter>& lhs, const BitIteratorBase<T, Iter>& rhs) {
335 return !(lhs == rhs);
336}
337
338template <typename T>
339class LowToHighBitIterator : public BitIteratorBase<T, LowToHighBitIterator<T>> {
340 public:
341 using BitIteratorBase<T, LowToHighBitIterator<T>>::BitIteratorBase;
342
343 uint32_t operator*() const {
344 DCHECK_NE(this->bits_, 0u);
345 return CTZ(this->bits_);
346 }
347};
348
349template <typename T>
350class HighToLowBitIterator : public BitIteratorBase<T, HighToLowBitIterator<T>> {
351 public:
352 using BitIteratorBase<T, HighToLowBitIterator<T>>::BitIteratorBase;
353
354 uint32_t operator*() const {
355 DCHECK_NE(this->bits_, 0u);
356 static_assert(std::numeric_limits<T>::radix == 2, "Unexpected radix!");
357 return std::numeric_limits<T>::digits - 1u - CLZ(this->bits_);
358 }
359};
360
361template <typename T>
362IterationRange<LowToHighBitIterator<T>> LowToHighBits(T bits) {
363 return IterationRange<LowToHighBitIterator<T>>(
364 LowToHighBitIterator<T>(bits), LowToHighBitIterator<T>());
365}
366
367template <typename T>
368IterationRange<HighToLowBitIterator<T>> HighToLowBits(T bits) {
369 return IterationRange<HighToLowBitIterator<T>>(
370 HighToLowBitIterator<T>(bits), HighToLowBitIterator<T>());
371}
372
373} // namespace art
374
375#endif // ART_RUNTIME_BASE_BIT_UTILS_H_