Allocator.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. return ::operator new(Size); // HLSL Change: use overridable operator new and throw on OOM
  87. }
  88. // Pull in base class overloads.
  89. using AllocatorBase<MallocAllocator>::Allocate;
  90. void Deallocate(const void *Ptr, size_t /*Size*/) {
  91. ::operator delete(const_cast<void*>(Ptr)); // HLSL Change: use overridable operator delete
  92. }
  93. // Pull in base class overloads.
  94. using AllocatorBase<MallocAllocator>::Deallocate;
  95. void PrintStats() const {}
  96. };
  97. namespace detail {
  98. // We call out to an external function to actually print the message as the
  99. // printing code uses Allocator.h in its implementation.
  100. void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated,
  101. size_t TotalMemory);
  102. } // End namespace detail.
  103. /// \brief Allocate memory in an ever growing pool, as if by bump-pointer.
  104. ///
  105. /// This isn't strictly a bump-pointer allocator as it uses backing slabs of
  106. /// memory rather than relying on a boundless contiguous heap. However, it has
  107. /// bump-pointer semantics in that it is a monotonically growing pool of memory
  108. /// where every allocation is found by merely allocating the next N bytes in
  109. /// the slab, or the next N bytes in the next slab.
  110. ///
  111. /// Note that this also has a threshold for forcing allocations above a certain
  112. /// size into their own slab.
  113. ///
  114. /// The BumpPtrAllocatorImpl template defaults to using a MallocAllocator
  115. /// object, which wraps malloc, to allocate memory, but it can be changed to
  116. /// use a custom allocator.
  117. template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096,
  118. size_t SizeThreshold = SlabSize>
  119. class BumpPtrAllocatorImpl
  120. : public AllocatorBase<
  121. BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold>> {
  122. public:
  123. static_assert(SizeThreshold <= SlabSize,
  124. "The SizeThreshold must be at most the SlabSize to ensure "
  125. "that objects larger than a slab go into their own memory "
  126. "allocation.");
  127. BumpPtrAllocatorImpl()
  128. : CurPtr(nullptr), End(nullptr), BytesAllocated(0), Allocator() {}
  129. template <typename T>
  130. BumpPtrAllocatorImpl(T &&Allocator)
  131. : CurPtr(nullptr), End(nullptr), BytesAllocated(0),
  132. Allocator(std::forward<T &&>(Allocator)) {}
  133. // Manually implement a move constructor as we must clear the old allocator's
  134. // slabs as a matter of correctness.
  135. BumpPtrAllocatorImpl(BumpPtrAllocatorImpl &&Old)
  136. : CurPtr(Old.CurPtr), End(Old.End), Slabs(std::move(Old.Slabs)),
  137. CustomSizedSlabs(std::move(Old.CustomSizedSlabs)),
  138. BytesAllocated(Old.BytesAllocated),
  139. Allocator(std::move(Old.Allocator)) {
  140. Old.CurPtr = Old.End = nullptr;
  141. Old.BytesAllocated = 0;
  142. Old.Slabs.clear();
  143. Old.CustomSizedSlabs.clear();
  144. }
  145. ~BumpPtrAllocatorImpl() {
  146. DeallocateSlabs(Slabs.begin(), Slabs.end());
  147. DeallocateCustomSizedSlabs();
  148. }
  149. BumpPtrAllocatorImpl &operator=(BumpPtrAllocatorImpl &&RHS) {
  150. DeallocateSlabs(Slabs.begin(), Slabs.end());
  151. DeallocateCustomSizedSlabs();
  152. CurPtr = RHS.CurPtr;
  153. End = RHS.End;
  154. BytesAllocated = RHS.BytesAllocated;
  155. Slabs = std::move(RHS.Slabs);
  156. CustomSizedSlabs = std::move(RHS.CustomSizedSlabs);
  157. Allocator = std::move(RHS.Allocator);
  158. RHS.CurPtr = RHS.End = nullptr;
  159. RHS.BytesAllocated = 0;
  160. RHS.Slabs.clear();
  161. RHS.CustomSizedSlabs.clear();
  162. return *this;
  163. }
  164. /// \brief Deallocate all but the current slab and reset the current pointer
  165. /// to the beginning of it, freeing all memory allocated so far.
  166. void Reset() {
  167. DeallocateCustomSizedSlabs();
  168. CustomSizedSlabs.clear();
  169. if (Slabs.empty())
  170. return;
  171. // Reset the state.
  172. BytesAllocated = 0;
  173. CurPtr = (char *)Slabs.front();
  174. End = CurPtr + SlabSize;
  175. // Deallocate all but the first slab, and deallocate all custom-sized slabs.
  176. DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
  177. Slabs.erase(std::next(Slabs.begin()), Slabs.end());
  178. }
  179. /// \brief Allocate space at the specified alignment.
  180. LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void *
  181. Allocate(size_t Size, size_t Alignment) {
  182. assert(Alignment > 0 && "0-byte alignnment is not allowed. Use 1 instead.");
  183. // Keep track of how many bytes we've allocated.
  184. BytesAllocated += Size;
  185. size_t Adjustment = alignmentAdjustment(CurPtr, Alignment);
  186. assert(Adjustment + Size >= Size && "Adjustment + Size must not overflow");
  187. // Check if we have enough space.
  188. if (Adjustment + Size <= size_t(End - CurPtr)) {
  189. char *AlignedPtr = CurPtr + Adjustment;
  190. CurPtr = AlignedPtr + Size;
  191. // Update the allocation point of this memory block in MemorySanitizer.
  192. // Without this, MemorySanitizer messages for values originated from here
  193. // will point to the allocation of the entire slab.
  194. __msan_allocated_memory(AlignedPtr, Size);
  195. return AlignedPtr;
  196. }
  197. // If Size is really big, allocate a separate slab for it.
  198. size_t PaddedSize = Size + Alignment - 1;
  199. if (PaddedSize > SizeThreshold) {
  200. void *NewSlab = Allocator.Allocate(PaddedSize, 0);
  201. CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
  202. uintptr_t AlignedAddr = alignAddr(NewSlab, Alignment);
  203. assert(AlignedAddr + Size <= (uintptr_t)NewSlab + PaddedSize);
  204. char *AlignedPtr = (char*)AlignedAddr;
  205. __msan_allocated_memory(AlignedPtr, Size);
  206. return AlignedPtr;
  207. }
  208. // Otherwise, start a new slab and try again.
  209. StartNewSlab();
  210. uintptr_t AlignedAddr = alignAddr(CurPtr, Alignment);
  211. assert(AlignedAddr + Size <= (uintptr_t)End &&
  212. "Unable to allocate memory!");
  213. char *AlignedPtr = (char*)AlignedAddr;
  214. CurPtr = AlignedPtr + Size;
  215. __msan_allocated_memory(AlignedPtr, Size);
  216. return AlignedPtr;
  217. }
  218. // Pull in base class overloads.
  219. using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
  220. void Deallocate(const void * /*Ptr*/, size_t /*Size*/) {}
  221. // Pull in base class overloads.
  222. using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate;
  223. size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
  224. size_t getTotalMemory() const {
  225. size_t TotalMemory = 0;
  226. for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
  227. TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
  228. for (auto &PtrAndSize : CustomSizedSlabs)
  229. TotalMemory += PtrAndSize.second;
  230. return TotalMemory;
  231. }
  232. void PrintStats() const {
  233. detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
  234. getTotalMemory());
  235. }
  236. private:
  237. /// \brief The current pointer into the current slab.
  238. ///
  239. /// This points to the next free byte in the slab.
  240. char *CurPtr;
  241. /// \brief The end of the current slab.
  242. char *End;
  243. /// \brief The slabs allocated so far.
  244. SmallVector<void *, 4> Slabs;
  245. /// \brief Custom-sized slabs allocated for too-large allocation requests.
  246. SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
  247. /// \brief How many bytes we've allocated.
  248. ///
  249. /// Used so that we can compute how much space was wasted.
  250. size_t BytesAllocated;
  251. /// \brief The allocator instance we use to get slabs of memory.
  252. AllocatorT Allocator;
  253. static size_t computeSlabSize(unsigned SlabIdx) {
  254. // Scale the actual allocated slab size based on the number of slabs
  255. // allocated. Every 128 slabs allocated, we double the allocated size to
  256. // reduce allocation frequency, but saturate at multiplying the slab size by
  257. // 2^30.
  258. return SlabSize * ((size_t)1 << std::min<size_t>(30, SlabIdx / 128));
  259. }
  260. /// \brief Allocate a new slab and move the bump pointers over into the new
  261. /// slab, modifying CurPtr and End.
  262. void StartNewSlab() {
  263. size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
  264. Slabs.reserve(Slabs.size() + 1); // HLSL Change: Prevent leak on push_back exception
  265. void *NewSlab = Allocator.Allocate(AllocatedSlabSize, 0);
  266. Slabs.push_back(NewSlab);
  267. CurPtr = (char *)(NewSlab);
  268. End = ((char *)NewSlab) + AllocatedSlabSize;
  269. }
  270. /// \brief Deallocate a sequence of slabs.
  271. void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
  272. SmallVectorImpl<void *>::iterator E) {
  273. for (; I != E; ++I) {
  274. size_t AllocatedSlabSize =
  275. computeSlabSize(std::distance(Slabs.begin(), I));
  276. Allocator.Deallocate(*I, AllocatedSlabSize);
  277. }
  278. }
  279. /// \brief Deallocate all memory for custom sized slabs.
  280. void DeallocateCustomSizedSlabs() {
  281. for (auto &PtrAndSize : CustomSizedSlabs) {
  282. void *Ptr = PtrAndSize.first;
  283. size_t Size = PtrAndSize.second;
  284. Allocator.Deallocate(Ptr, Size);
  285. }
  286. }
  287. template <typename T> friend class SpecificBumpPtrAllocator;
  288. };
  289. /// \brief The standard BumpPtrAllocator which just uses the default template
  290. /// paramaters.
  291. typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
  292. /// \brief A BumpPtrAllocator that allows only elements of a specific type to be
  293. /// allocated.
  294. ///
  295. /// This allows calling the destructor in DestroyAll() and when the allocator is
  296. /// destroyed.
  297. template <typename T> class SpecificBumpPtrAllocator {
  298. BumpPtrAllocator Allocator;
  299. public:
  300. SpecificBumpPtrAllocator() : Allocator() {}
  301. SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old)
  302. : Allocator(std::move(Old.Allocator)) {}
  303. ~SpecificBumpPtrAllocator() { DestroyAll(); }
  304. SpecificBumpPtrAllocator &operator=(SpecificBumpPtrAllocator &&RHS) {
  305. Allocator = std::move(RHS.Allocator);
  306. return *this;
  307. }
  308. /// Call the destructor of each allocated object and deallocate all but the
  309. /// current slab and reset the current pointer to the beginning of it, freeing
  310. /// all memory allocated so far.
  311. void DestroyAll() {
  312. auto DestroyElements = [](char *Begin, char *End) {
  313. assert(Begin == (char*)alignAddr(Begin, alignOf<T>()));
  314. for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
  315. reinterpret_cast<T *>(Ptr)->~T();
  316. };
  317. for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
  318. ++I) {
  319. size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
  320. std::distance(Allocator.Slabs.begin(), I));
  321. char *Begin = (char*)alignAddr(*I, alignOf<T>());
  322. char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
  323. : (char *)*I + AllocatedSlabSize;
  324. DestroyElements(Begin, End);
  325. }
  326. for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
  327. void *Ptr = PtrAndSize.first;
  328. size_t Size = PtrAndSize.second;
  329. DestroyElements((char*)alignAddr(Ptr, alignOf<T>()), (char *)Ptr + Size);
  330. }
  331. Allocator.Reset();
  332. }
  333. /// \brief Allocate space for an array of objects without constructing them.
  334. T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
  335. };
  336. } // end namespace llvm
  337. // HLSL Change Starts - undef min due to conflict with std::min
  338. #ifdef min
  339. #undef min
  340. #endif
  341. // HLSL Change Ends
  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. template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
  359. void operator delete(
  360. void *, llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold> &) {
  361. }
  362. #endif // LLVM_SUPPORT_ALLOCATOR_H