add missing include to ThreadId.h
[folly.git] / folly / Bits.h
1 /*
2  * Copyright 2017 Facebook, Inc.
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 /**
18  * Various low-level, bit-manipulation routines.
19  *
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)
23  *
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))
28  *
29  * nextPowTwo(x)  [constexpr]
30  *    Finds the next power of two >= x.
31  *
32  * isPowTwo(x)  [constexpr]
33  *    return true iff x is a power of two
34  *
35  * popcount(x)
36  *    return the number of 1 bits in x
37  *
38  * Endian
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
43  *
44  * BitIterator
45  *    Wrapper around an iterator over an integral type that iterates
46  *    over its underlying bits in MSb to LSb order
47  *
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
51  *
52  * @author Tudor Bosman (tudorb@fb.com)
53  */
54
55 #pragma once
56
57 #if !defined(__clang__) && !(defined(_MSC_VER) && (_MSC_VER < 1900))
58 #define FOLLY_INTRINSIC_CONSTEXPR constexpr
59 #else
60 // GCC and MSVC 2015+ are the only compilers with
61 // intrinsics constexpr.
62 #define FOLLY_INTRINSIC_CONSTEXPR const
63 #endif
64
65 #include <folly/Portability.h>
66 #include <folly/portability/Builtins.h>
67
68 #include <folly/Assume.h>
69 #include <folly/detail/BitIteratorDetail.h>
70 #include <folly/Likely.h>
71
72 #include <cassert>
73 #include <cstring>
74 #include <cinttypes>
75 #include <iterator>
76 #include <limits>
77 #include <type_traits>
78 #include <boost/iterator/iterator_adaptor.hpp>
79 #include <stdint.h>
80
81 namespace folly {
82
83 // Generate overloads for findFirstSet as wrappers around
84 // appropriate ffs, ffsl, ffsll gcc builtins
85 template <class T>
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)),
91   unsigned int>::type
92   findFirstSet(T x) {
93   return static_cast<unsigned int>(__builtin_ffs(static_cast<int>(x)));
94 }
95
96 template <class T>
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)),
103   unsigned int>::type
104   findFirstSet(T x) {
105   return static_cast<unsigned int>(__builtin_ffsl(static_cast<long>(x)));
106 }
107
108 template <class T>
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)),
115   unsigned int>::type
116   findFirstSet(T x) {
117   return static_cast<unsigned int>(__builtin_ffsll(static_cast<long long>(x)));
118 }
119
120 template <class T>
121 inline FOLLY_INTRINSIC_CONSTEXPR
122 typename std::enable_if<
123   (std::is_integral<T>::value && std::is_signed<T>::value),
124   unsigned int>::type
125   findFirstSet(T x) {
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));
130 }
131
132 // findLastSet: return the 1-based index of the highest bit set
133 // for x > 0, findLastSet(x) == 1 + floor(log2(x))
134 template <class T>
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)),
140   unsigned int>::type
141   findLastSet(T x) {
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;
145 }
146
147 template <class T>
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)),
154   unsigned int>::type
155   findLastSet(T x) {
156   return x ? ((8 * sizeof(unsigned long) - 1) ^ __builtin_clzl(x)) + 1 : 0;
157 }
158
159 template <class T>
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)),
166   unsigned int>::type
167   findLastSet(T x) {
168   return x ? ((8 * sizeof(unsigned long long) - 1) ^ __builtin_clzll(x)) + 1
169            : 0;
170 }
171
172 template <class T>
173 inline FOLLY_INTRINSIC_CONSTEXPR
174 typename std::enable_if<
175   (std::is_integral<T>::value &&
176    std::is_signed<T>::value),
177   unsigned int>::type
178   findLastSet(T x) {
179   return findLastSet(static_cast<typename std::make_unsigned<T>::type>(x));
180 }
181
182 template <class T>
183 inline FOLLY_INTRINSIC_CONSTEXPR
184 typename std::enable_if<
185   std::is_integral<T>::value && std::is_unsigned<T>::value,
186   T>::type
187 nextPowTwo(T v) {
188   return v ? (T(1) << findLastSet(v - 1)) : 1;
189 }
190
191 template <class T>
192 inline FOLLY_INTRINSIC_CONSTEXPR typename std::
193     enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value, T>::type
194     prevPowTwo(T v) {
195   return v ? (T(1) << (findLastSet(v) - 1)) : 0;
196 }
197
198 template <class T>
199 inline constexpr typename std::enable_if<
200     std::is_integral<T>::value && std::is_unsigned<T>::value,
201     bool>::type
202 isPowTwo(T v) {
203   return (v != 0) && !(v & (v - 1));
204 }
205
206 /**
207  * Population count
208  */
209 template <class T>
210 inline typename std::enable_if<
211   (std::is_integral<T>::value &&
212    std::is_unsigned<T>::value &&
213    sizeof(T) <= sizeof(unsigned int)),
214   size_t>::type
215   popcount(T x) {
216   return size_t(__builtin_popcount(x));
217 }
218
219 template <class T>
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)),
225   size_t>::type
226   popcount(T x) {
227   return size_t(__builtin_popcountll(x));
228 }
229
230 /**
231  * Endianness detection and manipulation primitives.
232  */
233 namespace detail {
234
235 template <size_t Size>
236 struct uint_types_by_size;
237
238 #define FB_GEN(sz, fn)                                      \
239   static inline uint##sz##_t byteswap_gen(uint##sz##_t v) { \
240     return fn(v);                                           \
241   }                                                         \
242   template <>                                               \
243   struct uint_types_by_size<sz / 8> {                       \
244     using type = uint##sz##_t;                              \
245   };
246
247 FB_GEN(8, uint8_t)
248 #ifdef _MSC_VER
249 FB_GEN(64, _byteswap_uint64)
250 FB_GEN(32, _byteswap_ulong)
251 FB_GEN(16, _byteswap_ushort)
252 #else
253 FB_GEN(64, __builtin_bswap64)
254 FB_GEN(32, __builtin_bswap32)
255 FB_GEN(16, __builtin_bswap16)
256 #endif
257
258 #undef FB_GEN
259
260 template <class T>
261 struct EndianInt {
262   static_assert(
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");
266   static T swap(T x) {
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;
271     B b;
272     std::memcpy(&b, &x, s);
273     b = byteswap_gen(b);
274     std::memcpy(&x, &b, s);
275     return x;
276   }
277   static T big(T x) {
278     return kIsLittleEndian ? EndianInt::swap(x) : x;
279   }
280   static T little(T x) {
281     return kIsBigEndian ? EndianInt::swap(x) : x;
282   }
283 };
284
285 }  // namespace detail
286
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
290 //
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); } \
295
296 #define FB_GEN2(t, sz) \
297   FB_GEN1(swap, t, sz) \
298   FB_GEN1(big, t, sz) \
299   FB_GEN1(little, t, sz)
300
301 #define FB_GEN(sz) \
302   FB_GEN2(uint##sz##_t, sz) \
303   FB_GEN2(int##sz##_t, sz)
304
305 class Endian {
306  public:
307   enum class Order : uint8_t {
308     LITTLE,
309     BIG
310   };
311
312   static constexpr Order order = kIsLittleEndian ? Order::LITTLE : Order::BIG;
313
314   template <class T> static T swap(T x) {
315     return folly::detail::EndianInt<T>::swap(x);
316   }
317   template <class T> static T big(T x) {
318     return folly::detail::EndianInt<T>::big(x);
319   }
320   template <class T> static T little(T x) {
321     return folly::detail::EndianInt<T>::little(x);
322   }
323
324 #if !defined(__ANDROID__)
325   FB_GEN(64)
326   FB_GEN(32)
327   FB_GEN(16)
328   FB_GEN(8)
329 #endif
330 };
331
332 #undef FB_GEN
333 #undef FB_GEN2
334 #undef FB_GEN1
335
336 /**
337  * Fast bit iteration facility.
338  */
339
340
341 template <class BaseIter> class BitIterator;
342 template <class BaseIter>
343 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
344                                    BitIterator<BaseIter>);
345 /**
346  * Wrapper around an iterator over an integer type that iterates
347  * over its underlying bits in LSb to MSb order.
348  *
349  * BitIterator models the same iterator concepts as the base iterator.
350  */
351 template <class BaseIter>
352 class BitIterator
353   : public bititerator_detail::BitIteratorBase<BaseIter>::type {
354  public:
355   /**
356    * Return the number of bits in an element of the underlying iterator.
357    */
358   static unsigned int bitsPerBlock() {
359     return std::numeric_limits<
360       typename std::make_unsigned<
361         typename std::iterator_traits<BaseIter>::value_type
362       >::type
363     >::digits;
364   }
365
366   /**
367    * Construct a BitIterator that points at a given bit offset (default 0)
368    * in iter.
369    */
370   explicit BitIterator(const BaseIter& iter, size_t bitOff=0)
371     : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
372       bitOffset_(bitOff) {
373     assert(bitOffset_ < bitsPerBlock());
374   }
375
376   size_t bitOffset() const {
377     return bitOffset_;
378   }
379
380   void advanceToNextBlock() {
381     bitOffset_ = 0;
382     ++this->base_reference();
383   }
384
385   BitIterator& operator=(const BaseIter& other) {
386     this->~BitIterator();
387     new (this) BitIterator(other);
388     return *this;
389   }
390
391  private:
392   friend class boost::iterator_core_access;
393   friend BitIterator findFirstSet<>(BitIterator, BitIterator);
394
395   typedef bititerator_detail::BitReference<
396       typename std::iterator_traits<BaseIter>::reference,
397       typename std::iterator_traits<BaseIter>::value_type
398     > BitRef;
399
400   void advanceInBlock(size_t n) {
401     bitOffset_ += n;
402     assert(bitOffset_ < bitsPerBlock());
403   }
404
405   BitRef dereference() const {
406     return BitRef(*this->base_reference(), bitOffset_);
407   }
408
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) {
414       bitOffset_ -= bpb;
415       ++blocks;
416     }
417     this->base_reference() += blocks;
418   }
419
420   void increment() {
421     if (++bitOffset_ == bitsPerBlock()) {
422       advanceToNextBlock();
423     }
424   }
425
426   void decrement() {
427     if (bitOffset_-- == 0) {
428       bitOffset_ = bitsPerBlock() - 1;
429       --this->base_reference();
430     }
431   }
432
433   bool equal(const BitIterator& other) const {
434     return (bitOffset_ == other.bitOffset_ &&
435             this->base_reference() == other.base_reference());
436   }
437
438   ssize_t distance_to(const BitIterator& other) const {
439     return ssize_t(
440         (other.base_reference() - this->base_reference()) * bitsPerBlock() +
441         other.bitOffset_ - bitOffset_);
442   }
443
444   size_t bitOffset_;
445 };
446
447 /**
448  * Helper function, so you can write
449  * auto bi = makeBitIterator(container.begin());
450  */
451 template <class BaseIter>
452 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
453   return BitIterator<BaseIter>(iter);
454 }
455
456
457 /**
458  * Find first bit set in a range of bit iterators.
459  * 4.5x faster than the obvious std::find(begin, end, true);
460  */
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;
466
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);
472     if (firstSet) {
473       --firstSet;  // now it's 0-based
474       assert(firstSet >= begin.bitOffset());
475       begin.advanceInBlock(firstSet - begin.bitOffset());
476       return begin;
477     }
478     begin.advanceToNextBlock();
479   }
480
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);
489     if (firstSet) {
490       --firstSet;  // now it's 0-based
491       assert(firstSet >= begin.bitOffset());
492       begin.advanceInBlock(firstSet - begin.bitOffset());
493       return begin;
494     }
495   }
496
497   return end;
498 }
499
500
501 template <class T, class Enable=void> struct Unaligned;
502
503 /**
504  * Representation of an unaligned value of a POD type.
505  */
506 FOLLY_PACK_PUSH
507 template <class T>
508 struct Unaligned<
509     T,
510     typename std::enable_if<std::is_pod<T>::value>::type> {
511   Unaligned() = default;  // uninitialized
512   /* implicit */ Unaligned(T v) : value(v) { }
513   T value;
514 } FOLLY_PACK_ATTR;
515 FOLLY_PACK_POP
516
517 /**
518  * Read an unaligned value of type T and return it.
519  */
520 template <class T>
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;
526   } else {
527     T value;
528     memcpy(&value, p, sizeof(T));
529     return value;
530   }
531 }
532
533 /**
534  * Write an unaligned value of type T.
535  */
536 template <class 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);
548   } else {
549     memcpy(p, &value, sizeof(T));
550   }
551 }
552
553 }  // namespace folly