Add <new> header for placement new
[folly.git] / folly / Bits.h
1 /*
2  * Copyright 2016 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
67 #include <folly/detail/BitsDetail.h>
68 #include <folly/detail/BitIteratorDetail.h>
69 #include <folly/Likely.h>
70
71 #if FOLLY_HAVE_BYTESWAP_H
72 # include <byteswap.h>
73 #endif
74
75 #include <cassert>
76 #include <cinttypes>
77 #include <iterator>
78 #include <limits>
79 #include <type_traits>
80 #include <boost/iterator/iterator_adaptor.hpp>
81 #include <stdint.h>
82
83 namespace folly {
84
85 // Generate overloads for findFirstSet as wrappers around
86 // appropriate ffs, ffsl, ffsll gcc builtins
87 template <class T>
88 inline FOLLY_INTRINSIC_CONSTEXPR
89 typename std::enable_if<
90   (std::is_integral<T>::value &&
91    std::is_unsigned<T>::value &&
92    sizeof(T) <= sizeof(unsigned int)),
93   unsigned int>::type
94   findFirstSet(T x) {
95   return __builtin_ffs(x);
96 }
97
98 template <class T>
99 inline FOLLY_INTRINSIC_CONSTEXPR
100 typename std::enable_if<
101   (std::is_integral<T>::value &&
102    std::is_unsigned<T>::value &&
103    sizeof(T) > sizeof(unsigned int) &&
104    sizeof(T) <= sizeof(unsigned long)),
105   unsigned int>::type
106   findFirstSet(T x) {
107   return __builtin_ffsl(x);
108 }
109
110 template <class T>
111 inline FOLLY_INTRINSIC_CONSTEXPR
112 typename std::enable_if<
113   (std::is_integral<T>::value &&
114    std::is_unsigned<T>::value &&
115    sizeof(T) > sizeof(unsigned long) &&
116    sizeof(T) <= sizeof(unsigned long long)),
117   unsigned int>::type
118   findFirstSet(T x) {
119   return __builtin_ffsll(x);
120 }
121
122 template <class T>
123 inline FOLLY_INTRINSIC_CONSTEXPR
124 typename std::enable_if<
125   (std::is_integral<T>::value && std::is_signed<T>::value),
126   unsigned int>::type
127   findFirstSet(T x) {
128   // Note that conversion from a signed type to the corresponding unsigned
129   // type is technically implementation-defined, but will likely work
130   // on any impementation that uses two's complement.
131   return findFirstSet(static_cast<typename std::make_unsigned<T>::type>(x));
132 }
133
134 // findLastSet: return the 1-based index of the highest bit set
135 // for x > 0, findLastSet(x) == 1 + floor(log2(x))
136 template <class T>
137 inline FOLLY_INTRINSIC_CONSTEXPR
138 typename std::enable_if<
139   (std::is_integral<T>::value &&
140    std::is_unsigned<T>::value &&
141    sizeof(T) <= sizeof(unsigned int)),
142   unsigned int>::type
143   findLastSet(T x) {
144   return x ? 8 * sizeof(unsigned int) - __builtin_clz(x) : 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) - __builtin_clzl(x) : 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) - __builtin_clzll(x) : 0;
169 }
170
171 template <class T>
172 inline FOLLY_INTRINSIC_CONSTEXPR
173 typename std::enable_if<
174   (std::is_integral<T>::value &&
175    std::is_signed<T>::value),
176   unsigned int>::type
177   findLastSet(T x) {
178   return findLastSet(static_cast<typename std::make_unsigned<T>::type>(x));
179 }
180
181 template <class T>
182 inline FOLLY_INTRINSIC_CONSTEXPR
183 typename std::enable_if<
184   std::is_integral<T>::value && std::is_unsigned<T>::value,
185   T>::type
186 nextPowTwo(T v) {
187   return v ? (1ul << findLastSet(v - 1)) : 1;
188 }
189
190 template <class T>
191 inline constexpr
192 typename std::enable_if<
193   std::is_integral<T>::value && std::is_unsigned<T>::value,
194   bool>::type
195 isPowTwo(T v) {
196   return (v != 0) && !(v & (v - 1));
197 }
198
199 /**
200  * Population count
201  */
202 template <class T>
203 inline typename std::enable_if<
204   (std::is_integral<T>::value &&
205    std::is_unsigned<T>::value &&
206    sizeof(T) <= sizeof(unsigned int)),
207   size_t>::type
208   popcount(T x) {
209   return detail::popcount(x);
210 }
211
212 template <class T>
213 inline typename std::enable_if<
214   (std::is_integral<T>::value &&
215    std::is_unsigned<T>::value &&
216    sizeof(T) > sizeof(unsigned int) &&
217    sizeof(T) <= sizeof(unsigned long long)),
218   size_t>::type
219   popcount(T x) {
220   return detail::popcountll(x);
221 }
222
223 /**
224  * Endianness detection and manipulation primitives.
225  */
226 namespace detail {
227
228 template <class T>
229 struct EndianIntBase {
230  public:
231   static T swap(T x);
232 };
233
234 #ifndef _MSC_VER
235
236 /**
237  * If we have the bswap_16 macro from byteswap.h, use it; otherwise, provide our
238  * own definition.
239  */
240 #ifdef bswap_16
241 # define our_bswap16 bswap_16
242 #else
243
244 template<class Int16>
245 inline constexpr typename std::enable_if<
246   sizeof(Int16) == 2,
247   Int16>::type
248 our_bswap16(Int16 x) {
249   return ((x >> 8) & 0xff) | ((x & 0xff) << 8);
250 }
251 #endif
252
253 #endif
254
255 #define FB_GEN(t, fn) \
256 template<> inline t EndianIntBase<t>::swap(t x) { return fn(x); }
257
258 // fn(x) expands to (x) if the second argument is empty, which is exactly
259 // what we want for [u]int8_t. Also, gcc 4.7 on Intel doesn't have
260 // __builtin_bswap16 for some reason, so we have to provide our own.
261 FB_GEN( int8_t,)
262 FB_GEN(uint8_t,)
263 #ifdef _MSC_VER
264 FB_GEN( int64_t, _byteswap_uint64)
265 FB_GEN(uint64_t, _byteswap_uint64)
266 FB_GEN( int32_t, _byteswap_ulong)
267 FB_GEN(uint32_t, _byteswap_ulong)
268 FB_GEN( int16_t, _byteswap_ushort)
269 FB_GEN(uint16_t, _byteswap_ushort)
270 #else
271 FB_GEN( int64_t, __builtin_bswap64)
272 FB_GEN(uint64_t, __builtin_bswap64)
273 FB_GEN( int32_t, __builtin_bswap32)
274 FB_GEN(uint32_t, __builtin_bswap32)
275 FB_GEN( int16_t, our_bswap16)
276 FB_GEN(uint16_t, our_bswap16)
277 #endif
278
279 #undef FB_GEN
280
281 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
282
283 template <class T>
284 struct EndianInt : public detail::EndianIntBase<T> {
285  public:
286   static T big(T x) { return EndianInt::swap(x); }
287   static T little(T x) { return x; }
288 };
289
290 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
291
292 template <class T>
293 struct EndianInt : public detail::EndianIntBase<T> {
294  public:
295   static T big(T x) { return x; }
296   static T little(T x) { return EndianInt::swap(x); }
297 };
298
299 #else
300 # error Your machine uses a weird endianness!
301 #endif  /* __BYTE_ORDER__ */
302
303 }  // namespace detail
304
305 // big* convert between native and big-endian representations
306 // little* convert between native and little-endian representations
307 // swap* convert between big-endian and little-endian representations
308 //
309 // ntohs, htons == big16
310 // ntohl, htonl == big32
311 #define FB_GEN1(fn, t, sz) \
312   static t fn##sz(t x) { return fn<t>(x); } \
313
314 #define FB_GEN2(t, sz) \
315   FB_GEN1(swap, t, sz) \
316   FB_GEN1(big, t, sz) \
317   FB_GEN1(little, t, sz)
318
319 #define FB_GEN(sz) \
320   FB_GEN2(uint##sz##_t, sz) \
321   FB_GEN2(int##sz##_t, sz)
322
323 class Endian {
324  public:
325   enum class Order : uint8_t {
326     LITTLE,
327     BIG
328   };
329
330   static constexpr Order order =
331 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
332     Order::LITTLE;
333 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
334     Order::BIG;
335 #else
336 # error Your machine uses a weird endianness!
337 #endif  /* __BYTE_ORDER__ */
338
339   template <class T> static T swap(T x) {
340     return detail::EndianInt<T>::swap(x);
341   }
342   template <class T> static T big(T x) {
343     return detail::EndianInt<T>::big(x);
344   }
345   template <class T> static T little(T x) {
346     return detail::EndianInt<T>::little(x);
347   }
348
349 #if !defined(__ANDROID__)
350   FB_GEN(64)
351   FB_GEN(32)
352   FB_GEN(16)
353   FB_GEN(8)
354 #endif
355 };
356
357 #undef FB_GEN
358 #undef FB_GEN2
359 #undef FB_GEN1
360
361 /**
362  * Fast bit iteration facility.
363  */
364
365
366 template <class BaseIter> class BitIterator;
367 template <class BaseIter>
368 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
369                                    BitIterator<BaseIter>);
370 /**
371  * Wrapper around an iterator over an integer type that iterates
372  * over its underlying bits in LSb to MSb order.
373  *
374  * BitIterator models the same iterator concepts as the base iterator.
375  */
376 template <class BaseIter>
377 class BitIterator
378   : public bititerator_detail::BitIteratorBase<BaseIter>::type {
379  public:
380   /**
381    * Return the number of bits in an element of the underlying iterator.
382    */
383   static unsigned int bitsPerBlock() {
384     return std::numeric_limits<
385       typename std::make_unsigned<
386         typename std::iterator_traits<BaseIter>::value_type
387       >::type
388     >::digits;
389   }
390
391   /**
392    * Construct a BitIterator that points at a given bit offset (default 0)
393    * in iter.
394    */
395   #pragma GCC diagnostic push // bitOffset shadows a member
396   #pragma GCC diagnostic ignored "-Wshadow"
397   explicit BitIterator(const BaseIter& iter, size_t bitOffset=0)
398     : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
399       bitOffset_(bitOffset) {
400     assert(bitOffset_ < bitsPerBlock());
401   }
402   #pragma GCC diagnostic pop
403
404   size_t bitOffset() const {
405     return bitOffset_;
406   }
407
408   void advanceToNextBlock() {
409     bitOffset_ = 0;
410     ++this->base_reference();
411   }
412
413   BitIterator& operator=(const BaseIter& other) {
414     this->~BitIterator();
415     new (this) BitIterator(other);
416     return *this;
417   }
418
419  private:
420   friend class boost::iterator_core_access;
421   friend BitIterator findFirstSet<>(BitIterator, BitIterator);
422
423   typedef bititerator_detail::BitReference<
424       typename std::iterator_traits<BaseIter>::reference,
425       typename std::iterator_traits<BaseIter>::value_type
426     > BitRef;
427
428   void advanceInBlock(size_t n) {
429     bitOffset_ += n;
430     assert(bitOffset_ < bitsPerBlock());
431   }
432
433   BitRef dereference() const {
434     return BitRef(*this->base_reference(), bitOffset_);
435   }
436
437   void advance(ssize_t n) {
438     size_t bpb = bitsPerBlock();
439     ssize_t blocks = n / bpb;
440     bitOffset_ += n % bpb;
441     if (bitOffset_ >= bpb) {
442       bitOffset_ -= bpb;
443       ++blocks;
444     }
445     this->base_reference() += blocks;
446   }
447
448   void increment() {
449     if (++bitOffset_ == bitsPerBlock()) {
450       advanceToNextBlock();
451     }
452   }
453
454   void decrement() {
455     if (bitOffset_-- == 0) {
456       bitOffset_ = bitsPerBlock() - 1;
457       --this->base_reference();
458     }
459   }
460
461   bool equal(const BitIterator& other) const {
462     return (bitOffset_ == other.bitOffset_ &&
463             this->base_reference() == other.base_reference());
464   }
465
466   ssize_t distance_to(const BitIterator& other) const {
467     return
468       (other.base_reference() - this->base_reference()) * bitsPerBlock() +
469       other.bitOffset_ - bitOffset_;
470   }
471
472   unsigned int bitOffset_;
473 };
474
475 /**
476  * Helper function, so you can write
477  * auto bi = makeBitIterator(container.begin());
478  */
479 template <class BaseIter>
480 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
481   return BitIterator<BaseIter>(iter);
482 }
483
484
485 /**
486  * Find first bit set in a range of bit iterators.
487  * 4.5x faster than the obvious std::find(begin, end, true);
488  */
489 template <class BaseIter>
490 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
491                                    BitIterator<BaseIter> end) {
492   // shortcut to avoid ugly static_cast<>
493   static const typename BaseIter::value_type one = 1;
494
495   while (begin.base() != end.base()) {
496     typename BaseIter::value_type v = *begin.base();
497     // mask out the bits that don't matter (< begin.bitOffset)
498     v &= ~((one << begin.bitOffset()) - 1);
499     size_t firstSet = findFirstSet(v);
500     if (firstSet) {
501       --firstSet;  // now it's 0-based
502       assert(firstSet >= begin.bitOffset());
503       begin.advanceInBlock(firstSet - begin.bitOffset());
504       return begin;
505     }
506     begin.advanceToNextBlock();
507   }
508
509   // now begin points to the same block as end
510   if (end.bitOffset() != 0) {  // assume end is dereferenceable
511     typename BaseIter::value_type v = *begin.base();
512     // mask out the bits that don't matter (< begin.bitOffset)
513     v &= ~((one << begin.bitOffset()) - 1);
514     // mask out the bits that don't matter (>= end.bitOffset)
515     v &= (one << end.bitOffset()) - 1;
516     size_t firstSet = findFirstSet(v);
517     if (firstSet) {
518       --firstSet;  // now it's 0-based
519       assert(firstSet >= begin.bitOffset());
520       begin.advanceInBlock(firstSet - begin.bitOffset());
521       return begin;
522     }
523   }
524
525   return end;
526 }
527
528
529 template <class T, class Enable=void> struct Unaligned;
530
531 /**
532  * Representation of an unaligned value of a POD type.
533  */
534 FOLLY_PACK_PUSH
535 template <class T>
536 struct Unaligned<
537     T,
538     typename std::enable_if<std::is_pod<T>::value>::type> {
539   Unaligned() = default;  // uninitialized
540   /* implicit */ Unaligned(T v) : value(v) { }
541   T value;
542 } FOLLY_PACK_ATTR;
543 FOLLY_PACK_POP
544
545 /**
546  * Read an unaligned value of type T and return it.
547  */
548 template <class T>
549 inline T loadUnaligned(const void* p) {
550   static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
551   static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
552   if (kHasUnalignedAccess) {
553     return static_cast<const Unaligned<T>*>(p)->value;
554   } else {
555     T value;
556     memcpy(&value, p, sizeof(T));
557     return value;
558   }
559 }
560
561 /**
562  * Write an unaligned value of type T.
563  */
564 template <class T>
565 inline void storeUnaligned(void* p, T value) {
566   static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
567   static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
568   if (kHasUnalignedAccess) {
569     new (p) Unaligned<T>(value);
570   } else {
571     memcpy(p, &value, sizeof(T));
572   }
573 }
574
575 }  // namespace folly