MathExtras.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. //===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains some functions that are useful for math stuff.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_SUPPORT_MATHEXTRAS_H
  14. #define LLVM_SUPPORT_MATHEXTRAS_H
  15. #include "llvm/Support/Compiler.h"
  16. #include "llvm/Support/SwapByteOrder.h"
  17. #include <cassert>
  18. #include <cstring>
  19. #include <type_traits>
  20. #ifdef _MSC_VER
  21. #include <intrin.h>
  22. #endif
  23. #ifdef __ANDROID_NDK__
  24. #include <android/api-level.h>
  25. #endif
  26. namespace llvm {
  27. /// \brief The behavior an operation has on an input of 0.
  28. enum ZeroBehavior {
  29. /// \brief The returned value is undefined.
  30. ZB_Undefined,
  31. /// \brief The returned value is numeric_limits<T>::max()
  32. ZB_Max,
  33. /// \brief The returned value is numeric_limits<T>::digits
  34. ZB_Width
  35. };
  36. namespace detail {
  37. template <typename T, std::size_t SizeOfT> struct TrailingZerosCounter {
  38. static std::size_t count(T Val, ZeroBehavior) {
  39. if (!Val)
  40. return std::numeric_limits<T>::digits;
  41. if (Val & 0x1)
  42. return 0;
  43. // Bisection method.
  44. std::size_t ZeroBits = 0;
  45. T Shift = std::numeric_limits<T>::digits >> 1;
  46. T Mask = std::numeric_limits<T>::max() >> Shift;
  47. while (Shift) {
  48. if ((Val & Mask) == 0) {
  49. Val >>= Shift;
  50. ZeroBits |= Shift;
  51. }
  52. Shift >>= 1;
  53. Mask >>= Shift;
  54. }
  55. return ZeroBits;
  56. }
  57. };
  58. #if __GNUC__ >= 4 || _MSC_VER
  59. template <typename T> struct TrailingZerosCounter<T, 4> {
  60. static std::size_t count(T Val, ZeroBehavior ZB) {
  61. if (ZB != ZB_Undefined && Val == 0)
  62. return 32;
  63. #if __has_builtin(__builtin_ctz) || LLVM_GNUC_PREREQ(4, 0, 0)
  64. return __builtin_ctz(Val);
  65. #elif _MSC_VER
  66. unsigned long Index;
  67. _BitScanForward(&Index, Val);
  68. return Index;
  69. #endif
  70. }
  71. };
  72. #if !defined(_MSC_VER) || defined(_M_X64)
  73. template <typename T> struct TrailingZerosCounter<T, 8> {
  74. static std::size_t count(T Val, ZeroBehavior ZB) {
  75. if (ZB != ZB_Undefined && Val == 0)
  76. return 64;
  77. #if __has_builtin(__builtin_ctzll) || LLVM_GNUC_PREREQ(4, 0, 0)
  78. return __builtin_ctzll(Val);
  79. #elif _MSC_VER
  80. unsigned long Index;
  81. _BitScanForward64(&Index, Val);
  82. return Index;
  83. #endif
  84. }
  85. };
  86. #endif
  87. #endif
  88. } // namespace detail
  89. /// \brief Count number of 0's from the least significant bit to the most
  90. /// stopping at the first 1.
  91. ///
  92. /// Only unsigned integral types are allowed.
  93. ///
  94. /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
  95. /// valid arguments.
  96. template <typename T>
  97. std::size_t countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
  98. static_assert(std::numeric_limits<T>::is_integer &&
  99. !std::numeric_limits<T>::is_signed,
  100. "Only unsigned integral types are allowed.");
  101. return detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB);
  102. }
  103. namespace detail {
  104. template <typename T, std::size_t SizeOfT> struct LeadingZerosCounter {
  105. static std::size_t count(T Val, ZeroBehavior) {
  106. if (!Val)
  107. return std::numeric_limits<T>::digits;
  108. // Bisection method.
  109. std::size_t ZeroBits = 0;
  110. for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
  111. T Tmp = Val >> Shift;
  112. if (Tmp)
  113. Val = Tmp;
  114. else
  115. ZeroBits |= Shift;
  116. }
  117. return ZeroBits;
  118. }
  119. };
  120. #if __GNUC__ >= 4 || _MSC_VER
  121. template <typename T> struct LeadingZerosCounter<T, 4> {
  122. static std::size_t count(T Val, ZeroBehavior ZB) {
  123. if (ZB != ZB_Undefined && Val == 0)
  124. return 32;
  125. #if __has_builtin(__builtin_clz) || LLVM_GNUC_PREREQ(4, 0, 0)
  126. return __builtin_clz(Val);
  127. #elif _MSC_VER
  128. unsigned long Index;
  129. _BitScanReverse(&Index, Val);
  130. return Index ^ 31;
  131. #endif
  132. }
  133. };
  134. #if !defined(_MSC_VER) || defined(_M_X64)
  135. template <typename T> struct LeadingZerosCounter<T, 8> {
  136. static std::size_t count(T Val, ZeroBehavior ZB) {
  137. if (ZB != ZB_Undefined && Val == 0)
  138. return 64;
  139. #if __has_builtin(__builtin_clzll) || LLVM_GNUC_PREREQ(4, 0, 0)
  140. return __builtin_clzll(Val);
  141. #elif _MSC_VER
  142. unsigned long Index;
  143. _BitScanReverse64(&Index, Val);
  144. return Index ^ 63;
  145. #endif
  146. }
  147. };
  148. #endif
  149. #endif
  150. } // namespace detail
  151. /// \brief Count number of 0's from the most significant bit to the least
  152. /// stopping at the first 1.
  153. ///
  154. /// Only unsigned integral types are allowed.
  155. ///
  156. /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
  157. /// valid arguments.
  158. template <typename T>
  159. std::size_t countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
  160. static_assert(std::numeric_limits<T>::is_integer &&
  161. !std::numeric_limits<T>::is_signed,
  162. "Only unsigned integral types are allowed.");
  163. return detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB);
  164. }
  165. /// \brief Get the index of the first set bit starting from the least
  166. /// significant bit.
  167. ///
  168. /// Only unsigned integral types are allowed.
  169. ///
  170. /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
  171. /// valid arguments.
  172. template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
  173. if (ZB == ZB_Max && Val == 0)
  174. return std::numeric_limits<T>::max();
  175. return countTrailingZeros(Val, ZB_Undefined);
  176. }
  177. /// \brief Get the index of the last set bit starting from the least
  178. /// significant bit.
  179. ///
  180. /// Only unsigned integral types are allowed.
  181. ///
  182. /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
  183. /// valid arguments.
  184. template <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
  185. if (ZB == ZB_Max && Val == 0)
  186. return std::numeric_limits<T>::max();
  187. // Use ^ instead of - because both gcc and llvm can remove the associated ^
  188. // in the __builtin_clz intrinsic on x86.
  189. return countLeadingZeros(Val, ZB_Undefined) ^
  190. (std::numeric_limits<T>::digits - 1);
  191. }
  192. /// \brief Macro compressed bit reversal table for 256 bits.
  193. ///
  194. /// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
  195. static const unsigned char BitReverseTable256[256] = {
  196. #define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
  197. #define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
  198. #define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
  199. R6(0), R6(2), R6(1), R6(3)
  200. #undef R2
  201. #undef R4
  202. #undef R6
  203. };
  204. /// \brief Reverse the bits in \p Val.
  205. template <typename T>
  206. T reverseBits(T Val) {
  207. unsigned char in[sizeof(Val)];
  208. unsigned char out[sizeof(Val)];
  209. std::memcpy(in, &Val, sizeof(Val));
  210. for (unsigned i = 0; i < sizeof(Val); ++i)
  211. out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
  212. std::memcpy(&Val, out, sizeof(Val));
  213. return Val;
  214. }
  215. // NOTE: The following support functions use the _32/_64 extensions instead of
  216. // type overloading so that signed and unsigned integers can be used without
  217. // ambiguity.
  218. /// Hi_32 - This function returns the high 32 bits of a 64 bit value.
  219. inline uint32_t Hi_32(uint64_t Value) {
  220. return static_cast<uint32_t>(Value >> 32);
  221. }
  222. /// Lo_32 - This function returns the low 32 bits of a 64 bit value.
  223. inline uint32_t Lo_32(uint64_t Value) {
  224. return static_cast<uint32_t>(Value);
  225. }
  226. /// Make_64 - This functions makes a 64-bit integer from a high / low pair of
  227. /// 32-bit integers.
  228. inline uint64_t Make_64(uint32_t High, uint32_t Low) {
  229. return ((uint64_t)High << 32) | (uint64_t)Low;
  230. }
  231. /// isInt - Checks if an integer fits into the given bit width.
  232. template<unsigned N>
  233. inline bool isInt(int64_t x) {
  234. return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));
  235. }
  236. // Template specializations to get better code for common cases.
  237. template<>
  238. inline bool isInt<8>(int64_t x) {
  239. return static_cast<int8_t>(x) == x;
  240. }
  241. template<>
  242. inline bool isInt<16>(int64_t x) {
  243. return static_cast<int16_t>(x) == x;
  244. }
  245. template<>
  246. inline bool isInt<32>(int64_t x) {
  247. return static_cast<int32_t>(x) == x;
  248. }
  249. /// isShiftedInt<N,S> - Checks if a signed integer is an N bit number shifted
  250. /// left by S.
  251. template<unsigned N, unsigned S>
  252. inline bool isShiftedInt(int64_t x) {
  253. return isInt<N+S>(x) && (x % (1<<S) == 0);
  254. }
  255. /// isUInt - Checks if an unsigned integer fits into the given bit width.
  256. template<unsigned N>
  257. inline bool isUInt(uint64_t x) {
  258. return N >= 64 || x < (UINT64_C(1)<<(N));
  259. }
  260. // Template specializations to get better code for common cases.
  261. template<>
  262. inline bool isUInt<8>(uint64_t x) {
  263. return static_cast<uint8_t>(x) == x;
  264. }
  265. template<>
  266. inline bool isUInt<16>(uint64_t x) {
  267. return static_cast<uint16_t>(x) == x;
  268. }
  269. template<>
  270. inline bool isUInt<32>(uint64_t x) {
  271. return static_cast<uint32_t>(x) == x;
  272. }
  273. /// isShiftedUInt<N,S> - Checks if a unsigned integer is an N bit number shifted
  274. /// left by S.
  275. template<unsigned N, unsigned S>
  276. inline bool isShiftedUInt(uint64_t x) {
  277. return isUInt<N+S>(x) && (x % (1<<S) == 0);
  278. }
  279. /// isUIntN - Checks if an unsigned integer fits into the given (dynamic)
  280. /// bit width.
  281. inline bool isUIntN(unsigned N, uint64_t x) {
  282. return x == (x & (~0ULL >> (64 - N)));
  283. }
  284. /// isIntN - Checks if an signed integer fits into the given (dynamic)
  285. /// bit width.
  286. inline bool isIntN(unsigned N, int64_t x) {
  287. return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));
  288. }
  289. /// isMask_32 - This function returns true if the argument is a non-empty
  290. /// sequence of ones starting at the least significant bit with the remainder
  291. /// zero (32 bit version). Ex. isMask_32(0x0000FFFFU) == true.
  292. inline bool isMask_32(uint32_t Value) {
  293. return Value && ((Value + 1) & Value) == 0;
  294. }
  295. /// isMask_64 - This function returns true if the argument is a non-empty
  296. /// sequence of ones starting at the least significant bit with the remainder
  297. /// zero (64 bit version).
  298. inline bool isMask_64(uint64_t Value) {
  299. return Value && ((Value + 1) & Value) == 0;
  300. }
  301. /// isShiftedMask_32 - This function returns true if the argument contains a
  302. /// non-empty sequence of ones with the remainder zero (32 bit version.)
  303. /// Ex. isShiftedMask_32(0x0000FF00U) == true.
  304. inline bool isShiftedMask_32(uint32_t Value) {
  305. return Value && isMask_32((Value - 1) | Value);
  306. }
  307. /// isShiftedMask_64 - This function returns true if the argument contains a
  308. /// non-empty sequence of ones with the remainder zero (64 bit version.)
  309. inline bool isShiftedMask_64(uint64_t Value) {
  310. return Value && isMask_64((Value - 1) | Value);
  311. }
  312. /// isPowerOf2_32 - This function returns true if the argument is a power of
  313. /// two > 0. Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
  314. inline bool isPowerOf2_32(uint32_t Value) {
  315. return Value && !(Value & (Value - 1));
  316. }
  317. /// isPowerOf2_64 - This function returns true if the argument is a power of two
  318. /// > 0 (64 bit edition.)
  319. inline bool isPowerOf2_64(uint64_t Value) {
  320. return Value && !(Value & (Value - int64_t(1L)));
  321. }
  322. /// ByteSwap_16 - This function returns a byte-swapped representation of the
  323. /// 16-bit argument, Value.
  324. inline uint16_t ByteSwap_16(uint16_t Value) {
  325. return sys::SwapByteOrder_16(Value);
  326. }
  327. /// ByteSwap_32 - This function returns a byte-swapped representation of the
  328. /// 32-bit argument, Value.
  329. inline uint32_t ByteSwap_32(uint32_t Value) {
  330. return sys::SwapByteOrder_32(Value);
  331. }
  332. /// ByteSwap_64 - This function returns a byte-swapped representation of the
  333. /// 64-bit argument, Value.
  334. inline uint64_t ByteSwap_64(uint64_t Value) {
  335. return sys::SwapByteOrder_64(Value);
  336. }
  337. /// \brief Count the number of ones from the most significant bit to the first
  338. /// zero bit.
  339. ///
  340. /// Ex. CountLeadingOnes(0xFF0FFF00) == 8.
  341. /// Only unsigned integral types are allowed.
  342. ///
  343. /// \param ZB the behavior on an input of all ones. Only ZB_Width and
  344. /// ZB_Undefined are valid arguments.
  345. template <typename T>
  346. std::size_t countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
  347. static_assert(std::numeric_limits<T>::is_integer &&
  348. !std::numeric_limits<T>::is_signed,
  349. "Only unsigned integral types are allowed.");
  350. return countLeadingZeros(~Value, ZB);
  351. }
  352. /// \brief Count the number of ones from the least significant bit to the first
  353. /// zero bit.
  354. ///
  355. /// Ex. countTrailingOnes(0x00FF00FF) == 8.
  356. /// Only unsigned integral types are allowed.
  357. ///
  358. /// \param ZB the behavior on an input of all ones. Only ZB_Width and
  359. /// ZB_Undefined are valid arguments.
  360. template <typename T>
  361. std::size_t countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
  362. static_assert(std::numeric_limits<T>::is_integer &&
  363. !std::numeric_limits<T>::is_signed,
  364. "Only unsigned integral types are allowed.");
  365. return countTrailingZeros(~Value, ZB);
  366. }
  367. namespace detail {
  368. template <typename T, std::size_t SizeOfT> struct PopulationCounter {
  369. static unsigned count(T Value) {
  370. // Generic version, forward to 32 bits.
  371. static_assert(SizeOfT <= 4, "Not implemented!");
  372. #if __GNUC__ >= 4
  373. return __builtin_popcount(Value);
  374. #else
  375. uint32_t v = Value;
  376. v = v - ((v >> 1) & 0x55555555);
  377. v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
  378. return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
  379. #endif
  380. }
  381. };
  382. template <typename T> struct PopulationCounter<T, 8> {
  383. static unsigned count(T Value) {
  384. #if __GNUC__ >= 4
  385. return __builtin_popcountll(Value);
  386. #else
  387. uint64_t v = Value;
  388. v = v - ((v >> 1) & 0x5555555555555555ULL);
  389. v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
  390. v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
  391. return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
  392. #endif
  393. }
  394. };
  395. } // namespace detail
  396. /// \brief Count the number of set bits in a value.
  397. /// Ex. countPopulation(0xF000F000) = 8
  398. /// Returns 0 if the word is zero.
  399. template <typename T>
  400. inline unsigned countPopulation(T Value) {
  401. static_assert(std::numeric_limits<T>::is_integer &&
  402. !std::numeric_limits<T>::is_signed,
  403. "Only unsigned integral types are allowed.");
  404. return detail::PopulationCounter<T, sizeof(T)>::count(Value);
  405. }
  406. /// Log2 - This function returns the log base 2 of the specified value
  407. inline double __cdecl Log2(double Value) { // HLSL Change - __cdecl
  408. #if defined(__ANDROID_API__) && __ANDROID_API__ < 18
  409. return __builtin_log(Value) / __builtin_log(2.0);
  410. #else
  411. return log2(Value);
  412. #endif
  413. }
  414. /// Log2_32 - This function returns the floor log base 2 of the specified value,
  415. /// -1 if the value is zero. (32 bit edition.)
  416. /// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
  417. inline unsigned Log2_32(uint32_t Value) {
  418. return 31 - (unsigned)countLeadingZeros(Value); // HLSL Change (unsigned)
  419. }
  420. /// Log2_64 - This function returns the floor log base 2 of the specified value,
  421. /// -1 if the value is zero. (64 bit edition.)
  422. inline unsigned Log2_64(uint64_t Value) {
  423. return 63 - (unsigned)countLeadingZeros(Value); // HLSL Change (unsigned)
  424. }
  425. /// Log2_32_Ceil - This function returns the ceil log base 2 of the specified
  426. /// value, 32 if the value is zero. (32 bit edition).
  427. /// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
  428. inline unsigned Log2_32_Ceil(uint32_t Value) {
  429. return 32 - (unsigned)countLeadingZeros(Value - 1); // HLSL Change (unsigned)
  430. }
  431. /// Log2_64_Ceil - This function returns the ceil log base 2 of the specified
  432. /// value, 64 if the value is zero. (64 bit edition.)
  433. inline unsigned Log2_64_Ceil(uint64_t Value) {
  434. return 64 - (unsigned)countLeadingZeros(Value - 1); // HLSL Change (unsigned)
  435. }
  436. /// GreatestCommonDivisor64 - Return the greatest common divisor of the two
  437. /// values using Euclid's algorithm.
  438. inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
  439. while (B) {
  440. uint64_t T = B;
  441. B = A % B;
  442. A = T;
  443. }
  444. return A;
  445. }
  446. /// BitsToDouble - This function takes a 64-bit integer and returns the bit
  447. /// equivalent double.
  448. inline double BitsToDouble(uint64_t Bits) {
  449. union {
  450. uint64_t L;
  451. double D;
  452. } T;
  453. T.L = Bits;
  454. return T.D;
  455. }
  456. /// BitsToFloat - This function takes a 32-bit integer and returns the bit
  457. /// equivalent float.
  458. inline float BitsToFloat(uint32_t Bits) {
  459. union {
  460. uint32_t I;
  461. float F;
  462. } T;
  463. T.I = Bits;
  464. return T.F;
  465. }
  466. /// DoubleToBits - This function takes a double and returns the bit
  467. /// equivalent 64-bit integer. Note that copying doubles around
  468. /// changes the bits of NaNs on some hosts, notably x86, so this
  469. /// routine cannot be used if these bits are needed.
  470. inline uint64_t DoubleToBits(double Double) {
  471. union {
  472. uint64_t L;
  473. double D;
  474. } T;
  475. T.D = Double;
  476. return T.L;
  477. }
  478. /// FloatToBits - This function takes a float and returns the bit
  479. /// equivalent 32-bit integer. Note that copying floats around
  480. /// changes the bits of NaNs on some hosts, notably x86, so this
  481. /// routine cannot be used if these bits are needed.
  482. inline uint32_t FloatToBits(float Float) {
  483. union {
  484. uint32_t I;
  485. float F;
  486. } T;
  487. T.F = Float;
  488. return T.I;
  489. }
  490. /// MinAlign - A and B are either alignments or offsets. Return the minimum
  491. /// alignment that may be assumed after adding the two together.
  492. inline uint64_t MinAlign(uint64_t A, uint64_t B) {
  493. // The largest power of 2 that divides both A and B.
  494. //
  495. // Replace "-Value" by "1+~Value" in the following commented code to avoid
  496. // MSVC warning C4146
  497. // return (A | B) & -(A | B);
  498. return (A | B) & (1 + ~(A | B));
  499. }
  500. /// \brief Aligns \c Addr to \c Alignment bytes, rounding up.
  501. ///
  502. /// Alignment should be a power of two. This method rounds up, so
  503. /// alignAddr(7, 4) == 8 and alignAddr(8, 4) == 8.
  504. inline uintptr_t alignAddr(const void *Addr, size_t Alignment) {
  505. assert(Alignment && isPowerOf2_64((uint64_t)Alignment) &&
  506. "Alignment is not a power of two!");
  507. assert((uintptr_t)Addr + Alignment - 1 >= (uintptr_t)Addr);
  508. return (((uintptr_t)Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1));
  509. }
  510. /// \brief Returns the necessary adjustment for aligning \c Ptr to \c Alignment
  511. /// bytes, rounding up.
  512. inline size_t alignmentAdjustment(const void *Ptr, size_t Alignment) {
  513. return alignAddr(Ptr, Alignment) - (uintptr_t)Ptr;
  514. }
  515. /// NextPowerOf2 - Returns the next power of two (in 64-bits)
  516. /// that is strictly greater than A. Returns zero on overflow.
  517. inline uint64_t NextPowerOf2(uint64_t A) {
  518. A |= (A >> 1);
  519. A |= (A >> 2);
  520. A |= (A >> 4);
  521. A |= (A >> 8);
  522. A |= (A >> 16);
  523. A |= (A >> 32);
  524. return A + 1;
  525. }
  526. /// Returns the power of two which is less than or equal to the given value.
  527. /// Essentially, it is a floor operation across the domain of powers of two.
  528. inline uint64_t PowerOf2Floor(uint64_t A) {
  529. if (!A) return 0;
  530. return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
  531. }
  532. /// Returns the next integer (mod 2**64) that is greater than or equal to
  533. /// \p Value and is a multiple of \p Align. \p Align must be non-zero.
  534. ///
  535. /// Examples:
  536. /// \code
  537. /// RoundUpToAlignment(5, 8) = 8
  538. /// RoundUpToAlignment(17, 8) = 24
  539. /// RoundUpToAlignment(~0LL, 8) = 0
  540. /// RoundUpToAlignment(321, 255) = 510
  541. /// \endcode
  542. inline uint64_t RoundUpToAlignment(uint64_t Value, uint64_t Align) {
  543. return (Value + Align - 1) / Align * Align;
  544. }
  545. /// Returns the offset to the next integer (mod 2**64) that is greater than
  546. /// or equal to \p Value and is a multiple of \p Align. \p Align must be
  547. /// non-zero.
  548. inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) {
  549. return RoundUpToAlignment(Value, Align) - Value;
  550. }
  551. /// SignExtend32 - Sign extend B-bit number x to 32-bit int.
  552. /// Usage int32_t r = SignExtend32<5>(x);
  553. template <unsigned B> inline int32_t SignExtend32(uint32_t x) {
  554. return int32_t(x << (32 - B)) >> (32 - B);
  555. }
  556. /// \brief Sign extend number in the bottom B bits of X to a 32-bit int.
  557. /// Requires 0 < B <= 32.
  558. inline int32_t SignExtend32(uint32_t X, unsigned B) {
  559. return int32_t(X << (32 - B)) >> (32 - B);
  560. }
  561. /// SignExtend64 - Sign extend B-bit number x to 64-bit int.
  562. /// Usage int64_t r = SignExtend64<5>(x);
  563. template <unsigned B> inline int64_t SignExtend64(uint64_t x) {
  564. return int64_t(x << (64 - B)) >> (64 - B);
  565. }
  566. /// \brief Sign extend number in the bottom B bits of X to a 64-bit int.
  567. /// Requires 0 < B <= 64.
  568. inline int64_t SignExtend64(uint64_t X, unsigned B) {
  569. return int64_t(X << (64 - B)) >> (64 - B);
  570. }
  571. extern const float huge_valf;
  572. } // End llvm namespace
  573. #endif