• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef V8_BASE_BITS_H_
6 #define V8_BASE_BITS_H_
7 
8 #include <stdint.h>
9 #include <type_traits>
10 
11 #include "src/base/base-export.h"
12 #include "src/base/macros.h"
13 #if V8_CC_MSVC
14 #include <intrin.h>
15 #endif
16 #if V8_OS_WIN32
17 #include "src/base/win32-headers.h"
18 #endif
19 
20 namespace v8 {
21 namespace base {
22 namespace bits {
23 
24 // CountPopulation(value) returns the number of bits set in |value|.
25 template <typename T>
26 constexpr inline
27     typename std::enable_if<std::is_unsigned<T>::value && sizeof(T) <= 8,
28                             unsigned>::type
CountPopulation(T value)29     CountPopulation(T value) {
30   STATIC_ASSERT(sizeof(T) <= 8);
31 #if V8_HAS_BUILTIN_POPCOUNT
32   return sizeof(T) == 8 ? __builtin_popcountll(static_cast<uint64_t>(value))
33                         : __builtin_popcount(static_cast<uint32_t>(value));
34 #else
35   // Fall back to divide-and-conquer popcount (see "Hacker's Delight" by Henry
36   // S. Warren, Jr.), chapter 5-1.
37   constexpr uint64_t mask[] = {0x5555555555555555, 0x3333333333333333,
38                                0x0f0f0f0f0f0f0f0f};
39   // Start with 64 buckets of 1 bits, holding values from [0,1].
40   value = ((value >> 1) & mask[0]) + (value & mask[0]);
41   // Having 32 buckets of 2 bits, holding values from [0,2] now.
42   value = ((value >> 2) & mask[1]) + (value & mask[1]);
43   // Having 16 buckets of 4 bits, holding values from [0,4] now.
44   value = ((value >> 4) & mask[2]) + (value & mask[2]);
45   // Having 8 buckets of 8 bits, holding values from [0,8] now.
46   // From this point on, the buckets are bigger than the number of bits
47   // required to hold the values, and the buckets are bigger the maximum
48   // result, so there's no need to mask value anymore, since there's no
49   // more risk of overflow between buckets.
50   if (sizeof(T) > 1) value = (value >> (sizeof(T) > 1 ? 8 : 0)) + value;
51   // Having 4 buckets of 16 bits, holding values from [0,16] now.
52   if (sizeof(T) > 2) value = (value >> (sizeof(T) > 2 ? 16 : 0)) + value;
53   // Having 2 buckets of 32 bits, holding values from [0,32] now.
54   if (sizeof(T) > 4) value = (value >> (sizeof(T) > 4 ? 32 : 0)) + value;
55   // Having 1 buckets of 64 bits, holding values from [0,64] now.
56   return static_cast<unsigned>(value & 0xff);
57 #endif
58 }
59 
60 // ReverseBits(value) returns |value| in reverse bit order.
61 template <typename T>
ReverseBits(T value)62 T ReverseBits(T value) {
63   STATIC_ASSERT((sizeof(value) == 1) || (sizeof(value) == 2) ||
64                 (sizeof(value) == 4) || (sizeof(value) == 8));
65   T result = 0;
66   for (unsigned i = 0; i < (sizeof(value) * 8); i++) {
67     result = (result << 1) | (value & 1);
68     value >>= 1;
69   }
70   return result;
71 }
72 
73 // CountLeadingZeros(value) returns the number of zero bits following the most
74 // significant 1 bit in |value| if |value| is non-zero, otherwise it returns
75 // {sizeof(T) * 8}.
76 template <typename T, unsigned bits = sizeof(T) * 8>
77 inline constexpr
78     typename std::enable_if<std::is_unsigned<T>::value && sizeof(T) <= 8,
79                             unsigned>::type
CountLeadingZeros(T value)80     CountLeadingZeros(T value) {
81   static_assert(bits > 0, "invalid instantiation");
82 #if V8_HAS_BUILTIN_CLZ
83   return value == 0
84              ? bits
85              : bits == 64
86                    ? __builtin_clzll(static_cast<uint64_t>(value))
87                    : __builtin_clz(static_cast<uint32_t>(value)) - (32 - bits);
88 #else
89   // Binary search algorithm taken from "Hacker's Delight" (by Henry S. Warren,
90   // Jr.), figures 5-11 and 5-12.
91   if (bits == 1) return static_cast<unsigned>(value) ^ 1;
92   T upper_half = value >> (bits / 2);
93   T next_value = upper_half != 0 ? upper_half : value;
94   unsigned add = upper_half != 0 ? 0 : bits / 2;
95   constexpr unsigned next_bits = bits == 1 ? 1 : bits / 2;
96   return CountLeadingZeros<T, next_bits>(next_value) + add;
97 #endif
98 }
99 
CountLeadingZeros32(uint32_t value)100 inline constexpr unsigned CountLeadingZeros32(uint32_t value) {
101   return CountLeadingZeros(value);
102 }
CountLeadingZeros64(uint64_t value)103 inline constexpr unsigned CountLeadingZeros64(uint64_t value) {
104   return CountLeadingZeros(value);
105 }
106 
107 // CountTrailingZeros(value) returns the number of zero bits preceding the
108 // least significant 1 bit in |value| if |value| is non-zero, otherwise it
109 // returns {sizeof(T) * 8}.
110 template <typename T, unsigned bits = sizeof(T) * 8>
111 inline constexpr
112     typename std::enable_if<std::is_integral<T>::value && sizeof(T) <= 8,
113                             unsigned>::type
CountTrailingZeros(T value)114     CountTrailingZeros(T value) {
115 #if V8_HAS_BUILTIN_CTZ
116   return value == 0 ? bits
117                     : bits == 64 ? __builtin_ctzll(static_cast<uint64_t>(value))
118                                  : __builtin_ctz(static_cast<uint32_t>(value));
119 #else
120   // Fall back to popcount (see "Hacker's Delight" by Henry S. Warren, Jr.),
121   // chapter 5-4. On x64, since is faster than counting in a loop and faster
122   // than doing binary search.
123   using U = typename std::make_unsigned<T>::type;
124   U u = value;
125   return CountPopulation(static_cast<U>(~u & (u - 1u)));
126 #endif
127 }
128 
CountTrailingZeros32(uint32_t value)129 inline constexpr unsigned CountTrailingZeros32(uint32_t value) {
130   return CountTrailingZeros(value);
131 }
CountTrailingZeros64(uint64_t value)132 inline constexpr unsigned CountTrailingZeros64(uint64_t value) {
133   return CountTrailingZeros(value);
134 }
135 
136 // Returns true iff |value| is a power of 2.
137 template <typename T,
138           typename = typename std::enable_if<std::is_integral<T>::value ||
139                                              std::is_enum<T>::value>::type>
IsPowerOfTwo(T value)140 constexpr inline bool IsPowerOfTwo(T value) {
141   return value > 0 && (value & (value - 1)) == 0;
142 }
143 
144 // Identical to {CountTrailingZeros}, but only works for powers of 2.
145 template <typename T,
146           typename = typename std::enable_if<std::is_integral<T>::value>::type>
WhichPowerOfTwo(T value)147 inline constexpr int WhichPowerOfTwo(T value) {
148   CONSTEXPR_DCHECK(IsPowerOfTwo(value));
149 #if V8_HAS_BUILTIN_CTZ
150   STATIC_ASSERT(sizeof(T) <= 8);
151   return sizeof(T) == 8 ? __builtin_ctzll(static_cast<uint64_t>(value))
152                         : __builtin_ctz(static_cast<uint32_t>(value));
153 #else
154   // Fall back to popcount (see "Hacker's Delight" by Henry S. Warren, Jr.),
155   // chapter 5-4. On x64, since is faster than counting in a loop and faster
156   // than doing binary search.
157   using U = typename std::make_unsigned<T>::type;
158   U u = value;
159   return CountPopulation(static_cast<U>(u - 1));
160 #endif
161 }
162 
163 // RoundUpToPowerOfTwo32(value) returns the smallest power of two which is
164 // greater than or equal to |value|. If you pass in a |value| that is already a
165 // power of two, it is returned as is. |value| must be less than or equal to
166 // 0x80000000u. Uses computation based on leading zeros if we have compiler
167 // support for that. Falls back to the implementation from "Hacker's Delight" by
168 // Henry S. Warren, Jr., figure 3-3, page 48, where the function is called clp2.
169 V8_BASE_EXPORT uint32_t RoundUpToPowerOfTwo32(uint32_t value);
170 // Same for 64 bit integers. |value| must be <= 2^63
171 V8_BASE_EXPORT uint64_t RoundUpToPowerOfTwo64(uint64_t value);
172 // Same for size_t integers.
RoundUpToPowerOfTwo(size_t value)173 inline size_t RoundUpToPowerOfTwo(size_t value) {
174   if (sizeof(size_t) == sizeof(uint64_t)) {
175     return RoundUpToPowerOfTwo64(value);
176   } else {
177     return RoundUpToPowerOfTwo32(value);
178   }
179 }
180 
181 // RoundDownToPowerOfTwo32(value) returns the greatest power of two which is
182 // less than or equal to |value|. If you pass in a |value| that is already a
183 // power of two, it is returned as is.
RoundDownToPowerOfTwo32(uint32_t value)184 inline uint32_t RoundDownToPowerOfTwo32(uint32_t value) {
185   if (value > 0x80000000u) return 0x80000000u;
186   uint32_t result = RoundUpToPowerOfTwo32(value);
187   if (result > value) result >>= 1;
188   return result;
189 }
190 
191 
192 // Precondition: 0 <= shift < 32
RotateRight32(uint32_t value,uint32_t shift)193 inline constexpr uint32_t RotateRight32(uint32_t value, uint32_t shift) {
194   return (value >> shift) | (value << ((32 - shift) & 31));
195 }
196 
197 // Precondition: 0 <= shift < 32
RotateLeft32(uint32_t value,uint32_t shift)198 inline constexpr uint32_t RotateLeft32(uint32_t value, uint32_t shift) {
199   return (value << shift) | (value >> ((32 - shift) & 31));
200 }
201 
202 // Precondition: 0 <= shift < 64
RotateRight64(uint64_t value,uint64_t shift)203 inline constexpr uint64_t RotateRight64(uint64_t value, uint64_t shift) {
204   return (value >> shift) | (value << ((64 - shift) & 63));
205 }
206 
207 // Precondition: 0 <= shift < 64
RotateLeft64(uint64_t value,uint64_t shift)208 inline constexpr uint64_t RotateLeft64(uint64_t value, uint64_t shift) {
209   return (value << shift) | (value >> ((64 - shift) & 63));
210 }
211 
212 // SignedAddOverflow32(lhs,rhs,val) performs a signed summation of |lhs| and
213 // |rhs| and stores the result into the variable pointed to by |val| and
214 // returns true if the signed summation resulted in an overflow.
SignedAddOverflow32(int32_t lhs,int32_t rhs,int32_t * val)215 inline bool SignedAddOverflow32(int32_t lhs, int32_t rhs, int32_t* val) {
216 #if V8_HAS_BUILTIN_SADD_OVERFLOW
217   return __builtin_sadd_overflow(lhs, rhs, val);
218 #else
219   uint32_t res = static_cast<uint32_t>(lhs) + static_cast<uint32_t>(rhs);
220   *val = bit_cast<int32_t>(res);
221   return ((res ^ lhs) & (res ^ rhs) & (1U << 31)) != 0;
222 #endif
223 }
224 
225 
226 // SignedSubOverflow32(lhs,rhs,val) performs a signed subtraction of |lhs| and
227 // |rhs| and stores the result into the variable pointed to by |val| and
228 // returns true if the signed subtraction resulted in an overflow.
SignedSubOverflow32(int32_t lhs,int32_t rhs,int32_t * val)229 inline bool SignedSubOverflow32(int32_t lhs, int32_t rhs, int32_t* val) {
230 #if V8_HAS_BUILTIN_SSUB_OVERFLOW
231   return __builtin_ssub_overflow(lhs, rhs, val);
232 #else
233   uint32_t res = static_cast<uint32_t>(lhs) - static_cast<uint32_t>(rhs);
234   *val = bit_cast<int32_t>(res);
235   return ((res ^ lhs) & (res ^ ~rhs) & (1U << 31)) != 0;
236 #endif
237 }
238 
239 // SignedMulOverflow32(lhs,rhs,val) performs a signed multiplication of |lhs|
240 // and |rhs| and stores the result into the variable pointed to by |val| and
241 // returns true if the signed multiplication resulted in an overflow.
242 V8_BASE_EXPORT bool SignedMulOverflow32(int32_t lhs, int32_t rhs, int32_t* val);
243 
244 // SignedAddOverflow64(lhs,rhs,val) performs a signed summation of |lhs| and
245 // |rhs| and stores the result into the variable pointed to by |val| and
246 // returns true if the signed summation resulted in an overflow.
SignedAddOverflow64(int64_t lhs,int64_t rhs,int64_t * val)247 inline bool SignedAddOverflow64(int64_t lhs, int64_t rhs, int64_t* val) {
248   uint64_t res = static_cast<uint64_t>(lhs) + static_cast<uint64_t>(rhs);
249   *val = bit_cast<int64_t>(res);
250   return ((res ^ lhs) & (res ^ rhs) & (1ULL << 63)) != 0;
251 }
252 
253 
254 // SignedSubOverflow64(lhs,rhs,val) performs a signed subtraction of |lhs| and
255 // |rhs| and stores the result into the variable pointed to by |val| and
256 // returns true if the signed subtraction resulted in an overflow.
SignedSubOverflow64(int64_t lhs,int64_t rhs,int64_t * val)257 inline bool SignedSubOverflow64(int64_t lhs, int64_t rhs, int64_t* val) {
258   uint64_t res = static_cast<uint64_t>(lhs) - static_cast<uint64_t>(rhs);
259   *val = bit_cast<int64_t>(res);
260   return ((res ^ lhs) & (res ^ ~rhs) & (1ULL << 63)) != 0;
261 }
262 
263 // SignedMulHigh32(lhs, rhs) multiplies two signed 32-bit values |lhs| and
264 // |rhs|, extracts the most significant 32 bits of the result, and returns
265 // those.
266 V8_BASE_EXPORT int32_t SignedMulHigh32(int32_t lhs, int32_t rhs);
267 
268 // SignedMulHighAndAdd32(lhs, rhs, acc) multiplies two signed 32-bit values
269 // |lhs| and |rhs|, extracts the most significant 32 bits of the result, and
270 // adds the accumulate value |acc|.
271 V8_BASE_EXPORT int32_t SignedMulHighAndAdd32(int32_t lhs, int32_t rhs,
272                                              int32_t acc);
273 
274 // SignedDiv32(lhs, rhs) divides |lhs| by |rhs| and returns the quotient
275 // truncated to int32. If |rhs| is zero, then zero is returned. If |lhs|
276 // is minint and |rhs| is -1, it returns minint.
277 V8_BASE_EXPORT int32_t SignedDiv32(int32_t lhs, int32_t rhs);
278 
279 // SignedMod32(lhs, rhs) divides |lhs| by |rhs| and returns the remainder
280 // truncated to int32. If either |rhs| is zero or |lhs| is minint and |rhs|
281 // is -1, it returns zero.
282 V8_BASE_EXPORT int32_t SignedMod32(int32_t lhs, int32_t rhs);
283 
284 // UnsignedAddOverflow32(lhs,rhs,val) performs an unsigned summation of |lhs|
285 // and |rhs| and stores the result into the variable pointed to by |val| and
286 // returns true if the unsigned summation resulted in an overflow.
UnsignedAddOverflow32(uint32_t lhs,uint32_t rhs,uint32_t * val)287 inline bool UnsignedAddOverflow32(uint32_t lhs, uint32_t rhs, uint32_t* val) {
288 #if V8_HAS_BUILTIN_SADD_OVERFLOW
289   return __builtin_uadd_overflow(lhs, rhs, val);
290 #else
291   *val = lhs + rhs;
292   return *val < (lhs | rhs);
293 #endif
294 }
295 
296 
297 // UnsignedDiv32(lhs, rhs) divides |lhs| by |rhs| and returns the quotient
298 // truncated to uint32. If |rhs| is zero, then zero is returned.
UnsignedDiv32(uint32_t lhs,uint32_t rhs)299 inline uint32_t UnsignedDiv32(uint32_t lhs, uint32_t rhs) {
300   return rhs ? lhs / rhs : 0u;
301 }
302 
303 
304 // UnsignedMod32(lhs, rhs) divides |lhs| by |rhs| and returns the remainder
305 // truncated to uint32. If |rhs| is zero, then zero is returned.
UnsignedMod32(uint32_t lhs,uint32_t rhs)306 inline uint32_t UnsignedMod32(uint32_t lhs, uint32_t rhs) {
307   return rhs ? lhs % rhs : 0u;
308 }
309 
310 
311 // SignedSaturatedAdd64(lhs, rhs) adds |lhs| and |rhs|,
312 // checks and returns the result.
313 V8_BASE_EXPORT int64_t SignedSaturatedAdd64(int64_t lhs, int64_t rhs);
314 
315 // SignedSaturatedSub64(lhs, rhs) subtracts |lhs| by |rhs|,
316 // checks and returns the result.
317 V8_BASE_EXPORT int64_t SignedSaturatedSub64(int64_t lhs, int64_t rhs);
318 
319 }  // namespace bits
320 }  // namespace base
321 }  // namespace v8
322 
323 #endif  // V8_BASE_BITS_H_
324