MathExtras.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. //===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains some functions that are useful for math stuff.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_SUPPORT_MATHEXTRAS_H
  13. #define LLVM_SUPPORT_MATHEXTRAS_H
  14. #include "llvm/Support/Compiler.h"
  15. #include <cassert>
  16. #include <climits>
  17. #include <cmath>
  18. #include <cstdint>
  19. #include <cstring>
  20. #include <limits>
  21. #include <type_traits>
  22. #ifdef __ANDROID_NDK__
  23. #include <android/api-level.h>
  24. #endif
  25. #ifdef _MSC_VER
  26. // Declare these intrinsics manually rather including intrin.h. It's very
  27. // expensive, and MathExtras.h is popular.
  28. // #include <intrin.h>
  29. extern "C" {
  30. unsigned char _BitScanForward(unsigned long *_Index, unsigned long _Mask);
  31. unsigned char _BitScanForward64(unsigned long *_Index, unsigned __int64 _Mask);
  32. unsigned char _BitScanReverse(unsigned long *_Index, unsigned long _Mask);
  33. unsigned char _BitScanReverse64(unsigned long *_Index, unsigned __int64 _Mask);
  34. }
  35. #endif
  36. namespace llvm {
  37. /// The behavior an operation has on an input of 0.
  38. enum ZeroBehavior {
  39. /// The returned value is undefined.
  40. ZB_Undefined,
  41. /// The returned value is numeric_limits<T>::max()
  42. ZB_Max,
  43. /// The returned value is numeric_limits<T>::digits
  44. ZB_Width
  45. };
  46. /// Mathematical constants.
  47. namespace numbers {
  48. // TODO: Track C++20 std::numbers.
  49. // TODO: Favor using the hexadecimal FP constants (requires C++17).
  50. constexpr double e = 2.7182818284590452354, // (0x1.5bf0a8b145749P+1) https://oeis.org/A001113
  51. egamma = .57721566490153286061, // (0x1.2788cfc6fb619P-1) https://oeis.org/A001620
  52. ln2 = .69314718055994530942, // (0x1.62e42fefa39efP-1) https://oeis.org/A002162
  53. ln10 = 2.3025850929940456840, // (0x1.24bb1bbb55516P+1) https://oeis.org/A002392
  54. log2e = 1.4426950408889634074, // (0x1.71547652b82feP+0)
  55. log10e = .43429448190325182765, // (0x1.bcb7b1526e50eP-2)
  56. pi = 3.1415926535897932385, // (0x1.921fb54442d18P+1) https://oeis.org/A000796
  57. inv_pi = .31830988618379067154, // (0x1.45f306bc9c883P-2) https://oeis.org/A049541
  58. sqrtpi = 1.7724538509055160273, // (0x1.c5bf891b4ef6bP+0) https://oeis.org/A002161
  59. inv_sqrtpi = .56418958354775628695, // (0x1.20dd750429b6dP-1) https://oeis.org/A087197
  60. sqrt2 = 1.4142135623730950488, // (0x1.6a09e667f3bcdP+0) https://oeis.org/A00219
  61. inv_sqrt2 = .70710678118654752440, // (0x1.6a09e667f3bcdP-1)
  62. sqrt3 = 1.7320508075688772935, // (0x1.bb67ae8584caaP+0) https://oeis.org/A002194
  63. inv_sqrt3 = .57735026918962576451, // (0x1.279a74590331cP-1)
  64. phi = 1.6180339887498948482; // (0x1.9e3779b97f4a8P+0) https://oeis.org/A001622
  65. constexpr float ef = 2.71828183F, // (0x1.5bf0a8P+1) https://oeis.org/A001113
  66. egammaf = .577215665F, // (0x1.2788d0P-1) https://oeis.org/A001620
  67. ln2f = .693147181F, // (0x1.62e430P-1) https://oeis.org/A002162
  68. ln10f = 2.30258509F, // (0x1.26bb1cP+1) https://oeis.org/A002392
  69. log2ef = 1.44269504F, // (0x1.715476P+0)
  70. log10ef = .434294482F, // (0x1.bcb7b2P-2)
  71. pif = 3.14159265F, // (0x1.921fb6P+1) https://oeis.org/A000796
  72. inv_pif = .318309886F, // (0x1.45f306P-2) https://oeis.org/A049541
  73. sqrtpif = 1.77245385F, // (0x1.c5bf8aP+0) https://oeis.org/A002161
  74. inv_sqrtpif = .564189584F, // (0x1.20dd76P-1) https://oeis.org/A087197
  75. sqrt2f = 1.41421356F, // (0x1.6a09e6P+0) https://oeis.org/A002193
  76. inv_sqrt2f = .707106781F, // (0x1.6a09e6P-1)
  77. sqrt3f = 1.73205081F, // (0x1.bb67aeP+0) https://oeis.org/A002194
  78. inv_sqrt3f = .577350269F, // (0x1.279a74P-1)
  79. phif = 1.61803399F; // (0x1.9e377aP+0) https://oeis.org/A001622
  80. } // namespace numbers
  81. namespace detail {
  82. template <typename T, std::size_t SizeOfT> struct TrailingZerosCounter {
  83. static unsigned count(T Val, ZeroBehavior) {
  84. if (!Val)
  85. return std::numeric_limits<T>::digits;
  86. if (Val & 0x1)
  87. return 0;
  88. // Bisection method.
  89. unsigned ZeroBits = 0;
  90. T Shift = std::numeric_limits<T>::digits >> 1;
  91. T Mask = std::numeric_limits<T>::max() >> Shift;
  92. while (Shift) {
  93. if ((Val & Mask) == 0) {
  94. Val >>= Shift;
  95. ZeroBits |= Shift;
  96. }
  97. Shift >>= 1;
  98. Mask >>= Shift;
  99. }
  100. return ZeroBits;
  101. }
  102. };
  103. #if defined(__GNUC__) || defined(_MSC_VER)
  104. template <typename T> struct TrailingZerosCounter<T, 4> {
  105. static unsigned count(T Val, ZeroBehavior ZB) {
  106. if (ZB != ZB_Undefined && Val == 0)
  107. return 32;
  108. #if __has_builtin(__builtin_ctz) || defined(__GNUC__)
  109. return __builtin_ctz(Val);
  110. #elif defined(_MSC_VER)
  111. unsigned long Index;
  112. _BitScanForward(&Index, Val);
  113. return Index;
  114. #endif
  115. }
  116. };
  117. #if !defined(_MSC_VER) || defined(_M_X64)
  118. template <typename T> struct TrailingZerosCounter<T, 8> {
  119. static unsigned count(T Val, ZeroBehavior ZB) {
  120. if (ZB != ZB_Undefined && Val == 0)
  121. return 64;
  122. #if __has_builtin(__builtin_ctzll) || defined(__GNUC__)
  123. return __builtin_ctzll(Val);
  124. #elif defined(_MSC_VER)
  125. unsigned long Index;
  126. _BitScanForward64(&Index, Val);
  127. return Index;
  128. #endif
  129. }
  130. };
  131. #endif
  132. #endif
  133. } // namespace detail
  134. /// Count number of 0's from the least significant bit to the most
  135. /// stopping at the first 1.
  136. ///
  137. /// Only unsigned integral types are allowed.
  138. ///
  139. /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
  140. /// valid arguments.
  141. template <typename T>
  142. unsigned countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
  143. static_assert(std::numeric_limits<T>::is_integer &&
  144. !std::numeric_limits<T>::is_signed,
  145. "Only unsigned integral types are allowed.");
  146. return llvm::detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB);
  147. }
  148. namespace detail {
  149. template <typename T, std::size_t SizeOfT> struct LeadingZerosCounter {
  150. static unsigned count(T Val, ZeroBehavior) {
  151. if (!Val)
  152. return std::numeric_limits<T>::digits;
  153. // Bisection method.
  154. unsigned ZeroBits = 0;
  155. for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
  156. T Tmp = Val >> Shift;
  157. if (Tmp)
  158. Val = Tmp;
  159. else
  160. ZeroBits |= Shift;
  161. }
  162. return ZeroBits;
  163. }
  164. };
  165. #if defined(__GNUC__) || defined(_MSC_VER)
  166. template <typename T> struct LeadingZerosCounter<T, 4> {
  167. static unsigned count(T Val, ZeroBehavior ZB) {
  168. if (ZB != ZB_Undefined && Val == 0)
  169. return 32;
  170. #if __has_builtin(__builtin_clz) || defined(__GNUC__)
  171. return __builtin_clz(Val);
  172. #elif defined(_MSC_VER)
  173. unsigned long Index;
  174. _BitScanReverse(&Index, Val);
  175. return Index ^ 31;
  176. #endif
  177. }
  178. };
  179. #if !defined(_MSC_VER) || defined(_M_X64)
  180. template <typename T> struct LeadingZerosCounter<T, 8> {
  181. static unsigned count(T Val, ZeroBehavior ZB) {
  182. if (ZB != ZB_Undefined && Val == 0)
  183. return 64;
  184. #if __has_builtin(__builtin_clzll) || defined(__GNUC__)
  185. return __builtin_clzll(Val);
  186. #elif defined(_MSC_VER)
  187. unsigned long Index;
  188. _BitScanReverse64(&Index, Val);
  189. return Index ^ 63;
  190. #endif
  191. }
  192. };
  193. #endif
  194. #endif
  195. } // namespace detail
  196. /// Count number of 0's from the most significant bit to the least
  197. /// stopping at the first 1.
  198. ///
  199. /// Only unsigned integral types are allowed.
  200. ///
  201. /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
  202. /// valid arguments.
  203. template <typename T>
  204. unsigned countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
  205. static_assert(std::numeric_limits<T>::is_integer &&
  206. !std::numeric_limits<T>::is_signed,
  207. "Only unsigned integral types are allowed.");
  208. return llvm::detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB);
  209. }
  210. /// Get the index of the first set bit starting from the least
  211. /// significant bit.
  212. ///
  213. /// Only unsigned integral types are allowed.
  214. ///
  215. /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
  216. /// valid arguments.
  217. template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
  218. if (ZB == ZB_Max && Val == 0)
  219. return std::numeric_limits<T>::max();
  220. return countTrailingZeros(Val, ZB_Undefined);
  221. }
  222. /// Create a bitmask with the N right-most bits set to 1, and all other
  223. /// bits set to 0. Only unsigned types are allowed.
  224. template <typename T> T maskTrailingOnes(unsigned N) {
  225. static_assert(std::is_unsigned<T>::value, "Invalid type!");
  226. const unsigned Bits = CHAR_BIT * sizeof(T);
  227. assert(N <= Bits && "Invalid bit index");
  228. return N == 0 ? 0 : (T(-1) >> (Bits - N));
  229. }
  230. /// Create a bitmask with the N left-most bits set to 1, and all other
  231. /// bits set to 0. Only unsigned types are allowed.
  232. template <typename T> T maskLeadingOnes(unsigned N) {
  233. return ~maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
  234. }
  235. /// Create a bitmask with the N right-most bits set to 0, and all other
  236. /// bits set to 1. Only unsigned types are allowed.
  237. template <typename T> T maskTrailingZeros(unsigned N) {
  238. return maskLeadingOnes<T>(CHAR_BIT * sizeof(T) - N);
  239. }
  240. /// Create a bitmask with the N left-most bits set to 0, and all other
  241. /// bits set to 1. Only unsigned types are allowed.
  242. template <typename T> T maskLeadingZeros(unsigned N) {
  243. return maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
  244. }
  245. /// Get the index of the last set bit starting from the least
  246. /// significant bit.
  247. ///
  248. /// Only unsigned integral types are allowed.
  249. ///
  250. /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
  251. /// valid arguments.
  252. template <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
  253. if (ZB == ZB_Max && Val == 0)
  254. return std::numeric_limits<T>::max();
  255. // Use ^ instead of - because both gcc and llvm can remove the associated ^
  256. // in the __builtin_clz intrinsic on x86.
  257. return countLeadingZeros(Val, ZB_Undefined) ^
  258. (std::numeric_limits<T>::digits - 1);
  259. }
  260. /// Macro compressed bit reversal table for 256 bits.
  261. ///
  262. /// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
  263. static const unsigned char BitReverseTable256[256] = {
  264. #define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
  265. #define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
  266. #define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
  267. R6(0), R6(2), R6(1), R6(3)
  268. #undef R2
  269. #undef R4
  270. #undef R6
  271. };
  272. /// Reverse the bits in \p Val.
  273. template <typename T>
  274. T reverseBits(T Val) {
  275. unsigned char in[sizeof(Val)];
  276. unsigned char out[sizeof(Val)];
  277. std::memcpy(in, &Val, sizeof(Val));
  278. for (unsigned i = 0; i < sizeof(Val); ++i)
  279. out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
  280. std::memcpy(&Val, out, sizeof(Val));
  281. return Val;
  282. }
  283. #if __has_builtin(__builtin_bitreverse8)
  284. template<>
  285. inline uint8_t reverseBits<uint8_t>(uint8_t Val) {
  286. return __builtin_bitreverse8(Val);
  287. }
  288. #endif
  289. #if __has_builtin(__builtin_bitreverse16)
  290. template<>
  291. inline uint16_t reverseBits<uint16_t>(uint16_t Val) {
  292. return __builtin_bitreverse16(Val);
  293. }
  294. #endif
  295. #if __has_builtin(__builtin_bitreverse32)
  296. template<>
  297. inline uint32_t reverseBits<uint32_t>(uint32_t Val) {
  298. return __builtin_bitreverse32(Val);
  299. }
  300. #endif
  301. #if __has_builtin(__builtin_bitreverse64)
  302. template<>
  303. inline uint64_t reverseBits<uint64_t>(uint64_t Val) {
  304. return __builtin_bitreverse64(Val);
  305. }
  306. #endif
  307. // NOTE: The following support functions use the _32/_64 extensions instead of
  308. // type overloading so that signed and unsigned integers can be used without
  309. // ambiguity.
  310. /// Return the high 32 bits of a 64 bit value.
  311. constexpr inline uint32_t Hi_32(uint64_t Value) {
  312. return static_cast<uint32_t>(Value >> 32);
  313. }
  314. /// Return the low 32 bits of a 64 bit value.
  315. constexpr inline uint32_t Lo_32(uint64_t Value) {
  316. return static_cast<uint32_t>(Value);
  317. }
  318. /// Make a 64-bit integer from a high / low pair of 32-bit integers.
  319. constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) {
  320. return ((uint64_t)High << 32) | (uint64_t)Low;
  321. }
  322. /// Checks if an integer fits into the given bit width.
  323. template <unsigned N> constexpr inline bool isInt(int64_t x) {
  324. return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));
  325. }
  326. // Template specializations to get better code for common cases.
  327. template <> constexpr inline bool isInt<8>(int64_t x) {
  328. return static_cast<int8_t>(x) == x;
  329. }
  330. template <> constexpr inline bool isInt<16>(int64_t x) {
  331. return static_cast<int16_t>(x) == x;
  332. }
  333. template <> constexpr inline bool isInt<32>(int64_t x) {
  334. return static_cast<int32_t>(x) == x;
  335. }
  336. /// Checks if a signed integer is an N bit number shifted left by S.
  337. template <unsigned N, unsigned S>
  338. constexpr inline bool isShiftedInt(int64_t x) {
  339. static_assert(
  340. N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number.");
  341. static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
  342. return isInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
  343. }
  344. /// Checks if an unsigned integer fits into the given bit width.
  345. ///
  346. /// This is written as two functions rather than as simply
  347. ///
  348. /// return N >= 64 || X < (UINT64_C(1) << N);
  349. ///
  350. /// to keep MSVC from (incorrectly) warning on isUInt<64> that we're shifting
  351. /// left too many places.
  352. template <unsigned N>
  353. constexpr inline std::enable_if_t<(N < 64), bool> isUInt(uint64_t X) {
  354. static_assert(N > 0, "isUInt<0> doesn't make sense");
  355. return X < (UINT64_C(1) << (N));
  356. }
  357. template <unsigned N>
  358. constexpr inline std::enable_if_t<N >= 64, bool> isUInt(uint64_t) {
  359. return true;
  360. }
  361. // Template specializations to get better code for common cases.
  362. template <> constexpr inline bool isUInt<8>(uint64_t x) {
  363. return static_cast<uint8_t>(x) == x;
  364. }
  365. template <> constexpr inline bool isUInt<16>(uint64_t x) {
  366. return static_cast<uint16_t>(x) == x;
  367. }
  368. template <> constexpr inline bool isUInt<32>(uint64_t x) {
  369. return static_cast<uint32_t>(x) == x;
  370. }
  371. /// Checks if a unsigned integer is an N bit number shifted left by S.
  372. template <unsigned N, unsigned S>
  373. constexpr inline bool isShiftedUInt(uint64_t x) {
  374. static_assert(
  375. N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)");
  376. static_assert(N + S <= 64,
  377. "isShiftedUInt<N, S> with N + S > 64 is too wide.");
  378. // Per the two static_asserts above, S must be strictly less than 64. So
  379. // 1 << S is not undefined behavior.
  380. return isUInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
  381. }
  382. /// Gets the maximum value for a N-bit unsigned integer.
  383. inline uint64_t maxUIntN(uint64_t N) {
  384. assert(N > 0 && N <= 64 && "integer width out of range");
  385. // uint64_t(1) << 64 is undefined behavior, so we can't do
  386. // (uint64_t(1) << N) - 1
  387. // without checking first that N != 64. But this works and doesn't have a
  388. // branch.
  389. return UINT64_MAX >> (64 - N);
  390. }
  391. /// Gets the minimum value for a N-bit signed integer.
  392. inline int64_t minIntN(int64_t N) {
  393. assert(N > 0 && N <= 64 && "integer width out of range");
  394. return UINT64_C(1) + ~(UINT64_C(1) << (N - 1));
  395. }
  396. /// Gets the maximum value for a N-bit signed integer.
  397. inline int64_t maxIntN(int64_t N) {
  398. assert(N > 0 && N <= 64 && "integer width out of range");
  399. // This relies on two's complement wraparound when N == 64, so we convert to
  400. // int64_t only at the very end to avoid UB.
  401. return (UINT64_C(1) << (N - 1)) - 1;
  402. }
  403. /// Checks if an unsigned integer fits into the given (dynamic) bit width.
  404. inline bool isUIntN(unsigned N, uint64_t x) {
  405. return N >= 64 || x <= maxUIntN(N);
  406. }
  407. /// Checks if an signed integer fits into the given (dynamic) bit width.
  408. inline bool isIntN(unsigned N, int64_t x) {
  409. return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
  410. }
  411. /// Return true if the argument is a non-empty sequence of ones starting at the
  412. /// least significant bit with the remainder zero (32 bit version).
  413. /// Ex. isMask_32(0x0000FFFFU) == true.
  414. constexpr inline bool isMask_32(uint32_t Value) {
  415. return Value && ((Value + 1) & Value) == 0;
  416. }
  417. /// Return true if the argument is a non-empty sequence of ones starting at the
  418. /// least significant bit with the remainder zero (64 bit version).
  419. constexpr inline bool isMask_64(uint64_t Value) {
  420. return Value && ((Value + 1) & Value) == 0;
  421. }
  422. /// Return true if the argument contains a non-empty sequence of ones with the
  423. /// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
  424. constexpr inline bool isShiftedMask_32(uint32_t Value) {
  425. return Value && isMask_32((Value - 1) | Value);
  426. }
  427. /// Return true if the argument contains a non-empty sequence of ones with the
  428. /// remainder zero (64 bit version.)
  429. constexpr inline bool isShiftedMask_64(uint64_t Value) {
  430. return Value && isMask_64((Value - 1) | Value);
  431. }
  432. /// Return true if the argument is a power of two > 0.
  433. /// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
  434. constexpr inline bool isPowerOf2_32(uint32_t Value) {
  435. return Value && !(Value & (Value - 1));
  436. }
  437. /// Return true if the argument is a power of two > 0 (64 bit edition.)
  438. constexpr inline bool isPowerOf2_64(uint64_t Value) {
  439. return Value && !(Value & (Value - 1));
  440. }
  441. /// Count the number of ones from the most significant bit to the first
  442. /// zero bit.
  443. ///
  444. /// Ex. countLeadingOnes(0xFF0FFF00) == 8.
  445. /// Only unsigned integral types are allowed.
  446. ///
  447. /// \param ZB the behavior on an input of all ones. Only ZB_Width and
  448. /// ZB_Undefined are valid arguments.
  449. template <typename T>
  450. unsigned countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
  451. static_assert(std::numeric_limits<T>::is_integer &&
  452. !std::numeric_limits<T>::is_signed,
  453. "Only unsigned integral types are allowed.");
  454. return countLeadingZeros<T>(~Value, ZB);
  455. }
  456. /// Count the number of ones from the least significant bit to the first
  457. /// zero bit.
  458. ///
  459. /// Ex. countTrailingOnes(0x00FF00FF) == 8.
  460. /// Only unsigned integral types are allowed.
  461. ///
  462. /// \param ZB the behavior on an input of all ones. Only ZB_Width and
  463. /// ZB_Undefined are valid arguments.
  464. template <typename T>
  465. unsigned countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
  466. static_assert(std::numeric_limits<T>::is_integer &&
  467. !std::numeric_limits<T>::is_signed,
  468. "Only unsigned integral types are allowed.");
  469. return countTrailingZeros<T>(~Value, ZB);
  470. }
  471. namespace detail {
  472. template <typename T, std::size_t SizeOfT> struct PopulationCounter {
  473. static unsigned count(T Value) {
  474. // Generic version, forward to 32 bits.
  475. static_assert(SizeOfT <= 4, "Not implemented!");
  476. #if defined(__GNUC__)
  477. return __builtin_popcount(Value);
  478. #else
  479. uint32_t v = Value;
  480. v = v - ((v >> 1) & 0x55555555);
  481. v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
  482. return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
  483. #endif
  484. }
  485. };
  486. template <typename T> struct PopulationCounter<T, 8> {
  487. static unsigned count(T Value) {
  488. #if defined(__GNUC__)
  489. return __builtin_popcountll(Value);
  490. #else
  491. uint64_t v = Value;
  492. v = v - ((v >> 1) & 0x5555555555555555ULL);
  493. v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
  494. v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
  495. return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
  496. #endif
  497. }
  498. };
  499. } // namespace detail
  500. /// Count the number of set bits in a value.
  501. /// Ex. countPopulation(0xF000F000) = 8
  502. /// Returns 0 if the word is zero.
  503. template <typename T>
  504. inline unsigned countPopulation(T Value) {
  505. static_assert(std::numeric_limits<T>::is_integer &&
  506. !std::numeric_limits<T>::is_signed,
  507. "Only unsigned integral types are allowed.");
  508. return detail::PopulationCounter<T, sizeof(T)>::count(Value);
  509. }
  510. /// Compile time Log2.
  511. /// Valid only for positive powers of two.
  512. template <size_t kValue> constexpr inline size_t CTLog2() {
  513. static_assert(kValue > 0 && llvm::isPowerOf2_64(kValue),
  514. "Value is not a valid power of 2");
  515. return 1 + CTLog2<kValue / 2>();
  516. }
  517. template <> constexpr inline size_t CTLog2<1>() { return 0; }
  518. /// Return the log base 2 of the specified value.
  519. inline double Log2(double Value) {
  520. #if defined(__ANDROID_API__) && __ANDROID_API__ < 18
  521. return __builtin_log(Value) / __builtin_log(2.0);
  522. #else
  523. return log2(Value);
  524. #endif
  525. }
  526. /// Return the floor log base 2 of the specified value, -1 if the value is zero.
  527. /// (32 bit edition.)
  528. /// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
  529. inline unsigned Log2_32(uint32_t Value) {
  530. return 31 - countLeadingZeros(Value);
  531. }
  532. /// Return the floor log base 2 of the specified value, -1 if the value is zero.
  533. /// (64 bit edition.)
  534. inline unsigned Log2_64(uint64_t Value) {
  535. return 63 - countLeadingZeros(Value);
  536. }
  537. /// Return the ceil log base 2 of the specified value, 32 if the value is zero.
  538. /// (32 bit edition).
  539. /// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
  540. inline unsigned Log2_32_Ceil(uint32_t Value) {
  541. return 32 - countLeadingZeros(Value - 1);
  542. }
  543. /// Return the ceil log base 2 of the specified value, 64 if the value is zero.
  544. /// (64 bit edition.)
  545. inline unsigned Log2_64_Ceil(uint64_t Value) {
  546. return 64 - countLeadingZeros(Value - 1);
  547. }
  548. /// Return the greatest common divisor of the values using Euclid's algorithm.
  549. template <typename T>
  550. inline T greatestCommonDivisor(T A, T B) {
  551. while (B) {
  552. T Tmp = B;
  553. B = A % B;
  554. A = Tmp;
  555. }
  556. return A;
  557. }
  558. inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
  559. return greatestCommonDivisor<uint64_t>(A, B);
  560. }
  561. /// This function takes a 64-bit integer and returns the bit equivalent double.
  562. inline double BitsToDouble(uint64_t Bits) {
  563. double D;
  564. static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
  565. memcpy(&D, &Bits, sizeof(Bits));
  566. return D;
  567. }
  568. /// This function takes a 32-bit integer and returns the bit equivalent float.
  569. inline float BitsToFloat(uint32_t Bits) {
  570. float F;
  571. static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
  572. memcpy(&F, &Bits, sizeof(Bits));
  573. return F;
  574. }
  575. /// This function takes a double and returns the bit equivalent 64-bit integer.
  576. /// Note that copying doubles around changes the bits of NaNs on some hosts,
  577. /// notably x86, so this routine cannot be used if these bits are needed.
  578. inline uint64_t DoubleToBits(double Double) {
  579. uint64_t Bits;
  580. static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
  581. memcpy(&Bits, &Double, sizeof(Double));
  582. return Bits;
  583. }
  584. /// This function takes a float and returns the bit equivalent 32-bit integer.
  585. /// Note that copying floats around changes the bits of NaNs on some hosts,
  586. /// notably x86, so this routine cannot be used if these bits are needed.
  587. inline uint32_t FloatToBits(float Float) {
  588. uint32_t Bits;
  589. static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
  590. memcpy(&Bits, &Float, sizeof(Float));
  591. return Bits;
  592. }
  593. /// A and B are either alignments or offsets. Return the minimum alignment that
  594. /// may be assumed after adding the two together.
  595. constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) {
  596. // The largest power of 2 that divides both A and B.
  597. //
  598. // Replace "-Value" by "1+~Value" in the following commented code to avoid
  599. // MSVC warning C4146
  600. // return (A | B) & -(A | B);
  601. return (A | B) & (1 + ~(A | B));
  602. }
  603. /// Returns the next power of two (in 64-bits) that is strictly greater than A.
  604. /// Returns zero on overflow.
  605. inline uint64_t NextPowerOf2(uint64_t A) {
  606. A |= (A >> 1);
  607. A |= (A >> 2);
  608. A |= (A >> 4);
  609. A |= (A >> 8);
  610. A |= (A >> 16);
  611. A |= (A >> 32);
  612. return A + 1;
  613. }
  614. /// Returns the power of two which is less than or equal to the given value.
  615. /// Essentially, it is a floor operation across the domain of powers of two.
  616. inline uint64_t PowerOf2Floor(uint64_t A) {
  617. if (!A) return 0;
  618. return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
  619. }
  620. /// Returns the power of two which is greater than or equal to the given value.
  621. /// Essentially, it is a ceil operation across the domain of powers of two.
  622. inline uint64_t PowerOf2Ceil(uint64_t A) {
  623. if (!A)
  624. return 0;
  625. return NextPowerOf2(A - 1);
  626. }
  627. /// Returns the next integer (mod 2**64) that is greater than or equal to
  628. /// \p Value and is a multiple of \p Align. \p Align must be non-zero.
  629. ///
  630. /// If non-zero \p Skew is specified, the return value will be a minimal
  631. /// integer that is greater than or equal to \p Value and equal to
  632. /// \p Align * N + \p Skew for some integer N. If \p Skew is larger than
  633. /// \p Align, its value is adjusted to '\p Skew mod \p Align'.
  634. ///
  635. /// Examples:
  636. /// \code
  637. /// alignTo(5, 8) = 8
  638. /// alignTo(17, 8) = 24
  639. /// alignTo(~0LL, 8) = 0
  640. /// alignTo(321, 255) = 510
  641. ///
  642. /// alignTo(5, 8, 7) = 7
  643. /// alignTo(17, 8, 1) = 17
  644. /// alignTo(~0LL, 8, 3) = 3
  645. /// alignTo(321, 255, 42) = 552
  646. /// \endcode
  647. inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
  648. assert(Align != 0u && "Align can't be 0.");
  649. Skew %= Align;
  650. return (Value + Align - 1 - Skew) / Align * Align + Skew;
  651. }
  652. /// Returns the next integer (mod 2**64) that is greater than or equal to
  653. /// \p Value and is a multiple of \c Align. \c Align must be non-zero.
  654. template <uint64_t Align> constexpr inline uint64_t alignTo(uint64_t Value) {
  655. static_assert(Align != 0u, "Align must be non-zero");
  656. return (Value + Align - 1) / Align * Align;
  657. }
  658. /// Returns the integer ceil(Numerator / Denominator).
  659. inline uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
  660. return alignTo(Numerator, Denominator) / Denominator;
  661. }
  662. /// Returns the integer nearest(Numerator / Denominator).
  663. inline uint64_t divideNearest(uint64_t Numerator, uint64_t Denominator) {
  664. return (Numerator + (Denominator / 2)) / Denominator;
  665. }
  666. /// Returns the largest uint64_t less than or equal to \p Value and is
  667. /// \p Skew mod \p Align. \p Align must be non-zero
  668. inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
  669. assert(Align != 0u && "Align can't be 0.");
  670. Skew %= Align;
  671. return (Value - Skew) / Align * Align + Skew;
  672. }
  673. /// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
  674. /// Requires 0 < B <= 32.
  675. template <unsigned B> constexpr inline int32_t SignExtend32(uint32_t X) {
  676. static_assert(B > 0, "Bit width can't be 0.");
  677. static_assert(B <= 32, "Bit width out of range.");
  678. return int32_t(X << (32 - B)) >> (32 - B);
  679. }
  680. /// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
  681. /// Requires 0 < B <= 32.
  682. inline int32_t SignExtend32(uint32_t X, unsigned B) {
  683. assert(B > 0 && "Bit width can't be 0.");
  684. assert(B <= 32 && "Bit width out of range.");
  685. return int32_t(X << (32 - B)) >> (32 - B);
  686. }
  687. /// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
  688. /// Requires 0 < B <= 64.
  689. template <unsigned B> constexpr inline int64_t SignExtend64(uint64_t x) {
  690. static_assert(B > 0, "Bit width can't be 0.");
  691. static_assert(B <= 64, "Bit width out of range.");
  692. return int64_t(x << (64 - B)) >> (64 - B);
  693. }
  694. /// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
  695. /// Requires 0 < B <= 64.
  696. inline int64_t SignExtend64(uint64_t X, unsigned B) {
  697. assert(B > 0 && "Bit width can't be 0.");
  698. assert(B <= 64 && "Bit width out of range.");
  699. return int64_t(X << (64 - B)) >> (64 - B);
  700. }
  701. /// Subtract two unsigned integers, X and Y, of type T and return the absolute
  702. /// value of the result.
  703. template <typename T>
  704. std::enable_if_t<std::is_unsigned<T>::value, T> AbsoluteDifference(T X, T Y) {
  705. return X > Y ? (X - Y) : (Y - X);
  706. }
  707. /// Add two unsigned integers, X and Y, of type T. Clamp the result to the
  708. /// maximum representable value of T on overflow. ResultOverflowed indicates if
  709. /// the result is larger than the maximum representable value of type T.
  710. template <typename T>
  711. std::enable_if_t<std::is_unsigned<T>::value, T>
  712. SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
  713. bool Dummy;
  714. bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
  715. // Hacker's Delight, p. 29
  716. T Z = X + Y;
  717. Overflowed = (Z < X || Z < Y);
  718. if (Overflowed)
  719. return std::numeric_limits<T>::max();
  720. else
  721. return Z;
  722. }
  723. /// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the
  724. /// maximum representable value of T on overflow. ResultOverflowed indicates if
  725. /// the result is larger than the maximum representable value of type T.
  726. template <typename T>
  727. std::enable_if_t<std::is_unsigned<T>::value, T>
  728. SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
  729. bool Dummy;
  730. bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
  731. // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
  732. // because it fails for uint16_t (where multiplication can have undefined
  733. // behavior due to promotion to int), and requires a division in addition
  734. // to the multiplication.
  735. Overflowed = false;
  736. // Log2(Z) would be either Log2Z or Log2Z + 1.
  737. // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
  738. // will necessarily be less than Log2Max as desired.
  739. int Log2Z = Log2_64(X) + Log2_64(Y);
  740. const T Max = std::numeric_limits<T>::max();
  741. int Log2Max = Log2_64(Max);
  742. if (Log2Z < Log2Max) {
  743. return X * Y;
  744. }
  745. if (Log2Z > Log2Max) {
  746. Overflowed = true;
  747. return Max;
  748. }
  749. // We're going to use the top bit, and maybe overflow one
  750. // bit past it. Multiply all but the bottom bit then add
  751. // that on at the end.
  752. T Z = (X >> 1) * Y;
  753. if (Z & ~(Max >> 1)) {
  754. Overflowed = true;
  755. return Max;
  756. }
  757. Z <<= 1;
  758. if (X & 1)
  759. return SaturatingAdd(Z, Y, ResultOverflowed);
  760. return Z;
  761. }
  762. /// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
  763. /// the product. Clamp the result to the maximum representable value of T on
  764. /// overflow. ResultOverflowed indicates if the result is larger than the
  765. /// maximum representable value of type T.
  766. template <typename T>
  767. std::enable_if_t<std::is_unsigned<T>::value, T>
  768. SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
  769. bool Dummy;
  770. bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
  771. T Product = SaturatingMultiply(X, Y, &Overflowed);
  772. if (Overflowed)
  773. return Product;
  774. return SaturatingAdd(A, Product, &Overflowed);
  775. }
  776. /// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
  777. extern const float huge_valf;
  778. /// Add two signed integers, computing the two's complement truncated result,
  779. /// returning true if overflow occured.
  780. template <typename T>
  781. std::enable_if_t<std::is_signed<T>::value, T> AddOverflow(T X, T Y, T &Result) {
  782. #if __has_builtin(__builtin_add_overflow)
  783. return __builtin_add_overflow(X, Y, &Result);
  784. #else
  785. // Perform the unsigned addition.
  786. using U = std::make_unsigned_t<T>;
  787. const U UX = static_cast<U>(X);
  788. const U UY = static_cast<U>(Y);
  789. const U UResult = UX + UY;
  790. // Convert to signed.
  791. Result = static_cast<T>(UResult);
  792. // Adding two positive numbers should result in a positive number.
  793. if (X > 0 && Y > 0)
  794. return Result <= 0;
  795. // Adding two negatives should result in a negative number.
  796. if (X < 0 && Y < 0)
  797. return Result >= 0;
  798. return false;
  799. #endif
  800. }
  801. /// Subtract two signed integers, computing the two's complement truncated
  802. /// result, returning true if an overflow ocurred.
  803. template <typename T>
  804. std::enable_if_t<std::is_signed<T>::value, T> SubOverflow(T X, T Y, T &Result) {
  805. #if __has_builtin(__builtin_sub_overflow)
  806. return __builtin_sub_overflow(X, Y, &Result);
  807. #else
  808. // Perform the unsigned addition.
  809. using U = std::make_unsigned_t<T>;
  810. const U UX = static_cast<U>(X);
  811. const U UY = static_cast<U>(Y);
  812. const U UResult = UX - UY;
  813. // Convert to signed.
  814. Result = static_cast<T>(UResult);
  815. // Subtracting a positive number from a negative results in a negative number.
  816. if (X <= 0 && Y > 0)
  817. return Result >= 0;
  818. // Subtracting a negative number from a positive results in a positive number.
  819. if (X >= 0 && Y < 0)
  820. return Result <= 0;
  821. return false;
  822. #endif
  823. }
  824. /// Multiply two signed integers, computing the two's complement truncated
  825. /// result, returning true if an overflow ocurred.
  826. template <typename T>
  827. std::enable_if_t<std::is_signed<T>::value, T> MulOverflow(T X, T Y, T &Result) {
  828. // Perform the unsigned multiplication on absolute values.
  829. using U = std::make_unsigned_t<T>;
  830. const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
  831. const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
  832. const U UResult = UX * UY;
  833. // Convert to signed.
  834. const bool IsNegative = (X < 0) ^ (Y < 0);
  835. Result = IsNegative ? (0 - UResult) : UResult;
  836. // If any of the args was 0, result is 0 and no overflow occurs.
  837. if (UX == 0 || UY == 0)
  838. return false;
  839. // UX and UY are in [1, 2^n], where n is the number of digits.
  840. // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
  841. // positive) divided by an argument compares to the other.
  842. if (IsNegative)
  843. return UX > (static_cast<U>(std::numeric_limits<T>::max()) + U(1)) / UY;
  844. else
  845. return UX > (static_cast<U>(std::numeric_limits<T>::max())) / UY;
  846. }
  847. } // End llvm namespace
  848. #endif