v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
util.h
Go to the documentation of this file.
1// Copyright 2021 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_BIGINT_UTIL_H_
6#define V8_BIGINT_UTIL_H_
7
8// "Generic" helper functions (not specific to BigInts).
9
10#include <stdint.h>
11
12#include <type_traits>
13
14#ifdef _MSC_VER
15#include <intrin.h> // For _BitScanReverse.
16#endif
17
18// Integer division, rounding up.
19#define DIV_CEIL(x, y) (((x)-1) / (y) + 1)
20
21namespace v8 {
22namespace bigint {
23
24// Rounds up x to a multiple of y.
25inline constexpr int RoundUp(int x, int y) { return (x + y - 1) & -y; }
26
27// Different environments disagree on how 64-bit uintptr_t and uint64_t are
28// defined, so we have to use templates to be generic.
29template <typename T>
30constexpr int CountLeadingZeros(T value)
31 requires(std::is_unsigned<T>::value && sizeof(T) == 8)
32{
33#if __GNUC__ || __clang__
34 return value == 0 ? 64 : __builtin_clzll(value);
35#elif _MSC_VER
36 unsigned long index = 0; // NOLINT(runtime/int). MSVC insists.
37 return _BitScanReverse64(&index, value) ? 63 - index : 64;
38#else
39#error Unsupported compiler.
40#endif
41}
42
43constexpr int CountLeadingZeros(uint32_t value) {
44#if __GNUC__ || __clang__
45 return value == 0 ? 32 : __builtin_clz(value);
46#elif _MSC_VER
47 unsigned long index = 0; // NOLINT(runtime/int). MSVC insists.
48 return _BitScanReverse(&index, value) ? 31 - index : 32;
49#else
50#error Unsupported compiler.
51#endif
52}
53
54inline constexpr int CountTrailingZeros(uint32_t value) {
55#if __GNUC__ || __clang__
56 return value == 0 ? 32 : __builtin_ctz(value);
57#elif _MSC_VER
58 unsigned long index = 0; // NOLINT(runtime/int).
59 return _BitScanForward(&index, value) ? index : 32;
60#else
61#error Unsupported compiler.
62#endif
63}
64
65inline constexpr int BitLength(int n) {
66 return 32 - CountLeadingZeros(static_cast<uint32_t>(n));
67}
68
69inline constexpr bool IsPowerOfTwo(int value) {
70 return value > 0 && (value & (value - 1)) == 0;
71}
72
73} // namespace bigint
74} // namespace v8
75
76#endif // V8_BIGINT_UTIL_H_
#define T
OptionalOpIndex index
int y
int x
constexpr int BitLength(int n)
Definition util.h:65
constexpr int CountTrailingZeros(uint32_t value)
Definition util.h:54
constexpr int CountLeadingZeros(T value)
Definition util.h:30
constexpr bool IsPowerOfTwo(int value)
Definition util.h:69
constexpr int RoundUp(int x, int y)
Definition util.h:25