| 1 | /* -*- C++ -*- */ |
| 2 | |
| 3 | #ifndef HL_SIZETHREADHEAP_H |
| 4 | #define HL_SIZETHREADHEAP_H |
| 5 | |
| 6 | #include <assert.h> |
| 7 | |
| 8 | #include "threads/cpuinfo.h" |
| 9 | |
| 10 | namespace HL { |
| 11 | |
| 12 | template <class Super> |
| 13 | class SizeThreadHeap : public Super { |
| 14 | public: |
| 15 | |
| 16 | inline void * malloc (size_t sz) { |
| 17 | // Add room for a size field & a thread field. |
| 18 | // Both of these must fit in a double. |
| 19 | assert (sizeof(st) <= sizeof(double)); |
| 20 | st * ptr = (st *) Super::malloc (sz + sizeof(double)); |
| 21 | // Store the requested size. |
| 22 | ptr->size = sz; |
| 23 | assert (getOrigPtr(ptr + 1) == ptr); |
| 24 | return (void *) (ptr + 1); |
| 25 | } |
| 26 | |
| 27 | inline void free (void * ptr) { |
| 28 | void * origPtr = (void *) getOrigPtr(ptr); |
| 29 | Super::free (origPtr); |
| 30 | } |
| 31 | |
| 32 | static inline size_t& size (void * ptr) { |
| 33 | return getOrigPtr(ptr)->size; |
| 34 | } |
| 35 | |
| 36 | static inline int& thread (void * ptr) { |
| 37 | return getOrigPtr(ptr)->tid; |
| 38 | } |
| 39 | |
| 40 | private: |
| 41 | |
| 42 | typedef struct _st { |
| 43 | size_t size; |
| 44 | int tid; |
| 45 | } st; |
| 46 | |
| 47 | static inline st * getOrigPtr (void * ptr) { |
| 48 | return (st *) ((double *) ptr - 1); |
| 49 | } |
| 50 | |
| 51 | }; |
| 52 | |
| 53 | } |
| 54 | |
| 55 | #endif |