Use the new script to sort the includes of every file under lib.
[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 #define DEBUG_TYPE "jit"
15 #include "llvm/ExecutionEngine/JITMemoryManager.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/GlobalValue.h"
21 #include "llvm/Support/Allocator.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/DynamicLibrary.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/Memory.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <cassert>
30 #include <climits>
31 #include <cstring>
32 #include <vector>
33
34 #if defined(__linux__)
35 #if defined(HAVE_SYS_STAT_H)
36 #include <sys/stat.h>
37 #endif
38 #include <fcntl.h>
39 #include <unistd.h>
40 #endif
41
42 using namespace llvm;
43
44 STATISTIC(NumSlabs, "Number of slabs of memory allocated by the JIT");
45
46 JITMemoryManager::~JITMemoryManager() {}
47
48 //===----------------------------------------------------------------------===//
49 // Memory Block Implementation.
50 //===----------------------------------------------------------------------===//
51
52 namespace {
53   /// MemoryRangeHeader - For a range of memory, this is the header that we put
54   /// on the block of memory.  It is carefully crafted to be one word of memory.
55   /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
56   /// which starts with this.
57   struct FreeRangeHeader;
58   struct MemoryRangeHeader {
59     /// ThisAllocated - This is true if this block is currently allocated.  If
60     /// not, this can be converted to a FreeRangeHeader.
61     unsigned ThisAllocated : 1;
62
63     /// PrevAllocated - Keep track of whether the block immediately before us is
64     /// allocated.  If not, the word immediately before this header is the size
65     /// of the previous block.
66     unsigned PrevAllocated : 1;
67
68     /// BlockSize - This is the size in bytes of this memory block,
69     /// including this header.
70     uintptr_t BlockSize : (sizeof(intptr_t)*CHAR_BIT - 2);
71
72
73     /// getBlockAfter - Return the memory block immediately after this one.
74     ///
75     MemoryRangeHeader &getBlockAfter() const {
76       return *(MemoryRangeHeader*)((char*)this+BlockSize);
77     }
78
79     /// getFreeBlockBefore - If the block before this one is free, return it,
80     /// otherwise return null.
81     FreeRangeHeader *getFreeBlockBefore() const {
82       if (PrevAllocated) return 0;
83       intptr_t PrevSize = ((intptr_t *)this)[-1];
84       return (FreeRangeHeader*)((char*)this-PrevSize);
85     }
86
87     /// FreeBlock - Turn an allocated block into a free block, adjusting
88     /// bits in the object headers, and adding an end of region memory block.
89     FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
90
91     /// TrimAllocationToSize - If this allocated block is significantly larger
92     /// than NewSize, split it into two pieces (where the former is NewSize
93     /// bytes, including the header), and add the new block to the free list.
94     FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
95                                           uint64_t NewSize);
96   };
97
98   /// FreeRangeHeader - For a memory block that isn't already allocated, this
99   /// keeps track of the current block and has a pointer to the next free block.
100   /// Free blocks are kept on a circularly linked list.
101   struct FreeRangeHeader : public MemoryRangeHeader {
102     FreeRangeHeader *Prev;
103     FreeRangeHeader *Next;
104
105     /// getMinBlockSize - Get the minimum size for a memory block.  Blocks
106     /// smaller than this size cannot be created.
107     static unsigned getMinBlockSize() {
108       return sizeof(FreeRangeHeader)+sizeof(intptr_t);
109     }
110
111     /// SetEndOfBlockSizeMarker - The word at the end of every free block is
112     /// known to be the size of the free block.  Set it for this block.
113     void SetEndOfBlockSizeMarker() {
114       void *EndOfBlock = (char*)this + BlockSize;
115       ((intptr_t *)EndOfBlock)[-1] = BlockSize;
116     }
117
118     FreeRangeHeader *RemoveFromFreeList() {
119       assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
120       Next->Prev = Prev;
121       return Prev->Next = Next;
122     }
123
124     void AddToFreeList(FreeRangeHeader *FreeList) {
125       Next = FreeList;
126       Prev = FreeList->Prev;
127       Prev->Next = this;
128       Next->Prev = this;
129     }
130
131     /// GrowBlock - The block after this block just got deallocated.  Merge it
132     /// into the current block.
133     void GrowBlock(uintptr_t NewSize);
134
135     /// AllocateBlock - Mark this entire block allocated, updating freelists
136     /// etc.  This returns a pointer to the circular free-list.
137     FreeRangeHeader *AllocateBlock();
138   };
139 }
140
141
142 /// AllocateBlock - Mark this entire block allocated, updating freelists
143 /// etc.  This returns a pointer to the circular free-list.
144 FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
145   assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
146          "Cannot allocate an allocated block!");
147   // Mark this block allocated.
148   ThisAllocated = 1;
149   getBlockAfter().PrevAllocated = 1;
150
151   // Remove it from the free list.
152   return RemoveFromFreeList();
153 }
154
155 /// FreeBlock - Turn an allocated block into a free block, adjusting
156 /// bits in the object headers, and adding an end of region memory block.
157 /// If possible, coalesce this block with neighboring blocks.  Return the
158 /// FreeRangeHeader to allocate from.
159 FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
160   MemoryRangeHeader *FollowingBlock = &getBlockAfter();
161   assert(ThisAllocated && "This block is already free!");
162   assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
163
164   FreeRangeHeader *FreeListToReturn = FreeList;
165
166   // If the block after this one is free, merge it into this block.
167   if (!FollowingBlock->ThisAllocated) {
168     FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
169     // "FreeList" always needs to be a valid free block.  If we're about to
170     // coalesce with it, update our notion of what the free list is.
171     if (&FollowingFreeBlock == FreeList) {
172       FreeList = FollowingFreeBlock.Next;
173       FreeListToReturn = 0;
174       assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
175     }
176     FollowingFreeBlock.RemoveFromFreeList();
177
178     // Include the following block into this one.
179     BlockSize += FollowingFreeBlock.BlockSize;
180     FollowingBlock = &FollowingFreeBlock.getBlockAfter();
181
182     // Tell the block after the block we are coalescing that this block is
183     // allocated.
184     FollowingBlock->PrevAllocated = 1;
185   }
186
187   assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
188
189   if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
190     PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
191     return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
192   }
193
194   // Otherwise, mark this block free.
195   FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
196   FollowingBlock->PrevAllocated = 0;
197   FreeBlock.ThisAllocated = 0;
198
199   // Link this into the linked list of free blocks.
200   FreeBlock.AddToFreeList(FreeList);
201
202   // Add a marker at the end of the block, indicating the size of this free
203   // block.
204   FreeBlock.SetEndOfBlockSizeMarker();
205   return FreeListToReturn ? FreeListToReturn : &FreeBlock;
206 }
207
208 /// GrowBlock - The block after this block just got deallocated.  Merge it
209 /// into the current block.
210 void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
211   assert(NewSize > BlockSize && "Not growing block?");
212   BlockSize = NewSize;
213   SetEndOfBlockSizeMarker();
214   getBlockAfter().PrevAllocated = 0;
215 }
216
217 /// TrimAllocationToSize - If this allocated block is significantly larger
218 /// than NewSize, split it into two pieces (where the former is NewSize
219 /// bytes, including the header), and add the new block to the free list.
220 FreeRangeHeader *MemoryRangeHeader::
221 TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
222   assert(ThisAllocated && getBlockAfter().PrevAllocated &&
223          "Cannot deallocate part of an allocated block!");
224
225   // Don't allow blocks to be trimmed below minimum required size
226   NewSize = std::max<uint64_t>(FreeRangeHeader::getMinBlockSize(), NewSize);
227
228   // Round up size for alignment of header.
229   unsigned HeaderAlign = __alignof(FreeRangeHeader);
230   NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
231
232   // Size is now the size of the block we will remove from the start of the
233   // current block.
234   assert(NewSize <= BlockSize &&
235          "Allocating more space from this block than exists!");
236
237   // If splitting this block will cause the remainder to be too small, do not
238   // split the block.
239   if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
240     return FreeList;
241
242   // Otherwise, we splice the required number of bytes out of this block, form
243   // a new block immediately after it, then mark this block allocated.
244   MemoryRangeHeader &FormerNextBlock = getBlockAfter();
245
246   // Change the size of this block.
247   BlockSize = NewSize;
248
249   // Get the new block we just sliced out and turn it into a free block.
250   FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
251   NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
252   NewNextBlock.ThisAllocated = 0;
253   NewNextBlock.PrevAllocated = 1;
254   NewNextBlock.SetEndOfBlockSizeMarker();
255   FormerNextBlock.PrevAllocated = 0;
256   NewNextBlock.AddToFreeList(FreeList);
257   return &NewNextBlock;
258 }
259
260 //===----------------------------------------------------------------------===//
261 // Memory Block Implementation.
262 //===----------------------------------------------------------------------===//
263
264 namespace {
265
266   class DefaultJITMemoryManager;
267
268   class JITSlabAllocator : public SlabAllocator {
269     DefaultJITMemoryManager &JMM;
270   public:
271     JITSlabAllocator(DefaultJITMemoryManager &jmm) : JMM(jmm) { }
272     virtual ~JITSlabAllocator() { }
273     virtual MemSlab *Allocate(size_t Size);
274     virtual void Deallocate(MemSlab *Slab);
275   };
276
277   /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
278   /// This splits a large block of MAP_NORESERVE'd memory into two
279   /// sections, one for function stubs, one for the functions themselves.  We
280   /// have to do this because we may need to emit a function stub while in the
281   /// middle of emitting a function, and we don't know how large the function we
282   /// are emitting is.
283   class DefaultJITMemoryManager : public JITMemoryManager {
284
285     // Whether to poison freed memory.
286     bool PoisonMemory;
287
288     /// LastSlab - This points to the last slab allocated and is used as the
289     /// NearBlock parameter to AllocateRWX so that we can attempt to lay out all
290     /// stubs, data, and code contiguously in memory.  In general, however, this
291     /// is not possible because the NearBlock parameter is ignored on Windows
292     /// platforms and even on Unix it works on a best-effort pasis.
293     sys::MemoryBlock LastSlab;
294
295     // Memory slabs allocated by the JIT.  We refer to them as slabs so we don't
296     // confuse them with the blocks of memory described above.
297     std::vector<sys::MemoryBlock> CodeSlabs;
298     JITSlabAllocator BumpSlabAllocator;
299     BumpPtrAllocator StubAllocator;
300     BumpPtrAllocator DataAllocator;
301
302     // Circular list of free blocks.
303     FreeRangeHeader *FreeMemoryList;
304
305     // When emitting code into a memory block, this is the block.
306     MemoryRangeHeader *CurBlock;
307
308     uint8_t *GOTBase;     // Target Specific reserved memory
309   public:
310     DefaultJITMemoryManager();
311     ~DefaultJITMemoryManager();
312
313     /// allocateNewSlab - Allocates a new MemoryBlock and remembers it as the
314     /// last slab it allocated, so that subsequent allocations follow it.
315     sys::MemoryBlock allocateNewSlab(size_t size);
316
317     /// DefaultCodeSlabSize - When we have to go map more memory, we allocate at
318     /// least this much unless more is requested.
319     static const size_t DefaultCodeSlabSize;
320
321     /// DefaultSlabSize - Allocate data into slabs of this size unless we get
322     /// an allocation above SizeThreshold.
323     static const size_t DefaultSlabSize;
324
325     /// DefaultSizeThreshold - For any allocation larger than this threshold, we
326     /// should allocate a separate slab.
327     static const size_t DefaultSizeThreshold;
328
329     /// getPointerToNamedFunction - This method returns the address of the
330     /// specified function by using the dlsym function call.
331     virtual void *getPointerToNamedFunction(const std::string &Name,
332                                             bool AbortOnFailure = true);
333
334     void AllocateGOT();
335
336     // Testing methods.
337     virtual bool CheckInvariants(std::string &ErrorStr);
338     size_t GetDefaultCodeSlabSize() { return DefaultCodeSlabSize; }
339     size_t GetDefaultDataSlabSize() { return DefaultSlabSize; }
340     size_t GetDefaultStubSlabSize() { return DefaultSlabSize; }
341     unsigned GetNumCodeSlabs() { return CodeSlabs.size(); }
342     unsigned GetNumDataSlabs() { return DataAllocator.GetNumSlabs(); }
343     unsigned GetNumStubSlabs() { return StubAllocator.GetNumSlabs(); }
344
345     /// startFunctionBody - When a function starts, allocate a block of free
346     /// executable memory, returning a pointer to it and its actual size.
347     uint8_t *startFunctionBody(const Function *F, uintptr_t &ActualSize) {
348
349       FreeRangeHeader* candidateBlock = FreeMemoryList;
350       FreeRangeHeader* head = FreeMemoryList;
351       FreeRangeHeader* iter = head->Next;
352
353       uintptr_t largest = candidateBlock->BlockSize;
354
355       // Search for the largest free block
356       while (iter != head) {
357         if (iter->BlockSize > largest) {
358           largest = iter->BlockSize;
359           candidateBlock = iter;
360         }
361         iter = iter->Next;
362       }
363
364       largest = largest - sizeof(MemoryRangeHeader);
365
366       // If this block isn't big enough for the allocation desired, allocate
367       // another block of memory and add it to the free list.
368       if (largest < ActualSize ||
369           largest <= FreeRangeHeader::getMinBlockSize()) {
370         DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
371         candidateBlock = allocateNewCodeSlab((size_t)ActualSize);
372       }
373
374       // Select this candidate block for allocation
375       CurBlock = candidateBlock;
376
377       // Allocate the entire memory block.
378       FreeMemoryList = candidateBlock->AllocateBlock();
379       ActualSize = CurBlock->BlockSize - sizeof(MemoryRangeHeader);
380       return (uint8_t *)(CurBlock + 1);
381     }
382
383     /// allocateNewCodeSlab - Helper method to allocate a new slab of code
384     /// memory from the OS and add it to the free list.  Returns the new
385     /// FreeRangeHeader at the base of the slab.
386     FreeRangeHeader *allocateNewCodeSlab(size_t MinSize) {
387       // If the user needs at least MinSize free memory, then we account for
388       // two MemoryRangeHeaders: the one in the user's block, and the one at the
389       // end of the slab.
390       size_t PaddedMin = MinSize + 2 * sizeof(MemoryRangeHeader);
391       size_t SlabSize = std::max(DefaultCodeSlabSize, PaddedMin);
392       sys::MemoryBlock B = allocateNewSlab(SlabSize);
393       CodeSlabs.push_back(B);
394       char *MemBase = (char*)(B.base());
395
396       // Put a tiny allocated block at the end of the memory chunk, so when
397       // FreeBlock calls getBlockAfter it doesn't fall off the end.
398       MemoryRangeHeader *EndBlock =
399           (MemoryRangeHeader*)(MemBase + B.size()) - 1;
400       EndBlock->ThisAllocated = 1;
401       EndBlock->PrevAllocated = 0;
402       EndBlock->BlockSize = sizeof(MemoryRangeHeader);
403
404       // Start out with a vast new block of free memory.
405       FreeRangeHeader *NewBlock = (FreeRangeHeader*)MemBase;
406       NewBlock->ThisAllocated = 0;
407       // Make sure getFreeBlockBefore doesn't look into unmapped memory.
408       NewBlock->PrevAllocated = 1;
409       NewBlock->BlockSize = (uintptr_t)EndBlock - (uintptr_t)NewBlock;
410       NewBlock->SetEndOfBlockSizeMarker();
411       NewBlock->AddToFreeList(FreeMemoryList);
412
413       assert(NewBlock->BlockSize - sizeof(MemoryRangeHeader) >= MinSize &&
414              "The block was too small!");
415       return NewBlock;
416     }
417
418     /// endFunctionBody - The function F is now allocated, and takes the memory
419     /// in the range [FunctionStart,FunctionEnd).
420     void endFunctionBody(const Function *F, uint8_t *FunctionStart,
421                          uint8_t *FunctionEnd) {
422       assert(FunctionEnd > FunctionStart);
423       assert(FunctionStart == (uint8_t *)(CurBlock+1) &&
424              "Mismatched function start/end!");
425
426       uintptr_t BlockSize = FunctionEnd - (uint8_t *)CurBlock;
427
428       // Release the memory at the end of this block that isn't needed.
429       FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
430     }
431
432     /// allocateSpace - Allocate a memory block of the given size.  This method
433     /// cannot be called between calls to startFunctionBody and endFunctionBody.
434     uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
435       CurBlock = FreeMemoryList;
436       FreeMemoryList = FreeMemoryList->AllocateBlock();
437
438       uint8_t *result = (uint8_t *)(CurBlock + 1);
439
440       if (Alignment == 0) Alignment = 1;
441       result = (uint8_t*)(((intptr_t)result+Alignment-1) &
442                ~(intptr_t)(Alignment-1));
443
444       uintptr_t BlockSize = result + Size - (uint8_t *)CurBlock;
445       FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
446
447       return result;
448     }
449
450     /// allocateStub - Allocate memory for a function stub.
451     uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
452                           unsigned Alignment) {
453       return (uint8_t*)StubAllocator.Allocate(StubSize, Alignment);
454     }
455
456     /// allocateGlobal - Allocate memory for a global.
457     uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
458       return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
459     }
460
461     /// allocateCodeSection - Allocate memory for a code section.
462     uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
463                                  unsigned SectionID) {
464       // Grow the required block size to account for the block header
465       Size += sizeof(*CurBlock);
466
467       // FIXME: Alignement handling.
468       FreeRangeHeader* candidateBlock = FreeMemoryList;
469       FreeRangeHeader* head = FreeMemoryList;
470       FreeRangeHeader* iter = head->Next;
471
472       uintptr_t largest = candidateBlock->BlockSize;
473
474       // Search for the largest free block.
475       while (iter != head) {
476         if (iter->BlockSize > largest) {
477           largest = iter->BlockSize;
478           candidateBlock = iter;
479         }
480         iter = iter->Next;
481       }
482
483       largest = largest - sizeof(MemoryRangeHeader);
484
485       // If this block isn't big enough for the allocation desired, allocate
486       // another block of memory and add it to the free list.
487       if (largest < Size || largest <= FreeRangeHeader::getMinBlockSize()) {
488         DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
489         candidateBlock = allocateNewCodeSlab((size_t)Size);
490       }
491
492       // Select this candidate block for allocation
493       CurBlock = candidateBlock;
494
495       // Allocate the entire memory block.
496       FreeMemoryList = candidateBlock->AllocateBlock();
497       // Release the memory at the end of this block that isn't needed.
498       FreeMemoryList = CurBlock->TrimAllocationToSize(FreeMemoryList, Size);
499       return (uint8_t *)(CurBlock + 1);
500     }
501
502     /// allocateDataSection - Allocate memory for a data section.
503     uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
504                                  unsigned SectionID, bool IsReadOnly) {
505       return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
506     }
507
508     bool applyPermissions(std::string *ErrMsg) {
509       return false;
510     }
511
512     /// startExceptionTable - Use startFunctionBody to allocate memory for the
513     /// function's exception table.
514     uint8_t* startExceptionTable(const Function* F, uintptr_t &ActualSize) {
515       return startFunctionBody(F, ActualSize);
516     }
517
518     /// endExceptionTable - The exception table of F is now allocated,
519     /// and takes the memory in the range [TableStart,TableEnd).
520     void endExceptionTable(const Function *F, uint8_t *TableStart,
521                            uint8_t *TableEnd, uint8_t* FrameRegister) {
522       assert(TableEnd > TableStart);
523       assert(TableStart == (uint8_t *)(CurBlock+1) &&
524              "Mismatched table start/end!");
525
526       uintptr_t BlockSize = TableEnd - (uint8_t *)CurBlock;
527
528       // Release the memory at the end of this block that isn't needed.
529       FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
530     }
531
532     uint8_t *getGOTBase() const {
533       return GOTBase;
534     }
535
536     void deallocateBlock(void *Block) {
537       // Find the block that is allocated for this function.
538       MemoryRangeHeader *MemRange = static_cast<MemoryRangeHeader*>(Block) - 1;
539       assert(MemRange->ThisAllocated && "Block isn't allocated!");
540
541       // Fill the buffer with garbage!
542       if (PoisonMemory) {
543         memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
544       }
545
546       // Free the memory.
547       FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
548     }
549
550     /// deallocateFunctionBody - Deallocate all memory for the specified
551     /// function body.
552     void deallocateFunctionBody(void *Body) {
553       if (Body) deallocateBlock(Body);
554     }
555
556     /// deallocateExceptionTable - Deallocate memory for the specified
557     /// exception table.
558     void deallocateExceptionTable(void *ET) {
559       if (ET) deallocateBlock(ET);
560     }
561
562     /// setMemoryWritable - When code generation is in progress,
563     /// the code pages may need permissions changed.
564     void setMemoryWritable()
565     {
566       for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
567         sys::Memory::setWritable(CodeSlabs[i]);
568     }
569     /// setMemoryExecutable - When code generation is done and we're ready to
570     /// start execution, the code pages may need permissions changed.
571     void setMemoryExecutable()
572     {
573       for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
574         sys::Memory::setExecutable(CodeSlabs[i]);
575     }
576
577     /// setPoisonMemory - Controls whether we write garbage over freed memory.
578     ///
579     void setPoisonMemory(bool poison) {
580       PoisonMemory = poison;
581     }
582   };
583 }
584
585 MemSlab *JITSlabAllocator::Allocate(size_t Size) {
586   sys::MemoryBlock B = JMM.allocateNewSlab(Size);
587   MemSlab *Slab = (MemSlab*)B.base();
588   Slab->Size = B.size();
589   Slab->NextPtr = 0;
590   return Slab;
591 }
592
593 void JITSlabAllocator::Deallocate(MemSlab *Slab) {
594   sys::MemoryBlock B(Slab, Slab->Size);
595   sys::Memory::ReleaseRWX(B);
596 }
597
598 DefaultJITMemoryManager::DefaultJITMemoryManager()
599   :
600 #ifdef NDEBUG
601     PoisonMemory(false),
602 #else
603     PoisonMemory(true),
604 #endif
605     LastSlab(0, 0),
606     BumpSlabAllocator(*this),
607     StubAllocator(DefaultSlabSize, DefaultSizeThreshold, BumpSlabAllocator),
608     DataAllocator(DefaultSlabSize, DefaultSizeThreshold, BumpSlabAllocator) {
609
610   // Allocate space for code.
611   sys::MemoryBlock MemBlock = allocateNewSlab(DefaultCodeSlabSize);
612   CodeSlabs.push_back(MemBlock);
613   uint8_t *MemBase = (uint8_t*)MemBlock.base();
614
615   // We set up the memory chunk with 4 mem regions, like this:
616   //  [ START
617   //    [ Free      #0 ] -> Large space to allocate functions from.
618   //    [ Allocated #1 ] -> Tiny space to separate regions.
619   //    [ Free      #2 ] -> Tiny space so there is always at least 1 free block.
620   //    [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
621   //  END ]
622   //
623   // The last three blocks are never deallocated or touched.
624
625   // Add MemoryRangeHeader to the end of the memory region, indicating that
626   // the space after the block of memory is allocated.  This is block #3.
627   MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
628   Mem3->ThisAllocated = 1;
629   Mem3->PrevAllocated = 0;
630   Mem3->BlockSize     = sizeof(MemoryRangeHeader);
631
632   /// Add a tiny free region so that the free list always has one entry.
633   FreeRangeHeader *Mem2 =
634     (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
635   Mem2->ThisAllocated = 0;
636   Mem2->PrevAllocated = 1;
637   Mem2->BlockSize     = FreeRangeHeader::getMinBlockSize();
638   Mem2->SetEndOfBlockSizeMarker();
639   Mem2->Prev = Mem2;   // Mem2 *is* the free list for now.
640   Mem2->Next = Mem2;
641
642   /// Add a tiny allocated region so that Mem2 is never coalesced away.
643   MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
644   Mem1->ThisAllocated = 1;
645   Mem1->PrevAllocated = 0;
646   Mem1->BlockSize     = sizeof(MemoryRangeHeader);
647
648   // Add a FreeRangeHeader to the start of the function body region, indicating
649   // that the space is free.  Mark the previous block allocated so we never look
650   // at it.
651   FreeRangeHeader *Mem0 = (FreeRangeHeader*)MemBase;
652   Mem0->ThisAllocated = 0;
653   Mem0->PrevAllocated = 1;
654   Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
655   Mem0->SetEndOfBlockSizeMarker();
656   Mem0->AddToFreeList(Mem2);
657
658   // Start out with the freelist pointing to Mem0.
659   FreeMemoryList = Mem0;
660
661   GOTBase = NULL;
662 }
663
664 void DefaultJITMemoryManager::AllocateGOT() {
665   assert(GOTBase == 0 && "Cannot allocate the got multiple times");
666   GOTBase = new uint8_t[sizeof(void*) * 8192];
667   HasGOT = true;
668 }
669
670 DefaultJITMemoryManager::~DefaultJITMemoryManager() {
671   for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
672     sys::Memory::ReleaseRWX(CodeSlabs[i]);
673
674   delete[] GOTBase;
675 }
676
677 sys::MemoryBlock DefaultJITMemoryManager::allocateNewSlab(size_t size) {
678   // Allocate a new block close to the last one.
679   std::string ErrMsg;
680   sys::MemoryBlock *LastSlabPtr = LastSlab.base() ? &LastSlab : 0;
681   sys::MemoryBlock B = sys::Memory::AllocateRWX(size, LastSlabPtr, &ErrMsg);
682   if (B.base() == 0) {
683     report_fatal_error("Allocation failed when allocating new memory in the"
684                        " JIT\n" + Twine(ErrMsg));
685   }
686   LastSlab = B;
687   ++NumSlabs;
688   // Initialize the slab to garbage when debugging.
689   if (PoisonMemory) {
690     memset(B.base(), 0xCD, B.size());
691   }
692   return B;
693 }
694
695 /// CheckInvariants - For testing only.  Return "" if all internal invariants
696 /// are preserved, and a helpful error message otherwise.  For free and
697 /// allocated blocks, make sure that adding BlockSize gives a valid block.
698 /// For free blocks, make sure they're in the free list and that their end of
699 /// block size marker is correct.  This function should return an error before
700 /// accessing bad memory.  This function is defined here instead of in
701 /// JITMemoryManagerTest.cpp so that we don't have to expose all of the
702 /// implementation details of DefaultJITMemoryManager.
703 bool DefaultJITMemoryManager::CheckInvariants(std::string &ErrorStr) {
704   raw_string_ostream Err(ErrorStr);
705
706   // Construct a the set of FreeRangeHeader pointers so we can query it
707   // efficiently.
708   llvm::SmallPtrSet<MemoryRangeHeader*, 16> FreeHdrSet;
709   FreeRangeHeader* FreeHead = FreeMemoryList;
710   FreeRangeHeader* FreeRange = FreeHead;
711
712   do {
713     // Check that the free range pointer is in the blocks we've allocated.
714     bool Found = false;
715     for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
716          E = CodeSlabs.end(); I != E && !Found; ++I) {
717       char *Start = (char*)I->base();
718       char *End = Start + I->size();
719       Found = (Start <= (char*)FreeRange && (char*)FreeRange < End);
720     }
721     if (!Found) {
722       Err << "Corrupt free list; points to " << FreeRange;
723       return false;
724     }
725
726     if (FreeRange->Next->Prev != FreeRange) {
727       Err << "Next and Prev pointers do not match.";
728       return false;
729     }
730
731     // Otherwise, add it to the set.
732     FreeHdrSet.insert(FreeRange);
733     FreeRange = FreeRange->Next;
734   } while (FreeRange != FreeHead);
735
736   // Go over each block, and look at each MemoryRangeHeader.
737   for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
738        E = CodeSlabs.end(); I != E; ++I) {
739     char *Start = (char*)I->base();
740     char *End = Start + I->size();
741
742     // Check each memory range.
743     for (MemoryRangeHeader *Hdr = (MemoryRangeHeader*)Start, *LastHdr = NULL;
744          Start <= (char*)Hdr && (char*)Hdr < End;
745          Hdr = &Hdr->getBlockAfter()) {
746       if (Hdr->ThisAllocated == 0) {
747         // Check that this range is in the free list.
748         if (!FreeHdrSet.count(Hdr)) {
749           Err << "Found free header at " << Hdr << " that is not in free list.";
750           return false;
751         }
752
753         // Now make sure the size marker at the end of the block is correct.
754         uintptr_t *Marker = ((uintptr_t*)&Hdr->getBlockAfter()) - 1;
755         if (!(Start <= (char*)Marker && (char*)Marker < End)) {
756           Err << "Block size in header points out of current MemoryBlock.";
757           return false;
758         }
759         if (Hdr->BlockSize != *Marker) {
760           Err << "End of block size marker (" << *Marker << ") "
761               << "and BlockSize (" << Hdr->BlockSize << ") don't match.";
762           return false;
763         }
764       }
765
766       if (LastHdr && LastHdr->ThisAllocated != Hdr->PrevAllocated) {
767         Err << "Hdr->PrevAllocated (" << Hdr->PrevAllocated << ") != "
768             << "LastHdr->ThisAllocated (" << LastHdr->ThisAllocated << ")";
769         return false;
770       } else if (!LastHdr && !Hdr->PrevAllocated) {
771         Err << "The first header should have PrevAllocated true.";
772         return false;
773       }
774
775       // Remember the last header.
776       LastHdr = Hdr;
777     }
778   }
779
780   // All invariants are preserved.
781   return true;
782 }
783
784 //===----------------------------------------------------------------------===//
785 // getPointerToNamedFunction() implementation.
786 //===----------------------------------------------------------------------===//
787
788 // AtExitHandlers - List of functions to call when the program exits,
789 // registered with the atexit() library function.
790 static std::vector<void (*)()> AtExitHandlers;
791
792 /// runAtExitHandlers - Run any functions registered by the program's
793 /// calls to atexit(3), which we intercept and store in
794 /// AtExitHandlers.
795 ///
796 static void runAtExitHandlers() {
797   while (!AtExitHandlers.empty()) {
798     void (*Fn)() = AtExitHandlers.back();
799     AtExitHandlers.pop_back();
800     Fn();
801   }
802 }
803
804 //===----------------------------------------------------------------------===//
805 // Function stubs that are invoked instead of certain library calls
806 //
807 // Force the following functions to be linked in to anything that uses the
808 // JIT. This is a hack designed to work around the all-too-clever Glibc
809 // strategy of making these functions work differently when inlined vs. when
810 // not inlined, and hiding their real definitions in a separate archive file
811 // that the dynamic linker can't see. For more info, search for
812 // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
813 #if defined(__linux__)
814 /* stat functions are redirecting to __xstat with a version number.  On x86-64
815  * linking with libc_nonshared.a and -Wl,--export-dynamic doesn't make 'stat'
816  * available as an exported symbol, so we have to add it explicitly.
817  */
818 namespace {
819 class StatSymbols {
820 public:
821   StatSymbols() {
822     sys::DynamicLibrary::AddSymbol("stat", (void*)(intptr_t)stat);
823     sys::DynamicLibrary::AddSymbol("fstat", (void*)(intptr_t)fstat);
824     sys::DynamicLibrary::AddSymbol("lstat", (void*)(intptr_t)lstat);
825     sys::DynamicLibrary::AddSymbol("stat64", (void*)(intptr_t)stat64);
826     sys::DynamicLibrary::AddSymbol("\x1stat64", (void*)(intptr_t)stat64);
827     sys::DynamicLibrary::AddSymbol("\x1open64", (void*)(intptr_t)open64);
828     sys::DynamicLibrary::AddSymbol("\x1lseek64", (void*)(intptr_t)lseek64);
829     sys::DynamicLibrary::AddSymbol("fstat64", (void*)(intptr_t)fstat64);
830     sys::DynamicLibrary::AddSymbol("lstat64", (void*)(intptr_t)lstat64);
831     sys::DynamicLibrary::AddSymbol("atexit", (void*)(intptr_t)atexit);
832     sys::DynamicLibrary::AddSymbol("mknod", (void*)(intptr_t)mknod);
833   }
834 };
835 }
836 static StatSymbols initStatSymbols;
837 #endif // __linux__
838
839 // jit_exit - Used to intercept the "exit" library call.
840 static void jit_exit(int Status) {
841   runAtExitHandlers();   // Run atexit handlers...
842   exit(Status);
843 }
844
845 // jit_atexit - Used to intercept the "atexit" library call.
846 static int jit_atexit(void (*Fn)()) {
847   AtExitHandlers.push_back(Fn);    // Take note of atexit handler...
848   return 0;  // Always successful
849 }
850
851 static int jit_noop() {
852   return 0;
853 }
854
855 //===----------------------------------------------------------------------===//
856 //
857 /// getPointerToNamedFunction - This method returns the address of the specified
858 /// function by using the dynamic loader interface.  As such it is only useful
859 /// for resolving library symbols, not code generated symbols.
860 ///
861 void *DefaultJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
862                                                          bool AbortOnFailure) {
863   // Check to see if this is one of the functions we want to intercept.  Note,
864   // we cast to intptr_t here to silence a -pedantic warning that complains
865   // about casting a function pointer to a normal pointer.
866   if (Name == "exit") return (void*)(intptr_t)&jit_exit;
867   if (Name == "atexit") return (void*)(intptr_t)&jit_atexit;
868
869   // We should not invoke parent's ctors/dtors from generated main()!
870   // On Mingw and Cygwin, the symbol __main is resolved to
871   // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
872   // (and register wrong callee's dtors with atexit(3)).
873   // We expect ExecutionEngine::runStaticConstructorsDestructors()
874   // is called before ExecutionEngine::runFunctionAsMain() is called.
875   if (Name == "__main") return (void*)(intptr_t)&jit_noop;
876
877   const char *NameStr = Name.c_str();
878   // If this is an asm specifier, skip the sentinal.
879   if (NameStr[0] == 1) ++NameStr;
880
881   // If it's an external function, look it up in the process image...
882   void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
883   if (Ptr) return Ptr;
884
885   // If it wasn't found and if it starts with an underscore ('_') character,
886   // try again without the underscore.
887   if (NameStr[0] == '_') {
888     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
889     if (Ptr) return Ptr;
890   }
891
892   // Darwin/PPC adds $LDBLStub suffixes to various symbols like printf.  These
893   // are references to hidden visibility symbols that dlsym cannot resolve.
894   // If we have one of these, strip off $LDBLStub and try again.
895 #if defined(__APPLE__) && defined(__ppc__)
896   if (Name.size() > 9 && Name[Name.size()-9] == '$' &&
897       memcmp(&Name[Name.size()-8], "LDBLStub", 8) == 0) {
898     // First try turning $LDBLStub into $LDBL128. If that fails, strip it off.
899     // This mirrors logic in libSystemStubs.a.
900     std::string Prefix = std::string(Name.begin(), Name.end()-9);
901     if (void *Ptr = getPointerToNamedFunction(Prefix+"$LDBL128", false))
902       return Ptr;
903     if (void *Ptr = getPointerToNamedFunction(Prefix, false))
904       return Ptr;
905   }
906 #endif
907
908   if (AbortOnFailure) {
909     report_fatal_error("Program used external function '"+Name+
910                       "' which could not be resolved!");
911   }
912   return 0;
913 }
914
915
916
917 JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
918   return new DefaultJITMemoryManager();
919 }
920
921 // Allocate memory for code in 512K slabs.
922 const size_t DefaultJITMemoryManager::DefaultCodeSlabSize = 512 * 1024;
923
924 // Allocate globals and stubs in slabs of 64K.  (probably 16 pages)
925 const size_t DefaultJITMemoryManager::DefaultSlabSize = 64 * 1024;
926
927 // Waste at most 16K at the end of each bump slab.  (probably 4 pages)
928 const size_t DefaultJITMemoryManager::DefaultSizeThreshold = 16 * 1024;