1 //==- llvm/Support/Recycler.h - Recycling Allocator --------------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Recycler class template. See the doxygen comment for
11 // Recycler for more details.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_SUPPORT_RECYCLER_H
16 #define LLVM_SUPPORT_RECYCLER_H
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/Support/Allocator.h"
20 #include "llvm/Support/ErrorHandling.h"
25 /// PrintRecyclingAllocatorStats - Helper for RecyclingAllocator for
26 /// printing statistics.
28 void PrintRecyclerStats(size_t Size, size_t Align, size_t FreeListSize);
30 /// Recycler - This class manages a linked-list of deallocated nodes
31 /// and facilitates reusing deallocated memory in place of allocating
34 template <class T, size_t Size = sizeof(T), size_t Align = alignof(T)>
40 /// List of nodes that have deleted contents and are not in active use.
41 FreeNode *FreeList = nullptr;
45 FreeList = FreeList->Next;
49 void push(FreeNode *N) {
56 // If this fails, either the callee has lost track of some allocation,
57 // or the callee isn't tracking allocations and should just call
58 // clear() before deleting the Recycler.
59 assert(!FreeList && "Non-empty recycler deleted!");
62 /// clear - Release all the tracked allocations to the allocator. The
63 /// recycler must be free of any tracked allocations before being
64 /// deleted; calling clear is one way to ensure this.
65 template<class AllocatorType>
66 void clear(AllocatorType &Allocator) {
68 T *t = reinterpret_cast<T *>(pop_val());
69 Allocator.Deallocate(t);
73 /// Special case for BumpPtrAllocator which has an empty Deallocate()
76 /// There is no need to traverse the free list, pulling all the objects into
78 void clear(BumpPtrAllocator &) { FreeList = nullptr; }
80 template<class SubClass, class AllocatorType>
81 SubClass *Allocate(AllocatorType &Allocator) {
82 static_assert(alignof(SubClass) <= Align,
83 "Recycler allocation alignment is less than object align!");
84 static_assert(sizeof(SubClass) <= Size,
85 "Recycler allocation size is less than object size!");
86 return FreeList ? reinterpret_cast<SubClass *>(pop_val())
87 : static_cast<SubClass *>(Allocator.Allocate(Size, Align));
90 template<class AllocatorType>
91 T *Allocate(AllocatorType &Allocator) {
92 return Allocate<T>(Allocator);
95 template<class SubClass, class AllocatorType>
96 void Deallocate(AllocatorType & /*Allocator*/, SubClass* Element) {
97 push(reinterpret_cast<FreeNode *>(Element));
103 template <class T, size_t Size, size_t Align>
104 void Recycler<T, Size, Align>::PrintStats() {
106 for (auto *I = FreeList; I; I = I->Next)
108 PrintRecyclerStats(Size, Align, S);