Allocator.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Allocator.h - Simple memory allocation abstraction -------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. /// \file
  14. ///
  15. /// This file defines the BumpPtrAllocator interface. BumpPtrAllocator conforms
  16. /// to the LLVM "Allocator" concept and is similar to MallocAllocator, but
  17. /// objects cannot be deallocated. Their lifetime is tied to the lifetime of the
  18. /// allocator.
  19. ///
  20. //===----------------------------------------------------------------------===//
  21. #ifndef LLVM_SUPPORT_ALLOCATOR_H
  22. #define LLVM_SUPPORT_ALLOCATOR_H
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/Support/Alignment.h"
  25. #include "llvm/Support/AllocatorBase.h"
  26. #include "llvm/Support/Compiler.h"
  27. #include "llvm/Support/MathExtras.h"
  28. #include <algorithm>
  29. #include <cassert>
  30. #include <cstddef>
  31. #include <cstdint>
  32. #include <iterator>
  33. #include <optional>
  34. #include <utility>
  35. namespace llvm {
  36. namespace detail {
  37. // We call out to an external function to actually print the message as the
  38. // printing code uses Allocator.h in its implementation.
  39. void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated,
  40. size_t TotalMemory);
  41. } // end namespace detail
  42. /// Allocate memory in an ever growing pool, as if by bump-pointer.
  43. ///
  44. /// This isn't strictly a bump-pointer allocator as it uses backing slabs of
  45. /// memory rather than relying on a boundless contiguous heap. However, it has
  46. /// bump-pointer semantics in that it is a monotonically growing pool of memory
  47. /// where every allocation is found by merely allocating the next N bytes in
  48. /// the slab, or the next N bytes in the next slab.
  49. ///
  50. /// Note that this also has a threshold for forcing allocations above a certain
  51. /// size into their own slab.
  52. ///
  53. /// The BumpPtrAllocatorImpl template defaults to using a MallocAllocator
  54. /// object, which wraps malloc, to allocate memory, but it can be changed to
  55. /// use a custom allocator.
  56. ///
  57. /// The GrowthDelay specifies after how many allocated slabs the allocator
  58. /// increases the size of the slabs.
  59. template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096,
  60. size_t SizeThreshold = SlabSize, size_t GrowthDelay = 128>
  61. class BumpPtrAllocatorImpl
  62. : public AllocatorBase<BumpPtrAllocatorImpl<AllocatorT, SlabSize,
  63. SizeThreshold, GrowthDelay>>,
  64. private detail::AllocatorHolder<AllocatorT> {
  65. using AllocTy = detail::AllocatorHolder<AllocatorT>;
  66. public:
  67. static_assert(SizeThreshold <= SlabSize,
  68. "The SizeThreshold must be at most the SlabSize to ensure "
  69. "that objects larger than a slab go into their own memory "
  70. "allocation.");
  71. static_assert(GrowthDelay > 0,
  72. "GrowthDelay must be at least 1 which already increases the"
  73. "slab size after each allocated slab.");
  74. BumpPtrAllocatorImpl() = default;
  75. template <typename T>
  76. BumpPtrAllocatorImpl(T &&Allocator)
  77. : AllocTy(std::forward<T &&>(Allocator)) {}
  78. // Manually implement a move constructor as we must clear the old allocator's
  79. // slabs as a matter of correctness.
  80. BumpPtrAllocatorImpl(BumpPtrAllocatorImpl &&Old)
  81. : AllocTy(std::move(Old.getAllocator())), CurPtr(Old.CurPtr),
  82. End(Old.End), Slabs(std::move(Old.Slabs)),
  83. CustomSizedSlabs(std::move(Old.CustomSizedSlabs)),
  84. BytesAllocated(Old.BytesAllocated), RedZoneSize(Old.RedZoneSize) {
  85. Old.CurPtr = Old.End = nullptr;
  86. Old.BytesAllocated = 0;
  87. Old.Slabs.clear();
  88. Old.CustomSizedSlabs.clear();
  89. }
  90. ~BumpPtrAllocatorImpl() {
  91. DeallocateSlabs(Slabs.begin(), Slabs.end());
  92. DeallocateCustomSizedSlabs();
  93. }
  94. BumpPtrAllocatorImpl &operator=(BumpPtrAllocatorImpl &&RHS) {
  95. DeallocateSlabs(Slabs.begin(), Slabs.end());
  96. DeallocateCustomSizedSlabs();
  97. CurPtr = RHS.CurPtr;
  98. End = RHS.End;
  99. BytesAllocated = RHS.BytesAllocated;
  100. RedZoneSize = RHS.RedZoneSize;
  101. Slabs = std::move(RHS.Slabs);
  102. CustomSizedSlabs = std::move(RHS.CustomSizedSlabs);
  103. AllocTy::operator=(std::move(RHS.getAllocator()));
  104. RHS.CurPtr = RHS.End = nullptr;
  105. RHS.BytesAllocated = 0;
  106. RHS.Slabs.clear();
  107. RHS.CustomSizedSlabs.clear();
  108. return *this;
  109. }
  110. /// Deallocate all but the current slab and reset the current pointer
  111. /// to the beginning of it, freeing all memory allocated so far.
  112. void Reset() {
  113. // Deallocate all but the first slab, and deallocate all custom-sized slabs.
  114. DeallocateCustomSizedSlabs();
  115. CustomSizedSlabs.clear();
  116. if (Slabs.empty())
  117. return;
  118. // Reset the state.
  119. BytesAllocated = 0;
  120. CurPtr = (char *)Slabs.front();
  121. End = CurPtr + SlabSize;
  122. __asan_poison_memory_region(*Slabs.begin(), computeSlabSize(0));
  123. DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
  124. Slabs.erase(std::next(Slabs.begin()), Slabs.end());
  125. }
  126. /// Allocate space at the specified alignment.
  127. // This method is *not* marked noalias, because
  128. // SpecificBumpPtrAllocator::DestroyAll() loops over all allocations, and
  129. // that loop is not based on the Allocate() return value.
  130. //
  131. // Allocate(0, N) is valid, it returns a non-null pointer (which should not
  132. // be dereferenced).
  133. LLVM_ATTRIBUTE_RETURNS_NONNULL void *Allocate(size_t Size, Align Alignment) {
  134. // Keep track of how many bytes we've allocated.
  135. BytesAllocated += Size;
  136. size_t Adjustment = offsetToAlignedAddr(CurPtr, Alignment);
  137. assert(Adjustment + Size >= Size && "Adjustment + Size must not overflow");
  138. size_t SizeToAllocate = Size;
  139. #if LLVM_ADDRESS_SANITIZER_BUILD
  140. // Add trailing bytes as a "red zone" under ASan.
  141. SizeToAllocate += RedZoneSize;
  142. #endif
  143. // Check if we have enough space.
  144. if (Adjustment + SizeToAllocate <= size_t(End - CurPtr)
  145. // We can't return nullptr even for a zero-sized allocation!
  146. && CurPtr != nullptr) {
  147. char *AlignedPtr = CurPtr + Adjustment;
  148. CurPtr = AlignedPtr + SizeToAllocate;
  149. // Update the allocation point of this memory block in MemorySanitizer.
  150. // Without this, MemorySanitizer messages for values originated from here
  151. // will point to the allocation of the entire slab.
  152. __msan_allocated_memory(AlignedPtr, Size);
  153. // Similarly, tell ASan about this space.
  154. __asan_unpoison_memory_region(AlignedPtr, Size);
  155. return AlignedPtr;
  156. }
  157. // If Size is really big, allocate a separate slab for it.
  158. size_t PaddedSize = SizeToAllocate + Alignment.value() - 1;
  159. if (PaddedSize > SizeThreshold) {
  160. void *NewSlab =
  161. this->getAllocator().Allocate(PaddedSize, alignof(std::max_align_t));
  162. // We own the new slab and don't want anyone reading anyting other than
  163. // pieces returned from this method. So poison the whole slab.
  164. __asan_poison_memory_region(NewSlab, PaddedSize);
  165. CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
  166. uintptr_t AlignedAddr = alignAddr(NewSlab, Alignment);
  167. assert(AlignedAddr + Size <= (uintptr_t)NewSlab + PaddedSize);
  168. char *AlignedPtr = (char*)AlignedAddr;
  169. __msan_allocated_memory(AlignedPtr, Size);
  170. __asan_unpoison_memory_region(AlignedPtr, Size);
  171. return AlignedPtr;
  172. }
  173. // Otherwise, start a new slab and try again.
  174. StartNewSlab();
  175. uintptr_t AlignedAddr = alignAddr(CurPtr, Alignment);
  176. assert(AlignedAddr + SizeToAllocate <= (uintptr_t)End &&
  177. "Unable to allocate memory!");
  178. char *AlignedPtr = (char*)AlignedAddr;
  179. CurPtr = AlignedPtr + SizeToAllocate;
  180. __msan_allocated_memory(AlignedPtr, Size);
  181. __asan_unpoison_memory_region(AlignedPtr, Size);
  182. return AlignedPtr;
  183. }
  184. inline LLVM_ATTRIBUTE_RETURNS_NONNULL void *
  185. Allocate(size_t Size, size_t Alignment) {
  186. assert(Alignment > 0 && "0-byte alignment is not allowed. Use 1 instead.");
  187. return Allocate(Size, Align(Alignment));
  188. }
  189. // Pull in base class overloads.
  190. using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
  191. // Bump pointer allocators are expected to never free their storage; and
  192. // clients expect pointers to remain valid for non-dereferencing uses even
  193. // after deallocation.
  194. void Deallocate(const void *Ptr, size_t Size, size_t /*Alignment*/) {
  195. __asan_poison_memory_region(Ptr, Size);
  196. }
  197. // Pull in base class overloads.
  198. using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate;
  199. size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
  200. /// \return An index uniquely and reproducibly identifying
  201. /// an input pointer \p Ptr in the given allocator.
  202. /// The returned value is negative iff the object is inside a custom-size
  203. /// slab.
  204. /// Returns an empty optional if the pointer is not found in the allocator.
  205. std::optional<int64_t> identifyObject(const void *Ptr) {
  206. const char *P = static_cast<const char *>(Ptr);
  207. int64_t InSlabIdx = 0;
  208. for (size_t Idx = 0, E = Slabs.size(); Idx < E; Idx++) {
  209. const char *S = static_cast<const char *>(Slabs[Idx]);
  210. if (P >= S && P < S + computeSlabSize(Idx))
  211. return InSlabIdx + static_cast<int64_t>(P - S);
  212. InSlabIdx += static_cast<int64_t>(computeSlabSize(Idx));
  213. }
  214. // Use negative index to denote custom sized slabs.
  215. int64_t InCustomSizedSlabIdx = -1;
  216. for (size_t Idx = 0, E = CustomSizedSlabs.size(); Idx < E; Idx++) {
  217. const char *S = static_cast<const char *>(CustomSizedSlabs[Idx].first);
  218. size_t Size = CustomSizedSlabs[Idx].second;
  219. if (P >= S && P < S + Size)
  220. return InCustomSizedSlabIdx - static_cast<int64_t>(P - S);
  221. InCustomSizedSlabIdx -= static_cast<int64_t>(Size);
  222. }
  223. return std::nullopt;
  224. }
  225. /// A wrapper around identifyObject that additionally asserts that
  226. /// the object is indeed within the allocator.
  227. /// \return An index uniquely and reproducibly identifying
  228. /// an input pointer \p Ptr in the given allocator.
  229. int64_t identifyKnownObject(const void *Ptr) {
  230. std::optional<int64_t> Out = identifyObject(Ptr);
  231. assert(Out && "Wrong allocator used");
  232. return *Out;
  233. }
  234. /// A wrapper around identifyKnownObject. Accepts type information
  235. /// about the object and produces a smaller identifier by relying on
  236. /// the alignment information. Note that sub-classes may have different
  237. /// alignment, so the most base class should be passed as template parameter
  238. /// in order to obtain correct results. For that reason automatic template
  239. /// parameter deduction is disabled.
  240. /// \return An index uniquely and reproducibly identifying
  241. /// an input pointer \p Ptr in the given allocator. This identifier is
  242. /// different from the ones produced by identifyObject and
  243. /// identifyAlignedObject.
  244. template <typename T>
  245. int64_t identifyKnownAlignedObject(const void *Ptr) {
  246. int64_t Out = identifyKnownObject(Ptr);
  247. assert(Out % alignof(T) == 0 && "Wrong alignment information");
  248. return Out / alignof(T);
  249. }
  250. size_t getTotalMemory() const {
  251. size_t TotalMemory = 0;
  252. for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
  253. TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
  254. for (const auto &PtrAndSize : CustomSizedSlabs)
  255. TotalMemory += PtrAndSize.second;
  256. return TotalMemory;
  257. }
  258. size_t getBytesAllocated() const { return BytesAllocated; }
  259. void setRedZoneSize(size_t NewSize) {
  260. RedZoneSize = NewSize;
  261. }
  262. void PrintStats() const {
  263. detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
  264. getTotalMemory());
  265. }
  266. private:
  267. /// The current pointer into the current slab.
  268. ///
  269. /// This points to the next free byte in the slab.
  270. char *CurPtr = nullptr;
  271. /// The end of the current slab.
  272. char *End = nullptr;
  273. /// The slabs allocated so far.
  274. SmallVector<void *, 4> Slabs;
  275. /// Custom-sized slabs allocated for too-large allocation requests.
  276. SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
  277. /// How many bytes we've allocated.
  278. ///
  279. /// Used so that we can compute how much space was wasted.
  280. size_t BytesAllocated = 0;
  281. /// The number of bytes to put between allocations when running under
  282. /// a sanitizer.
  283. size_t RedZoneSize = 1;
  284. static size_t computeSlabSize(unsigned SlabIdx) {
  285. // Scale the actual allocated slab size based on the number of slabs
  286. // allocated. Every GrowthDelay slabs allocated, we double
  287. // the allocated size to reduce allocation frequency, but saturate at
  288. // multiplying the slab size by 2^30.
  289. return SlabSize *
  290. ((size_t)1 << std::min<size_t>(30, SlabIdx / GrowthDelay));
  291. }
  292. /// Allocate a new slab and move the bump pointers over into the new
  293. /// slab, modifying CurPtr and End.
  294. void StartNewSlab() {
  295. size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
  296. void *NewSlab = this->getAllocator().Allocate(AllocatedSlabSize,
  297. alignof(std::max_align_t));
  298. // We own the new slab and don't want anyone reading anything other than
  299. // pieces returned from this method. So poison the whole slab.
  300. __asan_poison_memory_region(NewSlab, AllocatedSlabSize);
  301. Slabs.push_back(NewSlab);
  302. CurPtr = (char *)(NewSlab);
  303. End = ((char *)NewSlab) + AllocatedSlabSize;
  304. }
  305. /// Deallocate a sequence of slabs.
  306. void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
  307. SmallVectorImpl<void *>::iterator E) {
  308. for (; I != E; ++I) {
  309. size_t AllocatedSlabSize =
  310. computeSlabSize(std::distance(Slabs.begin(), I));
  311. this->getAllocator().Deallocate(*I, AllocatedSlabSize,
  312. alignof(std::max_align_t));
  313. }
  314. }
  315. /// Deallocate all memory for custom sized slabs.
  316. void DeallocateCustomSizedSlabs() {
  317. for (auto &PtrAndSize : CustomSizedSlabs) {
  318. void *Ptr = PtrAndSize.first;
  319. size_t Size = PtrAndSize.second;
  320. this->getAllocator().Deallocate(Ptr, Size, alignof(std::max_align_t));
  321. }
  322. }
  323. template <typename T> friend class SpecificBumpPtrAllocator;
  324. };
  325. /// The standard BumpPtrAllocator which just uses the default template
  326. /// parameters.
  327. typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
  328. /// A BumpPtrAllocator that allows only elements of a specific type to be
  329. /// allocated.
  330. ///
  331. /// This allows calling the destructor in DestroyAll() and when the allocator is
  332. /// destroyed.
  333. template <typename T> class SpecificBumpPtrAllocator {
  334. BumpPtrAllocator Allocator;
  335. public:
  336. SpecificBumpPtrAllocator() {
  337. // Because SpecificBumpPtrAllocator walks the memory to call destructors,
  338. // it can't have red zones between allocations.
  339. Allocator.setRedZoneSize(0);
  340. }
  341. SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old)
  342. : Allocator(std::move(Old.Allocator)) {}
  343. ~SpecificBumpPtrAllocator() { DestroyAll(); }
  344. SpecificBumpPtrAllocator &operator=(SpecificBumpPtrAllocator &&RHS) {
  345. Allocator = std::move(RHS.Allocator);
  346. return *this;
  347. }
  348. /// Call the destructor of each allocated object and deallocate all but the
  349. /// current slab and reset the current pointer to the beginning of it, freeing
  350. /// all memory allocated so far.
  351. void DestroyAll() {
  352. auto DestroyElements = [](char *Begin, char *End) {
  353. assert(Begin == (char *)alignAddr(Begin, Align::Of<T>()));
  354. for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
  355. reinterpret_cast<T *>(Ptr)->~T();
  356. };
  357. for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
  358. ++I) {
  359. size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
  360. std::distance(Allocator.Slabs.begin(), I));
  361. char *Begin = (char *)alignAddr(*I, Align::Of<T>());
  362. char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
  363. : (char *)*I + AllocatedSlabSize;
  364. DestroyElements(Begin, End);
  365. }
  366. for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
  367. void *Ptr = PtrAndSize.first;
  368. size_t Size = PtrAndSize.second;
  369. DestroyElements((char *)alignAddr(Ptr, Align::Of<T>()),
  370. (char *)Ptr + Size);
  371. }
  372. Allocator.Reset();
  373. }
  374. /// Allocate space for an array of objects without constructing them.
  375. T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
  376. };
  377. } // end namespace llvm
  378. template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold,
  379. size_t GrowthDelay>
  380. void *
  381. operator new(size_t Size,
  382. llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold,
  383. GrowthDelay> &Allocator) {
  384. return Allocator.Allocate(Size, std::min((size_t)llvm::NextPowerOf2(Size),
  385. alignof(std::max_align_t)));
  386. }
  387. template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold,
  388. size_t GrowthDelay>
  389. void operator delete(void *,
  390. llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
  391. SizeThreshold, GrowthDelay> &) {
  392. }
  393. #endif // LLVM_SUPPORT_ALLOCATOR_H
  394. #ifdef __GNUC__
  395. #pragma GCC diagnostic pop
  396. #endif