1 //===-- JITMemoryManager.cpp - Memory Allocator for JIT'd code ------------===//
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 DefaultJITMemoryManager class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ExecutionEngine/JITMemoryManager.h"
15 #include "llvm/Support/Compiler.h"
16 #include "llvm/System/Memory.h"
23 JITMemoryManager::~JITMemoryManager() {}
25 //===----------------------------------------------------------------------===//
26 // Memory Block Implementation.
27 //===----------------------------------------------------------------------===//
30 /// MemoryRangeHeader - For a range of memory, this is the header that we put
31 /// on the block of memory. It is carefully crafted to be one word of memory.
32 /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
33 /// which starts with this.
34 struct FreeRangeHeader;
35 struct MemoryRangeHeader {
36 /// ThisAllocated - This is true if this block is currently allocated. If
37 /// not, this can be converted to a FreeRangeHeader.
38 unsigned ThisAllocated : 1;
40 /// PrevAllocated - Keep track of whether the block immediately before us is
41 /// allocated. If not, the word immediately before this header is the size
42 /// of the previous block.
43 unsigned PrevAllocated : 1;
45 /// BlockSize - This is the size in bytes of this memory block,
46 /// including this header.
47 uintptr_t BlockSize : (sizeof(intptr_t)*8 - 2);
50 /// getBlockAfter - Return the memory block immediately after this one.
52 MemoryRangeHeader &getBlockAfter() const {
53 return *(MemoryRangeHeader*)((char*)this+BlockSize);
56 /// getFreeBlockBefore - If the block before this one is free, return it,
57 /// otherwise return null.
58 FreeRangeHeader *getFreeBlockBefore() const {
59 if (PrevAllocated) return 0;
60 intptr_t PrevSize = ((intptr_t *)this)[-1];
61 return (FreeRangeHeader*)((char*)this-PrevSize);
64 /// FreeBlock - Turn an allocated block into a free block, adjusting
65 /// bits in the object headers, and adding an end of region memory block.
66 FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
68 /// TrimAllocationToSize - If this allocated block is significantly larger
69 /// than NewSize, split it into two pieces (where the former is NewSize
70 /// bytes, including the header), and add the new block to the free list.
71 FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
75 /// FreeRangeHeader - For a memory block that isn't already allocated, this
76 /// keeps track of the current block and has a pointer to the next free block.
77 /// Free blocks are kept on a circularly linked list.
78 struct FreeRangeHeader : public MemoryRangeHeader {
79 FreeRangeHeader *Prev;
80 FreeRangeHeader *Next;
82 /// getMinBlockSize - Get the minimum size for a memory block. Blocks
83 /// smaller than this size cannot be created.
84 static unsigned getMinBlockSize() {
85 return sizeof(FreeRangeHeader)+sizeof(intptr_t);
88 /// SetEndOfBlockSizeMarker - The word at the end of every free block is
89 /// known to be the size of the free block. Set it for this block.
90 void SetEndOfBlockSizeMarker() {
91 void *EndOfBlock = (char*)this + BlockSize;
92 ((intptr_t *)EndOfBlock)[-1] = BlockSize;
95 FreeRangeHeader *RemoveFromFreeList() {
96 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
98 return Prev->Next = Next;
101 void AddToFreeList(FreeRangeHeader *FreeList) {
103 Prev = FreeList->Prev;
108 /// GrowBlock - The block after this block just got deallocated. Merge it
109 /// into the current block.
110 void GrowBlock(uintptr_t NewSize);
112 /// AllocateBlock - Mark this entire block allocated, updating freelists
113 /// etc. This returns a pointer to the circular free-list.
114 FreeRangeHeader *AllocateBlock();
119 /// AllocateBlock - Mark this entire block allocated, updating freelists
120 /// etc. This returns a pointer to the circular free-list.
121 FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
122 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
123 "Cannot allocate an allocated block!");
124 // Mark this block allocated.
126 getBlockAfter().PrevAllocated = 1;
128 // Remove it from the free list.
129 return RemoveFromFreeList();
132 /// FreeBlock - Turn an allocated block into a free block, adjusting
133 /// bits in the object headers, and adding an end of region memory block.
134 /// If possible, coalesce this block with neighboring blocks. Return the
135 /// FreeRangeHeader to allocate from.
136 FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
137 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
138 assert(ThisAllocated && "This block is already allocated!");
139 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
141 FreeRangeHeader *FreeListToReturn = FreeList;
143 // If the block after this one is free, merge it into this block.
144 if (!FollowingBlock->ThisAllocated) {
145 FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
146 // "FreeList" always needs to be a valid free block. If we're about to
147 // coalesce with it, update our notion of what the free list is.
148 if (&FollowingFreeBlock == FreeList) {
149 FreeList = FollowingFreeBlock.Next;
150 FreeListToReturn = 0;
151 assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
153 FollowingFreeBlock.RemoveFromFreeList();
155 // Include the following block into this one.
156 BlockSize += FollowingFreeBlock.BlockSize;
157 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
159 // Tell the block after the block we are coalescing that this block is
161 FollowingBlock->PrevAllocated = 1;
164 assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
166 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
167 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
168 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
171 // Otherwise, mark this block free.
172 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
173 FollowingBlock->PrevAllocated = 0;
174 FreeBlock.ThisAllocated = 0;
176 // Link this into the linked list of free blocks.
177 FreeBlock.AddToFreeList(FreeList);
179 // Add a marker at the end of the block, indicating the size of this free
181 FreeBlock.SetEndOfBlockSizeMarker();
182 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
185 /// GrowBlock - The block after this block just got deallocated. Merge it
186 /// into the current block.
187 void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
188 assert(NewSize > BlockSize && "Not growing block?");
190 SetEndOfBlockSizeMarker();
191 getBlockAfter().PrevAllocated = 0;
194 /// TrimAllocationToSize - If this allocated block is significantly larger
195 /// than NewSize, split it into two pieces (where the former is NewSize
196 /// bytes, including the header), and add the new block to the free list.
197 FreeRangeHeader *MemoryRangeHeader::
198 TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
199 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
200 "Cannot deallocate part of an allocated block!");
202 // Round up size for alignment of header.
203 unsigned HeaderAlign = __alignof(FreeRangeHeader);
204 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
206 // Size is now the size of the block we will remove from the start of the
208 assert(NewSize <= BlockSize &&
209 "Allocating more space from this block than exists!");
211 // If splitting this block will cause the remainder to be too small, do not
213 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
216 // Otherwise, we splice the required number of bytes out of this block, form
217 // a new block immediately after it, then mark this block allocated.
218 MemoryRangeHeader &FormerNextBlock = getBlockAfter();
220 // Change the size of this block.
223 // Get the new block we just sliced out and turn it into a free block.
224 FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
225 NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
226 NewNextBlock.ThisAllocated = 0;
227 NewNextBlock.PrevAllocated = 1;
228 NewNextBlock.SetEndOfBlockSizeMarker();
229 FormerNextBlock.PrevAllocated = 0;
230 NewNextBlock.AddToFreeList(FreeList);
231 return &NewNextBlock;
234 //===----------------------------------------------------------------------===//
235 // Memory Block Implementation.
236 //===----------------------------------------------------------------------===//
239 /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
240 /// This splits a large block of MAP_NORESERVE'd memory into two
241 /// sections, one for function stubs, one for the functions themselves. We
242 /// have to do this because we may need to emit a function stub while in the
243 /// middle of emitting a function, and we don't know how large the function we
245 class VISIBILITY_HIDDEN DefaultJITMemoryManager : public JITMemoryManager {
246 std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
247 FreeRangeHeader *FreeMemoryList; // Circular list of free blocks.
249 // When emitting code into a memory block, this is the block.
250 MemoryRangeHeader *CurBlock;
252 unsigned char *CurStubPtr, *StubBase;
253 unsigned char *GOTBase; // Target Specific reserved memory
255 // Centralize memory block allocation.
256 sys::MemoryBlock getNewMemoryBlock(unsigned size);
258 std::map<const Function*, MemoryRangeHeader*> FunctionBlocks;
259 std::map<const Function*, MemoryRangeHeader*> TableBlocks;
261 DefaultJITMemoryManager();
262 ~DefaultJITMemoryManager();
266 unsigned char *allocateStub(unsigned StubSize, unsigned Alignment);
268 /// startFunctionBody - When a function starts, allocate a block of free
269 /// executable memory, returning a pointer to it and its actual size.
270 unsigned char *startFunctionBody(const Function *F, uintptr_t &ActualSize) {
271 CurBlock = FreeMemoryList;
273 // Allocate the entire memory block.
274 FreeMemoryList = FreeMemoryList->AllocateBlock();
275 ActualSize = CurBlock->BlockSize-sizeof(MemoryRangeHeader);
276 return (unsigned char *)(CurBlock+1);
279 /// endFunctionBody - The function F is now allocated, and takes the memory
280 /// in the range [FunctionStart,FunctionEnd).
281 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
282 unsigned char *FunctionEnd) {
283 assert(FunctionEnd > FunctionStart);
284 assert(FunctionStart == (unsigned char *)(CurBlock+1) &&
285 "Mismatched function start/end!");
287 uintptr_t BlockSize = FunctionEnd - (unsigned char *)CurBlock;
288 FunctionBlocks[F] = CurBlock;
290 // Release the memory at the end of this block that isn't needed.
291 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
294 /// startExceptionTable - Use startFunctionBody to allocate memory for the
295 /// function's exception table.
296 unsigned char* startExceptionTable(const Function* F, uintptr_t &ActualSize) {
297 return startFunctionBody(F, ActualSize);
300 /// endExceptionTable - The exception table of F is now allocated,
301 /// and takes the memory in the range [TableStart,TableEnd).
302 void endExceptionTable(const Function *F, unsigned char *TableStart,
303 unsigned char *TableEnd,
304 unsigned char* FrameRegister) {
305 assert(TableEnd > TableStart);
306 assert(TableStart == (unsigned char *)(CurBlock+1) &&
307 "Mismatched table start/end!");
309 uintptr_t BlockSize = TableEnd - (unsigned char *)CurBlock;
310 TableBlocks[F] = CurBlock;
312 // Release the memory at the end of this block that isn't needed.
313 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
316 unsigned char *getGOTBase() const {
320 /// deallocateMemForFunction - Deallocate all memory for the specified
322 void deallocateMemForFunction(const Function *F) {
323 std::map<const Function*, MemoryRangeHeader*>::iterator
324 I = FunctionBlocks.find(F);
325 if (I == FunctionBlocks.end()) return;
327 // Find the block that is allocated for this function.
328 MemoryRangeHeader *MemRange = I->second;
329 assert(MemRange->ThisAllocated && "Block isn't allocated!");
331 // Fill the buffer with garbage!
333 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
337 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
339 // Finally, remove this entry from FunctionBlocks.
340 FunctionBlocks.erase(I);
342 I = TableBlocks.find(F);
343 if (I == TableBlocks.end()) return;
345 // Find the block that is allocated for this function.
346 MemRange = I->second;
347 assert(MemRange->ThisAllocated && "Block isn't allocated!");
349 // Fill the buffer with garbage!
351 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
355 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
357 // Finally, remove this entry from TableBlocks.
358 TableBlocks.erase(I);
363 DefaultJITMemoryManager::DefaultJITMemoryManager() {
364 // Allocate a 16M block of memory for functions.
365 sys::MemoryBlock MemBlock = getNewMemoryBlock(16 << 20);
367 unsigned char *MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
369 // Allocate stubs backwards from the base, allocate functions forward
372 CurStubPtr = MemBase + 512*1024; // Use 512k for stubs, working backwards.
374 // We set up the memory chunk with 4 mem regions, like this:
376 // [ Free #0 ] -> Large space to allocate functions from.
377 // [ Allocated #1 ] -> Tiny space to separate regions.
378 // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
379 // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
382 // The last three blocks are never deallocated or touched.
384 // Add MemoryRangeHeader to the end of the memory region, indicating that
385 // the space after the block of memory is allocated. This is block #3.
386 MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
387 Mem3->ThisAllocated = 1;
388 Mem3->PrevAllocated = 0;
391 /// Add a tiny free region so that the free list always has one entry.
392 FreeRangeHeader *Mem2 =
393 (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
394 Mem2->ThisAllocated = 0;
395 Mem2->PrevAllocated = 1;
396 Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
397 Mem2->SetEndOfBlockSizeMarker();
398 Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
401 /// Add a tiny allocated region so that Mem2 is never coalesced away.
402 MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
403 Mem1->ThisAllocated = 1;
404 Mem1->PrevAllocated = 0;
405 Mem1->BlockSize = (char*)Mem2 - (char*)Mem1;
407 // Add a FreeRangeHeader to the start of the function body region, indicating
408 // that the space is free. Mark the previous block allocated so we never look
410 FreeRangeHeader *Mem0 = (FreeRangeHeader*)CurStubPtr;
411 Mem0->ThisAllocated = 0;
412 Mem0->PrevAllocated = 1;
413 Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
414 Mem0->SetEndOfBlockSizeMarker();
415 Mem0->AddToFreeList(Mem2);
417 // Start out with the freelist pointing to Mem0.
418 FreeMemoryList = Mem0;
423 void DefaultJITMemoryManager::AllocateGOT() {
424 assert(GOTBase == 0 && "Cannot allocate the got multiple times");
425 GOTBase = new unsigned char[sizeof(void*) * 8192];
430 DefaultJITMemoryManager::~DefaultJITMemoryManager() {
431 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
432 sys::Memory::ReleaseRWX(Blocks[i]);
438 unsigned char *DefaultJITMemoryManager::allocateStub(unsigned StubSize,
439 unsigned Alignment) {
440 CurStubPtr -= StubSize;
441 CurStubPtr = (unsigned char*)(((intptr_t)CurStubPtr) &
442 ~(intptr_t)(Alignment-1));
443 if (CurStubPtr < StubBase) {
444 // FIXME: allocate a new block
445 fprintf(stderr, "JIT ran out of memory for function stubs!\n");
451 sys::MemoryBlock DefaultJITMemoryManager::getNewMemoryBlock(unsigned size) {
452 // Allocate a new block close to the last one.
453 const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.front();
455 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld, &ErrMsg);
458 "Allocation failed when allocating new memory in the JIT\n%s\n",
467 JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
468 return new DefaultJITMemoryManager();