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