82c200abd0672f088efd0e1cdf6d54f4ccbd43fa
[oota-llvm.git] / include / llvm / Support / Allocator.h
1 //===--- Allocator.h - Simple memory allocation abstraction -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
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
17 /// AllocatorBase.
18 ///
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_SUPPORT_ALLOCATOR_H
22 #define LLVM_SUPPORT_ALLOCATOR_H
23
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"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstddef>
32 #include <cstdlib>
33
34 namespace llvm {
35 template <typename T> struct ReferenceAdder {
36   typedef T &result;
37 };
38 template <typename T> struct ReferenceAdder<T &> {
39   typedef T result;
40 };
41
42 /// \brief CRTP base class providing obvious overloads for the core \c
43 /// Allocate() methods of LLVM-style allocators.
44 ///
45 /// This base class both documents the full public interface exposed by all
46 /// LLVM-style allocators, and redirects all of the overloads to a single core
47 /// set of methods which the derived class must define.
48 template <typename DerivedT> class AllocatorBase {
49 public:
50   /// \brief Allocate \a Size bytes of \a Alignment aligned memory. This method
51   /// must be implemented by \c DerivedT.
52   void *Allocate(size_t Size, size_t Alignment) {
53 #ifdef __clang__
54     static_assert(static_cast<void *(AllocatorBase::*)(size_t, size_t)>(
55                       &AllocatorBase::Allocate) !=
56                       static_cast<void *(DerivedT::*)(size_t, size_t)>(
57                           &DerivedT::Allocate),
58                   "Class derives from AllocatorBase without implementing the "
59                   "core Allocate(size_t, size_t) overload!");
60 #endif
61     return static_cast<DerivedT *>(this)->Allocate(Size, Alignment);
62   }
63
64   /// \brief Deallocate \a Ptr to \a Size bytes of memory allocated by this
65   /// allocator.
66   void Deallocate(const void *Ptr, size_t Size) {
67 #ifdef __clang__
68     static_assert(static_cast<void (AllocatorBase::*)(const void *, size_t)>(
69                       &AllocatorBase::Deallocate) !=
70                       static_cast<void (DerivedT::*)(const void *, size_t)>(
71                           &DerivedT::Deallocate),
72                   "Class derives from AllocatorBase without implementing the "
73                   "core Deallocate(void *) overload!");
74 #endif
75     return static_cast<DerivedT *>(this)->Deallocate(Ptr, Size);
76   }
77
78   // The rest of these methods are helpers that redirect to one of the above
79   // core methods.
80
81   /// \brief Allocate space for a sequence of objects without constructing them.
82   template <typename T> T *Allocate(size_t Num = 1) {
83     return static_cast<T *>(Allocate(Num * sizeof(T), AlignOf<T>::Alignment));
84   }
85
86   /// \brief Deallocate space for a sequence of objects without constructing them.
87   template <typename T>
88   typename std::enable_if<
89       !std::is_same<typename std::remove_cv<T>::type, void>::value, void>::type
90   Deallocate(T *Ptr, size_t Num = 1) {
91     Deallocate(static_cast<const void *>(Ptr), Num * sizeof(T));
92   }
93 };
94
95 class MallocAllocator : public AllocatorBase<MallocAllocator> {
96 public:
97   MallocAllocator() {}
98   ~MallocAllocator() {}
99
100   void Reset() {}
101
102   void *Allocate(size_t Size, size_t /*Alignment*/) { return malloc(Size); }
103
104   // Pull in base class overloads.
105   using AllocatorBase<MallocAllocator>::Allocate;
106
107   void Deallocate(const void *Ptr, size_t /*Size*/) {
108     free(const_cast<void *>(Ptr));
109   }
110
111   // Pull in base class overloads.
112   using AllocatorBase<MallocAllocator>::Deallocate;
113
114   void PrintStats() const {}
115 };
116
117 namespace detail {
118
119 // We call out to an external function to actually print the message as the
120 // printing code uses Allocator.h in its implementation.
121 void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated,
122                                 size_t TotalMemory);
123 } // End namespace detail.
124
125 /// \brief Allocate memory in an ever growing pool, as if by bump-pointer.
126 ///
127 /// This isn't strictly a bump-pointer allocator as it uses backing slabs of
128 /// memory rather than relying on boundless contiguous heap. However, it has
129 /// bump-pointer semantics in that is a monotonically growing pool of memory
130 /// where every allocation is found by merely allocating the next N bytes in
131 /// the slab, or the next N bytes in the next slab.
132 ///
133 /// Note that this also has a threshold for forcing allocations above a certain
134 /// size into their own slab.
135 ///
136 /// The BumpPtrAllocatorImpl template defaults to using a MallocAllocator
137 /// object, which wraps malloc, to allocate memory, but it can be changed to
138 /// use a custom allocator.
139 template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096,
140           size_t SizeThreshold = SlabSize>
141 class BumpPtrAllocatorImpl
142     : public AllocatorBase<
143           BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold>> {
144   BumpPtrAllocatorImpl(const BumpPtrAllocatorImpl &) LLVM_DELETED_FUNCTION;
145   void operator=(const BumpPtrAllocatorImpl &) LLVM_DELETED_FUNCTION;
146
147 public:
148   static_assert(SizeThreshold <= SlabSize,
149                 "The SizeThreshold must be at most the SlabSize to ensure "
150                 "that objects larger than a slab go into their own memory "
151                 "allocation.");
152
153   BumpPtrAllocatorImpl()
154       : CurPtr(nullptr), End(nullptr), BytesAllocated(0), Allocator() {}
155   template <typename T>
156   BumpPtrAllocatorImpl(T &&Allocator)
157       : CurPtr(nullptr), End(nullptr), BytesAllocated(0),
158         Allocator(std::forward<T &&>(Allocator)) {}
159   ~BumpPtrAllocatorImpl() {
160     DeallocateSlabs(Slabs.begin(), Slabs.end());
161     DeallocateCustomSizedSlabs();
162   }
163
164   /// \brief Deallocate all but the current slab and reset the current pointer
165   /// to the beginning of it, freeing all memory allocated so far.
166   void Reset() {
167     if (Slabs.empty())
168       return;
169
170     // Reset the state.
171     BytesAllocated = 0;
172     CurPtr = (char *)Slabs.front();
173     End = CurPtr + SlabSize;
174
175     // Deallocate all but the first slab, and all custome sized slabs.
176     DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
177     Slabs.erase(std::next(Slabs.begin()), Slabs.end());
178     DeallocateCustomSizedSlabs();
179     CustomSizedSlabs.clear();
180   }
181
182   /// \brief Allocate space at the specified alignment.
183   void *Allocate(size_t Size, size_t Alignment) {
184     if (!CurPtr) // Start a new slab if we haven't allocated one already.
185       StartNewSlab();
186
187     // Keep track of how many bytes we've allocated.
188     BytesAllocated += Size;
189
190     // 0-byte alignment means 1-byte alignment.
191     if (Alignment == 0)
192       Alignment = 1;
193
194     // Allocate the aligned space, going forwards from CurPtr.
195     char *Ptr = alignPtr(CurPtr, Alignment);
196
197     // Check if we can hold it.
198     if (Ptr + Size <= End) {
199       CurPtr = Ptr + Size;
200       // Update the allocation point of this memory block in MemorySanitizer.
201       // Without this, MemorySanitizer messages for values originated from here
202       // will point to the allocation of the entire slab.
203       __msan_allocated_memory(Ptr, Size);
204       return Ptr;
205     }
206
207     // If Size is really big, allocate a separate slab for it.
208     size_t PaddedSize = Size + Alignment - 1;
209     if (PaddedSize > SizeThreshold) {
210       void *NewSlab = Allocator.Allocate(PaddedSize, 0);
211       CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
212
213       Ptr = alignPtr((char *)NewSlab, Alignment);
214       assert((uintptr_t)Ptr + Size <= (uintptr_t)NewSlab + PaddedSize);
215       __msan_allocated_memory(Ptr, Size);
216       return Ptr;
217     }
218
219     // Otherwise, start a new slab and try again.
220     StartNewSlab();
221     Ptr = alignPtr(CurPtr, Alignment);
222     CurPtr = Ptr + Size;
223     assert(CurPtr <= End && "Unable to allocate memory!");
224     __msan_allocated_memory(Ptr, Size);
225     return Ptr;
226   }
227
228   // Pull in base class overloads.
229   using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
230
231   void Deallocate(const void * /*Ptr*/, size_t /*Size*/) {}
232
233   // Pull in base class overloads.
234   using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate;
235
236   size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
237
238   size_t getTotalMemory() const {
239     size_t TotalMemory = 0;
240     for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
241       TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
242     for (auto &PtrAndSize : CustomSizedSlabs)
243       TotalMemory += PtrAndSize.second;
244     return TotalMemory;
245   }
246
247   void PrintStats() const {
248     detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
249                                        getTotalMemory());
250   }
251
252 private:
253   /// \brief The current pointer into the current slab.
254   ///
255   /// This points to the next free byte in the slab.
256   char *CurPtr;
257
258   /// \brief The end of the current slab.
259   char *End;
260
261   /// \brief The slabs allocated so far.
262   SmallVector<void *, 4> Slabs;
263
264   /// \brief Custom-sized slabs allocated for too-large allocation requests.
265   SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
266
267   /// \brief How many bytes we've allocated.
268   ///
269   /// Used so that we can compute how much space was wasted.
270   size_t BytesAllocated;
271
272   /// \brief The allocator instance we use to get slabs of memory.
273   AllocatorT Allocator;
274
275   static size_t computeSlabSize(unsigned SlabIdx) {
276     // Scale the actual allocated slab size based on the number of slabs
277     // allocated. Every 128 slabs allocated, we double the allocated size to
278     // reduce allocation frequency, but saturate at multiplying the slab size by
279     // 2^30.
280     return SlabSize * ((size_t)1 << std::min<size_t>(30, SlabIdx / 128));
281   }
282
283   /// \brief Allocate a new slab and move the bump pointers over into the new
284   /// slab, modifying CurPtr and End.
285   void StartNewSlab() {
286     size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
287
288     void *NewSlab = Allocator.Allocate(AllocatedSlabSize, 0);
289     Slabs.push_back(NewSlab);
290     CurPtr = (char *)(NewSlab);
291     End = ((char *)NewSlab) + AllocatedSlabSize;
292   }
293
294   /// \brief Deallocate a sequence of slabs.
295   void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
296                        SmallVectorImpl<void *>::iterator E) {
297     for (; I != E; ++I) {
298       size_t AllocatedSlabSize =
299           computeSlabSize(std::distance(Slabs.begin(), I));
300 #ifndef NDEBUG
301       // Poison the memory so stale pointers crash sooner.  Note we must
302       // preserve the Size and NextPtr fields at the beginning.
303       sys::Memory::setRangeWritable(*I, AllocatedSlabSize);
304       memset(*I, 0xCD, AllocatedSlabSize);
305 #endif
306       Allocator.Deallocate(*I, AllocatedSlabSize);
307     }
308   }
309
310   /// \brief Deallocate all memory for custom sized slabs.
311   void DeallocateCustomSizedSlabs() {
312     for (auto &PtrAndSize : CustomSizedSlabs) {
313       void *Ptr = PtrAndSize.first;
314       size_t Size = PtrAndSize.second;
315 #ifndef NDEBUG
316       // Poison the memory so stale pointers crash sooner.  Note we must
317       // preserve the Size and NextPtr fields at the beginning.
318       sys::Memory::setRangeWritable(Ptr, Size);
319       memset(Ptr, 0xCD, Size);
320 #endif
321       Allocator.Deallocate(Ptr, Size);
322     }
323   }
324
325   template <typename T> friend class SpecificBumpPtrAllocator;
326 };
327
328 /// \brief The standard BumpPtrAllocator which just uses the default template
329 /// paramaters.
330 typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
331
332 /// \brief A BumpPtrAllocator that allows only elements of a specific type to be
333 /// allocated.
334 ///
335 /// This allows calling the destructor in DestroyAll() and when the allocator is
336 /// destroyed.
337 template <typename T> class SpecificBumpPtrAllocator {
338   BumpPtrAllocator Allocator;
339
340 public:
341   SpecificBumpPtrAllocator() : Allocator() {}
342
343   ~SpecificBumpPtrAllocator() { DestroyAll(); }
344
345   /// Call the destructor of each allocated object and deallocate all but the
346   /// current slab and reset the current pointer to the beginning of it, freeing
347   /// all memory allocated so far.
348   void DestroyAll() {
349     auto DestroyElements = [](char *Begin, char *End) {
350       assert(Begin == alignPtr(Begin, alignOf<T>()));
351       for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
352         reinterpret_cast<T *>(Ptr)->~T();
353     };
354
355     for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
356          ++I) {
357       size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
358           std::distance(Allocator.Slabs.begin(), I));
359       char *Begin = alignPtr((char *)*I, alignOf<T>());
360       char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
361                                                : (char *)*I + AllocatedSlabSize;
362
363       DestroyElements(Begin, End);
364     }
365
366     for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
367       void *Ptr = PtrAndSize.first;
368       size_t Size = PtrAndSize.second;
369       DestroyElements(alignPtr((char *)Ptr, alignOf<T>()), (char *)Ptr + Size);
370     }
371
372     Allocator.Reset();
373   }
374
375   /// \brief Allocate space for an array of objects without constructing them.
376   T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
377
378 private:
379 };
380
381 }  // end namespace llvm
382
383 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
384 void *operator new(size_t Size,
385                    llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
386                                               SizeThreshold> &Allocator) {
387   struct S {
388     char c;
389     union {
390       double D;
391       long double LD;
392       long long L;
393       void *P;
394     } x;
395   };
396   return Allocator.Allocate(
397       Size, std::min((size_t)llvm::NextPowerOf2(Size), offsetof(S, x)));
398 }
399
400 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
401 void operator delete(
402     void *, llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold> &) {
403 }
404
405 #endif // LLVM_SUPPORT_ALLOCATOR_H