layout.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. // Copyright 2018 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // MOTIVATION AND TUTORIAL
  16. //
  17. // If you want to put in a single heap allocation N doubles followed by M ints,
  18. // it's easy if N and M are known at compile time.
  19. //
  20. // struct S {
  21. // double a[N];
  22. // int b[M];
  23. // };
  24. //
  25. // S* p = new S;
  26. //
  27. // But what if N and M are known only in run time? Class template Layout to the
  28. // rescue! It's a portable generalization of the technique known as struct hack.
  29. //
  30. // // This object will tell us everything we need to know about the memory
  31. // // layout of double[N] followed by int[M]. It's structurally identical to
  32. // // size_t[2] that stores N and M. It's very cheap to create.
  33. // const Layout<double, int> layout(N, M);
  34. //
  35. // // Allocate enough memory for both arrays. `AllocSize()` tells us how much
  36. // // memory is needed. We are free to use any allocation function we want as
  37. // // long as it returns aligned memory.
  38. // std::unique_ptr<unsigned char[]> p(new unsigned char[layout.AllocSize()]);
  39. //
  40. // // Obtain the pointer to the array of doubles.
  41. // // Equivalent to `reinterpret_cast<double*>(p.get())`.
  42. // //
  43. // // We could have written layout.Pointer<0>(p) instead. If all the types are
  44. // // unique you can use either form, but if some types are repeated you must
  45. // // use the index form.
  46. // double* a = layout.Pointer<double>(p.get());
  47. //
  48. // // Obtain the pointer to the array of ints.
  49. // // Equivalent to `reinterpret_cast<int*>(p.get() + N * 8)`.
  50. // int* b = layout.Pointer<int>(p);
  51. //
  52. // If we are unable to specify sizes of all fields, we can pass as many sizes as
  53. // we can to `Partial()`. In return, it'll allow us to access the fields whose
  54. // locations and sizes can be computed from the provided information.
  55. // `Partial()` comes in handy when the array sizes are embedded into the
  56. // allocation.
  57. //
  58. // // size_t[0] containing N, size_t[1] containing M, double[N], int[M].
  59. // using L = Layout<size_t, size_t, double, int>;
  60. //
  61. // unsigned char* Allocate(size_t n, size_t m) {
  62. // const L layout(1, 1, n, m);
  63. // unsigned char* p = new unsigned char[layout.AllocSize()];
  64. // *layout.Pointer<0>(p) = n;
  65. // *layout.Pointer<1>(p) = m;
  66. // return p;
  67. // }
  68. //
  69. // void Use(unsigned char* p) {
  70. // // First, extract N and M.
  71. // // Specify that the first array has only one element. Using `prefix` we
  72. // // can access the first two arrays but not more.
  73. // constexpr auto prefix = L::Partial(1);
  74. // size_t n = *prefix.Pointer<0>(p);
  75. // size_t m = *prefix.Pointer<1>(p);
  76. //
  77. // // Now we can get pointers to the payload.
  78. // const L layout(1, 1, n, m);
  79. // double* a = layout.Pointer<double>(p);
  80. // int* b = layout.Pointer<int>(p);
  81. // }
  82. //
  83. // The layout we used above combines fixed-size with dynamically-sized fields.
  84. // This is quite common. Layout is optimized for this use case and attempts to
  85. // generate optimal code. To help the compiler do that in more cases, you can
  86. // specify the fixed sizes using `WithStaticSizes`. This ensures that all
  87. // computations that can be performed at compile time are indeed performed at
  88. // compile time. Note that sometimes the `template` keyword is needed. E.g.:
  89. //
  90. // using SL = L::template WithStaticSizes<1, 1>;
  91. //
  92. // void Use(unsigned char* p) {
  93. // // First, extract N and M.
  94. // // Using `prefix` we can access the first three arrays but not more.
  95. // //
  96. // // More details: The first element always has offset 0. `SL`
  97. // // has offsets for the second and third array based on sizes of
  98. // // the first and second array, specified via `WithStaticSizes`.
  99. // constexpr auto prefix = SL::Partial();
  100. // size_t n = *prefix.Pointer<0>(p);
  101. // size_t m = *prefix.Pointer<1>(p);
  102. //
  103. // // Now we can get a pointer to the final payload.
  104. // const SL layout(n, m);
  105. // double* a = layout.Pointer<double>(p);
  106. // int* b = layout.Pointer<int>(p);
  107. // }
  108. //
  109. // Efficiency tip: The order of fields matters. In `Layout<T1, ..., TN>` try to
  110. // ensure that `alignof(T1) >= ... >= alignof(TN)`. This way you'll have no
  111. // padding in between arrays.
  112. //
  113. // You can manually override the alignment of an array by wrapping the type in
  114. // `Aligned<T, N>`. `Layout<..., Aligned<T, N>, ...>` has exactly the same API
  115. // and behavior as `Layout<..., T, ...>` except that the first element of the
  116. // array of `T` is aligned to `N` (the rest of the elements follow without
  117. // padding). `N` cannot be less than `alignof(T)`.
  118. //
  119. // `AllocSize()` and `Pointer()` are the most basic methods for dealing with
  120. // memory layouts. Check out the reference or code below to discover more.
  121. //
  122. // EXAMPLE
  123. //
  124. // // Immutable move-only string with sizeof equal to sizeof(void*). The
  125. // // string size and the characters are kept in the same heap allocation.
  126. // class CompactString {
  127. // public:
  128. // CompactString(const char* s = "") {
  129. // const size_t size = strlen(s);
  130. // // size_t[1] followed by char[size + 1].
  131. // const L layout(size + 1);
  132. // p_.reset(new unsigned char[layout.AllocSize()]);
  133. // // If running under ASAN, mark the padding bytes, if any, to catch
  134. // // memory errors.
  135. // layout.PoisonPadding(p_.get());
  136. // // Store the size in the allocation.
  137. // *layout.Pointer<size_t>(p_.get()) = size;
  138. // // Store the characters in the allocation.
  139. // memcpy(layout.Pointer<char>(p_.get()), s, size + 1);
  140. // }
  141. //
  142. // size_t size() const {
  143. // // Equivalent to reinterpret_cast<size_t&>(*p).
  144. // return *L::Partial().Pointer<size_t>(p_.get());
  145. // }
  146. //
  147. // const char* c_str() const {
  148. // // Equivalent to reinterpret_cast<char*>(p.get() + sizeof(size_t)).
  149. // return L::Partial().Pointer<char>(p_.get());
  150. // }
  151. //
  152. // private:
  153. // // Our heap allocation contains a single size_t followed by an array of
  154. // // chars.
  155. // using L = Layout<size_t, char>::WithStaticSizes<1>;
  156. // std::unique_ptr<unsigned char[]> p_;
  157. // };
  158. //
  159. // int main() {
  160. // CompactString s = "hello";
  161. // assert(s.size() == 5);
  162. // assert(strcmp(s.c_str(), "hello") == 0);
  163. // }
  164. //
  165. // DOCUMENTATION
  166. //
  167. // The interface exported by this file consists of:
  168. // - class `Layout<>` and its public members.
  169. // - The public members of classes `internal_layout::LayoutWithStaticSizes<>`
  170. // and `internal_layout::LayoutImpl<>`. Those classes aren't intended to be
  171. // used directly, and their name and template parameter list are internal
  172. // implementation details, but the classes themselves provide most of the
  173. // functionality in this file. See comments on their members for detailed
  174. // documentation.
  175. //
  176. // `Layout<T1,... Tn>::Partial(count1,..., countm)` (where `m` <= `n`) returns a
  177. // `LayoutImpl<>` object. `Layout<T1,..., Tn> layout(count1,..., countn)`
  178. // creates a `Layout` object, which exposes the same functionality by inheriting
  179. // from `LayoutImpl<>`.
  180. #ifndef Y_ABSL_CONTAINER_INTERNAL_LAYOUT_H_
  181. #define Y_ABSL_CONTAINER_INTERNAL_LAYOUT_H_
  182. #include <assert.h>
  183. #include <stddef.h>
  184. #include <stdint.h>
  185. #include <array>
  186. #include <util/generic/string.h>
  187. #include <tuple>
  188. #include <type_traits>
  189. #include <typeinfo>
  190. #include <utility>
  191. #include "y_absl/base/attributes.h"
  192. #include "y_absl/base/config.h"
  193. #include "y_absl/debugging/internal/demangle.h"
  194. #include "y_absl/meta/type_traits.h"
  195. #include "y_absl/strings/str_cat.h"
  196. #include "y_absl/types/span.h"
  197. #include "y_absl/utility/utility.h"
  198. #ifdef Y_ABSL_HAVE_ADDRESS_SANITIZER
  199. #include <sanitizer/asan_interface.h>
  200. #endif
  201. namespace y_absl {
  202. Y_ABSL_NAMESPACE_BEGIN
  203. namespace container_internal {
  204. // A type wrapper that instructs `Layout` to use the specific alignment for the
  205. // array. `Layout<..., Aligned<T, N>, ...>` has exactly the same API
  206. // and behavior as `Layout<..., T, ...>` except that the first element of the
  207. // array of `T` is aligned to `N` (the rest of the elements follow without
  208. // padding).
  209. //
  210. // Requires: `N >= alignof(T)` and `N` is a power of 2.
  211. template <class T, size_t N>
  212. struct Aligned;
  213. namespace internal_layout {
  214. template <class T>
  215. struct NotAligned {};
  216. template <class T, size_t N>
  217. struct NotAligned<const Aligned<T, N>> {
  218. static_assert(sizeof(T) == 0, "Aligned<T, N> cannot be const-qualified");
  219. };
  220. template <size_t>
  221. using IntToSize = size_t;
  222. template <class T>
  223. struct Type : NotAligned<T> {
  224. using type = T;
  225. };
  226. template <class T, size_t N>
  227. struct Type<Aligned<T, N>> {
  228. using type = T;
  229. };
  230. template <class T>
  231. struct SizeOf : NotAligned<T>, std::integral_constant<size_t, sizeof(T)> {};
  232. template <class T, size_t N>
  233. struct SizeOf<Aligned<T, N>> : std::integral_constant<size_t, sizeof(T)> {};
  234. // Note: workaround for https://gcc.gnu.org/PR88115
  235. template <class T>
  236. struct AlignOf : NotAligned<T> {
  237. static constexpr size_t value = alignof(T);
  238. };
  239. template <class T, size_t N>
  240. struct AlignOf<Aligned<T, N>> {
  241. static_assert(N % alignof(T) == 0,
  242. "Custom alignment can't be lower than the type's alignment");
  243. static constexpr size_t value = N;
  244. };
  245. // Does `Ts...` contain `T`?
  246. template <class T, class... Ts>
  247. using Contains = y_absl::disjunction<std::is_same<T, Ts>...>;
  248. template <class From, class To>
  249. using CopyConst =
  250. typename std::conditional<std::is_const<From>::value, const To, To>::type;
  251. // Note: We're not qualifying this with y_absl:: because it doesn't compile under
  252. // MSVC.
  253. template <class T>
  254. using SliceType = Span<T>;
  255. // This namespace contains no types. It prevents functions defined in it from
  256. // being found by ADL.
  257. namespace adl_barrier {
  258. template <class Needle, class... Ts>
  259. constexpr size_t Find(Needle, Needle, Ts...) {
  260. static_assert(!Contains<Needle, Ts...>(), "Duplicate element type");
  261. return 0;
  262. }
  263. template <class Needle, class T, class... Ts>
  264. constexpr size_t Find(Needle, T, Ts...) {
  265. return adl_barrier::Find(Needle(), Ts()...) + 1;
  266. }
  267. constexpr bool IsPow2(size_t n) { return !(n & (n - 1)); }
  268. // Returns `q * m` for the smallest `q` such that `q * m >= n`.
  269. // Requires: `m` is a power of two. It's enforced by IsLegalElementType below.
  270. constexpr size_t Align(size_t n, size_t m) { return (n + m - 1) & ~(m - 1); }
  271. constexpr size_t Min(size_t a, size_t b) { return b < a ? b : a; }
  272. constexpr size_t Max(size_t a) { return a; }
  273. template <class... Ts>
  274. constexpr size_t Max(size_t a, size_t b, Ts... rest) {
  275. return adl_barrier::Max(b < a ? a : b, rest...);
  276. }
  277. template <class T>
  278. TString TypeName() {
  279. TString out;
  280. return out;
  281. }
  282. } // namespace adl_barrier
  283. template <bool C>
  284. using EnableIf = typename std::enable_if<C, int>::type;
  285. // Can `T` be a template argument of `Layout`?
  286. template <class T>
  287. using IsLegalElementType = std::integral_constant<
  288. bool, !std::is_reference<T>::value && !std::is_volatile<T>::value &&
  289. !std::is_reference<typename Type<T>::type>::value &&
  290. !std::is_volatile<typename Type<T>::type>::value &&
  291. adl_barrier::IsPow2(AlignOf<T>::value)>;
  292. template <class Elements, class StaticSizeSeq, class RuntimeSizeSeq,
  293. class SizeSeq, class OffsetSeq>
  294. class LayoutImpl;
  295. // Public base class of `Layout` and the result type of `Layout::Partial()`.
  296. //
  297. // `Elements...` contains all template arguments of `Layout` that created this
  298. // instance.
  299. //
  300. // `StaticSizeSeq...` is an index_sequence containing the sizes specified at
  301. // compile-time.
  302. //
  303. // `RuntimeSizeSeq...` is `[0, NumRuntimeSizes)`, where `NumRuntimeSizes` is the
  304. // number of arguments passed to `Layout::Partial()` or `Layout::Layout()`.
  305. //
  306. // `SizeSeq...` is `[0, NumSizes)` where `NumSizes` is `NumRuntimeSizes` plus
  307. // the number of sizes in `StaticSizeSeq`.
  308. //
  309. // `OffsetSeq...` is `[0, NumOffsets)` where `NumOffsets` is
  310. // `Min(sizeof...(Elements), NumSizes + 1)` (the number of arrays for which we
  311. // can compute offsets).
  312. template <class... Elements, size_t... StaticSizeSeq, size_t... RuntimeSizeSeq,
  313. size_t... SizeSeq, size_t... OffsetSeq>
  314. class LayoutImpl<
  315. std::tuple<Elements...>, y_absl::index_sequence<StaticSizeSeq...>,
  316. y_absl::index_sequence<RuntimeSizeSeq...>, y_absl::index_sequence<SizeSeq...>,
  317. y_absl::index_sequence<OffsetSeq...>> {
  318. private:
  319. static_assert(sizeof...(Elements) > 0, "At least one field is required");
  320. static_assert(y_absl::conjunction<IsLegalElementType<Elements>...>::value,
  321. "Invalid element type (see IsLegalElementType)");
  322. static_assert(sizeof...(StaticSizeSeq) <= sizeof...(Elements),
  323. "Too many static sizes specified");
  324. enum {
  325. NumTypes = sizeof...(Elements),
  326. NumStaticSizes = sizeof...(StaticSizeSeq),
  327. NumRuntimeSizes = sizeof...(RuntimeSizeSeq),
  328. NumSizes = sizeof...(SizeSeq),
  329. NumOffsets = sizeof...(OffsetSeq),
  330. };
  331. // These are guaranteed by `Layout`.
  332. static_assert(NumStaticSizes + NumRuntimeSizes == NumSizes, "Internal error");
  333. static_assert(NumSizes <= NumTypes, "Internal error");
  334. static_assert(NumOffsets == adl_barrier::Min(NumTypes, NumSizes + 1),
  335. "Internal error");
  336. static_assert(NumTypes > 0, "Internal error");
  337. static constexpr std::array<size_t, sizeof...(StaticSizeSeq)> kStaticSizes = {
  338. StaticSizeSeq...};
  339. // Returns the index of `T` in `Elements...`. Results in a compilation error
  340. // if `Elements...` doesn't contain exactly one instance of `T`.
  341. template <class T>
  342. static constexpr size_t ElementIndex() {
  343. static_assert(Contains<Type<T>, Type<typename Type<Elements>::type>...>(),
  344. "Type not found");
  345. return adl_barrier::Find(Type<T>(),
  346. Type<typename Type<Elements>::type>()...);
  347. }
  348. template <size_t N>
  349. using ElementAlignment =
  350. AlignOf<typename std::tuple_element<N, std::tuple<Elements...>>::type>;
  351. public:
  352. // Element types of all arrays packed in a tuple.
  353. using ElementTypes = std::tuple<typename Type<Elements>::type...>;
  354. // Element type of the Nth array.
  355. template <size_t N>
  356. using ElementType = typename std::tuple_element<N, ElementTypes>::type;
  357. constexpr explicit LayoutImpl(IntToSize<RuntimeSizeSeq>... sizes)
  358. : size_{sizes...} {}
  359. // Alignment of the layout, equal to the strictest alignment of all elements.
  360. // All pointers passed to the methods of layout must be aligned to this value.
  361. static constexpr size_t Alignment() {
  362. return adl_barrier::Max(AlignOf<Elements>::value...);
  363. }
  364. // Offset in bytes of the Nth array.
  365. //
  366. // // int[3], 4 bytes of padding, double[4].
  367. // Layout<int, double> x(3, 4);
  368. // assert(x.Offset<0>() == 0); // The ints starts from 0.
  369. // assert(x.Offset<1>() == 16); // The doubles starts from 16.
  370. //
  371. // Requires: `N <= NumSizes && N < sizeof...(Ts)`.
  372. template <size_t N, EnableIf<N == 0> = 0>
  373. constexpr size_t Offset() const {
  374. return 0;
  375. }
  376. template <size_t N, EnableIf<N != 0> = 0>
  377. constexpr size_t Offset() const {
  378. static_assert(N < NumOffsets, "Index out of bounds");
  379. return adl_barrier::Align(
  380. Offset<N - 1>() + SizeOf<ElementType<N - 1>>::value * Size<N - 1>(),
  381. ElementAlignment<N>::value);
  382. }
  383. // Offset in bytes of the array with the specified element type. There must
  384. // be exactly one such array and its zero-based index must be at most
  385. // `NumSizes`.
  386. //
  387. // // int[3], 4 bytes of padding, double[4].
  388. // Layout<int, double> x(3, 4);
  389. // assert(x.Offset<int>() == 0); // The ints starts from 0.
  390. // assert(x.Offset<double>() == 16); // The doubles starts from 16.
  391. template <class T>
  392. constexpr size_t Offset() const {
  393. return Offset<ElementIndex<T>()>();
  394. }
  395. // Offsets in bytes of all arrays for which the offsets are known.
  396. constexpr std::array<size_t, NumOffsets> Offsets() const {
  397. return {{Offset<OffsetSeq>()...}};
  398. }
  399. // The number of elements in the Nth array (zero-based).
  400. //
  401. // // int[3], 4 bytes of padding, double[4].
  402. // Layout<int, double> x(3, 4);
  403. // assert(x.Size<0>() == 3);
  404. // assert(x.Size<1>() == 4);
  405. //
  406. // Requires: `N < NumSizes`.
  407. template <size_t N, EnableIf<(N < NumStaticSizes)> = 0>
  408. constexpr size_t Size() const {
  409. return kStaticSizes[N];
  410. }
  411. template <size_t N, EnableIf<(N >= NumStaticSizes)> = 0>
  412. constexpr size_t Size() const {
  413. static_assert(N < NumSizes, "Index out of bounds");
  414. return size_[N - NumStaticSizes];
  415. }
  416. // The number of elements in the array with the specified element type.
  417. // There must be exactly one such array and its zero-based index must be
  418. // at most `NumSizes`.
  419. //
  420. // // int[3], 4 bytes of padding, double[4].
  421. // Layout<int, double> x(3, 4);
  422. // assert(x.Size<int>() == 3);
  423. // assert(x.Size<double>() == 4);
  424. template <class T>
  425. constexpr size_t Size() const {
  426. return Size<ElementIndex<T>()>();
  427. }
  428. // The number of elements of all arrays for which they are known.
  429. constexpr std::array<size_t, NumSizes> Sizes() const {
  430. return {{Size<SizeSeq>()...}};
  431. }
  432. // Pointer to the beginning of the Nth array.
  433. //
  434. // `Char` must be `[const] [signed|unsigned] char`.
  435. //
  436. // // int[3], 4 bytes of padding, double[4].
  437. // Layout<int, double> x(3, 4);
  438. // unsigned char* p = new unsigned char[x.AllocSize()];
  439. // int* ints = x.Pointer<0>(p);
  440. // double* doubles = x.Pointer<1>(p);
  441. //
  442. // Requires: `N <= NumSizes && N < sizeof...(Ts)`.
  443. // Requires: `p` is aligned to `Alignment()`.
  444. template <size_t N, class Char>
  445. CopyConst<Char, ElementType<N>>* Pointer(Char* p) const {
  446. using C = typename std::remove_const<Char>::type;
  447. static_assert(
  448. std::is_same<C, char>() || std::is_same<C, unsigned char>() ||
  449. std::is_same<C, signed char>(),
  450. "The argument must be a pointer to [const] [signed|unsigned] char");
  451. constexpr size_t alignment = Alignment();
  452. (void)alignment;
  453. assert(reinterpret_cast<uintptr_t>(p) % alignment == 0);
  454. return reinterpret_cast<CopyConst<Char, ElementType<N>>*>(p + Offset<N>());
  455. }
  456. // Pointer to the beginning of the array with the specified element type.
  457. // There must be exactly one such array and its zero-based index must be at
  458. // most `NumSizes`.
  459. //
  460. // `Char` must be `[const] [signed|unsigned] char`.
  461. //
  462. // // int[3], 4 bytes of padding, double[4].
  463. // Layout<int, double> x(3, 4);
  464. // unsigned char* p = new unsigned char[x.AllocSize()];
  465. // int* ints = x.Pointer<int>(p);
  466. // double* doubles = x.Pointer<double>(p);
  467. //
  468. // Requires: `p` is aligned to `Alignment()`.
  469. template <class T, class Char>
  470. CopyConst<Char, T>* Pointer(Char* p) const {
  471. return Pointer<ElementIndex<T>()>(p);
  472. }
  473. // Pointers to all arrays for which pointers are known.
  474. //
  475. // `Char` must be `[const] [signed|unsigned] char`.
  476. //
  477. // // int[3], 4 bytes of padding, double[4].
  478. // Layout<int, double> x(3, 4);
  479. // unsigned char* p = new unsigned char[x.AllocSize()];
  480. //
  481. // int* ints;
  482. // double* doubles;
  483. // std::tie(ints, doubles) = x.Pointers(p);
  484. //
  485. // Requires: `p` is aligned to `Alignment()`.
  486. template <class Char>
  487. auto Pointers(Char* p) const {
  488. return std::tuple<CopyConst<Char, ElementType<OffsetSeq>>*...>(
  489. Pointer<OffsetSeq>(p)...);
  490. }
  491. // The Nth array.
  492. //
  493. // `Char` must be `[const] [signed|unsigned] char`.
  494. //
  495. // // int[3], 4 bytes of padding, double[4].
  496. // Layout<int, double> x(3, 4);
  497. // unsigned char* p = new unsigned char[x.AllocSize()];
  498. // Span<int> ints = x.Slice<0>(p);
  499. // Span<double> doubles = x.Slice<1>(p);
  500. //
  501. // Requires: `N < NumSizes`.
  502. // Requires: `p` is aligned to `Alignment()`.
  503. template <size_t N, class Char>
  504. SliceType<CopyConst<Char, ElementType<N>>> Slice(Char* p) const {
  505. return SliceType<CopyConst<Char, ElementType<N>>>(Pointer<N>(p), Size<N>());
  506. }
  507. // The array with the specified element type. There must be exactly one
  508. // such array and its zero-based index must be less than `NumSizes`.
  509. //
  510. // `Char` must be `[const] [signed|unsigned] char`.
  511. //
  512. // // int[3], 4 bytes of padding, double[4].
  513. // Layout<int, double> x(3, 4);
  514. // unsigned char* p = new unsigned char[x.AllocSize()];
  515. // Span<int> ints = x.Slice<int>(p);
  516. // Span<double> doubles = x.Slice<double>(p);
  517. //
  518. // Requires: `p` is aligned to `Alignment()`.
  519. template <class T, class Char>
  520. SliceType<CopyConst<Char, T>> Slice(Char* p) const {
  521. return Slice<ElementIndex<T>()>(p);
  522. }
  523. // All arrays with known sizes.
  524. //
  525. // `Char` must be `[const] [signed|unsigned] char`.
  526. //
  527. // // int[3], 4 bytes of padding, double[4].
  528. // Layout<int, double> x(3, 4);
  529. // unsigned char* p = new unsigned char[x.AllocSize()];
  530. //
  531. // Span<int> ints;
  532. // Span<double> doubles;
  533. // std::tie(ints, doubles) = x.Slices(p);
  534. //
  535. // Requires: `p` is aligned to `Alignment()`.
  536. //
  537. // Note: We mark the parameter as unused because GCC detects it is not used
  538. // when `SizeSeq` is empty [-Werror=unused-but-set-parameter].
  539. template <class Char>
  540. auto Slices(Y_ABSL_ATTRIBUTE_UNUSED Char* p) const {
  541. return std::tuple<SliceType<CopyConst<Char, ElementType<SizeSeq>>>...>(
  542. Slice<SizeSeq>(p)...);
  543. }
  544. // The size of the allocation that fits all arrays.
  545. //
  546. // // int[3], 4 bytes of padding, double[4].
  547. // Layout<int, double> x(3, 4);
  548. // unsigned char* p = new unsigned char[x.AllocSize()]; // 48 bytes
  549. //
  550. // Requires: `NumSizes == sizeof...(Ts)`.
  551. constexpr size_t AllocSize() const {
  552. static_assert(NumTypes == NumSizes, "You must specify sizes of all fields");
  553. return Offset<NumTypes - 1>() +
  554. SizeOf<ElementType<NumTypes - 1>>::value * Size<NumTypes - 1>();
  555. }
  556. // If built with --config=asan, poisons padding bytes (if any) in the
  557. // allocation. The pointer must point to a memory block at least
  558. // `AllocSize()` bytes in length.
  559. //
  560. // `Char` must be `[const] [signed|unsigned] char`.
  561. //
  562. // Requires: `p` is aligned to `Alignment()`.
  563. template <class Char, size_t N = NumOffsets - 1, EnableIf<N == 0> = 0>
  564. void PoisonPadding(const Char* p) const {
  565. Pointer<0>(p); // verify the requirements on `Char` and `p`
  566. }
  567. template <class Char, size_t N = NumOffsets - 1, EnableIf<N != 0> = 0>
  568. void PoisonPadding(const Char* p) const {
  569. static_assert(N < NumOffsets, "Index out of bounds");
  570. (void)p;
  571. #ifdef Y_ABSL_HAVE_ADDRESS_SANITIZER
  572. PoisonPadding<Char, N - 1>(p);
  573. // The `if` is an optimization. It doesn't affect the observable behaviour.
  574. if (ElementAlignment<N - 1>::value % ElementAlignment<N>::value) {
  575. size_t start =
  576. Offset<N - 1>() + SizeOf<ElementType<N - 1>>::value * Size<N - 1>();
  577. ASAN_POISON_MEMORY_REGION(p + start, Offset<N>() - start);
  578. }
  579. #endif
  580. }
  581. // Human-readable description of the memory layout. Useful for debugging.
  582. // Slow.
  583. //
  584. // // char[5], 3 bytes of padding, int[3], 4 bytes of padding, followed
  585. // // by an unknown number of doubles.
  586. // auto x = Layout<char, int, double>::Partial(5, 3);
  587. // assert(x.DebugString() ==
  588. // "@0<char>(1)[5]; @8<int>(4)[3]; @24<double>(8)");
  589. //
  590. // Each field is in the following format: @offset<type>(sizeof)[size] (<type>
  591. // may be missing depending on the target platform). For example,
  592. // @8<int>(4)[3] means that at offset 8 we have an array of ints, where each
  593. // int is 4 bytes, and we have 3 of those ints. The size of the last field may
  594. // be missing (as in the example above). Only fields with known offsets are
  595. // described. Type names may differ across platforms: one compiler might
  596. // produce "unsigned*" where another produces "unsigned int *".
  597. TString DebugString() const {
  598. const auto offsets = Offsets();
  599. const size_t sizes[] = {SizeOf<ElementType<OffsetSeq>>::value...};
  600. const TString types[] = {
  601. adl_barrier::TypeName<ElementType<OffsetSeq>>()...};
  602. TString res = y_absl::StrCat("@0", types[0], "(", sizes[0], ")");
  603. for (size_t i = 0; i != NumOffsets - 1; ++i) {
  604. y_absl::StrAppend(&res, "[", DebugSize(i), "]; @", offsets[i + 1],
  605. types[i + 1], "(", sizes[i + 1], ")");
  606. }
  607. // NumSizes is a constant that may be zero. Some compilers cannot see that
  608. // inside the if statement "size_[NumSizes - 1]" must be valid.
  609. int last = static_cast<int>(NumSizes) - 1;
  610. if (NumTypes == NumSizes && last >= 0) {
  611. y_absl::StrAppend(&res, "[", DebugSize(static_cast<size_t>(last)), "]");
  612. }
  613. return res;
  614. }
  615. private:
  616. size_t DebugSize(size_t n) const {
  617. if (n < NumStaticSizes) {
  618. return kStaticSizes[n];
  619. } else {
  620. return size_[n - NumStaticSizes];
  621. }
  622. }
  623. // Arguments of `Layout::Partial()` or `Layout::Layout()`.
  624. size_t size_[NumRuntimeSizes > 0 ? NumRuntimeSizes : 1];
  625. };
  626. // Defining a constexpr static class member variable is redundant and deprecated
  627. // in C++17, but required in C++14.
  628. template <class... Elements, size_t... StaticSizeSeq, size_t... RuntimeSizeSeq,
  629. size_t... SizeSeq, size_t... OffsetSeq>
  630. constexpr std::array<size_t, sizeof...(StaticSizeSeq)> LayoutImpl<
  631. std::tuple<Elements...>, y_absl::index_sequence<StaticSizeSeq...>,
  632. y_absl::index_sequence<RuntimeSizeSeq...>, y_absl::index_sequence<SizeSeq...>,
  633. y_absl::index_sequence<OffsetSeq...>>::kStaticSizes;
  634. template <class StaticSizeSeq, size_t NumRuntimeSizes, class... Ts>
  635. using LayoutType = LayoutImpl<
  636. std::tuple<Ts...>, StaticSizeSeq,
  637. y_absl::make_index_sequence<NumRuntimeSizes>,
  638. y_absl::make_index_sequence<NumRuntimeSizes + StaticSizeSeq::size()>,
  639. y_absl::make_index_sequence<adl_barrier::Min(
  640. sizeof...(Ts), NumRuntimeSizes + StaticSizeSeq::size() + 1)>>;
  641. template <class StaticSizeSeq, class... Ts>
  642. class LayoutWithStaticSizes
  643. : public LayoutType<StaticSizeSeq,
  644. sizeof...(Ts) - adl_barrier::Min(sizeof...(Ts),
  645. StaticSizeSeq::size()),
  646. Ts...> {
  647. private:
  648. using Super =
  649. LayoutType<StaticSizeSeq,
  650. sizeof...(Ts) -
  651. adl_barrier::Min(sizeof...(Ts), StaticSizeSeq::size()),
  652. Ts...>;
  653. public:
  654. // The result type of `Partial()` with `NumSizes` arguments.
  655. template <size_t NumSizes>
  656. using PartialType =
  657. internal_layout::LayoutType<StaticSizeSeq, NumSizes, Ts...>;
  658. // `Layout` knows the element types of the arrays we want to lay out in
  659. // memory but not the number of elements in each array.
  660. // `Partial(size1, ..., sizeN)` allows us to specify the latter. The
  661. // resulting immutable object can be used to obtain pointers to the
  662. // individual arrays.
  663. //
  664. // It's allowed to pass fewer array sizes than the number of arrays. E.g.,
  665. // if all you need is to the offset of the second array, you only need to
  666. // pass one argument -- the number of elements in the first array.
  667. //
  668. // // int[3] followed by 4 bytes of padding and an unknown number of
  669. // // doubles.
  670. // auto x = Layout<int, double>::Partial(3);
  671. // // doubles start at byte 16.
  672. // assert(x.Offset<1>() == 16);
  673. //
  674. // If you know the number of elements in all arrays, you can still call
  675. // `Partial()` but it's more convenient to use the constructor of `Layout`.
  676. //
  677. // Layout<int, double> x(3, 5);
  678. //
  679. // Note: The sizes of the arrays must be specified in number of elements,
  680. // not in bytes.
  681. //
  682. // Requires: `sizeof...(Sizes) + NumStaticSizes <= sizeof...(Ts)`.
  683. // Requires: all arguments are convertible to `size_t`.
  684. template <class... Sizes>
  685. static constexpr PartialType<sizeof...(Sizes)> Partial(Sizes&&... sizes) {
  686. static_assert(sizeof...(Sizes) + StaticSizeSeq::size() <= sizeof...(Ts),
  687. "");
  688. return PartialType<sizeof...(Sizes)>(
  689. static_cast<size_t>(std::forward<Sizes>(sizes))...);
  690. }
  691. // Inherit LayoutType's constructor.
  692. //
  693. // Creates a layout with the sizes of all arrays specified. If you know
  694. // only the sizes of the first N arrays (where N can be zero), you can use
  695. // `Partial()` defined above. The constructor is essentially equivalent to
  696. // calling `Partial()` and passing in all array sizes; the constructor is
  697. // provided as a convenient abbreviation.
  698. //
  699. // Note: The sizes of the arrays must be specified in number of elements,
  700. // not in bytes.
  701. //
  702. // Implementation note: we do this via a `using` declaration instead of
  703. // defining our own explicit constructor because the signature of LayoutType's
  704. // constructor depends on RuntimeSizeSeq, which we don't have access to here.
  705. // If we defined our own constructor here, it would have to use a parameter
  706. // pack and then cast the arguments to size_t when calling the superclass
  707. // constructor, similar to what Partial() does. But that would suffer from the
  708. // same problem that Partial() has, which is that the parameter types are
  709. // inferred from the arguments, which may be signed types, which must then be
  710. // cast to size_t. This can lead to negative values being silently (i.e. with
  711. // no compiler warnings) cast to an unsigned type. Having a constructor with
  712. // size_t parameters helps the compiler generate better warnings about
  713. // potential bad casts, while avoiding false warnings when positive literal
  714. // arguments are used. If an argument is a positive literal integer (e.g.
  715. // `1`), the compiler will understand that it can be safely converted to
  716. // size_t, and hence not generate a warning. But if a negative literal (e.g.
  717. // `-1`) or a variable with signed type is used, then it can generate a
  718. // warning about a potentially unsafe implicit cast. It would be great if we
  719. // could do this for Partial() too, but unfortunately as of C++23 there seems
  720. // to be no way to define a function with a variable number of parameters of a
  721. // certain type, a.k.a. homogeneous function parameter packs. So we're forced
  722. // to choose between explicitly casting the arguments to size_t, which
  723. // suppresses all warnings, even potentially valid ones, or implicitly casting
  724. // them to size_t, which generates bogus warnings whenever literal arguments
  725. // are used, even if they're positive.
  726. using Super::Super;
  727. };
  728. } // namespace internal_layout
  729. // Descriptor of arrays of various types and sizes laid out in memory one after
  730. // another. See the top of the file for documentation.
  731. //
  732. // Check out the public API of internal_layout::LayoutWithStaticSizes and
  733. // internal_layout::LayoutImpl above. Those types are internal to the library
  734. // but their methods are public, and they are inherited by `Layout`.
  735. template <class... Ts>
  736. class Layout : public internal_layout::LayoutWithStaticSizes<
  737. y_absl::make_index_sequence<0>, Ts...> {
  738. private:
  739. using Super =
  740. internal_layout::LayoutWithStaticSizes<y_absl::make_index_sequence<0>,
  741. Ts...>;
  742. public:
  743. // If you know the sizes of some or all of the arrays at compile time, you can
  744. // use `WithStaticSizes` or `WithStaticSizeSequence` to create a `Layout` type
  745. // with those sizes baked in. This can help the compiler generate optimal code
  746. // for calculating array offsets and AllocSize().
  747. //
  748. // Like `Partial()`, the N sizes you specify are for the first N arrays, and
  749. // they specify the number of elements in each array, not the number of bytes.
  750. template <class StaticSizeSeq>
  751. using WithStaticSizeSequence =
  752. internal_layout::LayoutWithStaticSizes<StaticSizeSeq, Ts...>;
  753. template <size_t... StaticSizes>
  754. using WithStaticSizes =
  755. WithStaticSizeSequence<std::index_sequence<StaticSizes...>>;
  756. // Inherit LayoutWithStaticSizes's constructor, which requires you to specify
  757. // all the array sizes.
  758. using Super::Super;
  759. };
  760. } // namespace container_internal
  761. Y_ABSL_NAMESPACE_END
  762. } // namespace y_absl
  763. #endif // Y_ABSL_CONTAINER_INTERNAL_LAYOUT_H_