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