Kill checks in configure.ac that aren't used
[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/BitsDetail.h>
70 #include <folly/detail/BitIteratorDetail.h>
71 #include <folly/Likely.h>
72
73 #include <cassert>
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(detail::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(detail::popcountll(x));
228 }
229
230 /**
231  * Endianness detection and manipulation primitives.
232  */
233 namespace detail {
234
235 template <class T>
236 struct EndianIntBase {
237  public:
238   static T swap(T x);
239 };
240
241 #define FB_GEN(t, fn)                             \
242   template <>                                     \
243   inline t EndianIntBase<t>::swap(t x) {          \
244     return t(fn(std::make_unsigned<t>::type(x))); \
245   }
246
247 // fn(x) expands to (x) if the second argument is empty, which is exactly
248 // what we want for [u]int8_t.
249 FB_GEN( int8_t,)
250 FB_GEN(uint8_t,)
251 #ifdef _MSC_VER
252 FB_GEN( int64_t, _byteswap_uint64)
253 FB_GEN(uint64_t, _byteswap_uint64)
254 FB_GEN( int32_t, _byteswap_ulong)
255 FB_GEN(uint32_t, _byteswap_ulong)
256 FB_GEN( int16_t, _byteswap_ushort)
257 FB_GEN(uint16_t, _byteswap_ushort)
258 #else
259 FB_GEN( int64_t, __builtin_bswap64)
260 FB_GEN(uint64_t, __builtin_bswap64)
261 FB_GEN( int32_t, __builtin_bswap32)
262 FB_GEN(uint32_t, __builtin_bswap32)
263 FB_GEN( int16_t, __builtin_bswap16)
264 FB_GEN(uint16_t, __builtin_bswap16)
265 #endif
266
267 #undef FB_GEN
268
269 template <class T>
270 struct EndianInt : public EndianIntBase<T> {
271  public:
272   static T big(T x) {
273     return kIsLittleEndian ? EndianInt::swap(x) : x;
274   }
275   static T little(T x) {
276     return kIsBigEndian ? EndianInt::swap(x) : x;
277   }
278 };
279
280 }  // namespace detail
281
282 // big* convert between native and big-endian representations
283 // little* convert between native and little-endian representations
284 // swap* convert between big-endian and little-endian representations
285 //
286 // ntohs, htons == big16
287 // ntohl, htonl == big32
288 #define FB_GEN1(fn, t, sz) \
289   static t fn##sz(t x) { return fn<t>(x); } \
290
291 #define FB_GEN2(t, sz) \
292   FB_GEN1(swap, t, sz) \
293   FB_GEN1(big, t, sz) \
294   FB_GEN1(little, t, sz)
295
296 #define FB_GEN(sz) \
297   FB_GEN2(uint##sz##_t, sz) \
298   FB_GEN2(int##sz##_t, sz)
299
300 class Endian {
301  public:
302   enum class Order : uint8_t {
303     LITTLE,
304     BIG
305   };
306
307   static constexpr Order order = kIsLittleEndian ? Order::LITTLE : Order::BIG;
308
309   template <class T> static T swap(T x) {
310     return folly::detail::EndianInt<T>::swap(x);
311   }
312   template <class T> static T big(T x) {
313     return folly::detail::EndianInt<T>::big(x);
314   }
315   template <class T> static T little(T x) {
316     return folly::detail::EndianInt<T>::little(x);
317   }
318
319 #if !defined(__ANDROID__)
320   FB_GEN(64)
321   FB_GEN(32)
322   FB_GEN(16)
323   FB_GEN(8)
324 #endif
325 };
326
327 #undef FB_GEN
328 #undef FB_GEN2
329 #undef FB_GEN1
330
331 /**
332  * Fast bit iteration facility.
333  */
334
335
336 template <class BaseIter> class BitIterator;
337 template <class BaseIter>
338 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
339                                    BitIterator<BaseIter>);
340 /**
341  * Wrapper around an iterator over an integer type that iterates
342  * over its underlying bits in LSb to MSb order.
343  *
344  * BitIterator models the same iterator concepts as the base iterator.
345  */
346 template <class BaseIter>
347 class BitIterator
348   : public bititerator_detail::BitIteratorBase<BaseIter>::type {
349  public:
350   /**
351    * Return the number of bits in an element of the underlying iterator.
352    */
353   static unsigned int bitsPerBlock() {
354     return std::numeric_limits<
355       typename std::make_unsigned<
356         typename std::iterator_traits<BaseIter>::value_type
357       >::type
358     >::digits;
359   }
360
361   /**
362    * Construct a BitIterator that points at a given bit offset (default 0)
363    * in iter.
364    */
365   explicit BitIterator(const BaseIter& iter, size_t bitOff=0)
366     : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
367       bitOffset_(bitOff) {
368     assert(bitOffset_ < bitsPerBlock());
369   }
370
371   size_t bitOffset() const {
372     return bitOffset_;
373   }
374
375   void advanceToNextBlock() {
376     bitOffset_ = 0;
377     ++this->base_reference();
378   }
379
380   BitIterator& operator=(const BaseIter& other) {
381     this->~BitIterator();
382     new (this) BitIterator(other);
383     return *this;
384   }
385
386  private:
387   friend class boost::iterator_core_access;
388   friend BitIterator findFirstSet<>(BitIterator, BitIterator);
389
390   typedef bititerator_detail::BitReference<
391       typename std::iterator_traits<BaseIter>::reference,
392       typename std::iterator_traits<BaseIter>::value_type
393     > BitRef;
394
395   void advanceInBlock(size_t n) {
396     bitOffset_ += n;
397     assert(bitOffset_ < bitsPerBlock());
398   }
399
400   BitRef dereference() const {
401     return BitRef(*this->base_reference(), bitOffset_);
402   }
403
404   void advance(ssize_t n) {
405     size_t bpb = bitsPerBlock();
406     ssize_t blocks = n / ssize_t(bpb);
407     bitOffset_ += n % bpb;
408     if (bitOffset_ >= bpb) {
409       bitOffset_ -= bpb;
410       ++blocks;
411     }
412     this->base_reference() += blocks;
413   }
414
415   void increment() {
416     if (++bitOffset_ == bitsPerBlock()) {
417       advanceToNextBlock();
418     }
419   }
420
421   void decrement() {
422     if (bitOffset_-- == 0) {
423       bitOffset_ = bitsPerBlock() - 1;
424       --this->base_reference();
425     }
426   }
427
428   bool equal(const BitIterator& other) const {
429     return (bitOffset_ == other.bitOffset_ &&
430             this->base_reference() == other.base_reference());
431   }
432
433   ssize_t distance_to(const BitIterator& other) const {
434     return ssize_t(
435         (other.base_reference() - this->base_reference()) * bitsPerBlock() +
436         other.bitOffset_ - bitOffset_);
437   }
438
439   size_t bitOffset_;
440 };
441
442 /**
443  * Helper function, so you can write
444  * auto bi = makeBitIterator(container.begin());
445  */
446 template <class BaseIter>
447 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
448   return BitIterator<BaseIter>(iter);
449 }
450
451
452 /**
453  * Find first bit set in a range of bit iterators.
454  * 4.5x faster than the obvious std::find(begin, end, true);
455  */
456 template <class BaseIter>
457 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
458                                    BitIterator<BaseIter> end) {
459   // shortcut to avoid ugly static_cast<>
460   static const typename BaseIter::value_type one = 1;
461
462   while (begin.base() != end.base()) {
463     typename BaseIter::value_type v = *begin.base();
464     // mask out the bits that don't matter (< begin.bitOffset)
465     v &= ~((one << begin.bitOffset()) - 1);
466     size_t firstSet = findFirstSet(v);
467     if (firstSet) {
468       --firstSet;  // now it's 0-based
469       assert(firstSet >= begin.bitOffset());
470       begin.advanceInBlock(firstSet - begin.bitOffset());
471       return begin;
472     }
473     begin.advanceToNextBlock();
474   }
475
476   // now begin points to the same block as end
477   if (end.bitOffset() != 0) {  // assume end is dereferenceable
478     typename BaseIter::value_type v = *begin.base();
479     // mask out the bits that don't matter (< begin.bitOffset)
480     v &= ~((one << begin.bitOffset()) - 1);
481     // mask out the bits that don't matter (>= end.bitOffset)
482     v &= (one << end.bitOffset()) - 1;
483     size_t firstSet = findFirstSet(v);
484     if (firstSet) {
485       --firstSet;  // now it's 0-based
486       assert(firstSet >= begin.bitOffset());
487       begin.advanceInBlock(firstSet - begin.bitOffset());
488       return begin;
489     }
490   }
491
492   return end;
493 }
494
495
496 template <class T, class Enable=void> struct Unaligned;
497
498 /**
499  * Representation of an unaligned value of a POD type.
500  */
501 FOLLY_PACK_PUSH
502 template <class T>
503 struct Unaligned<
504     T,
505     typename std::enable_if<std::is_pod<T>::value>::type> {
506   Unaligned() = default;  // uninitialized
507   /* implicit */ Unaligned(T v) : value(v) { }
508   T value;
509 } FOLLY_PACK_ATTR;
510 FOLLY_PACK_POP
511
512 /**
513  * Read an unaligned value of type T and return it.
514  */
515 template <class T>
516 inline T loadUnaligned(const void* p) {
517   static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
518   static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
519   if (kHasUnalignedAccess) {
520     return static_cast<const Unaligned<T>*>(p)->value;
521   } else {
522     T value;
523     memcpy(&value, p, sizeof(T));
524     return value;
525   }
526 }
527
528 /**
529  * Write an unaligned value of type T.
530  */
531 template <class T>
532 inline void storeUnaligned(void* p, T value) {
533   static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
534   static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
535   if (kHasUnalignedAccess) {
536     // Prior to C++14, the spec says that a placement new like this
537     // is required to check that p is not nullptr, and to do nothing
538     // if p is a nullptr. By assuming it's not a nullptr, we get a
539     // nice loud segfault in optimized builds if p is nullptr, rather
540     // than just silently doing nothing.
541     folly::assume(p != nullptr);
542     new (p) Unaligned<T>(value);
543   } else {
544     memcpy(p, &value, sizeof(T));
545   }
546 }
547
548 }  // namespace folly