xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Support/Allocator.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
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 
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Support/Alignment.h"
22 #include "llvm/Support/AllocatorBase.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/MathExtras.h"
25 #include <algorithm>
26 #include <cassert>
27 #include <cstddef>
28 #include <cstdint>
29 #include <iterator>
30 #include <optional>
31 #include <utility>
32 
33 namespace llvm {
34 
35 namespace 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.
39 LLVM_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.
62 template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096,
63           size_t SizeThreshold = SlabSize, size_t GrowthDelay = 128>
64 class BumpPtrAllocatorImpl
65     : public AllocatorBase<BumpPtrAllocatorImpl<AllocatorT, SlabSize,
66                                                 SizeThreshold, GrowthDelay>>,
67       private detail::AllocatorHolder<AllocatorT> {
68   using AllocTy = detail::AllocatorHolder<AllocatorT>;
69 
70 public:
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 
79   BumpPtrAllocatorImpl() = default;
80 
81   template <typename T>
BumpPtrAllocatorImpl(T && Allocator)82   BumpPtrAllocatorImpl(T &&Allocator)
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.
BumpPtrAllocatorImpl(BumpPtrAllocatorImpl && Old)87   BumpPtrAllocatorImpl(BumpPtrAllocatorImpl &&Old)
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 
~BumpPtrAllocatorImpl()98   ~BumpPtrAllocatorImpl() {
99     DeallocateSlabs(Slabs.begin(), Slabs.end());
100     DeallocateCustomSizedSlabs();
101   }
102 
103   BumpPtrAllocatorImpl &operator=(BumpPtrAllocatorImpl &&RHS) {
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.
Reset()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).
Allocate(size_t Size,Align Alignment)149   LLVM_ATTRIBUTE_RETURNS_NONNULL void *Allocate(size_t Size, Align Alignment) {
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 
182   LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_NOINLINE void *
AllocateSlow(size_t Size,size_t SizeToAllocate,Align Alignment)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);
198       __asan_unpoison_memory_region(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);
210     __asan_unpoison_memory_region(AlignedPtr, Size);
211     return AlignedPtr;
212   }
213 
214   inline LLVM_ATTRIBUTE_RETURNS_NONNULL void *
Allocate(size_t Size,size_t Alignment)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.
221   using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
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.
Deallocate(const void * Ptr,size_t Size,size_t)226   void Deallocate(const void *Ptr, size_t Size, size_t /*Alignment*/) {
227     __asan_poison_memory_region(Ptr, Size);
228   }
229 
230   // Pull in base class overloads.
231   using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate;
232 
GetNumSlabs()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.
identifyObject(const void * Ptr)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.
identifyKnownObject(const void * Ptr)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>
identifyKnownAlignedObject(const void * Ptr)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 
getTotalMemory()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 
getBytesAllocated()298   size_t getBytesAllocated() const { return BytesAllocated; }
299 
setRedZoneSize(size_t NewSize)300   void setRedZoneSize(size_t NewSize) {
301     RedZoneSize = NewSize;
302   }
303 
PrintStats()304   void PrintStats() const {
305     detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
306                                        getTotalMemory());
307   }
308 
309 private:
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.
319   SmallVector<void *, 4> Slabs;
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 
computeSlabSize(unsigned SlabIdx)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.
StartNewSlab()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.
DeallocateSlabs(SmallVectorImpl<void * >::iterator I,SmallVectorImpl<void * >::iterator E)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.
DeallocateCustomSizedSlabs()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.
383 typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
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.
390 template <typename T> class SpecificBumpPtrAllocator {
391   BumpPtrAllocator Allocator;
392 
393 public:
SpecificBumpPtrAllocator()394   SpecificBumpPtrAllocator() {
395     // Because SpecificBumpPtrAllocator walks the memory to call destructors,
396     // it can't have red zones between allocations.
397     Allocator.setRedZoneSize(0);
398   }
SpecificBumpPtrAllocator(SpecificBumpPtrAllocator && Old)399   SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old)
400       : Allocator(std::move(Old.Allocator)) {}
~SpecificBumpPtrAllocator()401   ~SpecificBumpPtrAllocator() { DestroyAll(); }
402 
403   SpecificBumpPtrAllocator &operator=(SpecificBumpPtrAllocator &&RHS) {
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.
DestroyAll()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.
identifyObject(const void * Ptr)445   std::optional<int64_t> identifyObject(const void *Ptr) {
446     return Allocator.identifyObject(Ptr);
447   }
448 };
449 
450 } // end namespace llvm
451 
452 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold,
453           size_t GrowthDelay>
454 void *
new(size_t Size,llvm::BumpPtrAllocatorImpl<AllocatorT,SlabSize,SizeThreshold,GrowthDelay> & Allocator)455 operator 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 
462 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold,
463           size_t GrowthDelay>
delete(void *,llvm::BumpPtrAllocatorImpl<AllocatorT,SlabSize,SizeThreshold,GrowthDelay> &)464 void operator delete(void *,
465                      llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
466                                                 SizeThreshold, GrowthDelay> &) {
467 }
468 
469 #endif // LLVM_SUPPORT_ALLOCATOR_H
470