LLVM API Documentation
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 LLVM_ATTRIBUTE_RETURNS_NONNULL void *Allocate(size_t Size, 00094 size_t /*Alignment*/) { 00095 return malloc(Size); 00096 } 00097 00098 // Pull in base class overloads. 00099 using AllocatorBase<MallocAllocator>::Allocate; 00100 00101 void Deallocate(const void *Ptr, size_t /*Size*/) { 00102 free(const_cast<void *>(Ptr)); 00103 } 00104 00105 // Pull in base class overloads. 00106 using AllocatorBase<MallocAllocator>::Deallocate; 00107 00108 void PrintStats() const {} 00109 }; 00110 00111 namespace detail { 00112 00113 // We call out to an external function to actually print the message as the 00114 // printing code uses Allocator.h in its implementation. 00115 void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated, 00116 size_t TotalMemory); 00117 } // End namespace detail. 00118 00119 /// \brief Allocate memory in an ever growing pool, as if by bump-pointer. 00120 /// 00121 /// This isn't strictly a bump-pointer allocator as it uses backing slabs of 00122 /// memory rather than relying on boundless contiguous heap. However, it has 00123 /// bump-pointer semantics in that is a monotonically growing pool of memory 00124 /// where every allocation is found by merely allocating the next N bytes in 00125 /// the slab, or the next N bytes in the next slab. 00126 /// 00127 /// Note that this also has a threshold for forcing allocations above a certain 00128 /// size into their own slab. 00129 /// 00130 /// The BumpPtrAllocatorImpl template defaults to using a MallocAllocator 00131 /// object, which wraps malloc, to allocate memory, but it can be changed to 00132 /// use a custom allocator. 00133 template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096, 00134 size_t SizeThreshold = SlabSize> 00135 class BumpPtrAllocatorImpl 00136 : public AllocatorBase< 00137 BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold>> { 00138 public: 00139 static_assert(SizeThreshold <= SlabSize, 00140 "The SizeThreshold must be at most the SlabSize to ensure " 00141 "that objects larger than a slab go into their own memory " 00142 "allocation."); 00143 00144 BumpPtrAllocatorImpl() 00145 : CurPtr(nullptr), End(nullptr), BytesAllocated(0), Allocator() {} 00146 template <typename T> 00147 BumpPtrAllocatorImpl(T &&Allocator) 00148 : CurPtr(nullptr), End(nullptr), BytesAllocated(0), 00149 Allocator(std::forward<T &&>(Allocator)) {} 00150 00151 // Manually implement a move constructor as we must clear the old allocators 00152 // slabs as a matter of correctness. 00153 BumpPtrAllocatorImpl(BumpPtrAllocatorImpl &&Old) 00154 : CurPtr(Old.CurPtr), End(Old.End), Slabs(std::move(Old.Slabs)), 00155 CustomSizedSlabs(std::move(Old.CustomSizedSlabs)), 00156 BytesAllocated(Old.BytesAllocated), 00157 Allocator(std::move(Old.Allocator)) { 00158 Old.CurPtr = Old.End = nullptr; 00159 Old.BytesAllocated = 0; 00160 Old.Slabs.clear(); 00161 Old.CustomSizedSlabs.clear(); 00162 } 00163 00164 ~BumpPtrAllocatorImpl() { 00165 DeallocateSlabs(Slabs.begin(), Slabs.end()); 00166 DeallocateCustomSizedSlabs(); 00167 } 00168 00169 BumpPtrAllocatorImpl &operator=(BumpPtrAllocatorImpl &&RHS) { 00170 DeallocateSlabs(Slabs.begin(), Slabs.end()); 00171 DeallocateCustomSizedSlabs(); 00172 00173 CurPtr = RHS.CurPtr; 00174 End = RHS.End; 00175 BytesAllocated = RHS.BytesAllocated; 00176 Slabs = std::move(RHS.Slabs); 00177 CustomSizedSlabs = std::move(RHS.CustomSizedSlabs); 00178 Allocator = std::move(RHS.Allocator); 00179 00180 RHS.CurPtr = RHS.End = nullptr; 00181 RHS.BytesAllocated = 0; 00182 RHS.Slabs.clear(); 00183 RHS.CustomSizedSlabs.clear(); 00184 return *this; 00185 } 00186 00187 /// \brief Deallocate all but the current slab and reset the current pointer 00188 /// to the beginning of it, freeing all memory allocated so far. 00189 void Reset() { 00190 if (Slabs.empty()) 00191 return; 00192 00193 // Reset the state. 00194 BytesAllocated = 0; 00195 CurPtr = (char *)Slabs.front(); 00196 End = CurPtr + SlabSize; 00197 00198 // Deallocate all but the first slab, and all custome sized slabs. 00199 DeallocateSlabs(std::next(Slabs.begin()), Slabs.end()); 00200 Slabs.erase(std::next(Slabs.begin()), Slabs.end()); 00201 DeallocateCustomSizedSlabs(); 00202 CustomSizedSlabs.clear(); 00203 } 00204 00205 /// \brief Allocate space at the specified alignment. 00206 LLVM_ATTRIBUTE_RETURNS_NONNULL void *Allocate(size_t Size, size_t Alignment) { 00207 assert(Alignment > 0 && "0-byte alignnment is not allowed. Use 1 instead."); 00208 00209 // Keep track of how many bytes we've allocated. 00210 BytesAllocated += Size; 00211 00212 size_t Adjustment = alignmentAdjustment(CurPtr, Alignment); 00213 assert(Adjustment + Size >= Size && "Adjustment + Size must not overflow"); 00214 00215 // Check if we have enough space. 00216 if (Adjustment + Size <= size_t(End - CurPtr)) { 00217 char *AlignedPtr = CurPtr + Adjustment; 00218 CurPtr = AlignedPtr + Size; 00219 // Update the allocation point of this memory block in MemorySanitizer. 00220 // Without this, MemorySanitizer messages for values originated from here 00221 // will point to the allocation of the entire slab. 00222 __msan_allocated_memory(AlignedPtr, Size); 00223 return AlignedPtr; 00224 } 00225 00226 // If Size is really big, allocate a separate slab for it. 00227 size_t PaddedSize = Size + Alignment - 1; 00228 if (PaddedSize > SizeThreshold) { 00229 void *NewSlab = Allocator.Allocate(PaddedSize, 0); 00230 CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize)); 00231 00232 uintptr_t AlignedAddr = alignAddr(NewSlab, Alignment); 00233 assert(AlignedAddr + Size <= (uintptr_t)NewSlab + PaddedSize); 00234 char *AlignedPtr = (char*)AlignedAddr; 00235 __msan_allocated_memory(AlignedPtr, Size); 00236 return AlignedPtr; 00237 } 00238 00239 // Otherwise, start a new slab and try again. 00240 StartNewSlab(); 00241 uintptr_t AlignedAddr = alignAddr(CurPtr, Alignment); 00242 assert(AlignedAddr + Size <= (uintptr_t)End && 00243 "Unable to allocate memory!"); 00244 char *AlignedPtr = (char*)AlignedAddr; 00245 CurPtr = AlignedPtr + Size; 00246 __msan_allocated_memory(AlignedPtr, Size); 00247 return AlignedPtr; 00248 } 00249 00250 // Pull in base class overloads. 00251 using AllocatorBase<BumpPtrAllocatorImpl>::Allocate; 00252 00253 void Deallocate(const void * /*Ptr*/, size_t /*Size*/) {} 00254 00255 // Pull in base class overloads. 00256 using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate; 00257 00258 size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); } 00259 00260 size_t getTotalMemory() const { 00261 size_t TotalMemory = 0; 00262 for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I) 00263 TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I)); 00264 for (auto &PtrAndSize : CustomSizedSlabs) 00265 TotalMemory += PtrAndSize.second; 00266 return TotalMemory; 00267 } 00268 00269 void PrintStats() const { 00270 detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated, 00271 getTotalMemory()); 00272 } 00273 00274 private: 00275 /// \brief The current pointer into the current slab. 00276 /// 00277 /// This points to the next free byte in the slab. 00278 char *CurPtr; 00279 00280 /// \brief The end of the current slab. 00281 char *End; 00282 00283 /// \brief The slabs allocated so far. 00284 SmallVector<void *, 4> Slabs; 00285 00286 /// \brief Custom-sized slabs allocated for too-large allocation requests. 00287 SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs; 00288 00289 /// \brief How many bytes we've allocated. 00290 /// 00291 /// Used so that we can compute how much space was wasted. 00292 size_t BytesAllocated; 00293 00294 /// \brief The allocator instance we use to get slabs of memory. 00295 AllocatorT Allocator; 00296 00297 static size_t computeSlabSize(unsigned SlabIdx) { 00298 // Scale the actual allocated slab size based on the number of slabs 00299 // allocated. Every 128 slabs allocated, we double the allocated size to 00300 // reduce allocation frequency, but saturate at multiplying the slab size by 00301 // 2^30. 00302 return SlabSize * ((size_t)1 << std::min<size_t>(30, SlabIdx / 128)); 00303 } 00304 00305 /// \brief Allocate a new slab and move the bump pointers over into the new 00306 /// slab, modifying CurPtr and End. 00307 void StartNewSlab() { 00308 size_t AllocatedSlabSize = computeSlabSize(Slabs.size()); 00309 00310 void *NewSlab = Allocator.Allocate(AllocatedSlabSize, 0); 00311 Slabs.push_back(NewSlab); 00312 CurPtr = (char *)(NewSlab); 00313 End = ((char *)NewSlab) + AllocatedSlabSize; 00314 } 00315 00316 /// \brief Deallocate a sequence of slabs. 00317 void DeallocateSlabs(SmallVectorImpl<void *>::iterator I, 00318 SmallVectorImpl<void *>::iterator E) { 00319 for (; I != E; ++I) { 00320 size_t AllocatedSlabSize = 00321 computeSlabSize(std::distance(Slabs.begin(), I)); 00322 #ifndef NDEBUG 00323 // Poison the memory so stale pointers crash sooner. Note we must 00324 // preserve the Size and NextPtr fields at the beginning. 00325 if (AllocatedSlabSize != 0) { 00326 sys::Memory::setRangeWritable(*I, AllocatedSlabSize); 00327 memset(*I, 0xCD, AllocatedSlabSize); 00328 } 00329 #endif 00330 Allocator.Deallocate(*I, AllocatedSlabSize); 00331 } 00332 } 00333 00334 /// \brief Deallocate all memory for custom sized slabs. 00335 void DeallocateCustomSizedSlabs() { 00336 for (auto &PtrAndSize : CustomSizedSlabs) { 00337 void *Ptr = PtrAndSize.first; 00338 size_t Size = PtrAndSize.second; 00339 #ifndef NDEBUG 00340 // Poison the memory so stale pointers crash sooner. Note we must 00341 // preserve the Size and NextPtr fields at the beginning. 00342 sys::Memory::setRangeWritable(Ptr, Size); 00343 memset(Ptr, 0xCD, Size); 00344 #endif 00345 Allocator.Deallocate(Ptr, Size); 00346 } 00347 } 00348 00349 template <typename T> friend class SpecificBumpPtrAllocator; 00350 }; 00351 00352 /// \brief The standard BumpPtrAllocator which just uses the default template 00353 /// paramaters. 00354 typedef BumpPtrAllocatorImpl<> BumpPtrAllocator; 00355 00356 /// \brief A BumpPtrAllocator that allows only elements of a specific type to be 00357 /// allocated. 00358 /// 00359 /// This allows calling the destructor in DestroyAll() and when the allocator is 00360 /// destroyed. 00361 template <typename T> class SpecificBumpPtrAllocator { 00362 BumpPtrAllocator Allocator; 00363 00364 public: 00365 SpecificBumpPtrAllocator() : Allocator() {} 00366 SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old) 00367 : Allocator(std::move(Old.Allocator)) {} 00368 ~SpecificBumpPtrAllocator() { DestroyAll(); } 00369 00370 SpecificBumpPtrAllocator &operator=(SpecificBumpPtrAllocator &&RHS) { 00371 Allocator = std::move(RHS.Allocator); 00372 return *this; 00373 } 00374 00375 /// Call the destructor of each allocated object and deallocate all but the 00376 /// current slab and reset the current pointer to the beginning of it, freeing 00377 /// all memory allocated so far. 00378 void DestroyAll() { 00379 auto DestroyElements = [](char *Begin, char *End) { 00380 assert(Begin == (char*)alignAddr(Begin, alignOf<T>())); 00381 for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T)) 00382 reinterpret_cast<T *>(Ptr)->~T(); 00383 }; 00384 00385 for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E; 00386 ++I) { 00387 size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize( 00388 std::distance(Allocator.Slabs.begin(), I)); 00389 char *Begin = (char*)alignAddr(*I, alignOf<T>()); 00390 char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr 00391 : (char *)*I + AllocatedSlabSize; 00392 00393 DestroyElements(Begin, End); 00394 } 00395 00396 for (auto &PtrAndSize : Allocator.CustomSizedSlabs) { 00397 void *Ptr = PtrAndSize.first; 00398 size_t Size = PtrAndSize.second; 00399 DestroyElements((char*)alignAddr(Ptr, alignOf<T>()), (char *)Ptr + Size); 00400 } 00401 00402 Allocator.Reset(); 00403 } 00404 00405 /// \brief Allocate space for an array of objects without constructing them. 00406 T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); } 00407 }; 00408 00409 } // end namespace llvm 00410 00411 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold> 00412 void *operator new(size_t Size, 00413 llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, 00414 SizeThreshold> &Allocator) { 00415 struct S { 00416 char c; 00417 union { 00418 double D; 00419 long double LD; 00420 long long L; 00421 void *P; 00422 } x; 00423 }; 00424 return Allocator.Allocate( 00425 Size, std::min((size_t)llvm::NextPowerOf2(Size), offsetof(S, x))); 00426 } 00427 00428 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold> 00429 void operator delete( 00430 void *, llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold> &) { 00431 } 00432 00433 #endif // LLVM_SUPPORT_ALLOCATOR_H