bit_util.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <climits>
  6. #include <cstddef>
  7. #ifdef _MSC_VER
  8. #include <intrin.h>
  9. #endif
  10. #include "common/common_types.h"
  11. namespace Common {
  12. /// Gets the size of a specified type T in bits.
  13. template <typename T>
  14. [[nodiscard]] constexpr std::size_t BitSize() {
  15. return sizeof(T) * CHAR_BIT;
  16. }
  17. #ifdef _MSC_VER
  18. [[nodiscard]] inline u32 MostSignificantBit32(const u32 value) {
  19. unsigned long result;
  20. _BitScanReverse(&result, value);
  21. return static_cast<u32>(result);
  22. }
  23. [[nodiscard]] inline u32 MostSignificantBit64(const u64 value) {
  24. unsigned long result;
  25. _BitScanReverse64(&result, value);
  26. return static_cast<u32>(result);
  27. }
  28. #else
  29. [[nodiscard]] inline u32 MostSignificantBit32(const u32 value) {
  30. return 31U - static_cast<u32>(__builtin_clz(value));
  31. }
  32. [[nodiscard]] inline u32 MostSignificantBit64(const u64 value) {
  33. return 63U - static_cast<u32>(__builtin_clzll(value));
  34. }
  35. #endif
  36. [[nodiscard]] inline u32 Log2Floor32(const u32 value) {
  37. return MostSignificantBit32(value);
  38. }
  39. [[nodiscard]] inline u32 Log2Ceil32(const u32 value) {
  40. const u32 log2_f = Log2Floor32(value);
  41. return log2_f + ((value ^ (1U << log2_f)) != 0U);
  42. }
  43. [[nodiscard]] inline u32 Log2Floor64(const u64 value) {
  44. return MostSignificantBit64(value);
  45. }
  46. [[nodiscard]] inline u32 Log2Ceil64(const u64 value) {
  47. const u64 log2_f = static_cast<u64>(Log2Floor64(value));
  48. return static_cast<u32>(log2_f + ((value ^ (1ULL << log2_f)) != 0ULL));
  49. }
  50. } // namespace Common