LLVM 22.0.0git
Allocator.h
Go to the documentation of this file.
1//===- Allocator.h - Simple memory allocation abstraction -------*- 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///
10/// This file defines the BumpPtrAllocator interface. BumpPtrAllocator conforms
11/// to the LLVM "Allocator" concept and is similar to MallocAllocator, but
12/// objects cannot be deallocated. Their lifetime is tied to the lifetime of the
13/// allocator.
14///
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_SUPPORT_ALLOCATOR_H
18#define LLVM_SUPPORT_ALLOCATOR_H
19
25#include <algorithm>
26#include <cassert>
27#include <cstddef>
28#include <cstdint>
29#include <iterator>
30#include <optional>
31#include <utility>
32
33namespace llvm {
34
35namespace detail {
36
37// We call out to an external function to actually print the message as the
38// printing code uses Allocator.h in its implementation.
39LLVM_ABI void printBumpPtrAllocatorStats(unsigned NumSlabs,
40 size_t BytesAllocated,
41 size_t TotalMemory);
42
43} // end namespace detail
44
45/// Allocate memory in an ever growing pool, as if by bump-pointer.
46///
47/// This isn't strictly a bump-pointer allocator as it uses backing slabs of
48/// memory rather than relying on a boundless contiguous heap. However, it has
49/// bump-pointer semantics in that it is a monotonically growing pool of memory
50/// where every allocation is found by merely allocating the next N bytes in
51/// the slab, or the next N bytes in the next slab.
52///
53/// Note that this also has a threshold for forcing allocations above a certain
54/// size into their own slab.
55///
56/// The BumpPtrAllocatorImpl template defaults to using a MallocAllocator
57/// object, which wraps malloc, to allocate memory, but it can be changed to
58/// use a custom allocator.
59///
60/// The GrowthDelay specifies after how many allocated slabs the allocator
61/// increases the size of the slabs.
62template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096,
63 size_t SizeThreshold = SlabSize, size_t GrowthDelay = 128>
65 : public AllocatorBase<BumpPtrAllocatorImpl<AllocatorT, SlabSize,
66 SizeThreshold, GrowthDelay>>,
67 private detail::AllocatorHolder<AllocatorT> {
69
70public:
71 static_assert(SizeThreshold <= SlabSize,
72 "The SizeThreshold must be at most the SlabSize to ensure "
73 "that objects larger than a slab go into their own memory "
74 "allocation.");
75 static_assert(GrowthDelay > 0,
76 "GrowthDelay must be at least 1 which already increases the"
77 "slab size after each allocated slab.");
78
80
81 template <typename T>
83 : AllocTy(std::forward<T &&>(Allocator)) {}
84
85 // Manually implement a move constructor as we must clear the old allocator's
86 // slabs as a matter of correctness.
88 : AllocTy(std::move(Old.getAllocator())), CurPtr(Old.CurPtr),
89 End(Old.End), Slabs(std::move(Old.Slabs)),
90 CustomSizedSlabs(std::move(Old.CustomSizedSlabs)),
91 BytesAllocated(Old.BytesAllocated), RedZoneSize(Old.RedZoneSize) {
92 Old.CurPtr = Old.End = nullptr;
93 Old.BytesAllocated = 0;
94 Old.Slabs.clear();
95 Old.CustomSizedSlabs.clear();
96 }
97
99 DeallocateSlabs(Slabs.begin(), Slabs.end());
100 DeallocateCustomSizedSlabs();
101 }
102
104 DeallocateSlabs(Slabs.begin(), Slabs.end());
105 DeallocateCustomSizedSlabs();
106
107 CurPtr = RHS.CurPtr;
108 End = RHS.End;
109 BytesAllocated = RHS.BytesAllocated;
110 RedZoneSize = RHS.RedZoneSize;
111 Slabs = std::move(RHS.Slabs);
112 CustomSizedSlabs = std::move(RHS.CustomSizedSlabs);
113 AllocTy::operator=(std::move(RHS.getAllocator()));
114
115 RHS.CurPtr = RHS.End = nullptr;
116 RHS.BytesAllocated = 0;
117 RHS.Slabs.clear();
118 RHS.CustomSizedSlabs.clear();
119 return *this;
120 }
121
122 /// Deallocate all but the current slab and reset the current pointer
123 /// to the beginning of it, freeing all memory allocated so far.
124 void Reset() {
125 // Deallocate all but the first slab, and deallocate all custom-sized slabs.
126 DeallocateCustomSizedSlabs();
127 CustomSizedSlabs.clear();
128
129 if (Slabs.empty())
130 return;
131
132 // Reset the state.
133 BytesAllocated = 0;
134 CurPtr = (char *)Slabs.front();
135 End = CurPtr + SlabSize;
136
137 __asan_poison_memory_region(*Slabs.begin(), computeSlabSize(0));
138 DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
139 Slabs.erase(std::next(Slabs.begin()), Slabs.end());
140 }
141
142 /// Allocate space at the specified alignment.
143 // This method is *not* marked noalias, because
144 // SpecificBumpPtrAllocator::DestroyAll() loops over all allocations, and
145 // that loop is not based on the Allocate() return value.
146 //
147 // Allocate(0, N) is valid, it returns a non-null pointer (which should not
148 // be dereferenced).
150 // Keep track of how many bytes we've allocated.
151 BytesAllocated += Size;
152
153 uintptr_t AlignedPtr = alignAddr(CurPtr, Alignment);
154
155 size_t SizeToAllocate = Size;
156#if LLVM_ADDRESS_SANITIZER_BUILD
157 // Add trailing bytes as a "red zone" under ASan.
158 SizeToAllocate += RedZoneSize;
159#endif
160
161 uintptr_t AllocEndPtr = AlignedPtr + SizeToAllocate;
162 assert(AllocEndPtr >= uintptr_t(CurPtr) &&
163 "Alignment + Size must not overflow");
164
165 // Check if we have enough space.
166 if (LLVM_LIKELY(AllocEndPtr <= uintptr_t(End)
167 // We can't return nullptr even for a zero-sized allocation!
168 && CurPtr != nullptr)) {
169 CurPtr = reinterpret_cast<char *>(AllocEndPtr);
170 // Update the allocation point of this memory block in MemorySanitizer.
171 // Without this, MemorySanitizer messages for values originated from here
172 // will point to the allocation of the entire slab.
173 __msan_allocated_memory(reinterpret_cast<char *>(AlignedPtr), Size);
174 // Similarly, tell ASan about this space.
175 __asan_unpoison_memory_region(reinterpret_cast<char *>(AlignedPtr), Size);
176 return reinterpret_cast<char *>(AlignedPtr);
177 }
178
179 return AllocateSlow(Size, SizeToAllocate, Alignment);
180 }
181
183 AllocateSlow(size_t Size, size_t SizeToAllocate, Align Alignment) {
184 // If Size is really big, allocate a separate slab for it.
185 size_t PaddedSize = SizeToAllocate + Alignment.value() - 1;
186 if (PaddedSize > SizeThreshold) {
187 void *NewSlab =
188 this->getAllocator().Allocate(PaddedSize, alignof(std::max_align_t));
189 // We own the new slab and don't want anyone reading anyting other than
190 // pieces returned from this method. So poison the whole slab.
191 __asan_poison_memory_region(NewSlab, PaddedSize);
192 CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
193
194 uintptr_t AlignedAddr = alignAddr(NewSlab, Alignment);
195 assert(AlignedAddr + Size <= (uintptr_t)NewSlab + PaddedSize);
196 char *AlignedPtr = (char*)AlignedAddr;
197 __msan_allocated_memory(AlignedPtr, Size);
199 return AlignedPtr;
200 }
201
202 // Otherwise, start a new slab and try again.
203 StartNewSlab();
204 uintptr_t AlignedAddr = alignAddr(CurPtr, Alignment);
205 assert(AlignedAddr + SizeToAllocate <= (uintptr_t)End &&
206 "Unable to allocate memory!");
207 char *AlignedPtr = (char*)AlignedAddr;
208 CurPtr = AlignedPtr + SizeToAllocate;
209 __msan_allocated_memory(AlignedPtr, Size);
211 return AlignedPtr;
212 }
213
215 Allocate(size_t Size, size_t Alignment) {
216 assert(Alignment > 0 && "0-byte alignment is not allowed. Use 1 instead.");
217 return Allocate(Size, Align(Alignment));
218 }
219
220 // Pull in base class overloads.
222
223 // Bump pointer allocators are expected to never free their storage; and
224 // clients expect pointers to remain valid for non-dereferencing uses even
225 // after deallocation.
226 void Deallocate(const void *Ptr, size_t Size, size_t /*Alignment*/) {
228 }
229
230 // Pull in base class overloads.
232
233 size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
234
235 /// \return An index uniquely and reproducibly identifying
236 /// an input pointer \p Ptr in the given allocator.
237 /// The returned value is negative iff the object is inside a custom-size
238 /// slab.
239 /// Returns an empty optional if the pointer is not found in the allocator.
240 std::optional<int64_t> identifyObject(const void *Ptr) {
241 const char *P = static_cast<const char *>(Ptr);
242 int64_t InSlabIdx = 0;
243 for (size_t Idx = 0, E = Slabs.size(); Idx < E; Idx++) {
244 const char *S = static_cast<const char *>(Slabs[Idx]);
245 if (P >= S && P < S + computeSlabSize(Idx))
246 return InSlabIdx + static_cast<int64_t>(P - S);
247 InSlabIdx += static_cast<int64_t>(computeSlabSize(Idx));
248 }
249
250 // Use negative index to denote custom sized slabs.
251 int64_t InCustomSizedSlabIdx = -1;
252 for (const auto &Slab : CustomSizedSlabs) {
253 const char *S = static_cast<const char *>(Slab.first);
254 size_t Size = Slab.second;
255 if (P >= S && P < S + Size)
256 return InCustomSizedSlabIdx - static_cast<int64_t>(P - S);
257 InCustomSizedSlabIdx -= static_cast<int64_t>(Size);
258 }
259 return std::nullopt;
260 }
261
262 /// A wrapper around identifyObject that additionally asserts that
263 /// the object is indeed within the allocator.
264 /// \return An index uniquely and reproducibly identifying
265 /// an input pointer \p Ptr in the given allocator.
266 int64_t identifyKnownObject(const void *Ptr) {
267 std::optional<int64_t> Out = identifyObject(Ptr);
268 assert(Out && "Wrong allocator used");
269 return *Out;
270 }
271
272 /// A wrapper around identifyKnownObject. Accepts type information
273 /// about the object and produces a smaller identifier by relying on
274 /// the alignment information. Note that sub-classes may have different
275 /// alignment, so the most base class should be passed as template parameter
276 /// in order to obtain correct results. For that reason automatic template
277 /// parameter deduction is disabled.
278 /// \return An index uniquely and reproducibly identifying
279 /// an input pointer \p Ptr in the given allocator. This identifier is
280 /// different from the ones produced by identifyObject and
281 /// identifyAlignedObject.
282 template <typename T>
283 int64_t identifyKnownAlignedObject(const void *Ptr) {
284 int64_t Out = identifyKnownObject(Ptr);
285 assert(Out % alignof(T) == 0 && "Wrong alignment information");
286 return Out / alignof(T);
287 }
288
289 size_t getTotalMemory() const {
290 size_t TotalMemory = 0;
291 for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
292 TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
293 for (const auto &PtrAndSize : CustomSizedSlabs)
294 TotalMemory += PtrAndSize.second;
295 return TotalMemory;
296 }
297
298 size_t getBytesAllocated() const { return BytesAllocated; }
299
300 void setRedZoneSize(size_t NewSize) {
301 RedZoneSize = NewSize;
302 }
303
304 void PrintStats() const {
305 detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
307 }
308
309private:
310 /// The current pointer into the current slab.
311 ///
312 /// This points to the next free byte in the slab.
313 char *CurPtr = nullptr;
314
315 /// The end of the current slab.
316 char *End = nullptr;
317
318 /// The slabs allocated so far.
320
321 /// Custom-sized slabs allocated for too-large allocation requests.
322 SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
323
324 /// How many bytes we've allocated.
325 ///
326 /// Used so that we can compute how much space was wasted.
327 size_t BytesAllocated = 0;
328
329 /// The number of bytes to put between allocations when running under
330 /// a sanitizer.
331 size_t RedZoneSize = 1;
332
333 static size_t computeSlabSize(unsigned SlabIdx) {
334 // Scale the actual allocated slab size based on the number of slabs
335 // allocated. Every GrowthDelay slabs allocated, we double
336 // the allocated size to reduce allocation frequency, but saturate at
337 // multiplying the slab size by 2^30.
338 return SlabSize *
339 ((size_t)1 << std::min<size_t>(30, SlabIdx / GrowthDelay));
340 }
341
342 /// Allocate a new slab and move the bump pointers over into the new
343 /// slab, modifying CurPtr and End.
344 void StartNewSlab() {
345 size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
346
347 void *NewSlab = this->getAllocator().Allocate(AllocatedSlabSize,
348 alignof(std::max_align_t));
349 // We own the new slab and don't want anyone reading anything other than
350 // pieces returned from this method. So poison the whole slab.
351 __asan_poison_memory_region(NewSlab, AllocatedSlabSize);
352
353 Slabs.push_back(NewSlab);
354 CurPtr = (char *)(NewSlab);
355 End = ((char *)NewSlab) + AllocatedSlabSize;
356 }
357
358 /// Deallocate a sequence of slabs.
359 void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
360 SmallVectorImpl<void *>::iterator E) {
361 for (; I != E; ++I) {
362 size_t AllocatedSlabSize =
363 computeSlabSize(std::distance(Slabs.begin(), I));
364 this->getAllocator().Deallocate(*I, AllocatedSlabSize,
365 alignof(std::max_align_t));
366 }
367 }
368
369 /// Deallocate all memory for custom sized slabs.
370 void DeallocateCustomSizedSlabs() {
371 for (auto &PtrAndSize : CustomSizedSlabs) {
372 void *Ptr = PtrAndSize.first;
373 size_t Size = PtrAndSize.second;
374 this->getAllocator().Deallocate(Ptr, Size, alignof(std::max_align_t));
375 }
376 }
377
378 template <typename T> friend class SpecificBumpPtrAllocator;
379};
380
381/// The standard BumpPtrAllocator which just uses the default template
382/// parameters.
384
385/// A BumpPtrAllocator that allows only elements of a specific type to be
386/// allocated.
387///
388/// This allows calling the destructor in DestroyAll() and when the allocator is
389/// destroyed.
390template <typename T> class SpecificBumpPtrAllocator {
391 BumpPtrAllocator Allocator;
392
393public:
395 // Because SpecificBumpPtrAllocator walks the memory to call destructors,
396 // it can't have red zones between allocations.
397 Allocator.setRedZoneSize(0);
398 }
400 : Allocator(std::move(Old.Allocator)) {}
402
404 Allocator = std::move(RHS.Allocator);
405 return *this;
406 }
407
408 /// Call the destructor of each allocated object and deallocate all but the
409 /// current slab and reset the current pointer to the beginning of it, freeing
410 /// all memory allocated so far.
411 void DestroyAll() {
412 auto DestroyElements = [](char *Begin, char *End) {
413 assert(Begin == (char *)alignAddr(Begin, Align::Of<T>()));
414 for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
415 reinterpret_cast<T *>(Ptr)->~T();
416 };
417
418 for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
419 ++I) {
420 size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
421 std::distance(Allocator.Slabs.begin(), I));
422 char *Begin = (char *)alignAddr(*I, Align::Of<T>());
423 char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
424 : (char *)*I + AllocatedSlabSize;
425
426 DestroyElements(Begin, End);
427 }
428
429 for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
430 void *Ptr = PtrAndSize.first;
431 size_t Size = PtrAndSize.second;
432 DestroyElements((char *)alignAddr(Ptr, Align::Of<T>()),
433 (char *)Ptr + Size);
434 }
435
436 Allocator.Reset();
437 }
438
439 /// Allocate space for an array of objects without constructing them.
440 T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
441
442 /// \return An index uniquely and reproducibly identifying
443 /// an input pointer \p Ptr in the given allocator.
444 /// Returns an empty optional if the pointer is not found in the allocator.
445 std::optional<int64_t> identifyObject(const void *Ptr) {
446 return Allocator.identifyObject(Ptr);
447 }
448};
449
450} // end namespace llvm
451
452template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold,
453 size_t GrowthDelay>
454void *
455operator new(size_t Size,
456 llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold,
457 GrowthDelay> &Allocator) {
458 return Allocator.Allocate(Size, std::min((size_t)llvm::NextPowerOf2(Size),
459 alignof(std::max_align_t)));
460}
461
462template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold,
463 size_t GrowthDelay>
464void operator delete(void *,
465 llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
466 SizeThreshold, GrowthDelay> &) {
467}
468
469#endif // LLVM_SUPPORT_ALLOCATOR_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines MallocAllocator.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition: Compiler.h:213
#define __asan_poison_memory_region(p, size)
Definition: Compiler.h:568
#define __asan_unpoison_memory_region(p, size)
Definition: Compiler.h:569
#define LLVM_ATTRIBUTE_NOINLINE
LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, mark a method "not for inl...
Definition: Compiler.h:346
#define LLVM_ATTRIBUTE_RETURNS_NONNULL
Definition: Compiler.h:373
#define __msan_allocated_memory(p, size)
Definition: Compiler.h:543
#define LLVM_LIKELY(EXPR)
Definition: Compiler.h:335
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
#define I(x, y, z)
Definition: MD5.cpp:58
#define T
#define P(N)
Basic Register Allocator
This file defines the SmallVector class.
Value * RHS
CRTP base class providing obvious overloads for the core Allocate() methods of LLVM-style allocators.
Definition: AllocatorBase.h:40
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:67
size_t GetNumSlabs() const
Definition: Allocator.h:233
LLVM_ATTRIBUTE_RETURNS_NONNULL void * Allocate(size_t Size, size_t Alignment)
Definition: Allocator.h:215
void setRedZoneSize(size_t NewSize)
Definition: Allocator.h:300
std::optional< int64_t > identifyObject(const void *Ptr)
Definition: Allocator.h:240
LLVM_ATTRIBUTE_RETURNS_NONNULL void * Allocate(size_t Size, Align Alignment)
Allocate space at the specified alignment.
Definition: Allocator.h:149
BumpPtrAllocatorImpl(BumpPtrAllocatorImpl &&Old)
Definition: Allocator.h:87
int64_t identifyKnownAlignedObject(const void *Ptr)
A wrapper around identifyKnownObject.
Definition: Allocator.h:283
size_t getBytesAllocated() const
Definition: Allocator.h:298
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it,...
Definition: Allocator.h:124
void Deallocate(const void *Ptr, size_t Size, size_t)
Definition: Allocator.h:226
BumpPtrAllocatorImpl(T &&Allocator)
Definition: Allocator.h:82
size_t getTotalMemory() const
Definition: Allocator.h:289
BumpPtrAllocatorImpl & operator=(BumpPtrAllocatorImpl &&RHS)
Definition: Allocator.h:103
int64_t identifyKnownObject(const void *Ptr)
A wrapper around identifyObject that additionally asserts that the object is indeed within the alloca...
Definition: Allocator.h:266
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_NOINLINE void * AllocateSlow(size_t Size, size_t SizeToAllocate, Align Alignment)
Definition: Allocator.h:183
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
iterator erase(const_iterator CI)
Definition: SmallVector.h:738
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
A BumpPtrAllocator that allows only elements of a specific type to be allocated.
Definition: Allocator.h:390
std::optional< int64_t > identifyObject(const void *Ptr)
Definition: Allocator.h:445
SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old)
Definition: Allocator.h:399
T * Allocate(size_t num=1)
Allocate space for an array of objects without constructing them.
Definition: Allocator.h:440
void DestroyAll()
Call the destructor of each allocated object and deallocate all but the current slab and reset the cu...
Definition: Allocator.h:411
SpecificBumpPtrAllocator & operator=(SpecificBumpPtrAllocator &&RHS)
Definition: Allocator.h:403
LLVM_ABI void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated, size_t TotalMemory)
Definition: Allocator.cpp:20
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition: Allocator.h:383
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1886
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition: MathExtras.h:378
uintptr_t alignAddr(const void *Addr, Align Alignment)
Aligns Addr to Alignment bytes, rounding up.
Definition: Alignment.h:187
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85