TrailingObjects.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===--- TrailingObjects.h - Variable-length classes ------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This header defines support for implementing classes that have
  16. /// some trailing object (or arrays of objects) appended to them. The
  17. /// main purpose is to make it obvious where this idiom is being used,
  18. /// and to make the usage more idiomatic and more difficult to get
  19. /// wrong.
  20. ///
  21. /// The TrailingObject template abstracts away the reinterpret_cast,
  22. /// pointer arithmetic, and size calculations used for the allocation
  23. /// and access of appended arrays of objects, and takes care that they
  24. /// are all allocated at their required alignment. Additionally, it
  25. /// ensures that the base type is final -- deriving from a class that
  26. /// expects data appended immediately after it is typically not safe.
  27. ///
  28. /// Users are expected to derive from this template, and provide
  29. /// numTrailingObjects implementations for each trailing type except
  30. /// the last, e.g. like this sample:
  31. ///
  32. /// \code
  33. /// class VarLengthObj : private TrailingObjects<VarLengthObj, int, double> {
  34. /// friend TrailingObjects;
  35. ///
  36. /// unsigned NumInts, NumDoubles;
  37. /// size_t numTrailingObjects(OverloadToken<int>) const { return NumInts; }
  38. /// };
  39. /// \endcode
  40. ///
  41. /// You can access the appended arrays via 'getTrailingObjects', and
  42. /// determine the size needed for allocation via
  43. /// 'additionalSizeToAlloc' and 'totalSizeToAlloc'.
  44. ///
  45. /// All the methods implemented by this class are are intended for use
  46. /// by the implementation of the class, not as part of its interface
  47. /// (thus, private inheritance is suggested).
  48. ///
  49. //===----------------------------------------------------------------------===//
  50. #ifndef LLVM_SUPPORT_TRAILINGOBJECTS_H
  51. #define LLVM_SUPPORT_TRAILINGOBJECTS_H
  52. #include "llvm/Support/AlignOf.h"
  53. #include "llvm/Support/Alignment.h"
  54. #include "llvm/Support/Compiler.h"
  55. #include "llvm/Support/MathExtras.h"
  56. #include "llvm/Support/type_traits.h"
  57. #include <new>
  58. #include <type_traits>
  59. namespace llvm {
  60. namespace trailing_objects_internal {
  61. /// Helper template to calculate the max alignment requirement for a set of
  62. /// objects.
  63. template <typename First, typename... Rest> class AlignmentCalcHelper {
  64. private:
  65. enum {
  66. FirstAlignment = alignof(First),
  67. RestAlignment = AlignmentCalcHelper<Rest...>::Alignment,
  68. };
  69. public:
  70. enum {
  71. Alignment = FirstAlignment > RestAlignment ? FirstAlignment : RestAlignment
  72. };
  73. };
  74. template <typename First> class AlignmentCalcHelper<First> {
  75. public:
  76. enum { Alignment = alignof(First) };
  77. };
  78. /// The base class for TrailingObjects* classes.
  79. class TrailingObjectsBase {
  80. protected:
  81. /// OverloadToken's purpose is to allow specifying function overloads
  82. /// for different types, without actually taking the types as
  83. /// parameters. (Necessary because member function templates cannot
  84. /// be specialized, so overloads must be used instead of
  85. /// specialization.)
  86. template <typename T> struct OverloadToken {};
  87. };
  88. // Just a little helper for transforming a type pack into the same
  89. // number of a different type. e.g.:
  90. // ExtractSecondType<Foo..., int>::type
  91. template <typename Ty1, typename Ty2> struct ExtractSecondType {
  92. typedef Ty2 type;
  93. };
  94. // TrailingObjectsImpl is somewhat complicated, because it is a
  95. // recursively inheriting template, in order to handle the template
  96. // varargs. Each level of inheritance picks off a single trailing type
  97. // then recurses on the rest. The "Align", "BaseTy", and
  98. // "TopTrailingObj" arguments are passed through unchanged through the
  99. // recursion. "PrevTy" is, at each level, the type handled by the
  100. // level right above it.
  101. template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
  102. typename... MoreTys>
  103. class TrailingObjectsImpl {
  104. // The main template definition is never used -- the two
  105. // specializations cover all possibilities.
  106. };
  107. template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
  108. typename NextTy, typename... MoreTys>
  109. class TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy, NextTy,
  110. MoreTys...>
  111. : public TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy,
  112. MoreTys...> {
  113. typedef TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy, MoreTys...>
  114. ParentType;
  115. struct RequiresRealignment {
  116. static const bool value = alignof(PrevTy) < alignof(NextTy);
  117. };
  118. static constexpr bool requiresRealignment() {
  119. return RequiresRealignment::value;
  120. }
  121. protected:
  122. // Ensure the inherited getTrailingObjectsImpl is not hidden.
  123. using ParentType::getTrailingObjectsImpl;
  124. // These two functions are helper functions for
  125. // TrailingObjects::getTrailingObjects. They recurse to the left --
  126. // the result for each type in the list of trailing types depends on
  127. // the result of calling the function on the type to the
  128. // left. However, the function for the type to the left is
  129. // implemented by a *subclass* of this class, so we invoke it via
  130. // the TopTrailingObj, which is, via the
  131. // curiously-recurring-template-pattern, the most-derived type in
  132. // this recursion, and thus, contains all the overloads.
  133. static const NextTy *
  134. getTrailingObjectsImpl(const BaseTy *Obj,
  135. TrailingObjectsBase::OverloadToken<NextTy>) {
  136. auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
  137. Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
  138. TopTrailingObj::callNumTrailingObjects(
  139. Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
  140. if (requiresRealignment())
  141. return reinterpret_cast<const NextTy *>(
  142. alignAddr(Ptr, Align::Of<NextTy>()));
  143. else
  144. return reinterpret_cast<const NextTy *>(Ptr);
  145. }
  146. static NextTy *
  147. getTrailingObjectsImpl(BaseTy *Obj,
  148. TrailingObjectsBase::OverloadToken<NextTy>) {
  149. auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
  150. Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
  151. TopTrailingObj::callNumTrailingObjects(
  152. Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
  153. if (requiresRealignment())
  154. return reinterpret_cast<NextTy *>(alignAddr(Ptr, Align::Of<NextTy>()));
  155. else
  156. return reinterpret_cast<NextTy *>(Ptr);
  157. }
  158. // Helper function for TrailingObjects::additionalSizeToAlloc: this
  159. // function recurses to superclasses, each of which requires one
  160. // fewer size_t argument, and adds its own size.
  161. static constexpr size_t additionalSizeToAllocImpl(
  162. size_t SizeSoFar, size_t Count1,
  163. typename ExtractSecondType<MoreTys, size_t>::type... MoreCounts) {
  164. return ParentType::additionalSizeToAllocImpl(
  165. (requiresRealignment() ? llvm::alignTo<alignof(NextTy)>(SizeSoFar)
  166. : SizeSoFar) +
  167. sizeof(NextTy) * Count1,
  168. MoreCounts...);
  169. }
  170. };
  171. // The base case of the TrailingObjectsImpl inheritance recursion,
  172. // when there's no more trailing types.
  173. template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy>
  174. class alignas(Align) TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy>
  175. : public TrailingObjectsBase {
  176. protected:
  177. // This is a dummy method, only here so the "using" doesn't fail --
  178. // it will never be called, because this function recurses backwards
  179. // up the inheritance chain to subclasses.
  180. static void getTrailingObjectsImpl();
  181. static constexpr size_t additionalSizeToAllocImpl(size_t SizeSoFar) {
  182. return SizeSoFar;
  183. }
  184. template <bool CheckAlignment> static void verifyTrailingObjectsAlignment() {}
  185. };
  186. } // end namespace trailing_objects_internal
  187. // Finally, the main type defined in this file, the one intended for users...
  188. /// See the file comment for details on the usage of the
  189. /// TrailingObjects type.
  190. template <typename BaseTy, typename... TrailingTys>
  191. class TrailingObjects : private trailing_objects_internal::TrailingObjectsImpl<
  192. trailing_objects_internal::AlignmentCalcHelper<
  193. TrailingTys...>::Alignment,
  194. BaseTy, TrailingObjects<BaseTy, TrailingTys...>,
  195. BaseTy, TrailingTys...> {
  196. template <int A, typename B, typename T, typename P, typename... M>
  197. friend class trailing_objects_internal::TrailingObjectsImpl;
  198. template <typename... Tys> class Foo {};
  199. typedef trailing_objects_internal::TrailingObjectsImpl<
  200. trailing_objects_internal::AlignmentCalcHelper<TrailingTys...>::Alignment,
  201. BaseTy, TrailingObjects<BaseTy, TrailingTys...>, BaseTy, TrailingTys...>
  202. ParentType;
  203. using TrailingObjectsBase = trailing_objects_internal::TrailingObjectsBase;
  204. using ParentType::getTrailingObjectsImpl;
  205. // This function contains only a static_assert BaseTy is final. The
  206. // static_assert must be in a function, and not at class-level
  207. // because BaseTy isn't complete at class instantiation time, but
  208. // will be by the time this function is instantiated.
  209. static void verifyTrailingObjectsAssertions() {
  210. static_assert(std::is_final<BaseTy>(), "BaseTy must be final.");
  211. }
  212. // These two methods are the base of the recursion for this method.
  213. static const BaseTy *
  214. getTrailingObjectsImpl(const BaseTy *Obj,
  215. TrailingObjectsBase::OverloadToken<BaseTy>) {
  216. return Obj;
  217. }
  218. static BaseTy *
  219. getTrailingObjectsImpl(BaseTy *Obj,
  220. TrailingObjectsBase::OverloadToken<BaseTy>) {
  221. return Obj;
  222. }
  223. // callNumTrailingObjects simply calls numTrailingObjects on the
  224. // provided Obj -- except when the type being queried is BaseTy
  225. // itself. There is always only one of the base object, so that case
  226. // is handled here. (An additional benefit of indirecting through
  227. // this function is that consumers only say "friend
  228. // TrailingObjects", and thus, only this class itself can call the
  229. // numTrailingObjects function.)
  230. static size_t
  231. callNumTrailingObjects(const BaseTy *Obj,
  232. TrailingObjectsBase::OverloadToken<BaseTy>) {
  233. return 1;
  234. }
  235. template <typename T>
  236. static size_t callNumTrailingObjects(const BaseTy *Obj,
  237. TrailingObjectsBase::OverloadToken<T>) {
  238. return Obj->numTrailingObjects(TrailingObjectsBase::OverloadToken<T>());
  239. }
  240. public:
  241. // Make this (privately inherited) member public.
  242. #ifndef _MSC_VER
  243. using ParentType::OverloadToken;
  244. #else
  245. // An MSVC bug prevents the above from working, (last tested at CL version
  246. // 19.28). "Class5" in TrailingObjectsTest.cpp tests the problematic case.
  247. template <typename T>
  248. using OverloadToken = typename ParentType::template OverloadToken<T>;
  249. #endif
  250. /// Returns a pointer to the trailing object array of the given type
  251. /// (which must be one of those specified in the class template). The
  252. /// array may have zero or more elements in it.
  253. template <typename T> const T *getTrailingObjects() const {
  254. verifyTrailingObjectsAssertions();
  255. // Forwards to an impl function with overloads, since member
  256. // function templates can't be specialized.
  257. return this->getTrailingObjectsImpl(
  258. static_cast<const BaseTy *>(this),
  259. TrailingObjectsBase::OverloadToken<T>());
  260. }
  261. /// Returns a pointer to the trailing object array of the given type
  262. /// (which must be one of those specified in the class template). The
  263. /// array may have zero or more elements in it.
  264. template <typename T> T *getTrailingObjects() {
  265. verifyTrailingObjectsAssertions();
  266. // Forwards to an impl function with overloads, since member
  267. // function templates can't be specialized.
  268. return this->getTrailingObjectsImpl(
  269. static_cast<BaseTy *>(this), TrailingObjectsBase::OverloadToken<T>());
  270. }
  271. /// Returns the size of the trailing data, if an object were
  272. /// allocated with the given counts (The counts are in the same order
  273. /// as the template arguments). This does not include the size of the
  274. /// base object. The template arguments must be the same as those
  275. /// used in the class; they are supplied here redundantly only so
  276. /// that it's clear what the counts are counting in callers.
  277. template <typename... Tys>
  278. static constexpr std::enable_if_t<
  279. std::is_same<Foo<TrailingTys...>, Foo<Tys...>>::value, size_t>
  280. additionalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
  281. TrailingTys, size_t>::type... Counts) {
  282. return ParentType::additionalSizeToAllocImpl(0, Counts...);
  283. }
  284. /// Returns the total size of an object if it were allocated with the
  285. /// given trailing object counts. This is the same as
  286. /// additionalSizeToAlloc, except it *does* include the size of the base
  287. /// object.
  288. template <typename... Tys>
  289. static constexpr std::enable_if_t<
  290. std::is_same<Foo<TrailingTys...>, Foo<Tys...>>::value, size_t>
  291. totalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
  292. TrailingTys, size_t>::type... Counts) {
  293. return sizeof(BaseTy) + ParentType::additionalSizeToAllocImpl(0, Counts...);
  294. }
  295. TrailingObjects() = default;
  296. TrailingObjects(const TrailingObjects &) = delete;
  297. TrailingObjects(TrailingObjects &&) = delete;
  298. TrailingObjects &operator=(const TrailingObjects &) = delete;
  299. TrailingObjects &operator=(TrailingObjects &&) = delete;
  300. /// A type where its ::with_counts template member has a ::type member
  301. /// suitable for use as uninitialized storage for an object with the given
  302. /// trailing object counts. The template arguments are similar to those
  303. /// of additionalSizeToAlloc.
  304. ///
  305. /// Use with FixedSizeStorageOwner, e.g.:
  306. ///
  307. /// \code{.cpp}
  308. ///
  309. /// MyObj::FixedSizeStorage<void *>::with_counts<1u>::type myStackObjStorage;
  310. /// MyObj::FixedSizeStorageOwner
  311. /// myStackObjOwner(new ((void *)&myStackObjStorage) MyObj);
  312. /// MyObj *const myStackObjPtr = myStackObjOwner.get();
  313. ///
  314. /// \endcode
  315. template <typename... Tys> struct FixedSizeStorage {
  316. template <size_t... Counts> struct with_counts {
  317. enum { Size = totalSizeToAlloc<Tys...>(Counts...) };
  318. struct type {
  319. alignas(BaseTy) char buffer[Size];
  320. };
  321. };
  322. };
  323. /// A type that acts as the owner for an object placed into fixed storage.
  324. class FixedSizeStorageOwner {
  325. public:
  326. FixedSizeStorageOwner(BaseTy *p) : p(p) {}
  327. ~FixedSizeStorageOwner() {
  328. assert(p && "FixedSizeStorageOwner owns null?");
  329. p->~BaseTy();
  330. }
  331. BaseTy *get() { return p; }
  332. const BaseTy *get() const { return p; }
  333. private:
  334. FixedSizeStorageOwner(const FixedSizeStorageOwner &) = delete;
  335. FixedSizeStorageOwner(FixedSizeStorageOwner &&) = delete;
  336. FixedSizeStorageOwner &operator=(const FixedSizeStorageOwner &) = delete;
  337. FixedSizeStorageOwner &operator=(FixedSizeStorageOwner &&) = delete;
  338. BaseTy *const p;
  339. };
  340. };
  341. } // end namespace llvm
  342. #endif
  343. #ifdef __GNUC__
  344. #pragma GCC diagnostic pop
  345. #endif