LLVM API Documentation

Allocator.h
Go to the documentation of this file.
00001 //===--- Allocator.h - Simple memory allocation abstraction -----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 /// \file
00010 ///
00011 /// This file defines the MallocAllocator and BumpPtrAllocator interfaces. Both
00012 /// of these conform to an LLVM "Allocator" concept which consists of an
00013 /// Allocate method accepting a size and alignment, and a Deallocate accepting
00014 /// a pointer and size. Further, the LLVM "Allocator" concept has overloads of
00015 /// Allocate and Deallocate for setting size and alignment based on the final
00016 /// type. These overloads are typically provided by a base class template \c
00017 /// AllocatorBase.
00018 ///
00019 //===----------------------------------------------------------------------===//
00020 
00021 #ifndef LLVM_SUPPORT_ALLOCATOR_H
00022 #define LLVM_SUPPORT_ALLOCATOR_H
00023 
00024 #include "llvm/ADT/SmallVector.h"
00025 #include "llvm/Support/AlignOf.h"
00026 #include "llvm/Support/DataTypes.h"
00027 #include "llvm/Support/MathExtras.h"
00028 #include "llvm/Support/Memory.h"
00029 #include <algorithm>
00030 #include <cassert>
00031 #include <cstddef>
00032 #include <cstdlib>
00033 
00034 namespace llvm {
00035 
00036 /// \brief CRTP base class providing obvious overloads for the core \c
00037 /// Allocate() methods of LLVM-style allocators.
00038 ///
00039 /// This base class both documents the full public interface exposed by all
00040 /// LLVM-style allocators, and redirects all of the overloads to a single core
00041 /// set of methods which the derived class must define.
00042 template <typename DerivedT> class AllocatorBase {
00043 public:
00044   /// \brief Allocate \a Size bytes of \a Alignment aligned memory. This method
00045   /// must be implemented by \c DerivedT.
00046   void *Allocate(size_t Size, size_t Alignment) {
00047 #ifdef __clang__
00048     static_assert(static_cast<void *(AllocatorBase::*)(size_t, size_t)>(
00049                       &AllocatorBase::Allocate) !=
00050                       static_cast<void *(DerivedT::*)(size_t, size_t)>(
00051                           &DerivedT::Allocate),
00052                   "Class derives from AllocatorBase without implementing the "
00053                   "core Allocate(size_t, size_t) overload!");
00054 #endif
00055     return static_cast<DerivedT *>(this)->Allocate(Size, Alignment);
00056   }
00057 
00058   /// \brief Deallocate \a Ptr to \a Size bytes of memory allocated by this
00059   /// allocator.
00060   void Deallocate(const void *Ptr, size_t Size) {
00061 #ifdef __clang__
00062     static_assert(static_cast<void (AllocatorBase::*)(const void *, size_t)>(
00063                       &AllocatorBase::Deallocate) !=
00064                       static_cast<void (DerivedT::*)(const void *, size_t)>(
00065                           &DerivedT::Deallocate),
00066                   "Class derives from AllocatorBase without implementing the "
00067                   "core Deallocate(void *) overload!");
00068 #endif
00069     return static_cast<DerivedT *>(this)->Deallocate(Ptr, Size);
00070   }
00071 
00072   // The rest of these methods are helpers that redirect to one of the above
00073   // core methods.
00074 
00075   /// \brief Allocate space for a sequence of objects without constructing them.
00076   template <typename T> T *Allocate(size_t Num = 1) {
00077     return static_cast<T *>(Allocate(Num * sizeof(T), AlignOf<T>::Alignment));
00078   }
00079 
00080   /// \brief Deallocate space for a sequence of objects without constructing them.
00081   template <typename T>
00082   typename std::enable_if<
00083       !std::is_same<typename std::remove_cv<T>::type, void>::value, void>::type
00084   Deallocate(T *Ptr, size_t Num = 1) {
00085     Deallocate(static_cast<const void *>(Ptr), Num * sizeof(T));
00086   }
00087 };
00088 
00089 class MallocAllocator : public AllocatorBase<MallocAllocator> {
00090 public:
00091   void Reset() {}
00092 
00093   void *Allocate(size_t Size, size_t /*Alignment*/) { return malloc(Size); }
00094 
00095   // Pull in base class overloads.
00096   using AllocatorBase<MallocAllocator>::Allocate;
00097 
00098   void Deallocate(const void *Ptr, size_t /*Size*/) {
00099     free(const_cast<void *>(Ptr));
00100   }
00101 
00102   // Pull in base class overloads.
00103   using AllocatorBase<MallocAllocator>::Deallocate;
00104 
00105   void PrintStats() const {}
00106 };
00107 
00108 namespace detail {
00109 
00110 // We call out to an external function to actually print the message as the
00111 // printing code uses Allocator.h in its implementation.
00112 void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated,
00113                                 size_t TotalMemory);
00114 } // End namespace detail.
00115 
00116 /// \brief Allocate memory in an ever growing pool, as if by bump-pointer.
00117 ///
00118 /// This isn't strictly a bump-pointer allocator as it uses backing slabs of
00119 /// memory rather than relying on boundless contiguous heap. However, it has
00120 /// bump-pointer semantics in that is a monotonically growing pool of memory
00121 /// where every allocation is found by merely allocating the next N bytes in
00122 /// the slab, or the next N bytes in the next slab.
00123 ///
00124 /// Note that this also has a threshold for forcing allocations above a certain
00125 /// size into their own slab.
00126 ///
00127 /// The BumpPtrAllocatorImpl template defaults to using a MallocAllocator
00128 /// object, which wraps malloc, to allocate memory, but it can be changed to
00129 /// use a custom allocator.
00130 template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096,
00131           size_t SizeThreshold = SlabSize>
00132 class BumpPtrAllocatorImpl
00133     : public AllocatorBase<
00134           BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold>> {
00135 public:
00136   static_assert(SizeThreshold <= SlabSize,
00137                 "The SizeThreshold must be at most the SlabSize to ensure "
00138                 "that objects larger than a slab go into their own memory "
00139                 "allocation.");
00140 
00141   BumpPtrAllocatorImpl()
00142       : CurPtr(nullptr), End(nullptr), BytesAllocated(0), Allocator() {}
00143   template <typename T>
00144   BumpPtrAllocatorImpl(T &&Allocator)
00145       : CurPtr(nullptr), End(nullptr), BytesAllocated(0),
00146         Allocator(std::forward<T &&>(Allocator)) {}
00147 
00148   // Manually implement a move constructor as we must clear the old allocators
00149   // slabs as a matter of correctness.
00150   BumpPtrAllocatorImpl(BumpPtrAllocatorImpl &&Old)
00151       : CurPtr(Old.CurPtr), End(Old.End), Slabs(std::move(Old.Slabs)),
00152         CustomSizedSlabs(std::move(Old.CustomSizedSlabs)),
00153         BytesAllocated(Old.BytesAllocated),
00154         Allocator(std::move(Old.Allocator)) {
00155     Old.CurPtr = Old.End = nullptr;
00156     Old.BytesAllocated = 0;
00157     Old.Slabs.clear();
00158     Old.CustomSizedSlabs.clear();
00159   }
00160 
00161   ~BumpPtrAllocatorImpl() {
00162     DeallocateSlabs(Slabs.begin(), Slabs.end());
00163     DeallocateCustomSizedSlabs();
00164   }
00165 
00166   BumpPtrAllocatorImpl &operator=(BumpPtrAllocatorImpl &&RHS) {
00167     DeallocateSlabs(Slabs.begin(), Slabs.end());
00168     DeallocateCustomSizedSlabs();
00169 
00170     CurPtr = RHS.CurPtr;
00171     End = RHS.End;
00172     BytesAllocated = RHS.BytesAllocated;
00173     Slabs = std::move(RHS.Slabs);
00174     CustomSizedSlabs = std::move(RHS.CustomSizedSlabs);
00175     Allocator = std::move(RHS.Allocator);
00176 
00177     RHS.CurPtr = RHS.End = nullptr;
00178     RHS.BytesAllocated = 0;
00179     RHS.Slabs.clear();
00180     RHS.CustomSizedSlabs.clear();
00181     return *this;
00182   }
00183 
00184   /// \brief Deallocate all but the current slab and reset the current pointer
00185   /// to the beginning of it, freeing all memory allocated so far.
00186   void Reset() {
00187     if (Slabs.empty())
00188       return;
00189 
00190     // Reset the state.
00191     BytesAllocated = 0;
00192     CurPtr = (char *)Slabs.front();
00193     End = CurPtr + SlabSize;
00194 
00195     // Deallocate all but the first slab, and all custome sized slabs.
00196     DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
00197     Slabs.erase(std::next(Slabs.begin()), Slabs.end());
00198     DeallocateCustomSizedSlabs();
00199     CustomSizedSlabs.clear();
00200   }
00201 
00202   /// \brief Allocate space at the specified alignment.
00203   void *Allocate(size_t Size, size_t Alignment) {
00204     if (!CurPtr) // Start a new slab if we haven't allocated one already.
00205       StartNewSlab();
00206 
00207     // Keep track of how many bytes we've allocated.
00208     BytesAllocated += Size;
00209 
00210     // 0-byte alignment means 1-byte alignment.
00211     if (Alignment == 0)
00212       Alignment = 1;
00213 
00214     // Allocate the aligned space, going forwards from CurPtr.
00215     char *Ptr = alignPtr(CurPtr, Alignment);
00216 
00217     // Check if we can hold it.
00218     if (Ptr + Size <= End) {
00219       CurPtr = Ptr + Size;
00220       // Update the allocation point of this memory block in MemorySanitizer.
00221       // Without this, MemorySanitizer messages for values originated from here
00222       // will point to the allocation of the entire slab.
00223       __msan_allocated_memory(Ptr, Size);
00224       return Ptr;
00225     }
00226 
00227     // If Size is really big, allocate a separate slab for it.
00228     size_t PaddedSize = Size + Alignment - 1;
00229     if (PaddedSize > SizeThreshold) {
00230       void *NewSlab = Allocator.Allocate(PaddedSize, 0);
00231       CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
00232 
00233       Ptr = alignPtr((char *)NewSlab, Alignment);
00234       assert((uintptr_t)Ptr + Size <= (uintptr_t)NewSlab + PaddedSize);
00235       __msan_allocated_memory(Ptr, Size);
00236       return Ptr;
00237     }
00238 
00239     // Otherwise, start a new slab and try again.
00240     StartNewSlab();
00241     Ptr = alignPtr(CurPtr, Alignment);
00242     CurPtr = Ptr + Size;
00243     assert(CurPtr <= End && "Unable to allocate memory!");
00244     __msan_allocated_memory(Ptr, Size);
00245     return Ptr;
00246   }
00247 
00248   // Pull in base class overloads.
00249   using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
00250 
00251   void Deallocate(const void * /*Ptr*/, size_t /*Size*/) {}
00252 
00253   // Pull in base class overloads.
00254   using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate;
00255 
00256   size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
00257 
00258   size_t getTotalMemory() const {
00259     size_t TotalMemory = 0;
00260     for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
00261       TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
00262     for (auto &PtrAndSize : CustomSizedSlabs)
00263       TotalMemory += PtrAndSize.second;
00264     return TotalMemory;
00265   }
00266 
00267   void PrintStats() const {
00268     detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
00269                                        getTotalMemory());
00270   }
00271 
00272 private:
00273   /// \brief The current pointer into the current slab.
00274   ///
00275   /// This points to the next free byte in the slab.
00276   char *CurPtr;
00277 
00278   /// \brief The end of the current slab.
00279   char *End;
00280 
00281   /// \brief The slabs allocated so far.
00282   SmallVector<void *, 4> Slabs;
00283 
00284   /// \brief Custom-sized slabs allocated for too-large allocation requests.
00285   SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
00286 
00287   /// \brief How many bytes we've allocated.
00288   ///
00289   /// Used so that we can compute how much space was wasted.
00290   size_t BytesAllocated;
00291 
00292   /// \brief The allocator instance we use to get slabs of memory.
00293   AllocatorT Allocator;
00294 
00295   static size_t computeSlabSize(unsigned SlabIdx) {
00296     // Scale the actual allocated slab size based on the number of slabs
00297     // allocated. Every 128 slabs allocated, we double the allocated size to
00298     // reduce allocation frequency, but saturate at multiplying the slab size by
00299     // 2^30.
00300     return SlabSize * ((size_t)1 << std::min<size_t>(30, SlabIdx / 128));
00301   }
00302 
00303   /// \brief Allocate a new slab and move the bump pointers over into the new
00304   /// slab, modifying CurPtr and End.
00305   void StartNewSlab() {
00306     size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
00307 
00308     void *NewSlab = Allocator.Allocate(AllocatedSlabSize, 0);
00309     Slabs.push_back(NewSlab);
00310     CurPtr = (char *)(NewSlab);
00311     End = ((char *)NewSlab) + AllocatedSlabSize;
00312   }
00313 
00314   /// \brief Deallocate a sequence of slabs.
00315   void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
00316                        SmallVectorImpl<void *>::iterator E) {
00317     for (; I != E; ++I) {
00318       size_t AllocatedSlabSize =
00319           computeSlabSize(std::distance(Slabs.begin(), I));
00320 #ifndef NDEBUG
00321       // Poison the memory so stale pointers crash sooner.  Note we must
00322       // preserve the Size and NextPtr fields at the beginning.
00323       sys::Memory::setRangeWritable(*I, AllocatedSlabSize);
00324       memset(*I, 0xCD, AllocatedSlabSize);
00325 #endif
00326       Allocator.Deallocate(*I, AllocatedSlabSize);
00327     }
00328   }
00329 
00330   /// \brief Deallocate all memory for custom sized slabs.
00331   void DeallocateCustomSizedSlabs() {
00332     for (auto &PtrAndSize : CustomSizedSlabs) {
00333       void *Ptr = PtrAndSize.first;
00334       size_t Size = PtrAndSize.second;
00335 #ifndef NDEBUG
00336       // Poison the memory so stale pointers crash sooner.  Note we must
00337       // preserve the Size and NextPtr fields at the beginning.
00338       sys::Memory::setRangeWritable(Ptr, Size);
00339       memset(Ptr, 0xCD, Size);
00340 #endif
00341       Allocator.Deallocate(Ptr, Size);
00342     }
00343   }
00344 
00345   template <typename T> friend class SpecificBumpPtrAllocator;
00346 };
00347 
00348 /// \brief The standard BumpPtrAllocator which just uses the default template
00349 /// paramaters.
00350 typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
00351 
00352 /// \brief A BumpPtrAllocator that allows only elements of a specific type to be
00353 /// allocated.
00354 ///
00355 /// This allows calling the destructor in DestroyAll() and when the allocator is
00356 /// destroyed.
00357 template <typename T> class SpecificBumpPtrAllocator {
00358   BumpPtrAllocator Allocator;
00359 
00360 public:
00361   SpecificBumpPtrAllocator() : Allocator() {}
00362   SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old)
00363       : Allocator(std::move(Old.Allocator)) {}
00364   ~SpecificBumpPtrAllocator() { DestroyAll(); }
00365 
00366   SpecificBumpPtrAllocator &operator=(SpecificBumpPtrAllocator &&RHS) {
00367     Allocator = std::move(RHS.Allocator);
00368     return *this;
00369   }
00370 
00371   /// Call the destructor of each allocated object and deallocate all but the
00372   /// current slab and reset the current pointer to the beginning of it, freeing
00373   /// all memory allocated so far.
00374   void DestroyAll() {
00375     auto DestroyElements = [](char *Begin, char *End) {
00376       assert(Begin == alignPtr(Begin, alignOf<T>()));
00377       for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
00378         reinterpret_cast<T *>(Ptr)->~T();
00379     };
00380 
00381     for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
00382          ++I) {
00383       size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
00384           std::distance(Allocator.Slabs.begin(), I));
00385       char *Begin = alignPtr((char *)*I, alignOf<T>());
00386       char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
00387                                                : (char *)*I + AllocatedSlabSize;
00388 
00389       DestroyElements(Begin, End);
00390     }
00391 
00392     for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
00393       void *Ptr = PtrAndSize.first;
00394       size_t Size = PtrAndSize.second;
00395       DestroyElements(alignPtr((char *)Ptr, alignOf<T>()), (char *)Ptr + Size);
00396     }
00397 
00398     Allocator.Reset();
00399   }
00400 
00401   /// \brief Allocate space for an array of objects without constructing them.
00402   T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
00403 };
00404 
00405 }  // end namespace llvm
00406 
00407 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
00408 void *operator new(size_t Size,
00409                    llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
00410                                               SizeThreshold> &Allocator) {
00411   struct S {
00412     char c;
00413     union {
00414       double D;
00415       long double LD;
00416       long long L;
00417       void *P;
00418     } x;
00419   };
00420   return Allocator.Allocate(
00421       Size, std::min((size_t)llvm::NextPowerOf2(Size), offsetof(S, x)));
00422 }
00423 
00424 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
00425 void operator delete(
00426     void *, llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold> &) {
00427 }
00428 
00429 #endif // LLVM_SUPPORT_ALLOCATOR_H