source: icGREP/icgrep-devel/icgrep/util/slab_allocator.h @ 5230

Last change on this file since 5230 was 5230, checked in by nmedfort, 3 years ago

Multi-threading support for PabloAST / PabloCompiler?. Requires unique LLVM Context / Module for each thread.

File size: 1.9 KB
Line 
1#ifndef SLAB_ALLOCATOR_H
2#define SLAB_ALLOCATOR_H
3
4#include <llvm/Support/Allocator.h>
5
6template <typename T>
7class SlabAllocator {
8    using LLVMAllocator = llvm::BumpPtrAllocator;
9public:
10
11    using value_type = T;
12    using pointer = value_type*;
13    using const_pointer = const value_type*;
14    using reference = value_type&;
15    using const_reference = const value_type&;
16    using size_type = std::size_t;
17    using difference_type = std::ptrdiff_t;
18
19    template<class U>
20    struct rebind {
21        typedef SlabAllocator<U> other;
22    };
23
24    template<typename Type = T>
25    inline Type * allocate(size_type n, const_pointer = nullptr) noexcept {
26        static_assert(sizeof(Type) > 0, "Cannot allocate a zero-length type.");
27        assert ("Cannot allocate 0 items." && n > 0);
28        auto ptr = static_cast<Type *>(mAllocator.Allocate(n * sizeof(Type), sizeof(void*)));
29        assert ("Allocating returned a null pointer. Function was likely called before Allocator creation!" && ptr);
30        return ptr;
31    }
32
33    template<typename Type = T>
34    inline void deallocate(Type * p, size_type = 0) noexcept {
35        mAllocator.Deallocate(p);
36    }
37
38    inline size_type max_size() const {
39        return std::numeric_limits<size_type>::max();
40    }
41
42    inline LLVMAllocator & get_allocator() {
43        return mAllocator;
44    }
45
46    void reset() {
47        mAllocator.Reset();
48    }
49
50    template<typename Type = T>
51    inline bool operator==(SlabAllocator<Type> const & other) {
52        return &mAllocator == &other.mAllocator;
53    }
54
55    template<typename Type = T>
56    inline bool operator!=(SlabAllocator<Type> const & other) {
57        return &mAllocator != &other.mAllocator;
58    }
59
60    inline SlabAllocator() noexcept {}
61    inline SlabAllocator(const SlabAllocator &) noexcept {}
62    template <class U> inline SlabAllocator (const std::allocator<U>&) noexcept {}
63    inline ~SlabAllocator() { reset(); }
64private:
65    LLVMAllocator mAllocator;
66};
67
68#endif // SLAB_ALLOCATOR_H
Note: See TracBrowser for help on using the repository browser.