1 //===--- Allocator.h - Simple memory allocation abstraction -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file defines the MallocAllocator and BumpPtrAllocator interfaces. Both
12 /// of these conform to an LLVM "Allocator" concept which consists of an
13 /// Allocate method accepting a size and alignment, and a Deallocate accepting
14 /// a pointer and size. Further, the LLVM "Allocator" concept has overloads of
15 /// Allocate and Deallocate for setting size and alignment based on the final
16 /// type. These overloads are typically provided by a base class template \c
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_SUPPORT_ALLOCATOR_H
22 #define LLVM_SUPPORT_ALLOCATOR_H
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/AlignOf.h"
26 #include "llvm/Support/DataTypes.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/Memory.h"
36 /// \brief CRTP base class providing obvious overloads for the core \c
37 /// Allocate() methods of LLVM-style allocators.
39 /// This base class both documents the full public interface exposed by all
40 /// LLVM-style allocators, and redirects all of the overloads to a single core
41 /// set of methods which the derived class must define.
42 template <typename DerivedT> class AllocatorBase {
44 /// \brief Allocate \a Size bytes of \a Alignment aligned memory. This method
45 /// must be implemented by \c DerivedT.
46 void *Allocate(size_t Size, size_t Alignment) {
48 static_assert(static_cast<void *(AllocatorBase::*)(size_t, size_t)>(
49 &AllocatorBase::Allocate) !=
50 static_cast<void *(DerivedT::*)(size_t, size_t)>(
52 "Class derives from AllocatorBase without implementing the "
53 "core Allocate(size_t, size_t) overload!");
55 return static_cast<DerivedT *>(this)->Allocate(Size, Alignment);
58 /// \brief Deallocate \a Ptr to \a Size bytes of memory allocated by this
60 void Deallocate(const void *Ptr, size_t Size) {
62 static_assert(static_cast<void (AllocatorBase::*)(const void *, size_t)>(
63 &AllocatorBase::Deallocate) !=
64 static_cast<void (DerivedT::*)(const void *, size_t)>(
65 &DerivedT::Deallocate),
66 "Class derives from AllocatorBase without implementing the "
67 "core Deallocate(void *) overload!");
69 return static_cast<DerivedT *>(this)->Deallocate(Ptr, Size);
72 // The rest of these methods are helpers that redirect to one of the above
75 /// \brief Allocate space for a sequence of objects without constructing them.
76 template <typename T> T *Allocate(size_t Num = 1) {
77 return static_cast<T *>(Allocate(Num * sizeof(T), AlignOf<T>::Alignment));
80 /// \brief Deallocate space for a sequence of objects without constructing them.
82 typename std::enable_if<
83 !std::is_same<typename std::remove_cv<T>::type, void>::value, void>::type
84 Deallocate(T *Ptr, size_t Num = 1) {
85 Deallocate(static_cast<const void *>(Ptr), Num * sizeof(T));
89 class MallocAllocator : public AllocatorBase<MallocAllocator> {
93 LLVM_ATTRIBUTE_RETURNS_NONNULL void *Allocate(size_t Size,
94 size_t /*Alignment*/) {
98 // Pull in base class overloads.
99 using AllocatorBase<MallocAllocator>::Allocate;
101 void Deallocate(const void *Ptr, size_t /*Size*/) {
102 free(const_cast<void *>(Ptr));
105 // Pull in base class overloads.
106 using AllocatorBase<MallocAllocator>::Deallocate;
108 void PrintStats() const {}
113 // We call out to an external function to actually print the message as the
114 // printing code uses Allocator.h in its implementation.
115 void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated,
117 } // End namespace detail.
119 /// \brief Allocate memory in an ever growing pool, as if by bump-pointer.
121 /// This isn't strictly a bump-pointer allocator as it uses backing slabs of
122 /// memory rather than relying on boundless contiguous heap. However, it has
123 /// bump-pointer semantics in that is a monotonically growing pool of memory
124 /// where every allocation is found by merely allocating the next N bytes in
125 /// the slab, or the next N bytes in the next slab.
127 /// Note that this also has a threshold for forcing allocations above a certain
128 /// size into their own slab.
130 /// The BumpPtrAllocatorImpl template defaults to using a MallocAllocator
131 /// object, which wraps malloc, to allocate memory, but it can be changed to
132 /// use a custom allocator.
133 template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096,
134 size_t SizeThreshold = SlabSize>
135 class BumpPtrAllocatorImpl
136 : public AllocatorBase<
137 BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold>> {
139 static_assert(SizeThreshold <= SlabSize,
140 "The SizeThreshold must be at most the SlabSize to ensure "
141 "that objects larger than a slab go into their own memory "
144 BumpPtrAllocatorImpl()
145 : CurPtr(nullptr), End(nullptr), BytesAllocated(0), Allocator() {}
146 template <typename T>
147 BumpPtrAllocatorImpl(T &&Allocator)
148 : CurPtr(nullptr), End(nullptr), BytesAllocated(0),
149 Allocator(std::forward<T &&>(Allocator)) {}
151 // Manually implement a move constructor as we must clear the old allocators
152 // slabs as a matter of correctness.
153 BumpPtrAllocatorImpl(BumpPtrAllocatorImpl &&Old)
154 : CurPtr(Old.CurPtr), End(Old.End), Slabs(std::move(Old.Slabs)),
155 CustomSizedSlabs(std::move(Old.CustomSizedSlabs)),
156 BytesAllocated(Old.BytesAllocated),
157 Allocator(std::move(Old.Allocator)) {
158 Old.CurPtr = Old.End = nullptr;
159 Old.BytesAllocated = 0;
161 Old.CustomSizedSlabs.clear();
164 ~BumpPtrAllocatorImpl() {
165 DeallocateSlabs(Slabs.begin(), Slabs.end());
166 DeallocateCustomSizedSlabs();
169 BumpPtrAllocatorImpl &operator=(BumpPtrAllocatorImpl &&RHS) {
170 DeallocateSlabs(Slabs.begin(), Slabs.end());
171 DeallocateCustomSizedSlabs();
175 BytesAllocated = RHS.BytesAllocated;
176 Slabs = std::move(RHS.Slabs);
177 CustomSizedSlabs = std::move(RHS.CustomSizedSlabs);
178 Allocator = std::move(RHS.Allocator);
180 RHS.CurPtr = RHS.End = nullptr;
181 RHS.BytesAllocated = 0;
183 RHS.CustomSizedSlabs.clear();
187 /// \brief Deallocate all but the current slab and reset the current pointer
188 /// to the beginning of it, freeing all memory allocated so far.
195 CurPtr = (char *)Slabs.front();
196 End = CurPtr + SlabSize;
198 // Deallocate all but the first slab, and all custome sized slabs.
199 DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
200 Slabs.erase(std::next(Slabs.begin()), Slabs.end());
201 DeallocateCustomSizedSlabs();
202 CustomSizedSlabs.clear();
205 /// \brief Allocate space at the specified alignment.
206 LLVM_ATTRIBUTE_RETURNS_NONNULL void *Allocate(size_t Size, size_t Alignment) {
207 assert(Alignment > 0 && "0-byte alignnment is not allowed. Use 1 instead.");
209 // Keep track of how many bytes we've allocated.
210 BytesAllocated += Size;
212 // Allocate the aligned space, going forwards from CurPtr.
213 char *Ptr = alignPtr(CurPtr, Alignment);
215 // Check if we can hold it.
216 if (Ptr + Size <= End) {
218 // Update the allocation point of this memory block in MemorySanitizer.
219 // Without this, MemorySanitizer messages for values originated from here
220 // will point to the allocation of the entire slab.
221 __msan_allocated_memory(Ptr, Size);
225 // If Size is really big, allocate a separate slab for it.
226 size_t PaddedSize = Size + Alignment - 1;
227 if (PaddedSize > SizeThreshold) {
228 void *NewSlab = Allocator.Allocate(PaddedSize, 0);
229 CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
231 Ptr = alignPtr((char *)NewSlab, Alignment);
232 assert((uintptr_t)Ptr + Size <= (uintptr_t)NewSlab + PaddedSize);
233 __msan_allocated_memory(Ptr, Size);
237 // Otherwise, start a new slab and try again.
239 Ptr = alignPtr(CurPtr, Alignment);
241 assert(CurPtr <= End && "Unable to allocate memory!");
242 __msan_allocated_memory(Ptr, Size);
246 // Pull in base class overloads.
247 using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
249 void Deallocate(const void * /*Ptr*/, size_t /*Size*/) {}
251 // Pull in base class overloads.
252 using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate;
254 size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
256 size_t getTotalMemory() const {
257 size_t TotalMemory = 0;
258 for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
259 TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
260 for (auto &PtrAndSize : CustomSizedSlabs)
261 TotalMemory += PtrAndSize.second;
265 void PrintStats() const {
266 detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
271 /// \brief The current pointer into the current slab.
273 /// This points to the next free byte in the slab.
276 /// \brief The end of the current slab.
279 /// \brief The slabs allocated so far.
280 SmallVector<void *, 4> Slabs;
282 /// \brief Custom-sized slabs allocated for too-large allocation requests.
283 SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
285 /// \brief How many bytes we've allocated.
287 /// Used so that we can compute how much space was wasted.
288 size_t BytesAllocated;
290 /// \brief The allocator instance we use to get slabs of memory.
291 AllocatorT Allocator;
293 static size_t computeSlabSize(unsigned SlabIdx) {
294 // Scale the actual allocated slab size based on the number of slabs
295 // allocated. Every 128 slabs allocated, we double the allocated size to
296 // reduce allocation frequency, but saturate at multiplying the slab size by
298 return SlabSize * ((size_t)1 << std::min<size_t>(30, SlabIdx / 128));
301 /// \brief Allocate a new slab and move the bump pointers over into the new
302 /// slab, modifying CurPtr and End.
303 void StartNewSlab() {
304 size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
306 void *NewSlab = Allocator.Allocate(AllocatedSlabSize, 0);
307 Slabs.push_back(NewSlab);
308 CurPtr = (char *)(NewSlab);
309 End = ((char *)NewSlab) + AllocatedSlabSize;
312 /// \brief Deallocate a sequence of slabs.
313 void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
314 SmallVectorImpl<void *>::iterator E) {
315 for (; I != E; ++I) {
316 size_t AllocatedSlabSize =
317 computeSlabSize(std::distance(Slabs.begin(), I));
319 // Poison the memory so stale pointers crash sooner. Note we must
320 // preserve the Size and NextPtr fields at the beginning.
321 if (AllocatedSlabSize != 0) {
322 sys::Memory::setRangeWritable(*I, AllocatedSlabSize);
323 memset(*I, 0xCD, AllocatedSlabSize);
326 Allocator.Deallocate(*I, AllocatedSlabSize);
330 /// \brief Deallocate all memory for custom sized slabs.
331 void DeallocateCustomSizedSlabs() {
332 for (auto &PtrAndSize : CustomSizedSlabs) {
333 void *Ptr = PtrAndSize.first;
334 size_t Size = PtrAndSize.second;
336 // Poison the memory so stale pointers crash sooner. Note we must
337 // preserve the Size and NextPtr fields at the beginning.
338 sys::Memory::setRangeWritable(Ptr, Size);
339 memset(Ptr, 0xCD, Size);
341 Allocator.Deallocate(Ptr, Size);
345 template <typename T> friend class SpecificBumpPtrAllocator;
348 /// \brief The standard BumpPtrAllocator which just uses the default template
350 typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
352 /// \brief A BumpPtrAllocator that allows only elements of a specific type to be
355 /// This allows calling the destructor in DestroyAll() and when the allocator is
357 template <typename T> class SpecificBumpPtrAllocator {
358 BumpPtrAllocator Allocator;
361 SpecificBumpPtrAllocator() : Allocator() {}
362 SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old)
363 : Allocator(std::move(Old.Allocator)) {}
364 ~SpecificBumpPtrAllocator() { DestroyAll(); }
366 SpecificBumpPtrAllocator &operator=(SpecificBumpPtrAllocator &&RHS) {
367 Allocator = std::move(RHS.Allocator);
371 /// Call the destructor of each allocated object and deallocate all but the
372 /// current slab and reset the current pointer to the beginning of it, freeing
373 /// all memory allocated so far.
375 auto DestroyElements = [](char *Begin, char *End) {
376 assert(Begin == alignPtr(Begin, alignOf<T>()));
377 for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
378 reinterpret_cast<T *>(Ptr)->~T();
381 for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
383 size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
384 std::distance(Allocator.Slabs.begin(), I));
385 char *Begin = alignPtr((char *)*I, alignOf<T>());
386 char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
387 : (char *)*I + AllocatedSlabSize;
389 DestroyElements(Begin, End);
392 for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
393 void *Ptr = PtrAndSize.first;
394 size_t Size = PtrAndSize.second;
395 DestroyElements(alignPtr((char *)Ptr, alignOf<T>()), (char *)Ptr + Size);
401 /// \brief Allocate space for an array of objects without constructing them.
402 T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
405 } // end namespace llvm
407 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
408 void *operator new(size_t Size,
409 llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
410 SizeThreshold> &Allocator) {
420 return Allocator.Allocate(
421 Size, std::min((size_t)llvm::NextPowerOf2(Size), offsetof(S, x)));
424 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
425 void operator delete(
426 void *, llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold> &) {
429 #endif // LLVM_SUPPORT_ALLOCATOR_H