blob: cc072a896c22512eda7e661ec5fbb1d1d7c315ea [file] [log] [blame]
Chris Lattner8907b4b2007-12-05 23:39:57 +00001//===-- JITMemoryManager.cpp - Memory Allocator for JIT'd code ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner8907b4b2007-12-05 23:39:57 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the DefaultJITMemoryManager class.
11//
12//===----------------------------------------------------------------------===//
13
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +000014#include "llvm/GlobalValue.h"
Chris Lattner8907b4b2007-12-05 23:39:57 +000015#include "llvm/ExecutionEngine/JITMemoryManager.h"
16#include "llvm/Support/Compiler.h"
17#include "llvm/System/Memory.h"
18#include <map>
19#include <vector>
Chuck Rose III3012ac62007-12-06 02:03:01 +000020#include <cassert>
Duncan Sands4520dd22008-10-08 07:23:46 +000021#include <cstdio>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000022#include <cstdlib>
23#include <cstring>
Chris Lattner8907b4b2007-12-05 23:39:57 +000024using namespace llvm;
25
26
27JITMemoryManager::~JITMemoryManager() {}
28
29//===----------------------------------------------------------------------===//
30// Memory Block Implementation.
31//===----------------------------------------------------------------------===//
32
33namespace {
34 /// MemoryRangeHeader - For a range of memory, this is the header that we put
35 /// on the block of memory. It is carefully crafted to be one word of memory.
36 /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
37 /// which starts with this.
38 struct FreeRangeHeader;
39 struct MemoryRangeHeader {
40 /// ThisAllocated - This is true if this block is currently allocated. If
41 /// not, this can be converted to a FreeRangeHeader.
42 unsigned ThisAllocated : 1;
43
44 /// PrevAllocated - Keep track of whether the block immediately before us is
45 /// allocated. If not, the word immediately before this header is the size
46 /// of the previous block.
47 unsigned PrevAllocated : 1;
48
49 /// BlockSize - This is the size in bytes of this memory block,
50 /// including this header.
51 uintptr_t BlockSize : (sizeof(intptr_t)*8 - 2);
52
53
54 /// getBlockAfter - Return the memory block immediately after this one.
55 ///
56 MemoryRangeHeader &getBlockAfter() const {
57 return *(MemoryRangeHeader*)((char*)this+BlockSize);
58 }
59
60 /// getFreeBlockBefore - If the block before this one is free, return it,
61 /// otherwise return null.
62 FreeRangeHeader *getFreeBlockBefore() const {
63 if (PrevAllocated) return 0;
64 intptr_t PrevSize = ((intptr_t *)this)[-1];
65 return (FreeRangeHeader*)((char*)this-PrevSize);
66 }
67
68 /// FreeBlock - Turn an allocated block into a free block, adjusting
69 /// bits in the object headers, and adding an end of region memory block.
70 FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
71
72 /// TrimAllocationToSize - If this allocated block is significantly larger
73 /// than NewSize, split it into two pieces (where the former is NewSize
74 /// bytes, including the header), and add the new block to the free list.
75 FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
76 uint64_t NewSize);
77 };
78
79 /// FreeRangeHeader - For a memory block that isn't already allocated, this
80 /// keeps track of the current block and has a pointer to the next free block.
81 /// Free blocks are kept on a circularly linked list.
82 struct FreeRangeHeader : public MemoryRangeHeader {
83 FreeRangeHeader *Prev;
84 FreeRangeHeader *Next;
85
86 /// getMinBlockSize - Get the minimum size for a memory block. Blocks
87 /// smaller than this size cannot be created.
88 static unsigned getMinBlockSize() {
89 return sizeof(FreeRangeHeader)+sizeof(intptr_t);
90 }
91
92 /// SetEndOfBlockSizeMarker - The word at the end of every free block is
93 /// known to be the size of the free block. Set it for this block.
94 void SetEndOfBlockSizeMarker() {
95 void *EndOfBlock = (char*)this + BlockSize;
96 ((intptr_t *)EndOfBlock)[-1] = BlockSize;
97 }
98
99 FreeRangeHeader *RemoveFromFreeList() {
100 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
101 Next->Prev = Prev;
102 return Prev->Next = Next;
103 }
104
105 void AddToFreeList(FreeRangeHeader *FreeList) {
106 Next = FreeList;
107 Prev = FreeList->Prev;
108 Prev->Next = this;
109 Next->Prev = this;
110 }
111
112 /// GrowBlock - The block after this block just got deallocated. Merge it
113 /// into the current block.
114 void GrowBlock(uintptr_t NewSize);
115
116 /// AllocateBlock - Mark this entire block allocated, updating freelists
117 /// etc. This returns a pointer to the circular free-list.
118 FreeRangeHeader *AllocateBlock();
119 };
120}
121
122
123/// AllocateBlock - Mark this entire block allocated, updating freelists
124/// etc. This returns a pointer to the circular free-list.
125FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
126 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
127 "Cannot allocate an allocated block!");
128 // Mark this block allocated.
129 ThisAllocated = 1;
130 getBlockAfter().PrevAllocated = 1;
131
132 // Remove it from the free list.
133 return RemoveFromFreeList();
134}
135
136/// FreeBlock - Turn an allocated block into a free block, adjusting
137/// bits in the object headers, and adding an end of region memory block.
138/// If possible, coalesce this block with neighboring blocks. Return the
139/// FreeRangeHeader to allocate from.
140FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
141 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
142 assert(ThisAllocated && "This block is already allocated!");
143 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
144
145 FreeRangeHeader *FreeListToReturn = FreeList;
146
147 // If the block after this one is free, merge it into this block.
148 if (!FollowingBlock->ThisAllocated) {
149 FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
150 // "FreeList" always needs to be a valid free block. If we're about to
151 // coalesce with it, update our notion of what the free list is.
152 if (&FollowingFreeBlock == FreeList) {
153 FreeList = FollowingFreeBlock.Next;
154 FreeListToReturn = 0;
155 assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
156 }
157 FollowingFreeBlock.RemoveFromFreeList();
158
159 // Include the following block into this one.
160 BlockSize += FollowingFreeBlock.BlockSize;
161 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
162
163 // Tell the block after the block we are coalescing that this block is
164 // allocated.
165 FollowingBlock->PrevAllocated = 1;
166 }
167
168 assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
169
170 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
171 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
172 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
173 }
174
175 // Otherwise, mark this block free.
176 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
177 FollowingBlock->PrevAllocated = 0;
178 FreeBlock.ThisAllocated = 0;
179
180 // Link this into the linked list of free blocks.
181 FreeBlock.AddToFreeList(FreeList);
182
183 // Add a marker at the end of the block, indicating the size of this free
184 // block.
185 FreeBlock.SetEndOfBlockSizeMarker();
186 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
187}
188
189/// GrowBlock - The block after this block just got deallocated. Merge it
190/// into the current block.
191void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
192 assert(NewSize > BlockSize && "Not growing block?");
193 BlockSize = NewSize;
194 SetEndOfBlockSizeMarker();
195 getBlockAfter().PrevAllocated = 0;
196}
197
198/// TrimAllocationToSize - If this allocated block is significantly larger
199/// than NewSize, split it into two pieces (where the former is NewSize
200/// bytes, including the header), and add the new block to the free list.
201FreeRangeHeader *MemoryRangeHeader::
202TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
203 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
204 "Cannot deallocate part of an allocated block!");
205
Evan Cheng60b75f42008-07-29 07:38:32 +0000206 // Don't allow blocks to be trimmed below minimum required size
207 NewSize = std::max<uint64_t>(FreeRangeHeader::getMinBlockSize(), NewSize);
208
Chris Lattner8907b4b2007-12-05 23:39:57 +0000209 // Round up size for alignment of header.
210 unsigned HeaderAlign = __alignof(FreeRangeHeader);
211 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
212
213 // Size is now the size of the block we will remove from the start of the
214 // current block.
215 assert(NewSize <= BlockSize &&
216 "Allocating more space from this block than exists!");
217
218 // If splitting this block will cause the remainder to be too small, do not
219 // split the block.
220 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
221 return FreeList;
222
223 // Otherwise, we splice the required number of bytes out of this block, form
224 // a new block immediately after it, then mark this block allocated.
225 MemoryRangeHeader &FormerNextBlock = getBlockAfter();
226
227 // Change the size of this block.
228 BlockSize = NewSize;
229
230 // Get the new block we just sliced out and turn it into a free block.
231 FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
232 NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
233 NewNextBlock.ThisAllocated = 0;
234 NewNextBlock.PrevAllocated = 1;
235 NewNextBlock.SetEndOfBlockSizeMarker();
236 FormerNextBlock.PrevAllocated = 0;
237 NewNextBlock.AddToFreeList(FreeList);
238 return &NewNextBlock;
239}
240
241//===----------------------------------------------------------------------===//
242// Memory Block Implementation.
243//===----------------------------------------------------------------------===//
244
245namespace {
246 /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
247 /// This splits a large block of MAP_NORESERVE'd memory into two
248 /// sections, one for function stubs, one for the functions themselves. We
249 /// have to do this because we may need to emit a function stub while in the
250 /// middle of emitting a function, and we don't know how large the function we
251 /// are emitting is.
252 class VISIBILITY_HIDDEN DefaultJITMemoryManager : public JITMemoryManager {
253 std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
254 FreeRangeHeader *FreeMemoryList; // Circular list of free blocks.
255
256 // When emitting code into a memory block, this is the block.
257 MemoryRangeHeader *CurBlock;
258
259 unsigned char *CurStubPtr, *StubBase;
260 unsigned char *GOTBase; // Target Specific reserved memory
261
262 // Centralize memory block allocation.
263 sys::MemoryBlock getNewMemoryBlock(unsigned size);
264
265 std::map<const Function*, MemoryRangeHeader*> FunctionBlocks;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000266 std::map<const Function*, MemoryRangeHeader*> TableBlocks;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000267 public:
268 DefaultJITMemoryManager();
269 ~DefaultJITMemoryManager();
270
271 void AllocateGOT();
272
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000273 unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
274 unsigned Alignment);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000275
276 /// startFunctionBody - When a function starts, allocate a block of free
277 /// executable memory, returning a pointer to it and its actual size.
278 unsigned char *startFunctionBody(const Function *F, uintptr_t &ActualSize) {
279 CurBlock = FreeMemoryList;
280
281 // Allocate the entire memory block.
282 FreeMemoryList = FreeMemoryList->AllocateBlock();
283 ActualSize = CurBlock->BlockSize-sizeof(MemoryRangeHeader);
284 return (unsigned char *)(CurBlock+1);
285 }
286
287 /// endFunctionBody - The function F is now allocated, and takes the memory
288 /// in the range [FunctionStart,FunctionEnd).
289 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
290 unsigned char *FunctionEnd) {
291 assert(FunctionEnd > FunctionStart);
292 assert(FunctionStart == (unsigned char *)(CurBlock+1) &&
293 "Mismatched function start/end!");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000294
Chris Lattner8907b4b2007-12-05 23:39:57 +0000295 uintptr_t BlockSize = FunctionEnd - (unsigned char *)CurBlock;
296 FunctionBlocks[F] = CurBlock;
297
298 // Release the memory at the end of this block that isn't needed.
299 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
300 }
Nuno Lopescef75272008-10-21 11:42:16 +0000301
302 /// allocateSpace - Allocate a memory block of the given size.
303 unsigned char *allocateSpace(intptr_t Size, unsigned Alignment) {
304 CurBlock = FreeMemoryList;
305 FreeMemoryList = FreeMemoryList->AllocateBlock();
306
307 unsigned char *result = (unsigned char *)CurBlock+1;
308
309 if (Alignment == 0) Alignment = 1;
310 result = (unsigned char*)(((intptr_t)result+Alignment-1) &
311 ~(intptr_t)(Alignment-1));
312
313 uintptr_t BlockSize = result + Size - (unsigned char *)CurBlock;
314 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
315
316 return result;
317 }
318
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000319 /// startExceptionTable - Use startFunctionBody to allocate memory for the
320 /// function's exception table.
Chris Lattner0fdaa0b2008-03-07 20:05:43 +0000321 unsigned char* startExceptionTable(const Function* F,
322 uintptr_t &ActualSize) {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000323 return startFunctionBody(F, ActualSize);
324 }
325
326 /// endExceptionTable - The exception table of F is now allocated,
327 /// and takes the memory in the range [TableStart,TableEnd).
328 void endExceptionTable(const Function *F, unsigned char *TableStart,
329 unsigned char *TableEnd,
330 unsigned char* FrameRegister) {
331 assert(TableEnd > TableStart);
332 assert(TableStart == (unsigned char *)(CurBlock+1) &&
333 "Mismatched table start/end!");
334
335 uintptr_t BlockSize = TableEnd - (unsigned char *)CurBlock;
336 TableBlocks[F] = CurBlock;
337
338 // Release the memory at the end of this block that isn't needed.
339 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
340 }
341
Chris Lattner8907b4b2007-12-05 23:39:57 +0000342 unsigned char *getGOTBase() const {
343 return GOTBase;
344 }
345
346 /// deallocateMemForFunction - Deallocate all memory for the specified
347 /// function body.
348 void deallocateMemForFunction(const Function *F) {
349 std::map<const Function*, MemoryRangeHeader*>::iterator
350 I = FunctionBlocks.find(F);
351 if (I == FunctionBlocks.end()) return;
352
353 // Find the block that is allocated for this function.
354 MemoryRangeHeader *MemRange = I->second;
355 assert(MemRange->ThisAllocated && "Block isn't allocated!");
356
357 // Fill the buffer with garbage!
358#ifndef NDEBUG
359 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
360#endif
361
362 // Free the memory.
363 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
364
365 // Finally, remove this entry from FunctionBlocks.
366 FunctionBlocks.erase(I);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000367
368 I = TableBlocks.find(F);
369 if (I == TableBlocks.end()) return;
370
371 // Find the block that is allocated for this function.
372 MemRange = I->second;
373 assert(MemRange->ThisAllocated && "Block isn't allocated!");
374
375 // Fill the buffer with garbage!
376#ifndef NDEBUG
377 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
378#endif
379
380 // Free the memory.
381 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
382
383 // Finally, remove this entry from TableBlocks.
384 TableBlocks.erase(I);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000385 }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000386
387 /// setMemoryWritable - When code generation is in progress,
388 /// the code pages may need permissions changed.
389 void setMemoryWritable(void)
390 {
391 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
392 sys::Memory::setWritable(Blocks[i]);
393 }
394 /// setMemoryExecutable - When code generation is done and we're ready to
395 /// start execution, the code pages may need permissions changed.
396 void setMemoryExecutable(void)
397 {
398 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
399 sys::Memory::setExecutable(Blocks[i]);
400 }
Chris Lattner8907b4b2007-12-05 23:39:57 +0000401 };
402}
403
404DefaultJITMemoryManager::DefaultJITMemoryManager() {
405 // Allocate a 16M block of memory for functions.
Evan Chengbc4707a2008-09-18 07:54:21 +0000406#if defined(__APPLE__) && defined(__arm__)
407 sys::MemoryBlock MemBlock = getNewMemoryBlock(4 << 20);
408#else
Chris Lattner8907b4b2007-12-05 23:39:57 +0000409 sys::MemoryBlock MemBlock = getNewMemoryBlock(16 << 20);
Evan Chengbc4707a2008-09-18 07:54:21 +0000410#endif
Chris Lattner8907b4b2007-12-05 23:39:57 +0000411
Dan Gohman933e51c2008-06-21 20:17:03 +0000412 unsigned char *MemBase = static_cast<unsigned char*>(MemBlock.base());
Chris Lattner8907b4b2007-12-05 23:39:57 +0000413
414 // Allocate stubs backwards from the base, allocate functions forward
415 // from the base.
416 StubBase = MemBase;
417 CurStubPtr = MemBase + 512*1024; // Use 512k for stubs, working backwards.
418
419 // We set up the memory chunk with 4 mem regions, like this:
420 // [ START
421 // [ Free #0 ] -> Large space to allocate functions from.
422 // [ Allocated #1 ] -> Tiny space to separate regions.
423 // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
424 // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
425 // END ]
426 //
427 // The last three blocks are never deallocated or touched.
428
429 // Add MemoryRangeHeader to the end of the memory region, indicating that
430 // the space after the block of memory is allocated. This is block #3.
431 MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
432 Mem3->ThisAllocated = 1;
433 Mem3->PrevAllocated = 0;
434 Mem3->BlockSize = 0;
435
436 /// Add a tiny free region so that the free list always has one entry.
437 FreeRangeHeader *Mem2 =
438 (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
439 Mem2->ThisAllocated = 0;
440 Mem2->PrevAllocated = 1;
441 Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
442 Mem2->SetEndOfBlockSizeMarker();
443 Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
444 Mem2->Next = Mem2;
445
446 /// Add a tiny allocated region so that Mem2 is never coalesced away.
447 MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
448 Mem1->ThisAllocated = 1;
449 Mem1->PrevAllocated = 0;
450 Mem1->BlockSize = (char*)Mem2 - (char*)Mem1;
451
452 // Add a FreeRangeHeader to the start of the function body region, indicating
453 // that the space is free. Mark the previous block allocated so we never look
454 // at it.
455 FreeRangeHeader *Mem0 = (FreeRangeHeader*)CurStubPtr;
456 Mem0->ThisAllocated = 0;
457 Mem0->PrevAllocated = 1;
458 Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
459 Mem0->SetEndOfBlockSizeMarker();
460 Mem0->AddToFreeList(Mem2);
461
462 // Start out with the freelist pointing to Mem0.
463 FreeMemoryList = Mem0;
464
465 GOTBase = NULL;
466}
467
468void DefaultJITMemoryManager::AllocateGOT() {
469 assert(GOTBase == 0 && "Cannot allocate the got multiple times");
470 GOTBase = new unsigned char[sizeof(void*) * 8192];
471 HasGOT = true;
472}
473
474
475DefaultJITMemoryManager::~DefaultJITMemoryManager() {
476 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
477 sys::Memory::ReleaseRWX(Blocks[i]);
478
479 delete[] GOTBase;
480 Blocks.clear();
481}
482
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000483unsigned char *DefaultJITMemoryManager::allocateStub(const GlobalValue* F,
484 unsigned StubSize,
Chris Lattner8907b4b2007-12-05 23:39:57 +0000485 unsigned Alignment) {
486 CurStubPtr -= StubSize;
487 CurStubPtr = (unsigned char*)(((intptr_t)CurStubPtr) &
488 ~(intptr_t)(Alignment-1));
489 if (CurStubPtr < StubBase) {
490 // FIXME: allocate a new block
491 fprintf(stderr, "JIT ran out of memory for function stubs!\n");
492 abort();
493 }
494 return CurStubPtr;
495}
496
497sys::MemoryBlock DefaultJITMemoryManager::getNewMemoryBlock(unsigned size) {
498 // Allocate a new block close to the last one.
499 const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.front();
500 std::string ErrMsg;
501 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld, &ErrMsg);
502 if (B.base() == 0) {
503 fprintf(stderr,
504 "Allocation failed when allocating new memory in the JIT\n%s\n",
505 ErrMsg.c_str());
506 abort();
507 }
508 Blocks.push_back(B);
509 return B;
510}
511
512
513JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
514 return new DefaultJITMemoryManager();
515}