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 CallableT, typename ThisT>
63 std::enable_if_t<!std::is_same<remove_cvref_t<CallableT>, ThisT>::value>;
64template <typename CallableT, typename Ret, typename... Params>
65using EnableIfCallable = std::enable_if_t<std::disjunction<
66 std::is_void<Ret>,
67 std::is_same<decltype(std::declval<CallableT>()(std::declval<Params>()...)),
68 Ret>,
69 std::is_same<const decltype(std::declval<CallableT>()(
70 std::declval<Params>()...)),
71 Ret>,
72 std::is_convertible<decltype(std::declval<CallableT>()(
73 std::declval<Params>()...)),
74 Ret>>::value>;
75
76template <typename ReturnT, typename... ParamTs> class UniqueFunctionBase {
77protected:
78 static constexpr size_t InlineStorageSize = sizeof(void *) * 3;
79 static constexpr size_t InlineStorageAlign = alignof(void *);
80
81 // Provide a type function to map parameters that won't observe extra copies
82 // or moves and which are small enough to likely pass in register to values
83 // and all other types to l-value reference types. We use this to compute the
84 // types used in our erased call utility to minimize copies and moves unless
85 // doing so would force things unnecessarily into memory.
86 //
87 // The heuristic used is related to common ABI register passing conventions.
88 // It doesn't have to be exact though, and in one way it is more strict
89 // because we want to still be able to observe either moves *or* copies.
90 template <typename T> struct AdjustedParamTBase {
91 static_assert(!std::is_reference<T>::value,
92 "references should be handled by template specialization");
93 static constexpr bool IsSizeLessThanThreshold =
94 sizeof(T) <= 2 * sizeof(void *);
95 using type =
96 std::conditional_t<std::is_trivially_copy_constructible<T>::value &&
97 std::is_trivially_move_constructible<T>::value &&
99 T, T &>;
100 };
101
102 // This specialization ensures that 'AdjustedParam<V<T>&>' or
103 // 'AdjustedParam<V<T>&&>' does not trigger a compile-time error when 'T' is
104 // an incomplete type and V a templated type.
105 template <typename T> struct AdjustedParamTBase<T &> { using type = T &; };
106 template <typename T> struct AdjustedParamTBase<T &&> { using type = T &; };
107
108 template <typename T>
110
111 // The type of the erased function pointer we use as a callback to dispatch to
112 // the stored callable when it is trivial to move and destroy.
113 using CallPtrT = ReturnT (*)(void *CallableAddr,
114 AdjustedParamT<ParamTs>... Params);
115 using MovePtrT = void (*)(void *LHSCallableAddr, void *RHSCallableAddr);
116 using DestroyPtrT = void (*)(void *CallableAddr);
117
118 /// A struct to hold a single trivial callback with sufficient alignment for
119 /// our bitpacking.
120 struct alignas(8) TrivialCallback {
122 };
123
124 /// A struct we use to aggregate three callbacks when we need full set of
125 /// operations.
131
132 // Create a pointer union between either a pointer to a static trivial call
133 // pointer in a struct or a pointer to a static struct of the call, move, and
134 // destroy pointers.
137
138 // The main storage buffer. This will either have a pointer to out-of-line
139 // storage or an inline buffer storing the callable.
141 // For out-of-line storage we keep a pointer to the underlying storage and
142 // the size. This is enough to deallocate the memory.
148 static_assert(
149 sizeof(OutOfLineStorageT) <= InlineStorageSize,
150 "Should always use all of the out-of-line storage for inline storage!");
151
152 // For in-line storage, we just provide an aligned character buffer. We
153 // provide three pointers worth of storage here.
154 // This is mutable as an inlined `const unique_function<void() const>` may
155 // still modify its own mutable members.
156 alignas(InlineStorageAlign) mutable std::byte
159
160 // A compressed pointer to either our dispatching callback or our table of
161 // dispatching callbacks and the flag for whether the callable itself is
162 // stored inline or not.
164
165 bool isInlineStorage() const { return CallbackAndInlineFlag.getInt(); }
166
167 bool isTrivialCallback() const {
169 }
170
172 return cast<TrivialCallback *>(CallbackAndInlineFlag.getPointer())->CallPtr;
173 }
174
175 NonTrivialCallbacks *getNonTrivialCallbacks() const {
177 }
178
183
184 // These three functions are only const in the narrow sense. They return
185 // mutable pointers to function state.
186 // This allows unique_function<T const>::operator() to be const, even if the
187 // underlying functor may be internally mutable.
188 //
189 // const callers must ensure they're only used in const-correct ways.
190 void *getCalleePtr() const {
192 }
193 void *getInlineStorage() const { return &StorageUnion.InlineStorage; }
194 void *getOutOfLineStorage() const {
195 return StorageUnion.OutOfLineStorage.StoragePtr;
196 }
197
198 size_t getOutOfLineStorageSize() const {
199 return StorageUnion.OutOfLineStorage.Size;
200 }
202 return StorageUnion.OutOfLineStorage.Alignment;
203 }
204
205 void setOutOfLineStorage(void *Ptr, size_t Size, size_t Alignment) {
206 StorageUnion.OutOfLineStorage = {Ptr, Size, Alignment};
207 }
208
209 template <typename CalledAsT>
210 static ReturnT CallImpl(void *CallableAddr,
211 AdjustedParamT<ParamTs>... Params) {
212 auto &Func = *reinterpret_cast<CalledAsT *>(CallableAddr);
213 return Func(std::forward<ParamTs>(Params)...);
214 }
215
216 template <typename CallableT>
217 static void MoveImpl(void *LHSCallableAddr, void *RHSCallableAddr) noexcept {
218 new (LHSCallableAddr)
219 CallableT(std::move(*reinterpret_cast<CallableT *>(RHSCallableAddr)));
220 }
221
222 template <typename CallableT>
223 static void DestroyImpl(void *CallableAddr) noexcept {
224 reinterpret_cast<CallableT *>(CallableAddr)->~CallableT();
225 }
226
227 // The pointers to call/move/destroy functions are determined for each
228 // callable type (and called-as type, which determines the overload chosen).
229
230 // By default, we need an object that contains all the different
231 // type erased behaviors needed. Create a static instance of the struct type
232 // here and each instance will contain a pointer to it.
233 // Wrap in a struct to avoid https://gcc.gnu.org/PR71954
234 template <typename CallableT, typename CalledAs> struct CallbacksHolder {
235 inline static auto Callbacks = []() constexpr {
236 // For trivial callables, we don't need to store move and destroy
237 // callbacks.
238 if constexpr (std::is_trivially_move_constructible_v<CallableT> &&
239 std::is_trivially_destructible_v<CallableT>)
241 else
244 }();
245 };
246
247 // A simple tag type so the call-as type to be passed to the constructor.
248 template <typename T> struct CalledAs {};
249
250 // Essentially the "main" unique_function constructor, but subclasses
251 // provide the qualified type to be used for the call.
252 // (We always store a T, even if the call will use a pointer to const T).
253 template <typename CallableT, typename CalledAsT>
254 UniqueFunctionBase(CallableT Callable, CalledAs<CalledAsT>) {
255 bool IsInlineStorage = true;
256 void *CallableAddr = getInlineStorage();
257 if (sizeof(CallableT) > InlineStorageSize ||
258 alignof(CallableT) > InlineStorageAlign) {
259 IsInlineStorage = false;
260 // Allocate out-of-line storage. FIXME: Use an explicit alignment
261 // parameter in C++17 mode.
262 auto Size = sizeof(CallableT);
263 auto Alignment = alignof(CallableT);
264 CallableAddr = allocate_buffer(Size, Alignment);
265 setOutOfLineStorage(CallableAddr, Size, Alignment);
266 }
267
268 // Now move into the storage.
269 new (CallableAddr) CallableT(std::move(Callable));
270 CallbackAndInlineFlag.setPointerAndInt(
272 }
273
275 if (!CallbackAndInlineFlag.getPointer())
276 return;
277
278 // Cache this value so we don't re-check it after type-erased operations.
279 bool IsInlineStorage = isInlineStorage();
280
281 if (!isTrivialCallback())
283 IsInlineStorage ? getInlineStorage() : getOutOfLineStorage());
284
285 if (!IsInlineStorage)
288 }
289
291 // Copy the callback and inline flag.
292 CallbackAndInlineFlag = RHS.CallbackAndInlineFlag;
293
294 // If the RHS is empty, just copying the above is sufficient.
295 if (!RHS)
296 return;
297
298 if (!isInlineStorage()) {
299 // The out-of-line case is easiest to move.
300 StorageUnion.OutOfLineStorage = RHS.StorageUnion.OutOfLineStorage;
301 } else if (isTrivialCallback()) {
302 // Move is trivial, just memcpy the bytes across.
303 memcpy(getInlineStorage(), RHS.getInlineStorage(), InlineStorageSize);
304 } else {
305 // Non-trivial move, so dispatch to a type-erased implementation.
307 RHS.getInlineStorage());
308 getNonTrivialCallbacks()->DestroyPtr(RHS.getInlineStorage());
309 }
310
311 // Clear the old callback and inline flag to get back to as-if-null.
312 RHS.CallbackAndInlineFlag = {};
313
314#if !defined(NDEBUG) && !LLVM_ADDRESS_SANITIZER_BUILD
315 // In debug builds without ASan, we also scribble across the rest of the
316 // storage. Scribbling under AddressSanitizer (ASan) is disabled to prevent
317 // overwriting poisoned objects (e.g., annotated short strings).
318 memset(RHS.getInlineStorage(), 0xAD, InlineStorageSize);
319#endif
320 }
321
323 if (this == &RHS)
324 return *this;
325
326 // Because we don't try to provide any exception safety guarantees we can
327 // implement move assignment very simply by first destroying the current
328 // object and then move-constructing over top of it.
329 this->~UniqueFunctionBase();
330 new (this) UniqueFunctionBase(std::move(RHS));
331 return *this;
332 }
333
335
336public:
337 explicit operator bool() const {
338 return (bool)CallbackAndInlineFlag.getPointer();
339 }
340};
341
342} // namespace detail
343
344template <typename R, typename... P>
345class unique_function<R(P...)> : public detail::UniqueFunctionBase<R, P...> {
346 using Base = detail::UniqueFunctionBase<R, P...>;
347
348public:
349 unique_function() = default;
350 unique_function(std::nullptr_t) {}
355
356 template <typename CallableT>
358 CallableT Callable,
361 : Base(std::forward<CallableT>(Callable),
362 typename Base::template CalledAs<CallableT>{}) {}
363
364 R operator()(P... Params) {
365 return this->getCallPtr()(this->getCalleePtr(), Params...);
366 }
367};
368
369template <typename R, typename... P>
371 : public detail::UniqueFunctionBase<R, P...> {
372 using Base = detail::UniqueFunctionBase<R, P...>;
373
374public:
375 unique_function() = default;
376 unique_function(std::nullptr_t) {}
381
382 template <typename CallableT>
384 CallableT Callable,
387 : Base(std::forward<CallableT>(Callable),
388 typename Base::template CalledAs<const CallableT>{}) {}
389
390 R operator()(P... Params) const {
391 return this->getCallPtr()(this->getCalleePtr(), Params...);
392 }
393};
394
395} // end namespace llvm
396
397#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
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
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:870
std::conditional_t< std::is_trivially_copy_constructible< T >::value && std::is_trivially_move_constructible< T >::value && IsSizeLessThanThreshold, 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