WPILibC++ 2027.0.0-alpha-2
Loading...
Searching...
No Matches
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 WPIUTIL_WPI_FUNCTIONEXTRAS_H
33#define WPIUTIL_WPI_FUNCTIONEXTRAS_H
34
35#include "wpi/PointerIntPair.h"
36#include "wpi/PointerUnion.h"
38#include "wpi/Compiler.h"
39#include "wpi/MemAlloc.h"
40#include "wpi/type_traits.h"
41#include <cstring>
42#include <memory>
43#include <type_traits>
44
45namespace wpi {
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
59// GCC warns on OutOfLineStorage
60#if defined(__GNUC__) && !defined(__clang__)
61#pragma GCC diagnostic push
62#pragma GCC diagnostic ignored "-Warray-bounds"
63#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
64#endif
65
66namespace detail {
67
68template <typename T>
70 std::enable_if_t<std::is_trivially_move_constructible<T>::value &&
71 std::is_trivially_destructible<T>::value>;
72template <typename CallableT, typename ThisT>
74 std::enable_if_t<!std::is_same<remove_cvref_t<CallableT>, ThisT>::value>;
75template <typename CallableT, typename Ret, typename... Params>
76using EnableIfCallable = std::enable_if_t<std::disjunction<
77 std::is_void<Ret>,
78 std::is_same<decltype(std::declval<CallableT>()(std::declval<Params>()...)),
79 Ret>,
80 std::is_same<const decltype(std::declval<CallableT>()(
81 std::declval<Params>()...)),
82 Ret>,
83 std::is_convertible<decltype(std::declval<CallableT>()(
84 std::declval<Params>()...)),
85 Ret>>::value>;
86
87template <typename ReturnT, typename... ParamTs> class UniqueFunctionBase {
88protected:
89 static constexpr size_t InlineStorageSize = sizeof(void *) * 4;
90 static constexpr size_t InlineStorageAlign = alignof(void *);
91
92 template <typename T, class = void>
93 struct IsSizeLessThanThresholdT : std::false_type {};
94
95 template <typename T>
97 T, std::enable_if_t<sizeof(T) <= 2 * sizeof(void *)>> : std::true_type {};
98
99 // Provide a type function to map parameters that won't observe extra copies
100 // or moves and which are small enough to likely pass in register to values
101 // and all other types to l-value reference types. We use this to compute the
102 // types used in our erased call utility to minimize copies and moves unless
103 // doing so would force things unnecessarily into memory.
104 //
105 // The heuristic used is related to common ABI register passing conventions.
106 // It doesn't have to be exact though, and in one way it is more strict
107 // because we want to still be able to observe either moves *or* copies.
108 template <typename T> struct AdjustedParamTBase {
109 static_assert(!std::is_reference<T>::value,
110 "references should be handled by template specialization");
111 using type =
112 std::conditional_t<std::is_trivially_copy_constructible<T>::value &&
113 std::is_trivially_move_constructible<T>::value &&
115 T, T &>;
116 };
117
118 // This specialization ensures that 'AdjustedParam<V<T>&>' or
119 // 'AdjustedParam<V<T>&&>' does not trigger a compile-time error when 'T' is
120 // an incomplete type and V a templated type.
121 template <typename T> struct AdjustedParamTBase<T &> { using type = T &; };
122 template <typename T> struct AdjustedParamTBase<T &&> { using type = T &; };
123
124 template <typename T>
126
127 // The type of the erased function pointer we use as a callback to dispatch to
128 // the stored callable when it is trivial to move and destroy.
129 using CallPtrT = ReturnT (*)(void *CallableAddr,
130 AdjustedParamT<ParamTs>... Params);
131 using MovePtrT = void (*)(void *LHSCallableAddr, void *RHSCallableAddr);
132 using DestroyPtrT = void (*)(void *CallableAddr);
133
134 /// A struct to hold a single trivial callback with sufficient alignment for
135 /// our bitpacking.
136 struct alignas(8) TrivialCallback {
138 };
139
140 /// A struct we use to aggregate three callbacks when we need full set of
141 /// operations.
147
148 // Create a pointer union between either a pointer to a static trivial call
149 // pointer in a struct or a pointer to a static struct of the call, move, and
150 // destroy pointers.
153
154 // The main storage buffer. This will either have a pointer to out-of-line
155 // storage or an inline buffer storing the callable.
157 // For out-of-line storage we keep a pointer to the underlying storage and
158 // the size. This is enough to deallocate the memory.
164 static_assert(
165 sizeof(OutOfLineStorageT) <= InlineStorageSize,
166 "Should always use all of the out-of-line storage for inline storage!");
167
168 // For in-line storage, we just provide an aligned character buffer. We
169 // provide four pointers worth of storage here.
170 // This is mutable as an inlined `const unique_function<void() const>` may
171 // still modify its own mutable members.
172 alignas(InlineStorageAlign) mutable std::byte
175
176 // A compressed pointer to either our dispatching callback or our table of
177 // dispatching callbacks and the flag for whether the callable itself is
178 // stored inline or not.
180
181 bool isInlineStorage() const { return CallbackAndInlineFlag.getInt(); }
182
183 bool isTrivialCallback() const {
185 }
186
188 return cast<TrivialCallback *>(CallbackAndInlineFlag.getPointer())->CallPtr;
189 }
190
194
199
200 // These three functions are only const in the narrow sense. They return
201 // mutable pointers to function state.
202 // This allows unique_function<T const>::operator() to be const, even if the
203 // underlying functor may be internally mutable.
204 //
205 // const callers must ensure they're only used in const-correct ways.
206 void *getCalleePtr() const {
208 }
209 void *getInlineStorage() const { return &StorageUnion.InlineStorage; }
213
214 size_t getOutOfLineStorageSize() const {
216 }
220
221 void setOutOfLineStorage(void *Ptr, size_t Size, size_t Alignment) {
222 StorageUnion.OutOfLineStorage = {Ptr, Size, Alignment};
223 }
224
225 template <typename CalledAsT>
226 static ReturnT CallImpl(void *CallableAddr,
227 AdjustedParamT<ParamTs>... Params) {
228 auto &Func = *reinterpret_cast<CalledAsT *>(CallableAddr);
229 return Func(std::forward<ParamTs>(Params)...);
230 }
231
232 template <typename CallableT>
233 static void MoveImpl(void *LHSCallableAddr, void *RHSCallableAddr) noexcept {
234 new (LHSCallableAddr)
235 CallableT(std::move(*reinterpret_cast<CallableT *>(RHSCallableAddr)));
236 }
237
238 template <typename CallableT>
239 static void DestroyImpl(void *CallableAddr) noexcept {
240 reinterpret_cast<CallableT *>(CallableAddr)->~CallableT();
241 }
242
243 // The pointers to call/move/destroy functions are determined for each
244 // callable type (and called-as type, which determines the overload chosen).
245 // (definitions are out-of-line).
246
247 // By default, we need an object that contains all the different
248 // type erased behaviors needed. Create a static instance of the struct type
249 // here and each instance will contain a pointer to it.
250 // Wrap in a struct to avoid https://gcc.gnu.org/PR71954
251 template <typename CallableT, typename CalledAs, typename Enable = void>
255 // See if we can create a trivial callback. We need the callable to be
256 // trivially moved and trivially destroyed so that we don't have to store
257 // type erased callbacks for those operations.
258 template <typename CallableT, typename CalledAs>
259 struct CallbacksHolder<CallableT, CalledAs, EnableIfTrivial<CallableT>> {
261 };
262
263 // A simple tag type so the call-as type to be passed to the constructor.
264 template <typename T> struct CalledAs {};
265
266 // Essentially the "main" unique_function constructor, but subclasses
267 // provide the qualified type to be used for the call.
268 // (We always store a T, even if the call will use a pointer to const T).
269 template <typename CallableT, typename CalledAsT>
271 bool IsInlineStorage = true;
272 void *CallableAddr = getInlineStorage();
273 if (sizeof(CallableT) > InlineStorageSize ||
274 alignof(CallableT) > InlineStorageAlign) {
275 IsInlineStorage = false;
276 // Allocate out-of-line storage. FIXME: Use an explicit alignment
277 // parameter in C++17 mode.
278 auto Size = sizeof(CallableT);
279 auto Alignment = alignof(CallableT);
280 CallableAddr = allocate_buffer(Size, Alignment);
281 setOutOfLineStorage(CallableAddr, Size, Alignment);
282 }
283
284 // Now move into the storage.
285 new (CallableAddr) CallableT(std::move(Callable));
286 CallbackAndInlineFlag.setPointerAndInt(
288 }
289
291 if (!CallbackAndInlineFlag.getPointer())
292 return;
293
294 // Cache this value so we don't re-check it after type-erased operations.
295 bool IsInlineStorage = isInlineStorage();
296
297 if (!isTrivialCallback())
299 IsInlineStorage ? getInlineStorage() : getOutOfLineStorage());
300
301 if (!IsInlineStorage)
304 }
305
307 // Copy the callback and inline flag.
308 CallbackAndInlineFlag = RHS.CallbackAndInlineFlag;
309
310 // If the RHS is empty, just copying the above is sufficient.
311 if (!RHS)
312 return;
313
314 if (!isInlineStorage()) {
315 // The out-of-line case is easiest to move.
316 StorageUnion.OutOfLineStorage = RHS.StorageUnion.OutOfLineStorage;
317 } else if (isTrivialCallback()) {
318 // Move is trivial, just memcpy the bytes across.
319 memcpy(getInlineStorage(), RHS.getInlineStorage(), InlineStorageSize);
320 } else {
321 // Non-trivial move, so dispatch to a type-erased implementation.
323 RHS.getInlineStorage());
324 getNonTrivialCallbacks()->DestroyPtr(RHS.getInlineStorage());
325 }
326
327 // Clear the old callback and inline flag to get back to as-if-null.
328 RHS.CallbackAndInlineFlag = {};
329
330#if !defined(NDEBUG) && !LLVM_ADDRESS_SANITIZER_BUILD
331 // In debug builds without ASan, we also scribble across the rest of the
332 // storage. Scribbling under AddressSanitizer (ASan) is disabled to prevent
333 // overwriting poisoned objects (e.g., annotated short strings).
334 memset(RHS.getInlineStorage(), 0xAD, InlineStorageSize);
335#endif
336 }
337
339 if (this == &RHS)
340 return *this;
341
342 // Because we don't try to provide any exception safety guarantees we can
343 // implement move assignment very simply by first destroying the current
344 // object and then move-constructing over top of it.
345 this->~UniqueFunctionBase();
346 new (this) UniqueFunctionBase(std::move(RHS));
347 return *this;
348 }
349
351
352public:
353 explicit operator bool() const {
354 return (bool)CallbackAndInlineFlag.getPointer();
355 }
356};
357
358template <typename R, typename... P>
359template <typename CallableT, typename CalledAsT, typename Enable>
360typename UniqueFunctionBase<R, P...>::NonTrivialCallbacks UniqueFunctionBase<
361 R, P...>::CallbacksHolder<CallableT, CalledAsT, Enable>::Callbacks = {
362 &CallImpl<CalledAsT>, &MoveImpl<CallableT>, &DestroyImpl<CallableT>};
363
364template <typename R, typename... P>
365template <typename CallableT, typename CalledAsT>
366typename UniqueFunctionBase<R, P...>::TrivialCallback
367 UniqueFunctionBase<R, P...>::CallbacksHolder<
368 CallableT, CalledAsT, EnableIfTrivial<CallableT>>::Callbacks{
369 &CallImpl<CalledAsT>};
370
371} // namespace detail
372
373template <typename R, typename... P>
374class unique_function<R(P...)> : public detail::UniqueFunctionBase<R, P...> {
375 using Base = detail::UniqueFunctionBase<R, P...>;
376
377public:
378 unique_function() = default;
379 unique_function(std::nullptr_t) {}
384
385 template <typename CallableT>
387 CallableT Callable,
390 : Base(std::forward<CallableT>(Callable),
391 typename Base::template CalledAs<CallableT>{}) {}
392
393 R operator()(P... Params) {
394 return this->getCallPtr()(this->getCalleePtr(), Params...);
395 }
396};
397
398template <typename R, typename... P>
399class unique_function<R(P...) const>
400 : public detail::UniqueFunctionBase<R, P...> {
401 using Base = detail::UniqueFunctionBase<R, P...>;
402
403public:
404 unique_function() = default;
405 unique_function(std::nullptr_t) {}
410
411 template <typename CallableT>
413 CallableT Callable,
416 : Base(std::forward<CallableT>(Callable),
417 typename Base::template CalledAs<const CallableT>{}) {}
418
419 R operator()(P... Params) const {
420 return this->getCallPtr()(this->getCalleePtr(), Params...);
421 }
422};
423
424#if defined(__GNUC__) && !defined(__clang__)
425#pragma GCC diagnostic pop
426#endif
427
428} // end namespace wpi
429
430#endif // WPIUTIL_WPI_FUNCTIONEXTRAS_H
This file defines counterparts of C library allocation functions defined in the namespace 'std'.
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.
PointerIntPair - This class implements a pair of a pointer and small integer.
Definition PointerIntPair.h:80
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
Definition PointerUnion.h:163
Definition FunctionExtras.h:87
void(*)(void *CallableAddr) DestroyPtrT
Definition FunctionExtras.h:132
static constexpr size_t InlineStorageAlign
Definition FunctionExtras.h:90
void * getInlineStorage() const
Definition FunctionExtras.h:209
union wpi::detail::UniqueFunctionBase::StorageUnionT StorageUnion
static constexpr size_t InlineStorageSize
Definition FunctionExtras.h:89
UniqueFunctionBase & operator=(UniqueFunctionBase &&RHS) noexcept
Definition FunctionExtras.h:338
size_t getOutOfLineStorageSize() const
Definition FunctionExtras.h:214
void setOutOfLineStorage(void *Ptr, size_t Size, size_t Alignment)
Definition FunctionExtras.h:221
NonTrivialCallbacks * getNonTrivialCallbacks() const
Definition FunctionExtras.h:191
typename AdjustedParamTBase< T >::type AdjustedParamT
Definition FunctionExtras.h:125
static ReturnT CallImpl(void *CallableAddr, AdjustedParamT< ParamTs >... Params)
Definition FunctionExtras.h:226
bool isTrivialCallback() const
Definition FunctionExtras.h:183
UniqueFunctionBase(UniqueFunctionBase &&RHS) noexcept
Definition FunctionExtras.h:306
void(*)(void *LHSCallableAddr, void *RHSCallableAddr) MovePtrT
Definition FunctionExtras.h:131
size_t getOutOfLineStorageAlignment() const
Definition FunctionExtras.h:217
UniqueFunctionBase(CallableT Callable, CalledAs< CalledAsT >)
Definition FunctionExtras.h:270
static void DestroyImpl(void *CallableAddr) noexcept
Definition FunctionExtras.h:239
void * getCalleePtr() const
Definition FunctionExtras.h:206
ReturnT(*)(void *CallableAddr, AdjustedParamT< ParamTs >... Params) CallPtrT
Definition FunctionExtras.h:129
PointerIntPair< CallbackPointerUnionT, 1, bool > CallbackAndInlineFlag
Definition FunctionExtras.h:179
static void MoveImpl(void *LHSCallableAddr, void *RHSCallableAddr) noexcept
Definition FunctionExtras.h:233
bool isInlineStorage() const
Definition FunctionExtras.h:181
CallPtrT getCallPtr() const
Definition FunctionExtras.h:195
CallPtrT getTrivialCallback() const
Definition FunctionExtras.h:187
void * getOutOfLineStorage() const
Definition FunctionExtras.h:210
~UniqueFunctionBase()
Definition FunctionExtras.h:290
unique_function(const unique_function &)=delete
unique_function & operator=(unique_function &&)=default
R operator()(P... Params) const
Definition FunctionExtras.h:419
unique_function & operator=(const unique_function &)=delete
unique_function(unique_function &&)=default
unique_function(std::nullptr_t)
Definition FunctionExtras.h:405
unique_function(CallableT Callable, detail::EnableUnlessSameType< CallableT, unique_function > *=nullptr, detail::EnableIfCallable< const CallableT, R, P... > *=nullptr)
Definition FunctionExtras.h:412
R operator()(P... Params)
Definition FunctionExtras.h:393
unique_function(const unique_function &)=delete
unique_function(CallableT Callable, detail::EnableUnlessSameType< CallableT, unique_function > *=nullptr, detail::EnableIfCallable< CallableT, R, P... > *=nullptr)
Definition FunctionExtras.h:386
unique_function(std::nullptr_t)
Definition FunctionExtras.h:379
unique_function(unique_function &&)=default
unique_function & operator=(unique_function &&)=default
unique_function & operator=(const unique_function &)=delete
unique_function is a type-erasing functor similar to std::function.
Definition FunctionExtras.h:57
detail namespace with internal helper functions
Definition input_adapters.h:32
Definition PointerIntPair.h:280
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
Definition FunctionExtras.h:76
std::enable_if_t< std::is_trivially_move_constructible< T >::value && std::is_trivially_destructible< T >::value > EnableIfTrivial
Definition FunctionExtras.h:69
std::enable_if_t<!std::is_same< remove_cvref_t< CallableT >, ThisT >::value > EnableUnlessSameType
Definition FunctionExtras.h:73
Definition ntcore_cpp.h:26
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
void deallocate_buffer(void *Ptr, size_t Size, size_t Alignment)
Deallocate a buffer of memory with the given size and alignment.
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
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.
std::conditional_t< std::is_trivially_copy_constructible< T >::value && std::is_trivially_move_constructible< T >::value && IsSizeLessThanThresholdT< T >::value, T, T & > type
Definition FunctionExtras.h:111
static NonTrivialCallbacks Callbacks
Definition FunctionExtras.h:253
Definition FunctionExtras.h:264
A struct we use to aggregate three callbacks when we need full set of operations.
Definition FunctionExtras.h:142
MovePtrT MovePtr
Definition FunctionExtras.h:144
CallPtrT CallPtr
Definition FunctionExtras.h:143
DestroyPtrT DestroyPtr
Definition FunctionExtras.h:145
A struct to hold a single trivial callback with sufficient alignment for our bitpacking.
Definition FunctionExtras.h:136
CallPtrT CallPtr
Definition FunctionExtras.h:137
Definition FunctionExtras.h:156
struct wpi::detail::UniqueFunctionBase::StorageUnionT::OutOfLineStorageT OutOfLineStorage
std::byte InlineStorage[InlineStorageSize]
Definition FunctionExtras.h:173
typename std::enable_if< B, T >::type enable_if_t
Definition base.h:312