LLVM 22.0.0git
FunctionExtras.h
Go to the documentation of this file.
1//===- FunctionExtras.h - Function type erasure utilities -------*- 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/// \file
9/// This file provides a collection of function (or more generally, callable)
10/// type erasure utilities supplementing those provided by the standard library
11/// in `<function>`.
12///
13/// It provides `unique_function`, which works like `std::function` but supports
14/// move-only callable objects and const-qualification.
15///
16/// Future plans:
17/// - Add a `function` that provides ref-qualified support, which doesn't work
18/// with `std::function`.
19/// - Provide support for specifying multiple signatures to type erase callable
20/// objects with an overload set, such as those produced by generic lambdas.
21/// - Expand to include a copyable utility that directly replaces std::function
22/// but brings the above improvements.
23///
24/// Note that LLVM's utilities are greatly simplified by not supporting
25/// allocators.
26///
27/// If the standard library ever begins to provide comparable facilities we can
28/// consider switching to those.
29///
30//===----------------------------------------------------------------------===//
31
32#ifndef LLVM_ADT_FUNCTIONEXTRAS_H
33#define LLVM_ADT_FUNCTIONEXTRAS_H
34
41#include <cstring>
42#include <memory>
43#include <type_traits>
44
45namespace llvm {
46
47/// unique_function is a type-erasing functor similar to std::function.
48///
49/// It can hold move-only function objects, like lambdas capturing unique_ptrs.
50/// Accordingly, it is movable but not copyable.
51///
52/// It supports const-qualification:
53/// - unique_function<int() const> has a const operator().
54/// It can only hold functions which themselves have a const operator().
55/// - unique_function<int()> has a non-const operator().
56/// It can hold functions with a non-const operator(), like mutable lambdas.
57template <typename FunctionT> class unique_function;
58
59namespace detail {
60
61template <typename T>
63 std::enable_if_t<std::is_trivially_move_constructible<T>::value &&
64 std::is_trivially_destructible<T>::value>;
65template <typename CallableT, typename ThisT>
67 std::enable_if_t<!std::is_same<remove_cvref_t<CallableT>, ThisT>::value>;
68template <typename CallableT, typename Ret, typename... Params>
69using EnableIfCallable = std::enable_if_t<std::disjunction<
70 std::is_void<Ret>,
71 std::is_same<decltype(std::declval<CallableT>()(std::declval<Params>()...)),
72 Ret>,
73 std::is_same<const decltype(std::declval<CallableT>()(
74 std::declval<Params>()...)),
75 Ret>,
76 std::is_convertible<decltype(std::declval<CallableT>()(
77 std::declval<Params>()...)),
78 Ret>>::value>;
79
80template <typename ReturnT, typename... ParamTs> class UniqueFunctionBase {
81protected:
82 static constexpr size_t InlineStorageSize = sizeof(void *) * 3;
83 static constexpr size_t InlineStorageAlign = alignof(void *);
84
85 // Provide a type function to map parameters that won't observe extra copies
86 // or moves and which are small enough to likely pass in register to values
87 // and all other types to l-value reference types. We use this to compute the
88 // types used in our erased call utility to minimize copies and moves unless
89 // doing so would force things unnecessarily into memory.
90 //
91 // The heuristic used is related to common ABI register passing conventions.
92 // It doesn't have to be exact though, and in one way it is more strict
93 // because we want to still be able to observe either moves *or* copies.
94 template <typename T> struct AdjustedParamTBase {
95 static_assert(!std::is_reference<T>::value,
96 "references should be handled by template specialization");
97 template <typename U>
99 std::bool_constant<sizeof(U) <= 2 * sizeof(void *)>;
100 using type =
101 std::conditional_t<std::is_trivially_copy_constructible<T>::value &&
102 std::is_trivially_move_constructible<T>::value &&
104 T, T &>;
105 };
106
107 // This specialization ensures that 'AdjustedParam<V<T>&>' or
108 // 'AdjustedParam<V<T>&&>' does not trigger a compile-time error when 'T' is
109 // an incomplete type and V a templated type.
110 template <typename T> struct AdjustedParamTBase<T &> { using type = T &; };
111 template <typename T> struct AdjustedParamTBase<T &&> { using type = T &; };
112
113 template <typename T>
115
116 // The type of the erased function pointer we use as a callback to dispatch to
117 // the stored callable when it is trivial to move and destroy.
118 using CallPtrT = ReturnT (*)(void *CallableAddr,
119 AdjustedParamT<ParamTs>... Params);
120 using MovePtrT = void (*)(void *LHSCallableAddr, void *RHSCallableAddr);
121 using DestroyPtrT = void (*)(void *CallableAddr);
122
123 /// A struct to hold a single trivial callback with sufficient alignment for
124 /// our bitpacking.
125 struct alignas(8) TrivialCallback {
127 };
128
129 /// A struct we use to aggregate three callbacks when we need full set of
130 /// operations.
136
137 // Create a pointer union between either a pointer to a static trivial call
138 // pointer in a struct or a pointer to a static struct of the call, move, and
139 // destroy pointers.
142
143 // The main storage buffer. This will either have a pointer to out-of-line
144 // storage or an inline buffer storing the callable.
146 // For out-of-line storage we keep a pointer to the underlying storage and
147 // the size. This is enough to deallocate the memory.
153 static_assert(
154 sizeof(OutOfLineStorageT) <= InlineStorageSize,
155 "Should always use all of the out-of-line storage for inline storage!");
156
157 // For in-line storage, we just provide an aligned character buffer. We
158 // provide three pointers worth of storage here.
159 // This is mutable as an inlined `const unique_function<void() const>` may
160 // still modify its own mutable members.
161 alignas(InlineStorageAlign) mutable std::byte
164
165 // A compressed pointer to either our dispatching callback or our table of
166 // dispatching callbacks and the flag for whether the callable itself is
167 // stored inline or not.
169
170 bool isInlineStorage() const { return CallbackAndInlineFlag.getInt(); }
171
172 bool isTrivialCallback() const {
174 }
175
177 return cast<TrivialCallback *>(CallbackAndInlineFlag.getPointer())->CallPtr;
178 }
179
180 NonTrivialCallbacks *getNonTrivialCallbacks() const {
182 }
183
188
189 // These three functions are only const in the narrow sense. They return
190 // mutable pointers to function state.
191 // This allows unique_function<T const>::operator() to be const, even if the
192 // underlying functor may be internally mutable.
193 //
194 // const callers must ensure they're only used in const-correct ways.
195 void *getCalleePtr() const {
197 }
198 void *getInlineStorage() const { return &StorageUnion.InlineStorage; }
199 void *getOutOfLineStorage() const {
200 return StorageUnion.OutOfLineStorage.StoragePtr;
201 }
202
203 size_t getOutOfLineStorageSize() const {
204 return StorageUnion.OutOfLineStorage.Size;
205 }
207 return StorageUnion.OutOfLineStorage.Alignment;
208 }
209
210 void setOutOfLineStorage(void *Ptr, size_t Size, size_t Alignment) {
211 StorageUnion.OutOfLineStorage = {Ptr, Size, Alignment};
212 }
213
214 template <typename CalledAsT>
215 static ReturnT CallImpl(void *CallableAddr,
216 AdjustedParamT<ParamTs>... Params) {
217 auto &Func = *reinterpret_cast<CalledAsT *>(CallableAddr);
218 return Func(std::forward<ParamTs>(Params)...);
219 }
220
221 template <typename CallableT>
222 static void MoveImpl(void *LHSCallableAddr, void *RHSCallableAddr) noexcept {
223 new (LHSCallableAddr)
224 CallableT(std::move(*reinterpret_cast<CallableT *>(RHSCallableAddr)));
225 }
226
227 template <typename CallableT>
228 static void DestroyImpl(void *CallableAddr) noexcept {
229 reinterpret_cast<CallableT *>(CallableAddr)->~CallableT();
230 }
231
232 // The pointers to call/move/destroy functions are determined for each
233 // callable type (and called-as type, which determines the overload chosen).
234 // (definitions are out-of-line).
235
236 // By default, we need an object that contains all the different
237 // type erased behaviors needed. Create a static instance of the struct type
238 // here and each instance will contain a pointer to it.
239 // Wrap in a struct to avoid https://gcc.gnu.org/PR71954
240 template <typename CallableT, typename CalledAs, typename Enable = void>
244 // See if we can create a trivial callback. We need the callable to be
245 // trivially moved and trivially destroyed so that we don't have to store
246 // type erased callbacks for those operations.
247 template <typename CallableT, typename CalledAs>
248 struct CallbacksHolder<CallableT, CalledAs, EnableIfTrivial<CallableT>> {
250 };
251
252 // A simple tag type so the call-as type to be passed to the constructor.
253 template <typename T> struct CalledAs {};
254
255 // Essentially the "main" unique_function constructor, but subclasses
256 // provide the qualified type to be used for the call.
257 // (We always store a T, even if the call will use a pointer to const T).
258 template <typename CallableT, typename CalledAsT>
259 UniqueFunctionBase(CallableT Callable, CalledAs<CalledAsT>) {
260 bool IsInlineStorage = true;
261 void *CallableAddr = getInlineStorage();
262 if (sizeof(CallableT) > InlineStorageSize ||
263 alignof(CallableT) > InlineStorageAlign) {
264 IsInlineStorage = false;
265 // Allocate out-of-line storage. FIXME: Use an explicit alignment
266 // parameter in C++17 mode.
267 auto Size = sizeof(CallableT);
268 auto Alignment = alignof(CallableT);
269 CallableAddr = allocate_buffer(Size, Alignment);
270 setOutOfLineStorage(CallableAddr, Size, Alignment);
271 }
272
273 // Now move into the storage.
274 new (CallableAddr) CallableT(std::move(Callable));
275 CallbackAndInlineFlag.setPointerAndInt(
277 }
278
280 if (!CallbackAndInlineFlag.getPointer())
281 return;
282
283 // Cache this value so we don't re-check it after type-erased operations.
284 bool IsInlineStorage = isInlineStorage();
285
286 if (!isTrivialCallback())
288 IsInlineStorage ? getInlineStorage() : getOutOfLineStorage());
289
290 if (!IsInlineStorage)
293 }
294
296 // Copy the callback and inline flag.
297 CallbackAndInlineFlag = RHS.CallbackAndInlineFlag;
298
299 // If the RHS is empty, just copying the above is sufficient.
300 if (!RHS)
301 return;
302
303 if (!isInlineStorage()) {
304 // The out-of-line case is easiest to move.
305 StorageUnion.OutOfLineStorage = RHS.StorageUnion.OutOfLineStorage;
306 } else if (isTrivialCallback()) {
307 // Move is trivial, just memcpy the bytes across.
308 memcpy(getInlineStorage(), RHS.getInlineStorage(), InlineStorageSize);
309 } else {
310 // Non-trivial move, so dispatch to a type-erased implementation.
312 RHS.getInlineStorage());
313 getNonTrivialCallbacks()->DestroyPtr(RHS.getInlineStorage());
314 }
315
316 // Clear the old callback and inline flag to get back to as-if-null.
317 RHS.CallbackAndInlineFlag = {};
318
319#if !defined(NDEBUG) && !LLVM_ADDRESS_SANITIZER_BUILD
320 // In debug builds without ASan, we also scribble across the rest of the
321 // storage. Scribbling under AddressSanitizer (ASan) is disabled to prevent
322 // overwriting poisoned objects (e.g., annotated short strings).
323 memset(RHS.getInlineStorage(), 0xAD, InlineStorageSize);
324#endif
325 }
326
328 if (this == &RHS)
329 return *this;
330
331 // Because we don't try to provide any exception safety guarantees we can
332 // implement move assignment very simply by first destroying the current
333 // object and then move-constructing over top of it.
334 this->~UniqueFunctionBase();
335 new (this) UniqueFunctionBase(std::move(RHS));
336 return *this;
337 }
338
340
341public:
342 explicit operator bool() const {
343 return (bool)CallbackAndInlineFlag.getPointer();
344 }
345};
346
347template <typename R, typename... P>
348template <typename CallableT, typename CalledAsT, typename Enable>
349typename UniqueFunctionBase<R, P...>::NonTrivialCallbacks UniqueFunctionBase<
350 R, P...>::CallbacksHolder<CallableT, CalledAsT, Enable>::Callbacks = {
351 &CallImpl<CalledAsT>, &MoveImpl<CallableT>, &DestroyImpl<CallableT>};
352
353template <typename R, typename... P>
354template <typename CallableT, typename CalledAsT>
355typename UniqueFunctionBase<R, P...>::TrivialCallback
356 UniqueFunctionBase<R, P...>::CallbacksHolder<
358 &CallImpl<CalledAsT>};
359
360} // namespace detail
361
362template <typename R, typename... P>
363class unique_function<R(P...)> : public detail::UniqueFunctionBase<R, P...> {
364 using Base = detail::UniqueFunctionBase<R, P...>;
365
366public:
367 unique_function() = default;
368 unique_function(std::nullptr_t) {}
373
374 template <typename CallableT>
376 CallableT Callable,
379 : Base(std::forward<CallableT>(Callable),
380 typename Base::template CalledAs<CallableT>{}) {}
381
382 R operator()(P... Params) {
383 return this->getCallPtr()(this->getCalleePtr(), Params...);
384 }
385};
386
387template <typename R, typename... P>
389 : public detail::UniqueFunctionBase<R, P...> {
390 using Base = detail::UniqueFunctionBase<R, P...>;
391
392public:
393 unique_function() = default;
394 unique_function(std::nullptr_t) {}
399
400 template <typename CallableT>
402 CallableT Callable,
405 : Base(std::forward<CallableT>(Callable),
406 typename Base::template CalledAs<const CallableT>{}) {}
407
408 R operator()(P... Params) const {
409 return this->getCallPtr()(this->getCalleePtr(), Params...);
410 }
411};
412
413} // end namespace llvm
414
415#endif // LLVM_ADT_FUNCTIONEXTRAS_H
aarch64 promote const
This file defines counterparts of C library allocation functions defined in the namespace 'std'.
#define T
#define P(N)
This file defines the PointerIntPair class.
This file defines the PointerUnion class, which is a discriminated union of pointer types.
This file contains library features backported from future STL versions.
Value * RHS
PointerIntPair - This class implements a pair of a pointer and small integer.
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
void(*)(void *LHSCallableAddr, void *RHSCallableAddr) MovePtrT
PointerIntPair< CallbackPointerUnionT, 1, bool > CallbackAndInlineFlag
void setOutOfLineStorage(void *Ptr, size_t Size, size_t Alignment)
UniqueFunctionBase & operator=(UniqueFunctionBase &&RHS) noexcept
typename AdjustedParamTBase< T >::type AdjustedParamT
NonTrivialCallbacks * getNonTrivialCallbacks() const
PointerUnion< TrivialCallback *, NonTrivialCallbacks * > CallbackPointerUnionT
UniqueFunctionBase(CallableT Callable, CalledAs< CalledAsT >)
static void MoveImpl(void *LHSCallableAddr, void *RHSCallableAddr) noexcept
static void DestroyImpl(void *CallableAddr) noexcept
static ReturnT CallImpl(void *CallableAddr, AdjustedParamT< ParamTs >... Params)
union llvm::detail::UniqueFunctionBase::StorageUnionT StorageUnion
void(*)(void *CallableAddr) DestroyPtrT
ReturnT(*)(void *CallableAddr, AdjustedParamT< ParamTs >... Params) CallPtrT
UniqueFunctionBase(UniqueFunctionBase &&RHS) noexcept
unique_function(const unique_function &)=delete
unique_function(unique_function &&)=default
unique_function & operator=(const unique_function &)=delete
unique_function & operator=(unique_function &&)=default
unique_function(CallableT Callable, detail::EnableUnlessSameType< CallableT, unique_function > *=nullptr, detail::EnableIfCallable< const CallableT, R, P... > *=nullptr)
unique_function(unique_function &&)=default
unique_function & operator=(const unique_function &)=delete
unique_function(CallableT Callable, detail::EnableUnlessSameType< CallableT, unique_function > *=nullptr, detail::EnableIfCallable< CallableT, R, P... > *=nullptr)
unique_function & operator=(unique_function &&)=default
unique_function(const unique_function &)=delete
unique_function is a type-erasing functor similar to std::function.
std::enable_if_t<!std::is_same< remove_cvref_t< CallableT >, ThisT >::value > EnableUnlessSameType
const char unit< Period >::value[]
Definition Chrono.h:104
UniqueFunctionBase< R, P... >::NonTrivialCallbacks UniqueFunctionBase< R, P... >::CallbacksHolder< CallableT, CalledAsT, Enable >::Callbacks
std::enable_if_t< std::disjunction< std::is_void< Ret >, std::is_same< decltype(std::declval< CallableT >()(std::declval< Params >()...)), Ret >, std::is_same< const decltype(std::declval< CallableT >()( std::declval< Params >()...)), Ret >, std::is_convertible< decltype(std::declval< CallableT >()( std::declval< Params >()...)), Ret > >::value > EnableIfCallable
std::enable_if_t< std::is_trivially_move_constructible< T >::value && std::is_trivially_destructible< T >::value > EnableIfTrivial
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * allocate_buffer(size_t Size, size_t Alignment)
Allocate a buffer of memory with the given size and alignment.
Definition MemAlloc.cpp:15
LLVM_ABI void deallocate_buffer(void *Ptr, size_t Size, size_t Alignment)
Deallocate a buffer of memory with the given size and alignment.
Definition MemAlloc.cpp:27
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:851
std::bool_constant< sizeof(U)<=2 *sizeof(void *)> IsSizeLessThanThresholdT
std::conditional_t< std::is_trivially_copy_constructible< T >::value && std::is_trivially_move_constructible< T >::value && IsSizeLessThanThresholdT< T >::value, T, T & > type
A struct we use to aggregate three callbacks when we need full set of operations.
A struct to hold a single trivial callback with sufficient alignment for our bitpacking.
struct llvm::detail::UniqueFunctionBase::StorageUnionT::OutOfLineStorageT OutOfLineStorage