BitField.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. // Copyright 2014 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. // Copyright 2014 Tony Wasserka
  4. // All rights reserved.
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above copyright
  12. // notice, this list of conditions and the following disclaimer in the
  13. // documentation and/or other materials provided with the distribution.
  14. // * Neither the name of the owner nor the names of its contributors may
  15. // be used to endorse or promote products derived from this software
  16. // without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. #pragma once
  30. #include <cstddef>
  31. #include <fmt/format.h>
  32. #include <iterator>
  33. #include <limits>
  34. #include <type_traits>
  35. #include "Common/Inline.h"
  36. /*
  37. * Abstract bitfield class
  38. *
  39. * Allows endianness-independent access to individual bitfields within some raw
  40. * integer value. The assembly generated by this class is identical to the
  41. * usage of raw bitfields, so it's a perfectly fine replacement.
  42. *
  43. * For BitField<X,Y,Z>, X is the distance of the bitfield to the LSB of the
  44. * raw value, Y is the length in bits of the bitfield. Z is an integer type
  45. * which determines the sign of the bitfield. Z must have the same size as the
  46. * raw integer.
  47. *
  48. *
  49. * General usage:
  50. *
  51. * Create a new union with the raw integer value as a member.
  52. * Then for each bitfield you want to expose, add a BitField member
  53. * in the union. The template parameters are the bit offset and the number
  54. * of desired bits.
  55. *
  56. * Changes in the bitfield members will then get reflected in the raw integer
  57. * value and vice-versa.
  58. *
  59. *
  60. * Sample usage:
  61. *
  62. * union SomeRegister
  63. * {
  64. * u32 hex;
  65. *
  66. * BitField<0,7,u32> first_seven_bits; // unsigned
  67. * BitField<7,8,u32> next_eight_bits; // unsigned
  68. * BitField<3,15,s32> some_signed_fields; // signed
  69. * };
  70. *
  71. * This is equivalent to the little-endian specific code:
  72. *
  73. * union SomeRegister
  74. * {
  75. * u32 hex;
  76. *
  77. * struct
  78. * {
  79. * u32 first_seven_bits : 7;
  80. * u32 next_eight_bits : 8;
  81. * };
  82. * struct
  83. * {
  84. * u32 : 3; // padding
  85. * s32 some_signed_fields : 15;
  86. * };
  87. * };
  88. *
  89. *
  90. * Caveats:
  91. *
  92. * 1)
  93. * BitField provides automatic casting from and to the storage type where
  94. * appropriate. However, when using non-typesafe functions like printf, an
  95. * explicit cast must be performed on the BitField object to make sure it gets
  96. * passed correctly, e.g.:
  97. * printf("Value: %d", (s32)some_register.some_signed_fields);
  98. * Note that this does not apply when using fmt, as a formatter is provided that
  99. * handles this conversion automatically.
  100. *
  101. * 2)
  102. * Not really a caveat, but potentially irritating: This class is used in some
  103. * packed structures that do not guarantee proper alignment. Therefore we have
  104. * to use #pragma pack here not to pack the members of the class, but instead
  105. * to break GCC's assumption that the members of the class are aligned on
  106. * sizeof(StorageType).
  107. * TODO(neobrain): Confirm that this is a proper fix and not just masking
  108. * symptoms.
  109. */
  110. #pragma pack(1)
  111. template <std::size_t position, std::size_t bits, typename T,
  112. // StorageType is T for non-enum types and the underlying type of T if
  113. // T is an enumeration. Note that T is wrapped within an enable_if in the
  114. // former case to workaround compile errors which arise when using
  115. // std::underlying_type<T>::type directly.
  116. typename StorageType = typename std::conditional_t<
  117. std::is_enum<T>::value, std::underlying_type<T>, std::enable_if<true, T>>::type>
  118. struct BitField
  119. {
  120. private:
  121. // This constructor might be considered ambiguous:
  122. // Would it initialize the storage or just the bitfield?
  123. // Hence, delete it. Use the assignment operator to set bitfield values!
  124. BitField(T val) = delete;
  125. public:
  126. // Force default constructor to be created
  127. // so that we can use this within unions
  128. constexpr BitField() = default;
  129. // We explicitly delete the copy assignment operator here, because the
  130. // default copy assignment would copy the full storage value, rather than
  131. // just the bits relevant to this particular bit field.
  132. // Ideally, we would just implement the copy assignment to copy only the
  133. // relevant bits, but we're prevented from doing that because the savestate
  134. // code expects that this class is trivially copyable.
  135. BitField& operator=(const BitField&) = delete;
  136. DOLPHIN_FORCE_INLINE BitField& operator=(T val)
  137. {
  138. storage = (storage & ~GetMask()) | ((static_cast<StorageType>(val) << position) & GetMask());
  139. return *this;
  140. }
  141. constexpr T Value() const { return Value(std::is_signed<T>()); }
  142. constexpr operator T() const { return Value(); }
  143. static constexpr bool IsSigned() { return std::is_signed<T>(); }
  144. static constexpr std::size_t StartBit() { return position; }
  145. static constexpr std::size_t NumBits() { return bits; }
  146. private:
  147. // Unsigned version of StorageType
  148. using StorageTypeU = std::make_unsigned_t<StorageType>;
  149. constexpr T Value(std::true_type) const
  150. {
  151. const size_t shift_amount = 8 * sizeof(StorageType) - bits;
  152. return static_cast<T>((storage << (shift_amount - position)) >> shift_amount);
  153. }
  154. constexpr T Value(std::false_type) const
  155. {
  156. return static_cast<T>((storage & GetMask()) >> position);
  157. }
  158. static constexpr StorageType GetMask()
  159. {
  160. return (std::numeric_limits<StorageTypeU>::max() >> (8 * sizeof(StorageType) - bits))
  161. << position;
  162. }
  163. StorageType storage;
  164. static_assert(bits + position <= 8 * sizeof(StorageType), "Bitfield out of range");
  165. static_assert(sizeof(T) <= sizeof(StorageType), "T must fit in StorageType");
  166. // And, you know, just in case people specify something stupid like bits=position=0x80000000
  167. static_assert(position < 8 * sizeof(StorageType), "Invalid position");
  168. static_assert(bits <= 8 * sizeof(T), "Invalid number of bits");
  169. static_assert(bits > 0, "Invalid number of bits");
  170. };
  171. #pragma pack()
  172. // Use the underlying type's formatter for BitFields, if one exists
  173. template <std::size_t position, std::size_t bits, typename T, typename S>
  174. struct fmt::formatter<BitField<position, bits, T, S>>
  175. {
  176. fmt::formatter<T> m_formatter;
  177. constexpr auto parse(format_parse_context& ctx) { return m_formatter.parse(ctx); }
  178. template <typename FormatContext>
  179. auto format(const BitField<position, bits, T, S>& bitfield, FormatContext& ctx) const
  180. {
  181. return m_formatter.format(bitfield.Value(), ctx);
  182. }
  183. };
  184. // Language limitations require the following to make these formattable
  185. // (formatter<BitFieldArray<position, bits, size, T>::Ref> is not legal)
  186. template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
  187. class BitFieldArrayConstRef;
  188. template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
  189. class BitFieldArrayRef;
  190. template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
  191. class BitFieldArrayConstIterator;
  192. template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
  193. class BitFieldArrayIterator;
  194. #pragma pack(1)
  195. template <std::size_t position, std::size_t bits, std::size_t size, typename T,
  196. // StorageType is T for non-enum types and the underlying type of T if
  197. // T is an enumeration. Note that T is wrapped within an enable_if in the
  198. // former case to workaround compile errors which arise when using
  199. // std::underlying_type<T>::type directly.
  200. typename StorageType = typename std::conditional_t<
  201. std::is_enum<T>::value, std::underlying_type<T>, std::enable_if<true, T>>::type>
  202. struct BitFieldArray
  203. {
  204. using Ref = BitFieldArrayRef<position, bits, size, T, StorageType>;
  205. using ConstRef = BitFieldArrayConstRef<position, bits, size, T, StorageType>;
  206. using Iterator = BitFieldArrayIterator<position, bits, size, T, StorageType>;
  207. using ConstIterator = BitFieldArrayConstIterator<position, bits, size, T, StorageType>;
  208. private:
  209. // This constructor might be considered ambiguous:
  210. // Would it initialize the storage or just the bitfield?
  211. // Hence, delete it. Use the assignment operator to set bitfield values!
  212. BitFieldArray(T val) = delete;
  213. public:
  214. // Force default constructor to be created
  215. // so that we can use this within unions
  216. constexpr BitFieldArray() = default;
  217. // We explicitly delete the copy assignment operator here, because the
  218. // default copy assignment would copy the full storage value, rather than
  219. // just the bits relevant to this particular bit field.
  220. // Ideally, we would just implement the copy assignment to copy only the
  221. // relevant bits, but we're prevented from doing that because the savestate
  222. // code expects that this class is trivially copyable.
  223. BitFieldArray& operator=(const BitFieldArray&) = delete;
  224. public:
  225. constexpr bool IsSigned() const { return std::is_signed<T>(); }
  226. constexpr std::size_t StartBit() const { return position; }
  227. constexpr std::size_t NumBits() const { return bits; }
  228. constexpr std::size_t Size() const { return size; }
  229. constexpr std::size_t TotalNumBits() const { return bits * size; }
  230. constexpr T Value(size_t index) const { return Value(std::is_signed<T>(), index); }
  231. void SetValue(size_t index, T value)
  232. {
  233. const size_t pos = position + bits * index;
  234. storage = (storage & ~GetElementMask(index)) |
  235. ((static_cast<StorageType>(value) << pos) & GetElementMask(index));
  236. }
  237. Ref operator[](size_t index) { return Ref(this, index); }
  238. constexpr const ConstRef operator[](size_t index) const { return ConstRef(this, index); }
  239. constexpr Iterator begin() { return Iterator(this, 0); }
  240. constexpr Iterator end() { return Iterator(this, size); }
  241. constexpr ConstIterator begin() const { return ConstIterator(this, 0); }
  242. constexpr ConstIterator end() const { return ConstIterator(this, size); }
  243. constexpr ConstIterator cbegin() const { return begin(); }
  244. constexpr ConstIterator cend() const { return end(); }
  245. private:
  246. // Unsigned version of StorageType
  247. using StorageTypeU = std::make_unsigned_t<StorageType>;
  248. constexpr T Value(std::true_type, size_t index) const
  249. {
  250. const size_t pos = position + bits * index;
  251. const size_t shift_amount = 8 * sizeof(StorageType) - bits;
  252. return static_cast<T>((storage << (shift_amount - pos)) >> shift_amount);
  253. }
  254. constexpr T Value(std::false_type, size_t index) const
  255. {
  256. const size_t pos = position + bits * index;
  257. return static_cast<T>((storage & GetElementMask(index)) >> pos);
  258. }
  259. static constexpr StorageType GetElementMask(size_t index)
  260. {
  261. const size_t pos = position + bits * index;
  262. return (std::numeric_limits<StorageTypeU>::max() >> (8 * sizeof(StorageType) - bits)) << pos;
  263. }
  264. StorageType storage;
  265. static_assert(bits * size + position <= 8 * sizeof(StorageType), "Bitfield array out of range");
  266. static_assert(sizeof(T) <= sizeof(StorageType), "T must fit in StorageType");
  267. // And, you know, just in case people specify something stupid like bits=position=0x80000000
  268. static_assert(position < 8 * sizeof(StorageType), "Invalid position");
  269. static_assert(bits <= 8 * sizeof(T), "Invalid number of bits");
  270. static_assert(bits > 0, "Invalid number of bits");
  271. static_assert(size <= 8 * sizeof(StorageType), "Invalid size");
  272. static_assert(size > 0, "Invalid size");
  273. };
  274. #pragma pack()
  275. template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
  276. class BitFieldArrayConstRef
  277. {
  278. friend struct BitFieldArray<position, bits, size, T, S>;
  279. friend class BitFieldArrayConstIterator<position, bits, size, T, S>;
  280. public:
  281. constexpr T Value() const { return m_array->Value(m_index); }
  282. constexpr operator T() const { return Value(); }
  283. private:
  284. constexpr BitFieldArrayConstRef(const BitFieldArray<position, bits, size, T, S>* array,
  285. size_t index)
  286. : m_array(array), m_index(index)
  287. {
  288. }
  289. const BitFieldArray<position, bits, size, T, S>* const m_array;
  290. const size_t m_index;
  291. };
  292. template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
  293. class BitFieldArrayRef
  294. {
  295. friend struct BitFieldArray<position, bits, size, T, S>;
  296. friend class BitFieldArrayIterator<position, bits, size, T, S>;
  297. public:
  298. constexpr T Value() const { return m_array->Value(m_index); }
  299. constexpr operator T() const { return Value(); }
  300. T operator=(const BitFieldArrayRef<position, bits, size, T, S>& value) const
  301. {
  302. m_array->SetValue(m_index, value);
  303. return value;
  304. }
  305. T operator=(T value) const
  306. {
  307. m_array->SetValue(m_index, value);
  308. return value;
  309. }
  310. private:
  311. constexpr BitFieldArrayRef(BitFieldArray<position, bits, size, T, S>* array, size_t index)
  312. : m_array(array), m_index(index)
  313. {
  314. }
  315. BitFieldArray<position, bits, size, T, S>* const m_array;
  316. const size_t m_index;
  317. };
  318. // Satisfies LegacyOutputIterator / std::output_iterator.
  319. // Does not satisfy LegacyInputIterator / std::input_iterator as std::output_iterator_tag does not
  320. // extend std::input_iterator_tag.
  321. // Does not satisfy LegacyForwardIterator / std::forward_iterator, as that requires use of real
  322. // references instead of proxy objects.
  323. // This iterator allows use of BitFieldArray in range-based for loops, and with fmt::join.
  324. template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
  325. class BitFieldArrayIterator
  326. {
  327. friend struct BitFieldArray<position, bits, size, T, S>;
  328. public:
  329. using iterator_category = std::output_iterator_tag;
  330. using value_type = T;
  331. using difference_type = ptrdiff_t;
  332. using pointer = void;
  333. using reference = BitFieldArrayRef<position, bits, size, T, S>;
  334. private:
  335. constexpr BitFieldArrayIterator(BitFieldArray<position, bits, size, T, S>* array, size_t index)
  336. : m_array(array), m_index(index)
  337. {
  338. }
  339. public:
  340. // Required by std::input_or_output_iterator
  341. constexpr BitFieldArrayIterator() = default;
  342. // Required by LegacyIterator
  343. constexpr BitFieldArrayIterator(const BitFieldArrayIterator& other) = default;
  344. // Required by LegacyIterator
  345. BitFieldArrayIterator& operator=(const BitFieldArrayIterator& other) = default;
  346. // Move constructor and assignment operators, explicitly defined for completeness
  347. constexpr BitFieldArrayIterator(BitFieldArrayIterator&& other) = default;
  348. BitFieldArrayIterator& operator=(BitFieldArrayIterator&& other) = default;
  349. public:
  350. BitFieldArrayIterator& operator++()
  351. {
  352. m_index++;
  353. return *this;
  354. }
  355. BitFieldArrayIterator operator++(int)
  356. {
  357. BitFieldArrayIterator other(*this);
  358. ++*this;
  359. return other;
  360. }
  361. constexpr reference operator*() const { return reference(m_array, m_index); }
  362. constexpr bool operator==(BitFieldArrayIterator other) const { return m_index == other.m_index; }
  363. constexpr bool operator!=(BitFieldArrayIterator other) const { return m_index != other.m_index; }
  364. private:
  365. BitFieldArray<position, bits, size, T, S>* m_array;
  366. size_t m_index;
  367. };
  368. // Satisfies LegacyInputIterator / std::input_iterator.
  369. // Does not satisfy LegacyForwardIterator / std::forward_iterator, as that requires use of real
  370. // references instead of proxy objects.
  371. // This iterator allows use of BitFieldArray in range-based for loops, and with fmt::join.
  372. template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
  373. class BitFieldArrayConstIterator
  374. {
  375. friend struct BitFieldArray<position, bits, size, T, S>;
  376. public:
  377. using iterator_category = std::input_iterator_tag;
  378. using value_type = T;
  379. using difference_type = ptrdiff_t;
  380. using pointer = void;
  381. using reference = BitFieldArrayConstRef<position, bits, size, T, S>;
  382. private:
  383. constexpr BitFieldArrayConstIterator(const BitFieldArray<position, bits, size, T, S>* array,
  384. size_t index)
  385. : m_array(array), m_index(index)
  386. {
  387. }
  388. public:
  389. // Required by std::input_or_output_iterator
  390. constexpr BitFieldArrayConstIterator() = default;
  391. // Required by LegacyIterator
  392. constexpr BitFieldArrayConstIterator(const BitFieldArrayConstIterator& other) = default;
  393. // Required by LegacyIterator
  394. BitFieldArrayConstIterator& operator=(const BitFieldArrayConstIterator& other) = default;
  395. // Move constructor and assignment operators, explicitly defined for completeness
  396. constexpr BitFieldArrayConstIterator(BitFieldArrayConstIterator&& other) = default;
  397. BitFieldArrayConstIterator& operator=(BitFieldArrayConstIterator&& other) = default;
  398. public:
  399. BitFieldArrayConstIterator& operator++()
  400. {
  401. m_index++;
  402. return *this;
  403. }
  404. BitFieldArrayConstIterator operator++(int)
  405. {
  406. BitFieldArrayConstIterator other(*this);
  407. ++*this;
  408. return other;
  409. }
  410. constexpr reference operator*() const { return reference(m_array, m_index); }
  411. constexpr bool operator==(BitFieldArrayConstIterator other) const
  412. {
  413. return m_index == other.m_index;
  414. }
  415. constexpr bool operator!=(BitFieldArrayConstIterator other) const
  416. {
  417. return m_index != other.m_index;
  418. }
  419. private:
  420. const BitFieldArray<position, bits, size, T, S>* m_array;
  421. size_t m_index;
  422. };
  423. template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
  424. struct fmt::formatter<BitFieldArrayRef<position, bits, size, T, S>>
  425. {
  426. fmt::formatter<T> m_formatter;
  427. constexpr auto parse(format_parse_context& ctx) { return m_formatter.parse(ctx); }
  428. template <typename FormatContext>
  429. auto format(const BitFieldArrayRef<position, bits, size, T, S>& ref, FormatContext& ctx) const
  430. {
  431. return m_formatter.format(ref.Value(), ctx);
  432. }
  433. };
  434. template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
  435. struct fmt::formatter<BitFieldArrayConstRef<position, bits, size, T, S>>
  436. {
  437. fmt::formatter<T> m_formatter;
  438. constexpr auto parse(format_parse_context& ctx) { return m_formatter.parse(ctx); }
  439. template <typename FormatContext>
  440. auto format(const BitFieldArrayConstRef<position, bits, size, T, S>& ref,
  441. FormatContext& ctx) const
  442. {
  443. return m_formatter.format(ref.Value(), ctx);
  444. }
  445. };