Allocator.h 17 KB

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