Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:34

0001 //===--- TrailingObjects.h - Variable-length classes ------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 ///
0009 /// \file
0010 /// This header defines support for implementing classes that have
0011 /// some trailing object (or arrays of objects) appended to them. The
0012 /// main purpose is to make it obvious where this idiom is being used,
0013 /// and to make the usage more idiomatic and more difficult to get
0014 /// wrong.
0015 ///
0016 /// The TrailingObject template abstracts away the reinterpret_cast,
0017 /// pointer arithmetic, and size calculations used for the allocation
0018 /// and access of appended arrays of objects, and takes care that they
0019 /// are all allocated at their required alignment. Additionally, it
0020 /// ensures that the base type is final -- deriving from a class that
0021 /// expects data appended immediately after it is typically not safe.
0022 ///
0023 /// Users are expected to derive from this template, and provide
0024 /// numTrailingObjects implementations for each trailing type except
0025 /// the last, e.g. like this sample:
0026 ///
0027 /// \code
0028 /// class VarLengthObj : private TrailingObjects<VarLengthObj, int, double> {
0029 ///   friend TrailingObjects;
0030 ///
0031 ///   unsigned NumInts, NumDoubles;
0032 ///   size_t numTrailingObjects(OverloadToken<int>) const { return NumInts; }
0033 ///  };
0034 /// \endcode
0035 ///
0036 /// You can access the appended arrays via 'getTrailingObjects', and
0037 /// determine the size needed for allocation via
0038 /// 'additionalSizeToAlloc' and 'totalSizeToAlloc'.
0039 ///
0040 /// All the methods implemented by this class are intended for use
0041 /// by the implementation of the class, not as part of its interface
0042 /// (thus, private inheritance is suggested).
0043 ///
0044 //===----------------------------------------------------------------------===//
0045 
0046 #ifndef LLVM_SUPPORT_TRAILINGOBJECTS_H
0047 #define LLVM_SUPPORT_TRAILINGOBJECTS_H
0048 
0049 #include "llvm/Support/AlignOf.h"
0050 #include "llvm/Support/Alignment.h"
0051 #include "llvm/Support/Compiler.h"
0052 #include "llvm/Support/MathExtras.h"
0053 #include "llvm/Support/type_traits.h"
0054 #include <new>
0055 #include <type_traits>
0056 
0057 namespace llvm {
0058 
0059 namespace trailing_objects_internal {
0060 /// Helper template to calculate the max alignment requirement for a set of
0061 /// objects.
0062 template <typename First, typename... Rest> class AlignmentCalcHelper {
0063 private:
0064   enum {
0065     FirstAlignment = alignof(First),
0066     RestAlignment = AlignmentCalcHelper<Rest...>::Alignment,
0067   };
0068 
0069 public:
0070   enum {
0071     Alignment = FirstAlignment > RestAlignment ? FirstAlignment : RestAlignment
0072   };
0073 };
0074 
0075 template <typename First> class AlignmentCalcHelper<First> {
0076 public:
0077   enum { Alignment = alignof(First) };
0078 };
0079 
0080 /// The base class for TrailingObjects* classes.
0081 class TrailingObjectsBase {
0082 protected:
0083   /// OverloadToken's purpose is to allow specifying function overloads
0084   /// for different types, without actually taking the types as
0085   /// parameters. (Necessary because member function templates cannot
0086   /// be specialized, so overloads must be used instead of
0087   /// specialization.)
0088   template <typename T> struct OverloadToken {};
0089 };
0090 
0091 // Just a little helper for transforming a type pack into the same
0092 // number of a different type. e.g.:
0093 //   ExtractSecondType<Foo..., int>::type
0094 template <typename Ty1, typename Ty2> struct ExtractSecondType {
0095   typedef Ty2 type;
0096 };
0097 
0098 // TrailingObjectsImpl is somewhat complicated, because it is a
0099 // recursively inheriting template, in order to handle the template
0100 // varargs. Each level of inheritance picks off a single trailing type
0101 // then recurses on the rest. The "Align", "BaseTy", and
0102 // "TopTrailingObj" arguments are passed through unchanged through the
0103 // recursion. "PrevTy" is, at each level, the type handled by the
0104 // level right above it.
0105 
0106 template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
0107           typename... MoreTys>
0108 class TrailingObjectsImpl {
0109   // The main template definition is never used -- the two
0110   // specializations cover all possibilities.
0111 };
0112 
0113 template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
0114           typename NextTy, typename... MoreTys>
0115 class TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy, NextTy,
0116                           MoreTys...>
0117     : public TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy,
0118                                  MoreTys...> {
0119 
0120   typedef TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy, MoreTys...>
0121       ParentType;
0122 
0123   struct RequiresRealignment {
0124     static const bool value = alignof(PrevTy) < alignof(NextTy);
0125   };
0126 
0127   static constexpr bool requiresRealignment() {
0128     return RequiresRealignment::value;
0129   }
0130 
0131 protected:
0132   // Ensure the inherited getTrailingObjectsImpl is not hidden.
0133   using ParentType::getTrailingObjectsImpl;
0134 
0135   // These two functions are helper functions for
0136   // TrailingObjects::getTrailingObjects. They recurse to the left --
0137   // the result for each type in the list of trailing types depends on
0138   // the result of calling the function on the type to the
0139   // left. However, the function for the type to the left is
0140   // implemented by a *subclass* of this class, so we invoke it via
0141   // the TopTrailingObj, which is, via the
0142   // curiously-recurring-template-pattern, the most-derived type in
0143   // this recursion, and thus, contains all the overloads.
0144   static const NextTy *
0145   getTrailingObjectsImpl(const BaseTy *Obj,
0146                          TrailingObjectsBase::OverloadToken<NextTy>) {
0147     auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
0148                     Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
0149                 TopTrailingObj::callNumTrailingObjects(
0150                     Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
0151 
0152     if (requiresRealignment())
0153       return reinterpret_cast<const NextTy *>(
0154           alignAddr(Ptr, Align::Of<NextTy>()));
0155     else
0156       return reinterpret_cast<const NextTy *>(Ptr);
0157   }
0158 
0159   static NextTy *
0160   getTrailingObjectsImpl(BaseTy *Obj,
0161                          TrailingObjectsBase::OverloadToken<NextTy>) {
0162     auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
0163                     Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
0164                 TopTrailingObj::callNumTrailingObjects(
0165                     Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
0166 
0167     if (requiresRealignment())
0168       return reinterpret_cast<NextTy *>(alignAddr(Ptr, Align::Of<NextTy>()));
0169     else
0170       return reinterpret_cast<NextTy *>(Ptr);
0171   }
0172 
0173   // Helper function for TrailingObjects::additionalSizeToAlloc: this
0174   // function recurses to superclasses, each of which requires one
0175   // fewer size_t argument, and adds its own size.
0176   static constexpr size_t additionalSizeToAllocImpl(
0177       size_t SizeSoFar, size_t Count1,
0178       typename ExtractSecondType<MoreTys, size_t>::type... MoreCounts) {
0179     return ParentType::additionalSizeToAllocImpl(
0180         (requiresRealignment() ? llvm::alignTo<alignof(NextTy)>(SizeSoFar)
0181                                : SizeSoFar) +
0182             sizeof(NextTy) * Count1,
0183         MoreCounts...);
0184   }
0185 };
0186 
0187 // The base case of the TrailingObjectsImpl inheritance recursion,
0188 // when there's no more trailing types.
0189 template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy>
0190 class alignas(Align) TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy>
0191     : public TrailingObjectsBase {
0192 protected:
0193   // This is a dummy method, only here so the "using" doesn't fail --
0194   // it will never be called, because this function recurses backwards
0195   // up the inheritance chain to subclasses.
0196   static void getTrailingObjectsImpl();
0197 
0198   static constexpr size_t additionalSizeToAllocImpl(size_t SizeSoFar) {
0199     return SizeSoFar;
0200   }
0201 
0202   template <bool CheckAlignment> static void verifyTrailingObjectsAlignment() {}
0203 };
0204 
0205 } // end namespace trailing_objects_internal
0206 
0207 // Finally, the main type defined in this file, the one intended for users...
0208 
0209 /// See the file comment for details on the usage of the
0210 /// TrailingObjects type.
0211 template <typename BaseTy, typename... TrailingTys>
0212 class TrailingObjects : private trailing_objects_internal::TrailingObjectsImpl<
0213                             trailing_objects_internal::AlignmentCalcHelper<
0214                                 TrailingTys...>::Alignment,
0215                             BaseTy, TrailingObjects<BaseTy, TrailingTys...>,
0216                             BaseTy, TrailingTys...> {
0217 
0218   template <int A, typename B, typename T, typename P, typename... M>
0219   friend class trailing_objects_internal::TrailingObjectsImpl;
0220 
0221   template <typename... Tys> class Foo {};
0222 
0223   typedef trailing_objects_internal::TrailingObjectsImpl<
0224       trailing_objects_internal::AlignmentCalcHelper<TrailingTys...>::Alignment,
0225       BaseTy, TrailingObjects<BaseTy, TrailingTys...>, BaseTy, TrailingTys...>
0226       ParentType;
0227   using TrailingObjectsBase = trailing_objects_internal::TrailingObjectsBase;
0228 
0229   using ParentType::getTrailingObjectsImpl;
0230 
0231   // This function contains only a static_assert BaseTy is final. The
0232   // static_assert must be in a function, and not at class-level
0233   // because BaseTy isn't complete at class instantiation time, but
0234   // will be by the time this function is instantiated.
0235   static void verifyTrailingObjectsAssertions() {
0236     static_assert(std::is_final<BaseTy>(), "BaseTy must be final.");
0237   }
0238 
0239   // These two methods are the base of the recursion for this method.
0240   static const BaseTy *
0241   getTrailingObjectsImpl(const BaseTy *Obj,
0242                          TrailingObjectsBase::OverloadToken<BaseTy>) {
0243     return Obj;
0244   }
0245 
0246   static BaseTy *
0247   getTrailingObjectsImpl(BaseTy *Obj,
0248                          TrailingObjectsBase::OverloadToken<BaseTy>) {
0249     return Obj;
0250   }
0251 
0252   // callNumTrailingObjects simply calls numTrailingObjects on the
0253   // provided Obj -- except when the type being queried is BaseTy
0254   // itself. There is always only one of the base object, so that case
0255   // is handled here. (An additional benefit of indirecting through
0256   // this function is that consumers only say "friend
0257   // TrailingObjects", and thus, only this class itself can call the
0258   // numTrailingObjects function.)
0259   static size_t
0260   callNumTrailingObjects(const BaseTy *Obj,
0261                          TrailingObjectsBase::OverloadToken<BaseTy>) {
0262     return 1;
0263   }
0264 
0265   template <typename T>
0266   static size_t callNumTrailingObjects(const BaseTy *Obj,
0267                                        TrailingObjectsBase::OverloadToken<T>) {
0268     return Obj->numTrailingObjects(TrailingObjectsBase::OverloadToken<T>());
0269   }
0270 
0271 public:
0272   // Make this (privately inherited) member public.
0273 #ifndef _MSC_VER
0274   using ParentType::OverloadToken;
0275 #else
0276   // An MSVC bug prevents the above from working, (last tested at CL version
0277   // 19.28). "Class5" in TrailingObjectsTest.cpp tests the problematic case.
0278   template <typename T>
0279   using OverloadToken = typename ParentType::template OverloadToken<T>;
0280 #endif
0281 
0282   /// Returns a pointer to the trailing object array of the given type
0283   /// (which must be one of those specified in the class template). The
0284   /// array may have zero or more elements in it.
0285   template <typename T> const T *getTrailingObjects() const {
0286     verifyTrailingObjectsAssertions();
0287     // Forwards to an impl function with overloads, since member
0288     // function templates can't be specialized.
0289     return this->getTrailingObjectsImpl(
0290         static_cast<const BaseTy *>(this),
0291         TrailingObjectsBase::OverloadToken<T>());
0292   }
0293 
0294   /// Returns a pointer to the trailing object array of the given type
0295   /// (which must be one of those specified in the class template). The
0296   /// array may have zero or more elements in it.
0297   template <typename T> T *getTrailingObjects() {
0298     verifyTrailingObjectsAssertions();
0299     // Forwards to an impl function with overloads, since member
0300     // function templates can't be specialized.
0301     return this->getTrailingObjectsImpl(
0302         static_cast<BaseTy *>(this), TrailingObjectsBase::OverloadToken<T>());
0303   }
0304 
0305   /// Returns the size of the trailing data, if an object were
0306   /// allocated with the given counts (The counts are in the same order
0307   /// as the template arguments). This does not include the size of the
0308   /// base object.  The template arguments must be the same as those
0309   /// used in the class; they are supplied here redundantly only so
0310   /// that it's clear what the counts are counting in callers.
0311   template <typename... Tys>
0312   static constexpr std::enable_if_t<
0313       std::is_same_v<Foo<TrailingTys...>, Foo<Tys...>>, size_t>
0314   additionalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
0315                         TrailingTys, size_t>::type... Counts) {
0316     return ParentType::additionalSizeToAllocImpl(0, Counts...);
0317   }
0318 
0319   /// Returns the total size of an object if it were allocated with the
0320   /// given trailing object counts. This is the same as
0321   /// additionalSizeToAlloc, except it *does* include the size of the base
0322   /// object.
0323   template <typename... Tys>
0324   static constexpr std::enable_if_t<
0325       std::is_same_v<Foo<TrailingTys...>, Foo<Tys...>>, size_t>
0326   totalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
0327                    TrailingTys, size_t>::type... Counts) {
0328     return sizeof(BaseTy) + ParentType::additionalSizeToAllocImpl(0, Counts...);
0329   }
0330 
0331   TrailingObjects() = default;
0332   TrailingObjects(const TrailingObjects &) = delete;
0333   TrailingObjects(TrailingObjects &&) = delete;
0334   TrailingObjects &operator=(const TrailingObjects &) = delete;
0335   TrailingObjects &operator=(TrailingObjects &&) = delete;
0336 
0337   /// A type where its ::with_counts template member has a ::type member
0338   /// suitable for use as uninitialized storage for an object with the given
0339   /// trailing object counts. The template arguments are similar to those
0340   /// of additionalSizeToAlloc.
0341   ///
0342   /// Use with FixedSizeStorageOwner, e.g.:
0343   ///
0344   /// \code{.cpp}
0345   ///
0346   /// MyObj::FixedSizeStorage<void *>::with_counts<1u>::type myStackObjStorage;
0347   /// MyObj::FixedSizeStorageOwner
0348   ///     myStackObjOwner(new ((void *)&myStackObjStorage) MyObj);
0349   /// MyObj *const myStackObjPtr = myStackObjOwner.get();
0350   ///
0351   /// \endcode
0352   template <typename... Tys> struct FixedSizeStorage {
0353     template <size_t... Counts> struct with_counts {
0354       enum { Size = totalSizeToAlloc<Tys...>(Counts...) };
0355       struct type {
0356         alignas(BaseTy) char buffer[Size];
0357       };
0358     };
0359   };
0360 
0361   /// A type that acts as the owner for an object placed into fixed storage.
0362   class FixedSizeStorageOwner {
0363   public:
0364     FixedSizeStorageOwner(BaseTy *p) : p(p) {}
0365     ~FixedSizeStorageOwner() {
0366       assert(p && "FixedSizeStorageOwner owns null?");
0367       p->~BaseTy();
0368     }
0369 
0370     BaseTy *get() { return p; }
0371     const BaseTy *get() const { return p; }
0372 
0373   private:
0374     FixedSizeStorageOwner(const FixedSizeStorageOwner &) = delete;
0375     FixedSizeStorageOwner(FixedSizeStorageOwner &&) = delete;
0376     FixedSizeStorageOwner &operator=(const FixedSizeStorageOwner &) = delete;
0377     FixedSizeStorageOwner &operator=(FixedSizeStorageOwner &&) = delete;
0378 
0379     BaseTy *const p;
0380   };
0381 };
0382 
0383 } // end namespace llvm
0384 
0385 #endif