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/GlobalValue.h"
15 #include "llvm/ExecutionEngine/JITMemoryManager.h"
16 #include "llvm/Support/Compiler.h"
17 #include "llvm/System/Memory.h"
26 JITMemoryManager::~JITMemoryManager() {}
28 //===----------------------------------------------------------------------===//
29 // Memory Block Implementation.
30 //===----------------------------------------------------------------------===//
33 /// MemoryRangeHeader - For a range of memory, this is the header that we put
34 /// on the block of memory. It is carefully crafted to be one word of memory.
35 /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
36 /// which starts with this.
37 struct FreeRangeHeader;
38 struct MemoryRangeHeader {
39 /// ThisAllocated - This is true if this block is currently allocated. If
40 /// not, this can be converted to a FreeRangeHeader.
41 unsigned ThisAllocated : 1;
43 /// PrevAllocated - Keep track of whether the block immediately before us is
44 /// allocated. If not, the word immediately before this header is the size
45 /// of the previous block.
46 unsigned PrevAllocated : 1;
48 /// BlockSize - This is the size in bytes of this memory block,
49 /// including this header.
50 uintptr_t BlockSize : (sizeof(intptr_t)*8 - 2);
53 /// getBlockAfter - Return the memory block immediately after this one.
55 MemoryRangeHeader &getBlockAfter() const {
56 return *(MemoryRangeHeader*)((char*)this+BlockSize);
59 /// getFreeBlockBefore - If the block before this one is free, return it,
60 /// otherwise return null.
61 FreeRangeHeader *getFreeBlockBefore() const {
62 if (PrevAllocated) return 0;
63 intptr_t PrevSize = ((intptr_t *)this)[-1];
64 return (FreeRangeHeader*)((char*)this-PrevSize);
67 /// FreeBlock - Turn an allocated block into a free block, adjusting
68 /// bits in the object headers, and adding an end of region memory block.
69 FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
71 /// TrimAllocationToSize - If this allocated block is significantly larger
72 /// than NewSize, split it into two pieces (where the former is NewSize
73 /// bytes, including the header), and add the new block to the free list.
74 FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
78 /// FreeRangeHeader - For a memory block that isn't already allocated, this
79 /// keeps track of the current block and has a pointer to the next free block.
80 /// Free blocks are kept on a circularly linked list.
81 struct FreeRangeHeader : public MemoryRangeHeader {
82 FreeRangeHeader *Prev;
83 FreeRangeHeader *Next;
85 /// getMinBlockSize - Get the minimum size for a memory block. Blocks
86 /// smaller than this size cannot be created.
87 static unsigned getMinBlockSize() {
88 return sizeof(FreeRangeHeader)+sizeof(intptr_t);
91 /// SetEndOfBlockSizeMarker - The word at the end of every free block is
92 /// known to be the size of the free block. Set it for this block.
93 void SetEndOfBlockSizeMarker() {
94 void *EndOfBlock = (char*)this + BlockSize;
95 ((intptr_t *)EndOfBlock)[-1] = BlockSize;
98 FreeRangeHeader *RemoveFromFreeList() {
99 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
101 return Prev->Next = Next;
104 void AddToFreeList(FreeRangeHeader *FreeList) {
106 Prev = FreeList->Prev;
111 /// GrowBlock - The block after this block just got deallocated. Merge it
112 /// into the current block.
113 void GrowBlock(uintptr_t NewSize);
115 /// AllocateBlock - Mark this entire block allocated, updating freelists
116 /// etc. This returns a pointer to the circular free-list.
117 FreeRangeHeader *AllocateBlock();
122 /// AllocateBlock - Mark this entire block allocated, updating freelists
123 /// etc. This returns a pointer to the circular free-list.
124 FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
125 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
126 "Cannot allocate an allocated block!");
127 // Mark this block allocated.
129 getBlockAfter().PrevAllocated = 1;
131 // Remove it from the free list.
132 return RemoveFromFreeList();
135 /// FreeBlock - Turn an allocated block into a free block, adjusting
136 /// bits in the object headers, and adding an end of region memory block.
137 /// If possible, coalesce this block with neighboring blocks. Return the
138 /// FreeRangeHeader to allocate from.
139 FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
140 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
141 assert(ThisAllocated && "This block is already allocated!");
142 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
144 FreeRangeHeader *FreeListToReturn = FreeList;
146 // If the block after this one is free, merge it into this block.
147 if (!FollowingBlock->ThisAllocated) {
148 FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
149 // "FreeList" always needs to be a valid free block. If we're about to
150 // coalesce with it, update our notion of what the free list is.
151 if (&FollowingFreeBlock == FreeList) {
152 FreeList = FollowingFreeBlock.Next;
153 FreeListToReturn = 0;
154 assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
156 FollowingFreeBlock.RemoveFromFreeList();
158 // Include the following block into this one.
159 BlockSize += FollowingFreeBlock.BlockSize;
160 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
162 // Tell the block after the block we are coalescing that this block is
164 FollowingBlock->PrevAllocated = 1;
167 assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
169 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
170 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
171 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
174 // Otherwise, mark this block free.
175 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
176 FollowingBlock->PrevAllocated = 0;
177 FreeBlock.ThisAllocated = 0;
179 // Link this into the linked list of free blocks.
180 FreeBlock.AddToFreeList(FreeList);
182 // Add a marker at the end of the block, indicating the size of this free
184 FreeBlock.SetEndOfBlockSizeMarker();
185 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
188 /// GrowBlock - The block after this block just got deallocated. Merge it
189 /// into the current block.
190 void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
191 assert(NewSize > BlockSize && "Not growing block?");
193 SetEndOfBlockSizeMarker();
194 getBlockAfter().PrevAllocated = 0;
197 /// TrimAllocationToSize - If this allocated block is significantly larger
198 /// than NewSize, split it into two pieces (where the former is NewSize
199 /// bytes, including the header), and add the new block to the free list.
200 FreeRangeHeader *MemoryRangeHeader::
201 TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
202 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
203 "Cannot deallocate part of an allocated block!");
205 // Don't allow blocks to be trimmed below minimum required size
206 NewSize = std::max<uint64_t>(FreeRangeHeader::getMinBlockSize(), NewSize);
208 // Round up size for alignment of header.
209 unsigned HeaderAlign = __alignof(FreeRangeHeader);
210 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
212 // Size is now the size of the block we will remove from the start of the
214 assert(NewSize <= BlockSize &&
215 "Allocating more space from this block than exists!");
217 // If splitting this block will cause the remainder to be too small, do not
219 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
222 // Otherwise, we splice the required number of bytes out of this block, form
223 // a new block immediately after it, then mark this block allocated.
224 MemoryRangeHeader &FormerNextBlock = getBlockAfter();
226 // Change the size of this block.
229 // Get the new block we just sliced out and turn it into a free block.
230 FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
231 NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
232 NewNextBlock.ThisAllocated = 0;
233 NewNextBlock.PrevAllocated = 1;
234 NewNextBlock.SetEndOfBlockSizeMarker();
235 FormerNextBlock.PrevAllocated = 0;
236 NewNextBlock.AddToFreeList(FreeList);
237 return &NewNextBlock;
240 //===----------------------------------------------------------------------===//
241 // Memory Block Implementation.
242 //===----------------------------------------------------------------------===//
245 /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
246 /// This splits a large block of MAP_NORESERVE'd memory into two
247 /// sections, one for function stubs, one for the functions themselves. We
248 /// have to do this because we may need to emit a function stub while in the
249 /// middle of emitting a function, and we don't know how large the function we
251 class VISIBILITY_HIDDEN DefaultJITMemoryManager : public JITMemoryManager {
252 std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
253 FreeRangeHeader *FreeMemoryList; // Circular list of free blocks.
255 // When emitting code into a memory block, this is the block.
256 MemoryRangeHeader *CurBlock;
258 unsigned char *CurStubPtr, *StubBase;
259 unsigned char *GOTBase; // Target Specific reserved memory
261 // Centralize memory block allocation.
262 sys::MemoryBlock getNewMemoryBlock(unsigned size);
264 std::map<const Function*, MemoryRangeHeader*> FunctionBlocks;
265 std::map<const Function*, MemoryRangeHeader*> TableBlocks;
267 DefaultJITMemoryManager();
268 ~DefaultJITMemoryManager();
272 unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
275 /// startFunctionBody - When a function starts, allocate a block of free
276 /// executable memory, returning a pointer to it and its actual size.
277 unsigned char *startFunctionBody(const Function *F, uintptr_t &ActualSize) {
278 CurBlock = FreeMemoryList;
280 // Allocate the entire memory block.
281 FreeMemoryList = FreeMemoryList->AllocateBlock();
282 ActualSize = CurBlock->BlockSize-sizeof(MemoryRangeHeader);
283 return (unsigned char *)(CurBlock+1);
286 /// endFunctionBody - The function F is now allocated, and takes the memory
287 /// in the range [FunctionStart,FunctionEnd).
288 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
289 unsigned char *FunctionEnd) {
290 assert(FunctionEnd > FunctionStart);
291 assert(FunctionStart == (unsigned char *)(CurBlock+1) &&
292 "Mismatched function start/end!");
294 uintptr_t BlockSize = FunctionEnd - (unsigned char *)CurBlock;
295 FunctionBlocks[F] = CurBlock;
297 // Release the memory at the end of this block that isn't needed.
298 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
301 /// startExceptionTable - Use startFunctionBody to allocate memory for the
302 /// function's exception table.
303 unsigned char* startExceptionTable(const Function* F,
304 uintptr_t &ActualSize) {
305 return startFunctionBody(F, ActualSize);
308 /// endExceptionTable - The exception table of F is now allocated,
309 /// and takes the memory in the range [TableStart,TableEnd).
310 void endExceptionTable(const Function *F, unsigned char *TableStart,
311 unsigned char *TableEnd,
312 unsigned char* FrameRegister) {
313 assert(TableEnd > TableStart);
314 assert(TableStart == (unsigned char *)(CurBlock+1) &&
315 "Mismatched table start/end!");
317 uintptr_t BlockSize = TableEnd - (unsigned char *)CurBlock;
318 TableBlocks[F] = CurBlock;
320 // Release the memory at the end of this block that isn't needed.
321 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
324 unsigned char *getGOTBase() const {
328 /// deallocateMemForFunction - Deallocate all memory for the specified
330 void deallocateMemForFunction(const Function *F) {
331 std::map<const Function*, MemoryRangeHeader*>::iterator
332 I = FunctionBlocks.find(F);
333 if (I == FunctionBlocks.end()) return;
335 // Find the block that is allocated for this function.
336 MemoryRangeHeader *MemRange = I->second;
337 assert(MemRange->ThisAllocated && "Block isn't allocated!");
339 // Fill the buffer with garbage!
341 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
345 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
347 // Finally, remove this entry from FunctionBlocks.
348 FunctionBlocks.erase(I);
350 I = TableBlocks.find(F);
351 if (I == TableBlocks.end()) return;
353 // Find the block that is allocated for this function.
354 MemRange = I->second;
355 assert(MemRange->ThisAllocated && "Block isn't allocated!");
357 // Fill the buffer with garbage!
359 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
363 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
365 // Finally, remove this entry from TableBlocks.
366 TableBlocks.erase(I);
369 /// setMemoryWritable - When code generation is in progress,
370 /// the code pages may need permissions changed.
371 void setMemoryWritable(void)
373 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
374 sys::Memory::setWritable(Blocks[i]);
376 /// setMemoryExecutable - When code generation is done and we're ready to
377 /// start execution, the code pages may need permissions changed.
378 void setMemoryExecutable(void)
380 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
381 sys::Memory::setExecutable(Blocks[i]);
386 DefaultJITMemoryManager::DefaultJITMemoryManager() {
387 // Allocate a 16M block of memory for functions.
388 #if defined(__APPLE__) && defined(__arm__)
389 sys::MemoryBlock MemBlock = getNewMemoryBlock(4 << 20);
391 sys::MemoryBlock MemBlock = getNewMemoryBlock(16 << 20);
394 unsigned char *MemBase = static_cast<unsigned char*>(MemBlock.base());
396 // Allocate stubs backwards from the base, allocate functions forward
399 CurStubPtr = MemBase + 512*1024; // Use 512k for stubs, working backwards.
401 // We set up the memory chunk with 4 mem regions, like this:
403 // [ Free #0 ] -> Large space to allocate functions from.
404 // [ Allocated #1 ] -> Tiny space to separate regions.
405 // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
406 // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
409 // The last three blocks are never deallocated or touched.
411 // Add MemoryRangeHeader to the end of the memory region, indicating that
412 // the space after the block of memory is allocated. This is block #3.
413 MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
414 Mem3->ThisAllocated = 1;
415 Mem3->PrevAllocated = 0;
418 /// Add a tiny free region so that the free list always has one entry.
419 FreeRangeHeader *Mem2 =
420 (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
421 Mem2->ThisAllocated = 0;
422 Mem2->PrevAllocated = 1;
423 Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
424 Mem2->SetEndOfBlockSizeMarker();
425 Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
428 /// Add a tiny allocated region so that Mem2 is never coalesced away.
429 MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
430 Mem1->ThisAllocated = 1;
431 Mem1->PrevAllocated = 0;
432 Mem1->BlockSize = (char*)Mem2 - (char*)Mem1;
434 // Add a FreeRangeHeader to the start of the function body region, indicating
435 // that the space is free. Mark the previous block allocated so we never look
437 FreeRangeHeader *Mem0 = (FreeRangeHeader*)CurStubPtr;
438 Mem0->ThisAllocated = 0;
439 Mem0->PrevAllocated = 1;
440 Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
441 Mem0->SetEndOfBlockSizeMarker();
442 Mem0->AddToFreeList(Mem2);
444 // Start out with the freelist pointing to Mem0.
445 FreeMemoryList = Mem0;
450 void DefaultJITMemoryManager::AllocateGOT() {
451 assert(GOTBase == 0 && "Cannot allocate the got multiple times");
452 GOTBase = new unsigned char[sizeof(void*) * 8192];
457 DefaultJITMemoryManager::~DefaultJITMemoryManager() {
458 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
459 sys::Memory::ReleaseRWX(Blocks[i]);
465 unsigned char *DefaultJITMemoryManager::allocateStub(const GlobalValue* F,
467 unsigned Alignment) {
468 CurStubPtr -= StubSize;
469 CurStubPtr = (unsigned char*)(((intptr_t)CurStubPtr) &
470 ~(intptr_t)(Alignment-1));
471 if (CurStubPtr < StubBase) {
472 // FIXME: allocate a new block
473 fprintf(stderr, "JIT ran out of memory for function stubs!\n");
479 sys::MemoryBlock DefaultJITMemoryManager::getNewMemoryBlock(unsigned size) {
480 // Allocate a new block close to the last one.
481 const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.front();
483 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld, &ErrMsg);
486 "Allocation failed when allocating new memory in the JIT\n%s\n",
495 JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
496 return new DefaultJITMemoryManager();