bit_field.h 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // SPDX-FileCopyrightText: 2014 Tony Wasserka
  2. // SPDX-FileCopyrightText: 2014 Dolphin Emulator Project
  3. // SPDX-License-Identifier: BSD-3-Clause AND GPL-2.0-or-later
  4. #pragma once
  5. #include <cstddef>
  6. #include <limits>
  7. #include <type_traits>
  8. #include "common/swap.h"
  9. /*
  10. * Abstract bitfield class
  11. *
  12. * Allows endianness-independent access to individual bitfields within some raw
  13. * integer value. The assembly generated by this class is identical to the
  14. * usage of raw bitfields, so it's a perfectly fine replacement.
  15. *
  16. * For BitField<X,Y,Z>, X is the distance of the bitfield to the LSB of the
  17. * raw value, Y is the length in bits of the bitfield. Z is an integer type
  18. * which determines the sign of the bitfield. Z must have the same size as the
  19. * raw integer.
  20. *
  21. *
  22. * General usage:
  23. *
  24. * Create a new union with the raw integer value as a member.
  25. * Then for each bitfield you want to expose, add a BitField member
  26. * in the union. The template parameters are the bit offset and the number
  27. * of desired bits.
  28. *
  29. * Changes in the bitfield members will then get reflected in the raw integer
  30. * value and vice-versa.
  31. *
  32. *
  33. * Sample usage:
  34. *
  35. * union SomeRegister
  36. * {
  37. * u32 hex;
  38. *
  39. * BitField<0,7,u32> first_seven_bits; // unsigned
  40. * BitField<7,8,u32> next_eight_bits; // unsigned
  41. * BitField<3,15,s32> some_signed_fields; // signed
  42. * };
  43. *
  44. * This is equivalent to the little-endian specific code:
  45. *
  46. * union SomeRegister
  47. * {
  48. * u32 hex;
  49. *
  50. * struct
  51. * {
  52. * u32 first_seven_bits : 7;
  53. * u32 next_eight_bits : 8;
  54. * };
  55. * struct
  56. * {
  57. * u32 : 3; // padding
  58. * s32 some_signed_fields : 15;
  59. * };
  60. * };
  61. *
  62. *
  63. * Caveats:
  64. *
  65. * 1)
  66. * BitField provides automatic casting from and to the storage type where
  67. * appropriate. However, when using non-typesafe functions like printf, an
  68. * explicit cast must be performed on the BitField object to make sure it gets
  69. * passed correctly, e.g.:
  70. * printf("Value: %d", (s32)some_register.some_signed_fields);
  71. *
  72. * 2)
  73. * Not really a caveat, but potentially irritating: This class is used in some
  74. * packed structures that do not guarantee proper alignment. Therefore we have
  75. * to use #pragma pack here not to pack the members of the class, but instead
  76. * to break GCC's assumption that the members of the class are aligned on
  77. * sizeof(StorageType).
  78. * TODO(neobrain): Confirm that this is a proper fix and not just masking
  79. * symptoms.
  80. */
  81. #pragma pack(1)
  82. template <std::size_t Position, std::size_t Bits, typename T, typename EndianTag = LETag>
  83. struct BitField {
  84. private:
  85. // UnderlyingType is T for non-enum types and the underlying type of T if
  86. // T is an enumeration. Note that T is wrapped within an enable_if in the
  87. // former case to workaround compile errors which arise when using
  88. // std::underlying_type<T>::type directly.
  89. using UnderlyingType = typename std::conditional_t<std::is_enum_v<T>, std::underlying_type<T>,
  90. std::enable_if<true, T>>::type;
  91. // We store the value as the unsigned type to avoid undefined behaviour on value shifting
  92. using StorageType = std::make_unsigned_t<UnderlyingType>;
  93. using StorageTypeWithEndian = typename AddEndian<StorageType, EndianTag>::type;
  94. public:
  95. /// Constants to allow limited introspection of fields if needed
  96. static constexpr std::size_t position = Position;
  97. static constexpr std::size_t bits = Bits;
  98. static constexpr StorageType mask = (((StorageType)~0) >> (8 * sizeof(T) - bits)) << position;
  99. /**
  100. * Formats a value by masking and shifting it according to the field parameters. A value
  101. * containing several bitfields can be assembled by formatting each of their values and ORing
  102. * the results together.
  103. */
  104. [[nodiscard]] static constexpr StorageType FormatValue(const T& value) {
  105. return (static_cast<StorageType>(value) << position) & mask;
  106. }
  107. /**
  108. * Extracts a value from the passed storage. In most situations prefer use the member functions
  109. * (such as Value() or operator T), but this can be used to extract a value from a bitfield
  110. * union in a constexpr context.
  111. */
  112. [[nodiscard]] static constexpr T ExtractValue(const StorageType& storage) {
  113. if constexpr (std::numeric_limits<UnderlyingType>::is_signed) {
  114. std::size_t shift = 8 * sizeof(T) - bits;
  115. return static_cast<T>(static_cast<UnderlyingType>(storage << (shift - position)) >>
  116. shift);
  117. } else {
  118. return static_cast<T>((storage & mask) >> position);
  119. }
  120. }
  121. // This constructor and assignment operator might be considered ambiguous:
  122. // Would they initialize the storage or just the bitfield?
  123. // Hence, delete them. Use the Assign method to set bitfield values!
  124. BitField(T val) = delete;
  125. BitField& operator=(T val) = delete;
  126. constexpr BitField() noexcept = default;
  127. constexpr BitField(const BitField&) noexcept = default;
  128. constexpr BitField& operator=(const BitField&) noexcept = default;
  129. constexpr BitField(BitField&&) noexcept = default;
  130. constexpr BitField& operator=(BitField&&) noexcept = default;
  131. constexpr void Assign(const T& value) {
  132. #ifdef _MSC_VER
  133. storage = static_cast<StorageType>((storage & ~mask) | FormatValue(value));
  134. #else
  135. // Explicitly reload with memcpy to avoid compiler aliasing quirks
  136. // regarding optimization: GCC/Clang clobber chained stores to
  137. // different bitfields in the same struct with the last value.
  138. StorageTypeWithEndian storage_;
  139. std::memcpy(&storage_, &storage, sizeof(storage_));
  140. storage = static_cast<StorageType>((storage_ & ~mask) | FormatValue(value));
  141. #endif
  142. }
  143. [[nodiscard]] constexpr T Value() const {
  144. return ExtractValue(storage);
  145. }
  146. template <typename ConvertedToType>
  147. [[nodiscard]] constexpr ConvertedToType As() const {
  148. static_assert(!std::is_same_v<T, ConvertedToType>,
  149. "Unnecessary cast. Use Value() instead.");
  150. return static_cast<ConvertedToType>(Value());
  151. }
  152. [[nodiscard]] constexpr operator T() const {
  153. return Value();
  154. }
  155. [[nodiscard]] constexpr explicit operator bool() const {
  156. return Value() != 0;
  157. }
  158. private:
  159. StorageTypeWithEndian storage;
  160. static_assert(bits + position <= 8 * sizeof(T), "Bitfield out of range");
  161. // And, you know, just in case people specify something stupid like bits=position=0x80000000
  162. static_assert(position < 8 * sizeof(T), "Invalid position");
  163. static_assert(bits <= 8 * sizeof(T), "Invalid number of bits");
  164. static_assert(bits > 0, "Invalid number of bits");
  165. static_assert(std::is_trivially_copyable_v<T>, "T must be trivially copyable in a BitField");
  166. };
  167. #pragma pack()
  168. template <std::size_t Position, std::size_t Bits, typename T>
  169. using BitFieldBE = BitField<Position, Bits, T, BETag>;
  170. template <std::size_t Position, std::size_t Bits, typename T, typename EndianTag = LETag>
  171. inline auto format_as(BitField<Position, Bits, T, EndianTag> bitfield) {
  172. return bitfield.Value();
  173. }