MathExtras.h 20 KB

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