#ifndef LLVM_SUPPORT_RECYCLER_H
#define LLVM_SUPPORT_RECYCLER_H
#include "llvm/ADT/ilist.h"
#include "llvm/Support/AlignOf.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>
namespace llvm {
void PrintRecyclerStats(size_t Size, size_t Align, size_t FreeListSize);
template<class T, size_t Size = sizeof(T), size_t Align = AlignOf<T>::Alignment>
class Recycler {
struct FreeNode {
FreeNode *Next;
};
FreeNode *FreeList = nullptr;
FreeNode *pop_val() {
auto *Val = FreeList;
FreeList = FreeList->Next;
return Val;
}
void push(FreeNode *N) {
N->Next = FreeList;
FreeList = N;
}
public:
~Recycler() {
assert(!FreeList && "Non-empty recycler deleted!");
}
template<class AllocatorType>
void clear(AllocatorType &Allocator) {
while (FreeList) {
T *t = reinterpret_cast<T *>(pop_val());
Allocator.Deallocate(t);
}
}
void clear(BumpPtrAllocator &) { FreeList = nullptr; }
template<class SubClass, class AllocatorType>
SubClass *Allocate(AllocatorType &Allocator) {
static_assert(AlignOf<SubClass>::Alignment <= Align,
"Recycler allocation alignment is less than object align!");
static_assert(sizeof(SubClass) <= Size,
"Recycler allocation size is less than object size!");
return FreeList ? reinterpret_cast<SubClass *>(pop_val())
: static_cast<SubClass *>(Allocator.Allocate(Size, Align));
}
template<class AllocatorType>
T *Allocate(AllocatorType &Allocator) {
return Allocate<T>(Allocator);
}
template<class SubClass, class AllocatorType>
void Deallocate(AllocatorType & , SubClass* Element) {
push(reinterpret_cast<FreeNode *>(Element));
}
void PrintStats();
};
template <class T, size_t Size, size_t Align>
void Recycler<T, Size, Align>::PrintStats() {
size_t S = 0;
for (auto *I = FreeList; I; I = I->Next)
++S;
PrintRecyclerStats(Size, Align, S);
}
}
#endif