LLVM 22.0.0git
TrailingObjects.h
Go to the documentation of this file.
1//===--- TrailingObjects.h - Variable-length classes ------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This header defines support for implementing classes that have
11/// some trailing object (or arrays of objects) appended to them. The
12/// main purpose is to make it obvious where this idiom is being used,
13/// and to make the usage more idiomatic and more difficult to get
14/// wrong.
15///
16/// The TrailingObject template abstracts away the reinterpret_cast,
17/// pointer arithmetic, and size calculations used for the allocation
18/// and access of appended arrays of objects, and takes care that they
19/// are all allocated at their required alignment. Additionally, it
20/// ensures that the base type is final -- deriving from a class that
21/// expects data appended immediately after it is typically not safe.
22///
23/// Users are expected to derive from this template, and provide
24/// numTrailingObjects implementations for each trailing type except
25/// the last, e.g. like this sample:
26///
27/// \code
28/// class VarLengthObj : private TrailingObjects<VarLengthObj, int, double> {
29/// friend TrailingObjects;
30///
31/// unsigned NumInts, NumDoubles;
32/// size_t numTrailingObjects(OverloadToken<int>) const { return NumInts; }
33/// };
34/// \endcode
35///
36/// You can access the appended arrays via 'getTrailingObjects', and
37/// determine the size needed for allocation via
38/// 'additionalSizeToAlloc' and 'totalSizeToAlloc'.
39///
40/// All the methods implemented by this class are intended for use
41/// by the implementation of the class, not as part of its interface
42/// (thus, private inheritance is suggested).
43///
44//===----------------------------------------------------------------------===//
45
46#ifndef LLVM_SUPPORT_TRAILINGOBJECTS_H
47#define LLVM_SUPPORT_TRAILINGOBJECTS_H
48
49#include "llvm/ADT/ArrayRef.h"
54#include <new>
55#include <type_traits>
56
57namespace llvm {
58
60
61template <typename... T>
62inline constexpr size_t MaxAlignment = std::max({alignof(T)...});
63
64/// The base class for TrailingObjects* classes.
66protected:
67 /// OverloadToken's purpose is to allow specifying function overloads
68 /// for different types, without actually taking the types as
69 /// parameters. (Necessary because member function templates cannot
70 /// be specialized, so overloads must be used instead of
71 /// specialization.)
72 template <typename T> struct OverloadToken {};
73};
74
75// Just a little helper for transforming a type pack into the same
76// number of a different type. e.g.:
77// ExtractSecondType<Foo..., int>::type
78template <typename Ty1, typename Ty2> struct ExtractSecondType {
79 typedef Ty2 type;
80};
81
82// TrailingObjectsImpl is somewhat complicated, because it is a
83// recursively inheriting template, in order to handle the template
84// varargs. Each level of inheritance picks off a single trailing type
85// then recurses on the rest. The "Align", "BaseTy", and
86// "TopTrailingObj" arguments are passed through unchanged through the
87// recursion. "PrevTy" is, at each level, the type handled by the
88// level right above it.
89
90template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
91 typename... MoreTys>
93 // The main template definition is never used -- the two
94 // specializations cover all possibilities.
95};
96
97template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
98 typename NextTy, typename... MoreTys>
99class TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy, NextTy,
100 MoreTys...>
101 : public TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy,
102 MoreTys...> {
103
104 typedef TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy, MoreTys...>
105 ParentType;
106
107 struct RequiresRealignment {
108 static const bool value = alignof(PrevTy) < alignof(NextTy);
109 };
110
111 static constexpr bool requiresRealignment() {
112 return RequiresRealignment::value;
113 }
114
115protected:
116 // Ensure the inherited getTrailingObjectsImpl is not hidden.
117 using ParentType::getTrailingObjectsImpl;
118
119 // These two functions are helper functions for
120 // TrailingObjects::getTrailingObjects. They recurse to the left --
121 // the result for each type in the list of trailing types depends on
122 // the result of calling the function on the type to the
123 // left. However, the function for the type to the left is
124 // implemented by a *subclass* of this class, so we invoke it via
125 // the TopTrailingObj, which is, via the
126 // curiously-recurring-template-pattern, the most-derived type in
127 // this recursion, and thus, contains all the overloads.
128 static const NextTy *
129 getTrailingObjectsImpl(const BaseTy *Obj,
131 auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
133 TopTrailingObj::callNumTrailingObjects(
135
136 if (requiresRealignment())
137 return reinterpret_cast<const NextTy *>(
139 else
140 return reinterpret_cast<const NextTy *>(Ptr);
141 }
142
143 static NextTy *
146 auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
148 TopTrailingObj::callNumTrailingObjects(
150
151 if (requiresRealignment())
152 return reinterpret_cast<NextTy *>(alignAddr(Ptr, Align::Of<NextTy>()));
153 else
154 return reinterpret_cast<NextTy *>(Ptr);
155 }
156
157 // Helper function for TrailingObjects::additionalSizeToAlloc: this
158 // function recurses to superclasses, each of which requires one
159 // fewer size_t argument, and adds its own size.
160 static constexpr size_t additionalSizeToAllocImpl(
161 size_t SizeSoFar, size_t Count1,
162 typename ExtractSecondType<MoreTys, size_t>::type... MoreCounts) {
163 return ParentType::additionalSizeToAllocImpl(
164 (requiresRealignment() ? llvm::alignTo<alignof(NextTy)>(SizeSoFar)
165 : SizeSoFar) +
166 sizeof(NextTy) * Count1,
167 MoreCounts...);
168 }
169};
170
171// The base case of the TrailingObjectsImpl inheritance recursion,
172// when there's no more trailing types.
173template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy>
174class alignas(Align) TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy>
175 : public TrailingObjectsBase {
176protected:
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.
181
182 static constexpr size_t additionalSizeToAllocImpl(size_t SizeSoFar) {
183 return SizeSoFar;
184 }
185
186 template <bool CheckAlignment> static void verifyTrailingObjectsAlignment() {}
187};
188
189} // end namespace trailing_objects_internal
190
191// Finally, the main type defined in this file, the one intended for users...
192
193/// See the file comment for details on the usage of the
194/// TrailingObjects type.
195template <typename BaseTy, typename... TrailingTys>
198 trailing_objects_internal::MaxAlignment<TrailingTys...>, BaseTy,
199 TrailingObjects<BaseTy, TrailingTys...>, BaseTy, TrailingTys...> {
200
201 template <int A, typename B, typename T, typename P, typename... M>
203
204 template <typename... Tys> class Foo {};
205
207 trailing_objects_internal::MaxAlignment<TrailingTys...>, BaseTy,
208 TrailingObjects<BaseTy, TrailingTys...>, BaseTy, TrailingTys...>
209 ParentType;
210 using TrailingObjectsBase = trailing_objects_internal::TrailingObjectsBase;
211
212 using ParentType::getTrailingObjectsImpl;
213
214 template <bool Strict> static void verifyTrailingObjectsAssertions() {
215 // The static_assert for BaseTy must be in a function, and not at
216 // class-level because BaseTy isn't complete at class instantiation time,
217 // but will be by the time this function is instantiated.
218 static_assert(std::is_final<BaseTy>(), "BaseTy must be final.");
219
220 // Verify that templated getTrailingObjects() is used only with multiple
221 // trailing types. Use getTrailingObjectsNonStrict() which does not check
222 // this.
223 static_assert(!Strict || sizeof...(TrailingTys) > 1,
224 "Use templated getTrailingObjects() only when there are "
225 "multiple trailing types");
226 }
227
228 // These two methods are the base of the recursion for this method.
229 static const BaseTy *
230 getTrailingObjectsImpl(const BaseTy *Obj,
231 TrailingObjectsBase::OverloadToken<BaseTy>) {
232 return Obj;
233 }
234
235 static BaseTy *
236 getTrailingObjectsImpl(BaseTy *Obj,
237 TrailingObjectsBase::OverloadToken<BaseTy>) {
238 return Obj;
239 }
240
241 // callNumTrailingObjects simply calls numTrailingObjects on the
242 // provided Obj -- except when the type being queried is BaseTy
243 // itself. There is always only one of the base object, so that case
244 // is handled here. (An additional benefit of indirecting through
245 // this function is that consumers only say "friend
246 // TrailingObjects", and thus, only this class itself can call the
247 // numTrailingObjects function.)
248 static size_t
249 callNumTrailingObjects(const BaseTy *Obj,
250 TrailingObjectsBase::OverloadToken<BaseTy>) {
251 return 1;
252 }
253
254 template <typename T>
255 static size_t callNumTrailingObjects(const BaseTy *Obj,
256 TrailingObjectsBase::OverloadToken<T>) {
257 return Obj->numTrailingObjects(TrailingObjectsBase::OverloadToken<T>());
258 }
259
260public:
261 // Make this (privately inherited) member public.
262#ifndef _MSC_VER
263 using ParentType::OverloadToken;
264#else
265 // An MSVC bug prevents the above from working, (last tested at CL version
266 // 19.28). "Class5" in TrailingObjectsTest.cpp tests the problematic case.
267 template <typename T>
268 using OverloadToken = typename ParentType::template OverloadToken<T>;
269#endif
270
271 /// Returns a pointer to the trailing object array of the given type
272 /// (which must be one of those specified in the class template). The
273 /// array may have zero or more elements in it.
274 template <typename T> const T *getTrailingObjects() const {
275 verifyTrailingObjectsAssertions<true>();
276 // Forwards to an impl function with overloads, since member
277 // function templates can't be specialized.
278 return this->getTrailingObjectsImpl(
279 static_cast<const BaseTy *>(this),
281 }
282
283 /// Returns a pointer to the trailing object array of the given type
284 /// (which must be one of those specified in the class template). The
285 /// array may have zero or more elements in it.
286 template <typename T> T *getTrailingObjects() {
287 return const_cast<T *>(
288 static_cast<const TrailingObjects *>(this)->getTrailingObjects<T>());
289 }
290
291 // getTrailingObjects() specialization for a single trailing type.
293 typename std::tuple_element_t<0, std::tuple<TrailingTys...>>;
294
296 static_assert(sizeof...(TrailingTys) == 1,
297 "Can use non-templated getTrailingObjects() only when there "
298 "is a single trailing type");
299 verifyTrailingObjectsAssertions<false>();
300 return this->getTrailingObjectsImpl(
301 static_cast<const BaseTy *>(this),
303 }
304
306 return const_cast<FirstTrailingType *>(
307 static_cast<const TrailingObjects *>(this)->getTrailingObjects());
308 }
309
310 // Functions that return the trailing objects as ArrayRefs.
311 template <typename T> MutableArrayRef<T> getTrailingObjects(size_t N) {
313 }
314
315 template <typename T> ArrayRef<T> getTrailingObjects(size_t N) const {
317 }
318
322
326
327 // Non-strict forms of templated `getTrailingObjects` that work with single
328 // trailing type.
329 template <typename T> const T *getTrailingObjectsNonStrict() const {
330 verifyTrailingObjectsAssertions<false>();
331 return this->getTrailingObjectsImpl(
332 static_cast<const BaseTy *>(this),
334 }
335
336 template <typename T> T *getTrailingObjectsNonStrict() {
337 return const_cast<T *>(static_cast<const TrailingObjects *>(this)
338 ->getTrailingObjectsNonStrict<T>());
339 }
340
341 template <typename T>
345
346 template <typename T>
350
351 /// Returns the size of the trailing data, if an object were
352 /// allocated with the given counts (The counts are in the same order
353 /// as the template arguments). This does not include the size of the
354 /// base object. The template arguments must be the same as those
355 /// used in the class; they are supplied here redundantly only so
356 /// that it's clear what the counts are counting in callers.
357 template <typename... Tys>
358 static constexpr std::enable_if_t<
359 std::is_same_v<Foo<TrailingTys...>, Foo<Tys...>>, size_t>
361 TrailingTys, size_t>::type... Counts) {
362 return ParentType::additionalSizeToAllocImpl(0, Counts...);
363 }
364
365 /// Returns the total size of an object if it were allocated with the
366 /// given trailing object counts. This is the same as
367 /// additionalSizeToAlloc, except it *does* include the size of the base
368 /// object.
369 template <typename... Tys>
370 static constexpr std::enable_if_t<
371 std::is_same_v<Foo<TrailingTys...>, Foo<Tys...>>, size_t>
373 TrailingTys, size_t>::type... Counts) {
374 return sizeof(BaseTy) + ParentType::additionalSizeToAllocImpl(0, Counts...);
375 }
376
377 TrailingObjects() = default;
382
383 /// A type where its ::with_counts template member has a ::type member
384 /// suitable for use as uninitialized storage for an object with the given
385 /// trailing object counts. The template arguments are similar to those
386 /// of additionalSizeToAlloc.
387 ///
388 /// Use with FixedSizeStorageOwner, e.g.:
389 ///
390 /// \code{.cpp}
391 ///
392 /// MyObj::FixedSizeStorage<void *>::with_counts<1u>::type myStackObjStorage;
393 /// MyObj::FixedSizeStorageOwner
394 /// myStackObjOwner(new ((void *)&myStackObjStorage) MyObj);
395 /// MyObj *const myStackObjPtr = myStackObjOwner.get();
396 ///
397 /// \endcode
398 template <typename... Tys> struct FixedSizeStorage {
399 template <size_t... Counts> struct with_counts {
400 enum { Size = totalSizeToAlloc<Tys...>(Counts...) };
401 struct type {
402 alignas(BaseTy) char buffer[Size];
403 };
404 };
405 };
406
407 /// A type that acts as the owner for an object placed into fixed storage.
409 public:
410 FixedSizeStorageOwner(BaseTy *p) : p(p) {}
412 assert(p && "FixedSizeStorageOwner owns null?");
413 p->~BaseTy();
414 }
415
416 BaseTy *get() { return p; }
417 const BaseTy *get() const { return p; }
418
419 private:
424
425 BaseTy *const p;
426 };
427};
428
429} // end namespace llvm
430
431#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define T
#define P(N)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition ArrayRef.h:303
A type that acts as the owner for an object placed into fixed storage.
See the file comment for details on the usage of the TrailingObjects type.
TrailingObjects & operator=(TrailingObjects &&)=delete
const FirstTrailingType * getTrailingObjects() const
MutableArrayRef< T > getTrailingObjects(size_t N)
const T * getTrailingObjectsNonStrict() const
static constexpr std::enable_if_t< std::is_same_v< Foo< TrailingTys... >, Foo< Tys... > >, size_t > totalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType< TrailingTys, size_t >::type... Counts)
Returns the total size of an object if it were allocated with the given trailing object counts.
TrailingObjects & operator=(const TrailingObjects &)=delete
FirstTrailingType * getTrailingObjects()
ArrayRef< FirstTrailingType > getTrailingObjects(size_t N) const
ArrayRef< T > getTrailingObjectsNonStrict(size_t N) const
static constexpr std::enable_if_t< std::is_same_v< Foo< TrailingTys... >, Foo< Tys... > >, size_t > additionalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType< TrailingTys, size_t >::type... Counts)
Returns the size of the trailing data, if an object were allocated with the given counts (The counts ...
TrailingObjects(TrailingObjects &&)=delete
MutableArrayRef< T > getTrailingObjectsNonStrict(size_t N)
T * getTrailingObjects()
Returns a pointer to the trailing object array of the given type (which must be one of those specifie...
MutableArrayRef< FirstTrailingType > getTrailingObjects(size_t N)
const T * getTrailingObjects() const
Returns a pointer to the trailing object array of the given type (which must be one of those specifie...
ArrayRef< T > getTrailingObjects(size_t N) const
typename std::tuple_element_t< 0, std::tuple< TrailingTys... > > FirstTrailingType
TrailingObjects(const TrailingObjects &)=delete
The base class for TrailingObjects* classes.
static const NextTy * getTrailingObjectsImpl(const BaseTy *Obj, TrailingObjectsBase::OverloadToken< NextTy >)
static constexpr size_t additionalSizeToAllocImpl(size_t SizeSoFar, size_t Count1, typename ExtractSecondType< MoreTys, size_t >::type... MoreCounts)
static NextTy * getTrailingObjectsImpl(BaseTy *Obj, TrailingObjectsBase::OverloadToken< NextTy >)
This is an optimization pass for GlobalISel generic memory operations.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
uintptr_t alignAddr(const void *Addr, Align Alignment)
Aligns Addr to Alignment bytes, rounding up.
Definition Alignment.h:176
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static constexpr Align Of()
Allow constructions of constexpr Align from types.
Definition Alignment.h:94
A type where its with_counts template member has a type member suitable for use as uninitialized stor...
OverloadToken's purpose is to allow specifying function overloads for different types,...