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