2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Various low-level, bit-manipulation routines.
20 * findFirstSet(x) [constexpr]
21 * find first (least significant) bit set in a value of an integral type,
22 * 1-based (like ffs()). 0 = no bits are set (x == 0)
24 * findLastSet(x) [constexpr]
25 * find last (most significant) bit set in a value of an integral type,
26 * 1-based. 0 = no bits are set (x == 0)
27 * for x != 0, findLastSet(x) == 1 + floor(log2(x))
29 * nextPowTwo(x) [constexpr]
30 * Finds the next power of two >= x.
32 * isPowTwo(x) [constexpr]
33 * return true iff x is a power of two
36 * return the number of 1 bits in x
39 * convert between native, big, and little endian representation
40 * Endian::big(x) big <-> native
41 * Endian::little(x) little <-> native
42 * Endian::swap(x) big <-> little
45 * Wrapper around an iterator over an integral type that iterates
46 * over its underlying bits in MSb to LSb order
48 * findFirstSet(BitIterator begin, BitIterator end)
49 * return a BitIterator pointing to the first 1 bit in [begin, end), or
50 * end if all bits in [begin, end) are 0
52 * @author Tudor Bosman (tudorb@fb.com)
57 #if !defined(__clang__) && !(defined(_MSC_VER) && (_MSC_VER < 1900))
58 #define FOLLY_INTRINSIC_CONSTEXPR constexpr
60 // GCC and MSVC 2015+ are the only compilers with
61 // intrinsics constexpr.
62 #define FOLLY_INTRINSIC_CONSTEXPR const
65 #include <folly/Portability.h>
66 #include <folly/portability/Builtins.h>
68 #include <folly/Assume.h>
69 #include <folly/detail/BitIteratorDetail.h>
70 #include <folly/Likely.h>
77 #include <type_traits>
78 #include <boost/iterator/iterator_adaptor.hpp>
83 // Generate overloads for findFirstSet as wrappers around
84 // appropriate ffs, ffsl, ffsll gcc builtins
86 inline FOLLY_INTRINSIC_CONSTEXPR
87 typename std::enable_if<
88 (std::is_integral<T>::value &&
89 std::is_unsigned<T>::value &&
90 sizeof(T) <= sizeof(unsigned int)),
93 return static_cast<unsigned int>(__builtin_ffs(static_cast<int>(x)));
97 inline FOLLY_INTRINSIC_CONSTEXPR
98 typename std::enable_if<
99 (std::is_integral<T>::value &&
100 std::is_unsigned<T>::value &&
101 sizeof(T) > sizeof(unsigned int) &&
102 sizeof(T) <= sizeof(unsigned long)),
105 return static_cast<unsigned int>(__builtin_ffsl(static_cast<long>(x)));
109 inline FOLLY_INTRINSIC_CONSTEXPR
110 typename std::enable_if<
111 (std::is_integral<T>::value &&
112 std::is_unsigned<T>::value &&
113 sizeof(T) > sizeof(unsigned long) &&
114 sizeof(T) <= sizeof(unsigned long long)),
117 return static_cast<unsigned int>(__builtin_ffsll(static_cast<long long>(x)));
121 inline FOLLY_INTRINSIC_CONSTEXPR
122 typename std::enable_if<
123 (std::is_integral<T>::value && std::is_signed<T>::value),
126 // Note that conversion from a signed type to the corresponding unsigned
127 // type is technically implementation-defined, but will likely work
128 // on any impementation that uses two's complement.
129 return findFirstSet(static_cast<typename std::make_unsigned<T>::type>(x));
132 // findLastSet: return the 1-based index of the highest bit set
133 // for x > 0, findLastSet(x) == 1 + floor(log2(x))
135 inline FOLLY_INTRINSIC_CONSTEXPR
136 typename std::enable_if<
137 (std::is_integral<T>::value &&
138 std::is_unsigned<T>::value &&
139 sizeof(T) <= sizeof(unsigned int)),
142 // If X is a power of two X - Y = ((X - 1) ^ Y) + 1. Doing this transformation
143 // allows GCC to remove its own xor that it adds to implement clz using bsr
144 return x ? ((8 * sizeof(unsigned int) - 1) ^ __builtin_clz(x)) + 1 : 0;
148 inline FOLLY_INTRINSIC_CONSTEXPR
149 typename std::enable_if<
150 (std::is_integral<T>::value &&
151 std::is_unsigned<T>::value &&
152 sizeof(T) > sizeof(unsigned int) &&
153 sizeof(T) <= sizeof(unsigned long)),
156 return x ? ((8 * sizeof(unsigned long) - 1) ^ __builtin_clzl(x)) + 1 : 0;
160 inline FOLLY_INTRINSIC_CONSTEXPR
161 typename std::enable_if<
162 (std::is_integral<T>::value &&
163 std::is_unsigned<T>::value &&
164 sizeof(T) > sizeof(unsigned long) &&
165 sizeof(T) <= sizeof(unsigned long long)),
168 return x ? ((8 * sizeof(unsigned long long) - 1) ^ __builtin_clzll(x)) + 1
173 inline FOLLY_INTRINSIC_CONSTEXPR
174 typename std::enable_if<
175 (std::is_integral<T>::value &&
176 std::is_signed<T>::value),
179 return findLastSet(static_cast<typename std::make_unsigned<T>::type>(x));
183 inline FOLLY_INTRINSIC_CONSTEXPR
184 typename std::enable_if<
185 std::is_integral<T>::value && std::is_unsigned<T>::value,
188 return v ? (T(1) << findLastSet(v - 1)) : 1;
192 inline FOLLY_INTRINSIC_CONSTEXPR typename std::
193 enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value, T>::type
195 return v ? (T(1) << (findLastSet(v) - 1)) : 0;
199 inline constexpr typename std::enable_if<
200 std::is_integral<T>::value && std::is_unsigned<T>::value,
203 return (v != 0) && !(v & (v - 1));
210 inline typename std::enable_if<
211 (std::is_integral<T>::value &&
212 std::is_unsigned<T>::value &&
213 sizeof(T) <= sizeof(unsigned int)),
216 return size_t(__builtin_popcount(x));
220 inline typename std::enable_if<
221 (std::is_integral<T>::value &&
222 std::is_unsigned<T>::value &&
223 sizeof(T) > sizeof(unsigned int) &&
224 sizeof(T) <= sizeof(unsigned long long)),
227 return size_t(__builtin_popcountll(x));
231 * Endianness detection and manipulation primitives.
235 template <size_t Size>
236 struct uint_types_by_size;
238 #define FB_GEN(sz, fn) \
239 static inline uint##sz##_t byteswap_gen(uint##sz##_t v) { \
243 struct uint_types_by_size<sz / 8> { \
244 using type = uint##sz##_t; \
249 FB_GEN(64, _byteswap_uint64)
250 FB_GEN(32, _byteswap_ulong)
251 FB_GEN(16, _byteswap_ushort)
253 FB_GEN(64, __builtin_bswap64)
254 FB_GEN(32, __builtin_bswap32)
255 FB_GEN(16, __builtin_bswap16)
263 (std::is_integral<T>::value && !std::is_same<T, bool>::value) ||
264 std::is_floating_point<T>::value,
265 "template type parameter must be non-bool integral or floating point");
267 // we implement this with memcpy because that is defined behavior in C++
268 // we rely on compilers to optimize away the memcpy calls
269 constexpr auto s = sizeof(T);
270 using B = typename uint_types_by_size<s>::type;
272 std::memcpy(&b, &x, s);
274 std::memcpy(&x, &b, s);
278 return kIsLittleEndian ? EndianInt::swap(x) : x;
280 static T little(T x) {
281 return kIsBigEndian ? EndianInt::swap(x) : x;
285 } // namespace detail
287 // big* convert between native and big-endian representations
288 // little* convert between native and little-endian representations
289 // swap* convert between big-endian and little-endian representations
291 // ntohs, htons == big16
292 // ntohl, htonl == big32
293 #define FB_GEN1(fn, t, sz) \
294 static t fn##sz(t x) { return fn<t>(x); } \
296 #define FB_GEN2(t, sz) \
297 FB_GEN1(swap, t, sz) \
298 FB_GEN1(big, t, sz) \
299 FB_GEN1(little, t, sz)
302 FB_GEN2(uint##sz##_t, sz) \
303 FB_GEN2(int##sz##_t, sz)
307 enum class Order : uint8_t {
312 static constexpr Order order = kIsLittleEndian ? Order::LITTLE : Order::BIG;
314 template <class T> static T swap(T x) {
315 return folly::detail::EndianInt<T>::swap(x);
317 template <class T> static T big(T x) {
318 return folly::detail::EndianInt<T>::big(x);
320 template <class T> static T little(T x) {
321 return folly::detail::EndianInt<T>::little(x);
324 #if !defined(__ANDROID__)
337 * Fast bit iteration facility.
341 template <class BaseIter> class BitIterator;
342 template <class BaseIter>
343 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
344 BitIterator<BaseIter>);
346 * Wrapper around an iterator over an integer type that iterates
347 * over its underlying bits in LSb to MSb order.
349 * BitIterator models the same iterator concepts as the base iterator.
351 template <class BaseIter>
353 : public bititerator_detail::BitIteratorBase<BaseIter>::type {
356 * Return the number of bits in an element of the underlying iterator.
358 static unsigned int bitsPerBlock() {
359 return std::numeric_limits<
360 typename std::make_unsigned<
361 typename std::iterator_traits<BaseIter>::value_type
367 * Construct a BitIterator that points at a given bit offset (default 0)
370 explicit BitIterator(const BaseIter& iter, size_t bitOff=0)
371 : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
373 assert(bitOffset_ < bitsPerBlock());
376 size_t bitOffset() const {
380 void advanceToNextBlock() {
382 ++this->base_reference();
385 BitIterator& operator=(const BaseIter& other) {
386 this->~BitIterator();
387 new (this) BitIterator(other);
392 friend class boost::iterator_core_access;
393 friend BitIterator findFirstSet<>(BitIterator, BitIterator);
395 typedef bititerator_detail::BitReference<
396 typename std::iterator_traits<BaseIter>::reference,
397 typename std::iterator_traits<BaseIter>::value_type
400 void advanceInBlock(size_t n) {
402 assert(bitOffset_ < bitsPerBlock());
405 BitRef dereference() const {
406 return BitRef(*this->base_reference(), bitOffset_);
409 void advance(ssize_t n) {
410 size_t bpb = bitsPerBlock();
411 ssize_t blocks = n / ssize_t(bpb);
412 bitOffset_ += n % bpb;
413 if (bitOffset_ >= bpb) {
417 this->base_reference() += blocks;
421 if (++bitOffset_ == bitsPerBlock()) {
422 advanceToNextBlock();
427 if (bitOffset_-- == 0) {
428 bitOffset_ = bitsPerBlock() - 1;
429 --this->base_reference();
433 bool equal(const BitIterator& other) const {
434 return (bitOffset_ == other.bitOffset_ &&
435 this->base_reference() == other.base_reference());
438 ssize_t distance_to(const BitIterator& other) const {
440 (other.base_reference() - this->base_reference()) * bitsPerBlock() +
441 other.bitOffset_ - bitOffset_);
448 * Helper function, so you can write
449 * auto bi = makeBitIterator(container.begin());
451 template <class BaseIter>
452 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
453 return BitIterator<BaseIter>(iter);
458 * Find first bit set in a range of bit iterators.
459 * 4.5x faster than the obvious std::find(begin, end, true);
461 template <class BaseIter>
462 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
463 BitIterator<BaseIter> end) {
464 // shortcut to avoid ugly static_cast<>
465 static const typename BaseIter::value_type one = 1;
467 while (begin.base() != end.base()) {
468 typename BaseIter::value_type v = *begin.base();
469 // mask out the bits that don't matter (< begin.bitOffset)
470 v &= ~((one << begin.bitOffset()) - 1);
471 size_t firstSet = findFirstSet(v);
473 --firstSet; // now it's 0-based
474 assert(firstSet >= begin.bitOffset());
475 begin.advanceInBlock(firstSet - begin.bitOffset());
478 begin.advanceToNextBlock();
481 // now begin points to the same block as end
482 if (end.bitOffset() != 0) { // assume end is dereferenceable
483 typename BaseIter::value_type v = *begin.base();
484 // mask out the bits that don't matter (< begin.bitOffset)
485 v &= ~((one << begin.bitOffset()) - 1);
486 // mask out the bits that don't matter (>= end.bitOffset)
487 v &= (one << end.bitOffset()) - 1;
488 size_t firstSet = findFirstSet(v);
490 --firstSet; // now it's 0-based
491 assert(firstSet >= begin.bitOffset());
492 begin.advanceInBlock(firstSet - begin.bitOffset());
501 template <class T, class Enable=void> struct Unaligned;
504 * Representation of an unaligned value of a POD type.
510 typename std::enable_if<std::is_pod<T>::value>::type> {
511 Unaligned() = default; // uninitialized
512 /* implicit */ Unaligned(T v) : value(v) { }
518 * Read an unaligned value of type T and return it.
521 inline T loadUnaligned(const void* p) {
522 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
523 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
524 if (kHasUnalignedAccess) {
525 return static_cast<const Unaligned<T>*>(p)->value;
528 memcpy(&value, p, sizeof(T));
534 * Write an unaligned value of type T.
537 inline void storeUnaligned(void* p, T value) {
538 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
539 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
540 if (kHasUnalignedAccess) {
541 // Prior to C++14, the spec says that a placement new like this
542 // is required to check that p is not nullptr, and to do nothing
543 // if p is a nullptr. By assuming it's not a nullptr, we get a
544 // nice loud segfault in optimized builds if p is nullptr, rather
545 // than just silently doing nothing.
546 folly::assume(p != nullptr);
547 new (p) Unaligned<T>(value);
549 memcpy(p, &value, sizeof(T));