Allocator.h 15 KB

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