1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_LIBARTBASE_BASE_BIT_STRUCT_DETAIL_H_
18 #define ART_LIBARTBASE_BASE_BIT_STRUCT_DETAIL_H_
19 
20 #include "bit_utils.h"
21 #include "globals.h"
22 
23 #include <type_traits>
24 
25 // Implementation details for bit_struct.h
26 // Not intended to be used stand-alone.
27 
28 namespace art {
29 
30 template <typename T>
31 static constexpr size_t BitStructSizeOf();
32 
33 namespace detail {
34 // Select the smallest uintX_t that will fit kBitSize bits.
35 template <size_t kBitSize>
36 struct MinimumTypeUnsignedHelper {
37   using type =
38     typename std::conditional<kBitSize == 0, void,       // NOLINT [whitespace/operators] [3]
39     typename std::conditional<kBitSize <= 8, uint8_t,    // NOLINT [whitespace/operators] [3]
40     typename std::conditional<kBitSize <= 16, uint16_t,  // NOLINT [whitespace/operators] [3]
41     typename std::conditional<kBitSize <= 32, uint32_t,
42     typename std::conditional<kBitSize <= 64, uint64_t,
43     typename std::conditional<kBitSize <= BitSizeOf<uintmax_t>(), uintmax_t,
44                               void>::type>::type>::type>::type>::type>::type;
45 };
46 
47 // Select the smallest [u]intX_t that will fit kBitSize bits.
48 // Automatically picks intX_t or uintX_t based on the sign-ness of T.
49 template <typename T, size_t kBitSize>
50 struct MinimumTypeHelper {
51   using type_unsigned = typename MinimumTypeUnsignedHelper<kBitSize>::type;
52 
53   using type =
54     typename std::conditional</* if */   std::is_signed<T>::value,
55                               /* then */ typename std::make_signed<type_unsigned>::type,
56                               /* else */ type_unsigned>::type;
57 };
58 
59 // Helper for converting to and from T to an integral type.
60 template <typename T>
61 union ValueConverter {
62   using StorageType = typename MinimumTypeHelper<T, sizeof(T) * kBitsPerByte>::type;
63 
ToUnderlyingStorage(T value)64   static constexpr StorageType ToUnderlyingStorage(T value) {
65     ValueConverter converter;
66     converter.value_.val_ = value;
67     return converter.storage_.val_;
68   }
69 
FromUnderlyingStorage(StorageType storage)70   static constexpr T FromUnderlyingStorage(StorageType storage) {
71     ValueConverter converter;
72     converter.storage_.val_ = storage;
73     return converter.value_.val_;
74   }
75 
76   // Underlying values must be wrapped in separate standard-layout structs.
77   // See below for more details.
78   struct StorageWrapper {
79     StorageType val_;
80   };
81   struct ValueWrapper {
82     T val_;
83   };
84 
85   // Safely alias storage_ and value_ together.
86   //
87   // See C++ 9.5.1 [class.union]:
88   // If a standard-layout union contains several standard-layout structs that share a common
89   // initial sequence ... it is permitted to inspect the common initial sequence of any of
90   // standard-layout struct members.
91   StorageWrapper storage_;
92   ValueWrapper value_;
93 #if __cplusplus >= 202000L
94 #error "When upgrading to C++20, remove this error and check that this is OK for all use cases."
95   static_assert(std::is_layout_compatible_v<StorageWrapper, ValueWrapper>);
96 #endif
97 
98   // Future work: In theory almost non-standard layout can be supported here,
99   // assuming they don't rely on the address of (this).
100   // We just have to use memcpy since the union-aliasing would not work.
101 };
102 
103 // Denotes the beginning of a bit struct.
104 //
105 // This marker is required by the C++ standard in order to
106 // have a "common initial sequence".
107 //
108 // See C++ 9.5.1 [class.union]:
109 // If a standard-layout union contains several standard-layout structs that share a common
110 // initial sequence ... it is permitted to inspect the common initial sequence of any of
111 // standard-layout struct members.
112 template <size_t kSize>
113 struct DefineBitStructSize {
114  private:
115   typename MinimumTypeUnsignedHelper<kSize>::type _;
116 };
117 
118 // Check if type "T" has a member called _ in it.
119 template <typename T>
120 struct HasUnderscoreField {
121  private:
122   using TrueT = std::integral_constant<bool, true>::type;
123   using FalseT = std::integral_constant<bool, false>::type;
124 
125   template <typename C>
126   static constexpr auto Test(void*) -> decltype(std::declval<C>()._, TrueT{});
127 
128   template <typename>
129   static constexpr FalseT Test(...);
130 
131  public:
132   static constexpr bool value = decltype(Test<T>(nullptr))::value;
133 };
134 
135 // Infer the type of the member of &T::M.
136 template <typename T, typename M>
137 M GetMemberType(M T:: *);
138 
139 // Ensure the minimal type storage for 'T' matches its declared BitStructSizeOf.
140 // Nominally used by the BITSTRUCT_DEFINE_END macro.
141 template <typename T>
ValidateBitStructSize()142 static constexpr bool ValidateBitStructSize() {
143   static_assert(std::is_union<T>::value, "T must be union");
144   static_assert(std::is_standard_layout<T>::value, "T must be standard-layout");
145   static_assert(HasUnderscoreField<T>::value, "T must have the _ DefineBitStructSize");
146 
147   const size_t kBitStructSizeOf = BitStructSizeOf<T>();
148   static_assert(std::is_same<decltype(GetMemberType(&T::_)),
149                              DefineBitStructSize<kBitStructSizeOf>>::value,
150                 "T::_ must be a DefineBitStructSize of the same size");
151 
152   const size_t kExpectedSize = (BitStructSizeOf<T>() < kBitsPerByte)
153                                    ? kBitsPerByte
154                                    : RoundUpToPowerOfTwo(kBitStructSizeOf);
155 
156   // Ensure no extra fields were added in between START/END.
157   const size_t kActualSize = sizeof(T) * kBitsPerByte;
158   return kExpectedSize == kActualSize;
159 }
160 }  // namespace detail
161 }  // namespace art
162 
163 #endif  // ART_LIBARTBASE_BASE_BIT_STRUCT_DETAIL_H_
164