blob: 1aadcce266401bf45eecb035aef9b358559f8761 [file] [log] [blame]
Chris Lattner55d8c3f2007-12-05 23:39:57 +00001//===-- JITMemoryManager.cpp - Memory Allocator for JIT'd code ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Lattner55d8c3f2007-12-05 23:39:57 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the DefaultJITMemoryManager class.
11//
12//===----------------------------------------------------------------------===//
13
Reid Kleckner4b3a3562009-07-23 21:46:56 +000014#define DEBUG_TYPE "jit"
Reid Kleckner92167322009-07-23 01:40:54 +000015#include "llvm/ExecutionEngine/JITMemoryManager.h"
Reid Kleckner4b3a3562009-07-23 21:46:56 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/Statistic.h"
Benjamin Kramera6769262010-04-08 10:44:28 +000018#include "llvm/ADT/Twine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/GlobalValue.h"
Reid Kleckner4b3a3562009-07-23 21:46:56 +000021#include "llvm/Support/Allocator.h"
Chris Lattner55d8c3f2007-12-05 23:39:57 +000022#include "llvm/Support/Compiler.h"
Reid Kleckner4b3a3562009-07-23 21:46:56 +000023#include "llvm/Support/Debug.h"
Danil Malyshevbfee5422012-03-28 21:46:36 +000024#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Support/Memory.h"
27#include "llvm/Support/raw_ostream.h"
Chuck Rose IIIcc2a6612007-12-06 02:03:01 +000028#include <cassert>
Dan Gohmancff69532009-04-01 18:45:54 +000029#include <climits>
Anton Korobeynikov579f0712008-02-20 11:08:44 +000030#include <cstring>
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include <vector>
Danil Malyshevbfee5422012-03-28 21:46:36 +000032
33#if defined(__linux__)
34#if defined(HAVE_SYS_STAT_H)
35#include <sys/stat.h>
36#endif
37#include <fcntl.h>
38#include <unistd.h>
39#endif
40
Chris Lattner55d8c3f2007-12-05 23:39:57 +000041using namespace llvm;
42
Reid Kleckner4b3a3562009-07-23 21:46:56 +000043STATISTIC(NumSlabs, "Number of slabs of memory allocated by the JIT");
Chris Lattner55d8c3f2007-12-05 23:39:57 +000044
45JITMemoryManager::~JITMemoryManager() {}
46
47//===----------------------------------------------------------------------===//
48// Memory Block Implementation.
49//===----------------------------------------------------------------------===//
50
51namespace {
52 /// MemoryRangeHeader - For a range of memory, this is the header that we put
53 /// on the block of memory. It is carefully crafted to be one word of memory.
54 /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
55 /// which starts with this.
56 struct FreeRangeHeader;
57 struct MemoryRangeHeader {
58 /// ThisAllocated - This is true if this block is currently allocated. If
59 /// not, this can be converted to a FreeRangeHeader.
60 unsigned ThisAllocated : 1;
Eric Christopherebbfbee2009-11-12 01:06:08 +000061
Chris Lattner55d8c3f2007-12-05 23:39:57 +000062 /// PrevAllocated - Keep track of whether the block immediately before us is
63 /// allocated. If not, the word immediately before this header is the size
64 /// of the previous block.
65 unsigned PrevAllocated : 1;
Eric Christopherebbfbee2009-11-12 01:06:08 +000066
Chris Lattner55d8c3f2007-12-05 23:39:57 +000067 /// BlockSize - This is the size in bytes of this memory block,
68 /// including this header.
Dan Gohmancff69532009-04-01 18:45:54 +000069 uintptr_t BlockSize : (sizeof(intptr_t)*CHAR_BIT - 2);
Eric Christopherebbfbee2009-11-12 01:06:08 +000070
Chris Lattner55d8c3f2007-12-05 23:39:57 +000071
72 /// getBlockAfter - Return the memory block immediately after this one.
73 ///
74 MemoryRangeHeader &getBlockAfter() const {
David Greene8e46d892013-01-14 21:04:44 +000075 return *reinterpret_cast<MemoryRangeHeader *>(
76 reinterpret_cast<char*>(
77 const_cast<MemoryRangeHeader *>(this))+BlockSize);
Chris Lattner55d8c3f2007-12-05 23:39:57 +000078 }
Eric Christopherebbfbee2009-11-12 01:06:08 +000079
Chris Lattner55d8c3f2007-12-05 23:39:57 +000080 /// getFreeBlockBefore - If the block before this one is free, return it,
81 /// otherwise return null.
82 FreeRangeHeader *getFreeBlockBefore() const {
83 if (PrevAllocated) return 0;
David Greene8e46d892013-01-14 21:04:44 +000084 intptr_t PrevSize = reinterpret_cast<intptr_t *>(
85 const_cast<MemoryRangeHeader *>(this))[-1];
86 return reinterpret_cast<FreeRangeHeader *>(
87 reinterpret_cast<char*>(
88 const_cast<MemoryRangeHeader *>(this))-PrevSize);
Chris Lattner55d8c3f2007-12-05 23:39:57 +000089 }
Eric Christopherebbfbee2009-11-12 01:06:08 +000090
Chris Lattner55d8c3f2007-12-05 23:39:57 +000091 /// FreeBlock - Turn an allocated block into a free block, adjusting
92 /// bits in the object headers, and adding an end of region memory block.
93 FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
Eric Christopherebbfbee2009-11-12 01:06:08 +000094
Chris Lattner55d8c3f2007-12-05 23:39:57 +000095 /// TrimAllocationToSize - If this allocated block is significantly larger
96 /// than NewSize, split it into two pieces (where the former is NewSize
97 /// bytes, including the header), and add the new block to the free list.
Eric Christopherebbfbee2009-11-12 01:06:08 +000098 FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
Chris Lattner55d8c3f2007-12-05 23:39:57 +000099 uint64_t NewSize);
100 };
101
102 /// FreeRangeHeader - For a memory block that isn't already allocated, this
103 /// keeps track of the current block and has a pointer to the next free block.
104 /// Free blocks are kept on a circularly linked list.
105 struct FreeRangeHeader : public MemoryRangeHeader {
106 FreeRangeHeader *Prev;
107 FreeRangeHeader *Next;
Eric Christopherebbfbee2009-11-12 01:06:08 +0000108
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000109 /// getMinBlockSize - Get the minimum size for a memory block. Blocks
110 /// smaller than this size cannot be created.
111 static unsigned getMinBlockSize() {
112 return sizeof(FreeRangeHeader)+sizeof(intptr_t);
113 }
Eric Christopherebbfbee2009-11-12 01:06:08 +0000114
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000115 /// SetEndOfBlockSizeMarker - The word at the end of every free block is
116 /// known to be the size of the free block. Set it for this block.
117 void SetEndOfBlockSizeMarker() {
118 void *EndOfBlock = (char*)this + BlockSize;
119 ((intptr_t *)EndOfBlock)[-1] = BlockSize;
120 }
121
122 FreeRangeHeader *RemoveFromFreeList() {
123 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
124 Next->Prev = Prev;
125 return Prev->Next = Next;
126 }
Eric Christopherebbfbee2009-11-12 01:06:08 +0000127
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000128 void AddToFreeList(FreeRangeHeader *FreeList) {
129 Next = FreeList;
130 Prev = FreeList->Prev;
131 Prev->Next = this;
132 Next->Prev = this;
133 }
134
135 /// GrowBlock - The block after this block just got deallocated. Merge it
136 /// into the current block.
137 void GrowBlock(uintptr_t NewSize);
Eric Christopherebbfbee2009-11-12 01:06:08 +0000138
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000139 /// AllocateBlock - Mark this entire block allocated, updating freelists
140 /// etc. This returns a pointer to the circular free-list.
141 FreeRangeHeader *AllocateBlock();
142 };
143}
144
145
146/// AllocateBlock - Mark this entire block allocated, updating freelists
147/// etc. This returns a pointer to the circular free-list.
148FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
149 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
150 "Cannot allocate an allocated block!");
151 // Mark this block allocated.
152 ThisAllocated = 1;
153 getBlockAfter().PrevAllocated = 1;
Eric Christopherebbfbee2009-11-12 01:06:08 +0000154
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000155 // Remove it from the free list.
156 return RemoveFromFreeList();
157}
158
159/// FreeBlock - Turn an allocated block into a free block, adjusting
160/// bits in the object headers, and adding an end of region memory block.
161/// If possible, coalesce this block with neighboring blocks. Return the
162/// FreeRangeHeader to allocate from.
163FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
164 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000165 assert(ThisAllocated && "This block is already free!");
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000166 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
Eric Christopherebbfbee2009-11-12 01:06:08 +0000167
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000168 FreeRangeHeader *FreeListToReturn = FreeList;
Eric Christopherebbfbee2009-11-12 01:06:08 +0000169
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000170 // If the block after this one is free, merge it into this block.
171 if (!FollowingBlock->ThisAllocated) {
172 FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
173 // "FreeList" always needs to be a valid free block. If we're about to
174 // coalesce with it, update our notion of what the free list is.
175 if (&FollowingFreeBlock == FreeList) {
176 FreeList = FollowingFreeBlock.Next;
177 FreeListToReturn = 0;
178 assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
179 }
180 FollowingFreeBlock.RemoveFromFreeList();
Eric Christopherebbfbee2009-11-12 01:06:08 +0000181
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000182 // Include the following block into this one.
183 BlockSize += FollowingFreeBlock.BlockSize;
184 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
Eric Christopherebbfbee2009-11-12 01:06:08 +0000185
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000186 // Tell the block after the block we are coalescing that this block is
187 // allocated.
188 FollowingBlock->PrevAllocated = 1;
189 }
Eric Christopherebbfbee2009-11-12 01:06:08 +0000190
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000191 assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
Eric Christopherebbfbee2009-11-12 01:06:08 +0000192
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000193 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
194 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
195 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
196 }
197
198 // Otherwise, mark this block free.
199 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
200 FollowingBlock->PrevAllocated = 0;
201 FreeBlock.ThisAllocated = 0;
202
203 // Link this into the linked list of free blocks.
204 FreeBlock.AddToFreeList(FreeList);
205
206 // Add a marker at the end of the block, indicating the size of this free
207 // block.
208 FreeBlock.SetEndOfBlockSizeMarker();
209 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
210}
211
212/// GrowBlock - The block after this block just got deallocated. Merge it
213/// into the current block.
214void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
215 assert(NewSize > BlockSize && "Not growing block?");
216 BlockSize = NewSize;
217 SetEndOfBlockSizeMarker();
218 getBlockAfter().PrevAllocated = 0;
219}
220
221/// TrimAllocationToSize - If this allocated block is significantly larger
222/// than NewSize, split it into two pieces (where the former is NewSize
223/// bytes, including the header), and add the new block to the free list.
224FreeRangeHeader *MemoryRangeHeader::
225TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
226 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
227 "Cannot deallocate part of an allocated block!");
228
Evan Chengbf835792008-07-29 07:38:32 +0000229 // Don't allow blocks to be trimmed below minimum required size
230 NewSize = std::max<uint64_t>(FreeRangeHeader::getMinBlockSize(), NewSize);
231
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000232 // Round up size for alignment of header.
233 unsigned HeaderAlign = __alignof(FreeRangeHeader);
234 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
Eric Christopherebbfbee2009-11-12 01:06:08 +0000235
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000236 // Size is now the size of the block we will remove from the start of the
237 // current block.
238 assert(NewSize <= BlockSize &&
239 "Allocating more space from this block than exists!");
Eric Christopherebbfbee2009-11-12 01:06:08 +0000240
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000241 // If splitting this block will cause the remainder to be too small, do not
242 // split the block.
243 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
244 return FreeList;
Eric Christopherebbfbee2009-11-12 01:06:08 +0000245
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000246 // Otherwise, we splice the required number of bytes out of this block, form
247 // a new block immediately after it, then mark this block allocated.
248 MemoryRangeHeader &FormerNextBlock = getBlockAfter();
Eric Christopherebbfbee2009-11-12 01:06:08 +0000249
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000250 // Change the size of this block.
251 BlockSize = NewSize;
Eric Christopherebbfbee2009-11-12 01:06:08 +0000252
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000253 // Get the new block we just sliced out and turn it into a free block.
254 FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
255 NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
256 NewNextBlock.ThisAllocated = 0;
257 NewNextBlock.PrevAllocated = 1;
258 NewNextBlock.SetEndOfBlockSizeMarker();
259 FormerNextBlock.PrevAllocated = 0;
260 NewNextBlock.AddToFreeList(FreeList);
261 return &NewNextBlock;
262}
263
264//===----------------------------------------------------------------------===//
265// Memory Block Implementation.
266//===----------------------------------------------------------------------===//
267
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000268namespace {
269
270 class DefaultJITMemoryManager;
271
Chandler Carrutheed34662014-04-14 05:11:27 +0000272 class JITSlabAllocator {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000273 DefaultJITMemoryManager &JMM;
274 public:
275 JITSlabAllocator(DefaultJITMemoryManager &jmm) : JMM(jmm) { }
Chandler Carrutheed34662014-04-14 05:11:27 +0000276 void *Allocate(size_t Size);
277 void Deallocate(void *Slab, size_t Size);
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000278 };
279
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000280 /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
281 /// This splits a large block of MAP_NORESERVE'd memory into two
282 /// sections, one for function stubs, one for the functions themselves. We
283 /// have to do this because we may need to emit a function stub while in the
284 /// middle of emitting a function, and we don't know how large the function we
285 /// are emitting is.
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000286 class DefaultJITMemoryManager : public JITMemoryManager {
Chandler Carruthead0f762014-03-28 08:53:08 +0000287 public:
288 /// DefaultCodeSlabSize - When we have to go map more memory, we allocate at
289 /// least this much unless more is requested. Currently, in 512k slabs.
290 static const size_t DefaultCodeSlabSize = 512 * 1024;
Jeffrey Yasskin70415d92009-07-08 21:59:57 +0000291
Chandler Carruthead0f762014-03-28 08:53:08 +0000292 /// DefaultSlabSize - Allocate globals and stubs into slabs of 64K (probably
293 /// 16 pages) unless we get an allocation above SizeThreshold.
294 static const size_t DefaultSlabSize = 64 * 1024;
295
296 /// DefaultSizeThreshold - For any allocation larger than 16K (probably
297 /// 4 pages), we should allocate a separate slab to avoid wasted space at
298 /// the end of a normal slab.
299 static const size_t DefaultSizeThreshold = 16 * 1024;
300
301 private:
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000302 // Whether to poison freed memory.
303 bool PoisonMemory;
304
305 /// LastSlab - This points to the last slab allocated and is used as the
306 /// NearBlock parameter to AllocateRWX so that we can attempt to lay out all
307 /// stubs, data, and code contiguously in memory. In general, however, this
308 /// is not possible because the NearBlock parameter is ignored on Windows
309 /// platforms and even on Unix it works on a best-effort pasis.
310 sys::MemoryBlock LastSlab;
311
312 // Memory slabs allocated by the JIT. We refer to them as slabs so we don't
Eric Christopherebbfbee2009-11-12 01:06:08 +0000313 // confuse them with the blocks of memory described above.
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000314 std::vector<sys::MemoryBlock> CodeSlabs;
Chandler Carrutheed34662014-04-14 05:11:27 +0000315 BumpPtrAllocatorImpl<JITSlabAllocator, DefaultSlabSize,
316 DefaultSizeThreshold> StubAllocator;
317 BumpPtrAllocatorImpl<JITSlabAllocator, DefaultSlabSize,
318 DefaultSizeThreshold> DataAllocator;
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000319
320 // Circular list of free blocks.
321 FreeRangeHeader *FreeMemoryList;
322
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000323 // When emitting code into a memory block, this is the block.
324 MemoryRangeHeader *CurBlock;
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000325
Bruno Cardoso Lopes8a1be5e2009-06-04 00:15:51 +0000326 uint8_t *GOTBase; // Target Specific reserved memory
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000327 public:
328 DefaultJITMemoryManager();
329 ~DefaultJITMemoryManager();
330
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000331 /// allocateNewSlab - Allocates a new MemoryBlock and remembers it as the
332 /// last slab it allocated, so that subsequent allocations follow it.
333 sys::MemoryBlock allocateNewSlab(size_t size);
334
Danil Malyshevbfee5422012-03-28 21:46:36 +0000335 /// getPointerToNamedFunction - This method returns the address of the
336 /// specified function by using the dlsym function call.
Craig Topperb51ff602014-03-08 07:51:20 +0000337 void *getPointerToNamedFunction(const std::string &Name,
338 bool AbortOnFailure = true) override;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000339
Craig Topperb51ff602014-03-08 07:51:20 +0000340 void AllocateGOT() override;
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000341
342 // Testing methods.
Craig Topperb51ff602014-03-08 07:51:20 +0000343 bool CheckInvariants(std::string &ErrorStr) override;
344 size_t GetDefaultCodeSlabSize() override { return DefaultCodeSlabSize; }
345 size_t GetDefaultDataSlabSize() override { return DefaultSlabSize; }
346 size_t GetDefaultStubSlabSize() override { return DefaultSlabSize; }
347 unsigned GetNumCodeSlabs() override { return CodeSlabs.size(); }
348 unsigned GetNumDataSlabs() override { return DataAllocator.GetNumSlabs(); }
349 unsigned GetNumStubSlabs() override { return StubAllocator.GetNumSlabs(); }
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000350
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000351 /// startFunctionBody - When a function starts, allocate a block of free
352 /// executable memory, returning a pointer to it and its actual size.
Craig Topperb51ff602014-03-08 07:51:20 +0000353 uint8_t *startFunctionBody(const Function *F,
354 uintptr_t &ActualSize) override {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000355
Chris Lattner26161cd2009-03-09 21:34:10 +0000356 FreeRangeHeader* candidateBlock = FreeMemoryList;
357 FreeRangeHeader* head = FreeMemoryList;
358 FreeRangeHeader* iter = head->Next;
359
360 uintptr_t largest = candidateBlock->BlockSize;
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000361
Chris Lattner26161cd2009-03-09 21:34:10 +0000362 // Search for the largest free block
363 while (iter != head) {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000364 if (iter->BlockSize > largest) {
365 largest = iter->BlockSize;
366 candidateBlock = iter;
367 }
368 iter = iter->Next;
Chris Lattner26161cd2009-03-09 21:34:10 +0000369 }
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000370
Nicolas Geoffray956a8642009-07-29 22:55:02 +0000371 largest = largest - sizeof(MemoryRangeHeader);
Eric Christopherebbfbee2009-11-12 01:06:08 +0000372
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000373 // If this block isn't big enough for the allocation desired, allocate
374 // another block of memory and add it to the free list.
Nicolas Geoffray956a8642009-07-29 22:55:02 +0000375 if (largest < ActualSize ||
376 largest <= FreeRangeHeader::getMinBlockSize()) {
David Greene2baba962010-01-05 01:23:38 +0000377 DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000378 candidateBlock = allocateNewCodeSlab((size_t)ActualSize);
379 }
380
Chris Lattner26161cd2009-03-09 21:34:10 +0000381 // Select this candidate block for allocation
382 CurBlock = candidateBlock;
383
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000384 // Allocate the entire memory block.
Chris Lattner26161cd2009-03-09 21:34:10 +0000385 FreeMemoryList = candidateBlock->AllocateBlock();
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000386 ActualSize = CurBlock->BlockSize - sizeof(MemoryRangeHeader);
387 return (uint8_t *)(CurBlock + 1);
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000388 }
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000389
390 /// allocateNewCodeSlab - Helper method to allocate a new slab of code
391 /// memory from the OS and add it to the free list. Returns the new
392 /// FreeRangeHeader at the base of the slab.
393 FreeRangeHeader *allocateNewCodeSlab(size_t MinSize) {
394 // If the user needs at least MinSize free memory, then we account for
395 // two MemoryRangeHeaders: the one in the user's block, and the one at the
396 // end of the slab.
397 size_t PaddedMin = MinSize + 2 * sizeof(MemoryRangeHeader);
398 size_t SlabSize = std::max(DefaultCodeSlabSize, PaddedMin);
399 sys::MemoryBlock B = allocateNewSlab(SlabSize);
400 CodeSlabs.push_back(B);
401 char *MemBase = (char*)(B.base());
402
403 // Put a tiny allocated block at the end of the memory chunk, so when
404 // FreeBlock calls getBlockAfter it doesn't fall off the end.
405 MemoryRangeHeader *EndBlock =
406 (MemoryRangeHeader*)(MemBase + B.size()) - 1;
407 EndBlock->ThisAllocated = 1;
408 EndBlock->PrevAllocated = 0;
409 EndBlock->BlockSize = sizeof(MemoryRangeHeader);
410
411 // Start out with a vast new block of free memory.
412 FreeRangeHeader *NewBlock = (FreeRangeHeader*)MemBase;
413 NewBlock->ThisAllocated = 0;
414 // Make sure getFreeBlockBefore doesn't look into unmapped memory.
415 NewBlock->PrevAllocated = 1;
416 NewBlock->BlockSize = (uintptr_t)EndBlock - (uintptr_t)NewBlock;
417 NewBlock->SetEndOfBlockSizeMarker();
418 NewBlock->AddToFreeList(FreeMemoryList);
419
420 assert(NewBlock->BlockSize - sizeof(MemoryRangeHeader) >= MinSize &&
421 "The block was too small!");
422 return NewBlock;
423 }
424
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000425 /// endFunctionBody - The function F is now allocated, and takes the memory
426 /// in the range [FunctionStart,FunctionEnd).
Bruno Cardoso Lopes8a1be5e2009-06-04 00:15:51 +0000427 void endFunctionBody(const Function *F, uint8_t *FunctionStart,
Craig Topperb51ff602014-03-08 07:51:20 +0000428 uint8_t *FunctionEnd) override {
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000429 assert(FunctionEnd > FunctionStart);
Bruno Cardoso Lopes8a1be5e2009-06-04 00:15:51 +0000430 assert(FunctionStart == (uint8_t *)(CurBlock+1) &&
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000431 "Mismatched function start/end!");
Dale Johannesenb086d382008-08-07 01:30:15 +0000432
Bruno Cardoso Lopes8a1be5e2009-06-04 00:15:51 +0000433 uintptr_t BlockSize = FunctionEnd - (uint8_t *)CurBlock;
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000434
435 // Release the memory at the end of this block that isn't needed.
436 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
437 }
Nuno Lopes94844e22008-10-21 11:42:16 +0000438
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000439 /// allocateSpace - Allocate a memory block of the given size. This method
440 /// cannot be called between calls to startFunctionBody and endFunctionBody.
Craig Topperb51ff602014-03-08 07:51:20 +0000441 uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) override {
Nuno Lopes94844e22008-10-21 11:42:16 +0000442 CurBlock = FreeMemoryList;
443 FreeMemoryList = FreeMemoryList->AllocateBlock();
444
Jeffrey Yasskin70415d92009-07-08 21:59:57 +0000445 uint8_t *result = (uint8_t *)(CurBlock + 1);
Nuno Lopes94844e22008-10-21 11:42:16 +0000446
447 if (Alignment == 0) Alignment = 1;
Bruno Cardoso Lopes8a1be5e2009-06-04 00:15:51 +0000448 result = (uint8_t*)(((intptr_t)result+Alignment-1) &
Nuno Lopes94844e22008-10-21 11:42:16 +0000449 ~(intptr_t)(Alignment-1));
450
Bruno Cardoso Lopes8a1be5e2009-06-04 00:15:51 +0000451 uintptr_t BlockSize = result + Size - (uint8_t *)CurBlock;
Nuno Lopes94844e22008-10-21 11:42:16 +0000452 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
453
454 return result;
455 }
456
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000457 /// allocateStub - Allocate memory for a function stub.
458 uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
Craig Topperb51ff602014-03-08 07:51:20 +0000459 unsigned Alignment) override {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000460 return (uint8_t*)StubAllocator.Allocate(StubSize, Alignment);
461 }
462
463 /// allocateGlobal - Allocate memory for a global.
Craig Topperb51ff602014-03-08 07:51:20 +0000464 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) override {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000465 return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
Jeffrey Yasskin70415d92009-07-08 21:59:57 +0000466 }
467
Jim Grosbacheff0a402012-01-16 22:26:39 +0000468 /// allocateCodeSection - Allocate memory for a code section.
469 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Topperb51ff602014-03-08 07:51:20 +0000470 unsigned SectionID,
471 StringRef SectionName) override {
Sean Callanan219fc0f2012-08-15 20:53:52 +0000472 // Grow the required block size to account for the block header
473 Size += sizeof(*CurBlock);
474
Elena Demikhovskye4fd5ed2013-07-02 12:24:22 +0000475 // Alignment handling.
476 if (!Alignment)
477 Alignment = 16;
478 Size += Alignment - 1;
479
Jim Grosbacheff0a402012-01-16 22:26:39 +0000480 FreeRangeHeader* candidateBlock = FreeMemoryList;
481 FreeRangeHeader* head = FreeMemoryList;
482 FreeRangeHeader* iter = head->Next;
483
484 uintptr_t largest = candidateBlock->BlockSize;
485
486 // Search for the largest free block.
487 while (iter != head) {
488 if (iter->BlockSize > largest) {
489 largest = iter->BlockSize;
490 candidateBlock = iter;
491 }
492 iter = iter->Next;
493 }
494
495 largest = largest - sizeof(MemoryRangeHeader);
496
497 // If this block isn't big enough for the allocation desired, allocate
498 // another block of memory and add it to the free list.
499 if (largest < Size || largest <= FreeRangeHeader::getMinBlockSize()) {
500 DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
501 candidateBlock = allocateNewCodeSlab((size_t)Size);
502 }
503
504 // Select this candidate block for allocation
505 CurBlock = candidateBlock;
506
507 // Allocate the entire memory block.
508 FreeMemoryList = candidateBlock->AllocateBlock();
509 // Release the memory at the end of this block that isn't needed.
510 FreeMemoryList = CurBlock->TrimAllocationToSize(FreeMemoryList, Size);
Elena Demikhovskye4fd5ed2013-07-02 12:24:22 +0000511 uintptr_t unalignedAddr = (uintptr_t)CurBlock + sizeof(*CurBlock);
512 return (uint8_t*)RoundUpToAlignment((uint64_t)unalignedAddr, Alignment);
Jim Grosbacheff0a402012-01-16 22:26:39 +0000513 }
514
515 /// allocateDataSection - Allocate memory for a data section.
516 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000517 unsigned SectionID, StringRef SectionName,
Craig Topperb51ff602014-03-08 07:51:20 +0000518 bool IsReadOnly) override {
Jim Grosbacheff0a402012-01-16 22:26:39 +0000519 return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
520 }
521
Craig Topperb51ff602014-03-08 07:51:20 +0000522 bool finalizeMemory(std::string *ErrMsg) override {
Andrew Kaylora342cb92012-11-15 23:50:01 +0000523 return false;
524 }
525
Craig Topperb51ff602014-03-08 07:51:20 +0000526 uint8_t *getGOTBase() const override {
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000527 return GOTBase;
528 }
Eric Christopherebbfbee2009-11-12 01:06:08 +0000529
Jeffrey Yasskin27c66922009-10-20 18:13:21 +0000530 void deallocateBlock(void *Block) {
531 // Find the block that is allocated for this function.
532 MemoryRangeHeader *MemRange = static_cast<MemoryRangeHeader*>(Block) - 1;
533 assert(MemRange->ThisAllocated && "Block isn't allocated!");
534
535 // Fill the buffer with garbage!
536 if (PoisonMemory) {
537 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
538 }
539
540 // Free the memory.
541 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
542 }
543
544 /// deallocateFunctionBody - Deallocate all memory for the specified
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000545 /// function body.
Craig Topperb51ff602014-03-08 07:51:20 +0000546 void deallocateFunctionBody(void *Body) override {
Nicolas Geoffray7e8017c2009-10-22 14:35:57 +0000547 if (Body) deallocateBlock(Body);
Jeffrey Yasskin27c66922009-10-20 18:13:21 +0000548 }
Jeffrey Yasskin70415d92009-07-08 21:59:57 +0000549
Jim Grosbachb22ef712008-10-03 16:17:20 +0000550 /// setMemoryWritable - When code generation is in progress,
551 /// the code pages may need permissions changed.
Craig Topperb51ff602014-03-08 07:51:20 +0000552 void setMemoryWritable() override {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000553 for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
554 sys::Memory::setWritable(CodeSlabs[i]);
Jim Grosbachb22ef712008-10-03 16:17:20 +0000555 }
556 /// setMemoryExecutable - When code generation is done and we're ready to
557 /// start execution, the code pages may need permissions changed.
Craig Topperb51ff602014-03-08 07:51:20 +0000558 void setMemoryExecutable() override {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000559 for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
560 sys::Memory::setExecutable(CodeSlabs[i]);
Jim Grosbachb22ef712008-10-03 16:17:20 +0000561 }
Jeffrey Yasskin70415d92009-07-08 21:59:57 +0000562
563 /// setPoisonMemory - Controls whether we write garbage over freed memory.
564 ///
Craig Topperb51ff602014-03-08 07:51:20 +0000565 void setPoisonMemory(bool poison) override {
Jeffrey Yasskin70415d92009-07-08 21:59:57 +0000566 PoisonMemory = poison;
567 }
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000568 };
569}
570
Chandler Carruthf5babf92014-04-14 03:55:11 +0000571void *JITSlabAllocator::Allocate(size_t Size) {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000572 sys::MemoryBlock B = JMM.allocateNewSlab(Size);
Chandler Carruthf5babf92014-04-14 03:55:11 +0000573 return B.base();
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000574}
575
Chandler Carruthf5babf92014-04-14 03:55:11 +0000576void JITSlabAllocator::Deallocate(void *Slab, size_t Size) {
577 sys::MemoryBlock B(Slab, Size);
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000578 sys::Memory::ReleaseRWX(B);
579}
580
581DefaultJITMemoryManager::DefaultJITMemoryManager()
Chandler Carrutheed34662014-04-14 05:11:27 +0000582 :
Dan Gohmanfb3d84b2009-08-27 01:25:57 +0000583#ifdef NDEBUG
Chandler Carrutheed34662014-04-14 05:11:27 +0000584 PoisonMemory(false),
Dan Gohmanfb3d84b2009-08-27 01:25:57 +0000585#else
Chandler Carrutheed34662014-04-14 05:11:27 +0000586 PoisonMemory(true),
Dan Gohmanfb3d84b2009-08-27 01:25:57 +0000587#endif
Chandler Carrutheed34662014-04-14 05:11:27 +0000588 LastSlab(0, 0), StubAllocator(*this), DataAllocator(*this) {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000589
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000590 // Allocate space for code.
591 sys::MemoryBlock MemBlock = allocateNewSlab(DefaultCodeSlabSize);
592 CodeSlabs.push_back(MemBlock);
593 uint8_t *MemBase = (uint8_t*)MemBlock.base();
Jeffrey Yasskin70415d92009-07-08 21:59:57 +0000594
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000595 // We set up the memory chunk with 4 mem regions, like this:
596 // [ START
597 // [ Free #0 ] -> Large space to allocate functions from.
598 // [ Allocated #1 ] -> Tiny space to separate regions.
599 // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
600 // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
601 // END ]
602 //
603 // The last three blocks are never deallocated or touched.
Eric Christopherebbfbee2009-11-12 01:06:08 +0000604
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000605 // Add MemoryRangeHeader to the end of the memory region, indicating that
606 // the space after the block of memory is allocated. This is block #3.
607 MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
608 Mem3->ThisAllocated = 1;
609 Mem3->PrevAllocated = 0;
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000610 Mem3->BlockSize = sizeof(MemoryRangeHeader);
Eric Christopherebbfbee2009-11-12 01:06:08 +0000611
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000612 /// Add a tiny free region so that the free list always has one entry.
Eric Christopherebbfbee2009-11-12 01:06:08 +0000613 FreeRangeHeader *Mem2 =
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000614 (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
615 Mem2->ThisAllocated = 0;
616 Mem2->PrevAllocated = 1;
617 Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
618 Mem2->SetEndOfBlockSizeMarker();
619 Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
620 Mem2->Next = Mem2;
621
622 /// Add a tiny allocated region so that Mem2 is never coalesced away.
623 MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
624 Mem1->ThisAllocated = 1;
625 Mem1->PrevAllocated = 0;
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000626 Mem1->BlockSize = sizeof(MemoryRangeHeader);
Eric Christopherebbfbee2009-11-12 01:06:08 +0000627
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000628 // Add a FreeRangeHeader to the start of the function body region, indicating
629 // that the space is free. Mark the previous block allocated so we never look
630 // at it.
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000631 FreeRangeHeader *Mem0 = (FreeRangeHeader*)MemBase;
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000632 Mem0->ThisAllocated = 0;
633 Mem0->PrevAllocated = 1;
634 Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
635 Mem0->SetEndOfBlockSizeMarker();
636 Mem0->AddToFreeList(Mem2);
Eric Christopherebbfbee2009-11-12 01:06:08 +0000637
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000638 // Start out with the freelist pointing to Mem0.
639 FreeMemoryList = Mem0;
640
641 GOTBase = NULL;
642}
643
644void DefaultJITMemoryManager::AllocateGOT() {
645 assert(GOTBase == 0 && "Cannot allocate the got multiple times");
Bruno Cardoso Lopes8a1be5e2009-06-04 00:15:51 +0000646 GOTBase = new uint8_t[sizeof(void*) * 8192];
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000647 HasGOT = true;
648}
649
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000650DefaultJITMemoryManager::~DefaultJITMemoryManager() {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000651 for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
652 sys::Memory::ReleaseRWX(CodeSlabs[i]);
653
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000654 delete[] GOTBase;
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000655}
656
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000657sys::MemoryBlock DefaultJITMemoryManager::allocateNewSlab(size_t size) {
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000658 // Allocate a new block close to the last one.
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000659 std::string ErrMsg;
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000660 sys::MemoryBlock *LastSlabPtr = LastSlab.base() ? &LastSlab : 0;
661 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, LastSlabPtr, &ErrMsg);
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000662 if (B.base() == 0) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000663 report_fatal_error("Allocation failed when allocating new memory in the"
Benjamin Kramera6769262010-04-08 10:44:28 +0000664 " JIT\n" + Twine(ErrMsg));
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000665 }
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000666 LastSlab = B;
667 ++NumSlabs;
Reid Kleckner48ca9152009-08-21 21:03:57 +0000668 // Initialize the slab to garbage when debugging.
669 if (PoisonMemory) {
670 memset(B.base(), 0xCD, B.size());
671 }
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000672 return B;
673}
674
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000675/// CheckInvariants - For testing only. Return "" if all internal invariants
676/// are preserved, and a helpful error message otherwise. For free and
677/// allocated blocks, make sure that adding BlockSize gives a valid block.
678/// For free blocks, make sure they're in the free list and that their end of
679/// block size marker is correct. This function should return an error before
680/// accessing bad memory. This function is defined here instead of in
681/// JITMemoryManagerTest.cpp so that we don't have to expose all of the
682/// implementation details of DefaultJITMemoryManager.
683bool DefaultJITMemoryManager::CheckInvariants(std::string &ErrorStr) {
684 raw_string_ostream Err(ErrorStr);
685
686 // Construct a the set of FreeRangeHeader pointers so we can query it
687 // efficiently.
688 llvm::SmallPtrSet<MemoryRangeHeader*, 16> FreeHdrSet;
689 FreeRangeHeader* FreeHead = FreeMemoryList;
690 FreeRangeHeader* FreeRange = FreeHead;
691
692 do {
693 // Check that the free range pointer is in the blocks we've allocated.
694 bool Found = false;
695 for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
696 E = CodeSlabs.end(); I != E && !Found; ++I) {
697 char *Start = (char*)I->base();
698 char *End = Start + I->size();
699 Found = (Start <= (char*)FreeRange && (char*)FreeRange < End);
700 }
701 if (!Found) {
702 Err << "Corrupt free list; points to " << FreeRange;
703 return false;
704 }
705
706 if (FreeRange->Next->Prev != FreeRange) {
707 Err << "Next and Prev pointers do not match.";
708 return false;
709 }
710
711 // Otherwise, add it to the set.
712 FreeHdrSet.insert(FreeRange);
713 FreeRange = FreeRange->Next;
714 } while (FreeRange != FreeHead);
715
716 // Go over each block, and look at each MemoryRangeHeader.
717 for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
718 E = CodeSlabs.end(); I != E; ++I) {
719 char *Start = (char*)I->base();
720 char *End = Start + I->size();
721
722 // Check each memory range.
723 for (MemoryRangeHeader *Hdr = (MemoryRangeHeader*)Start, *LastHdr = NULL;
724 Start <= (char*)Hdr && (char*)Hdr < End;
725 Hdr = &Hdr->getBlockAfter()) {
726 if (Hdr->ThisAllocated == 0) {
727 // Check that this range is in the free list.
728 if (!FreeHdrSet.count(Hdr)) {
729 Err << "Found free header at " << Hdr << " that is not in free list.";
730 return false;
731 }
732
733 // Now make sure the size marker at the end of the block is correct.
734 uintptr_t *Marker = ((uintptr_t*)&Hdr->getBlockAfter()) - 1;
735 if (!(Start <= (char*)Marker && (char*)Marker < End)) {
736 Err << "Block size in header points out of current MemoryBlock.";
737 return false;
738 }
739 if (Hdr->BlockSize != *Marker) {
740 Err << "End of block size marker (" << *Marker << ") "
741 << "and BlockSize (" << Hdr->BlockSize << ") don't match.";
742 return false;
743 }
744 }
745
746 if (LastHdr && LastHdr->ThisAllocated != Hdr->PrevAllocated) {
747 Err << "Hdr->PrevAllocated (" << Hdr->PrevAllocated << ") != "
748 << "LastHdr->ThisAllocated (" << LastHdr->ThisAllocated << ")";
749 return false;
750 } else if (!LastHdr && !Hdr->PrevAllocated) {
751 Err << "The first header should have PrevAllocated true.";
752 return false;
753 }
754
755 // Remember the last header.
756 LastHdr = Hdr;
757 }
758 }
759
760 // All invariants are preserved.
761 return true;
762}
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000763
Danil Malyshevbfee5422012-03-28 21:46:36 +0000764//===----------------------------------------------------------------------===//
765// getPointerToNamedFunction() implementation.
766//===----------------------------------------------------------------------===//
767
768// AtExitHandlers - List of functions to call when the program exits,
769// registered with the atexit() library function.
770static std::vector<void (*)()> AtExitHandlers;
771
772/// runAtExitHandlers - Run any functions registered by the program's
773/// calls to atexit(3), which we intercept and store in
774/// AtExitHandlers.
775///
776static void runAtExitHandlers() {
777 while (!AtExitHandlers.empty()) {
778 void (*Fn)() = AtExitHandlers.back();
779 AtExitHandlers.pop_back();
780 Fn();
781 }
782}
783
784//===----------------------------------------------------------------------===//
785// Function stubs that are invoked instead of certain library calls
786//
787// Force the following functions to be linked in to anything that uses the
788// JIT. This is a hack designed to work around the all-too-clever Glibc
789// strategy of making these functions work differently when inlined vs. when
790// not inlined, and hiding their real definitions in a separate archive file
791// that the dynamic linker can't see. For more info, search for
792// 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
Andrew Kaylord9f33812013-11-15 17:59:43 +0000793#if defined(__linux__) && defined(__GLIBC__)
Danil Malyshevbfee5422012-03-28 21:46:36 +0000794/* stat functions are redirecting to __xstat with a version number. On x86-64
795 * linking with libc_nonshared.a and -Wl,--export-dynamic doesn't make 'stat'
796 * available as an exported symbol, so we have to add it explicitly.
797 */
798namespace {
799class StatSymbols {
800public:
801 StatSymbols() {
802 sys::DynamicLibrary::AddSymbol("stat", (void*)(intptr_t)stat);
803 sys::DynamicLibrary::AddSymbol("fstat", (void*)(intptr_t)fstat);
804 sys::DynamicLibrary::AddSymbol("lstat", (void*)(intptr_t)lstat);
805 sys::DynamicLibrary::AddSymbol("stat64", (void*)(intptr_t)stat64);
806 sys::DynamicLibrary::AddSymbol("\x1stat64", (void*)(intptr_t)stat64);
807 sys::DynamicLibrary::AddSymbol("\x1open64", (void*)(intptr_t)open64);
808 sys::DynamicLibrary::AddSymbol("\x1lseek64", (void*)(intptr_t)lseek64);
809 sys::DynamicLibrary::AddSymbol("fstat64", (void*)(intptr_t)fstat64);
810 sys::DynamicLibrary::AddSymbol("lstat64", (void*)(intptr_t)lstat64);
811 sys::DynamicLibrary::AddSymbol("atexit", (void*)(intptr_t)atexit);
812 sys::DynamicLibrary::AddSymbol("mknod", (void*)(intptr_t)mknod);
813 }
814};
815}
816static StatSymbols initStatSymbols;
817#endif // __linux__
818
819// jit_exit - Used to intercept the "exit" library call.
820static void jit_exit(int Status) {
821 runAtExitHandlers(); // Run atexit handlers...
822 exit(Status);
823}
824
825// jit_atexit - Used to intercept the "atexit" library call.
826static int jit_atexit(void (*Fn)()) {
827 AtExitHandlers.push_back(Fn); // Take note of atexit handler...
828 return 0; // Always successful
829}
830
831static int jit_noop() {
832 return 0;
833}
834
835//===----------------------------------------------------------------------===//
836//
837/// getPointerToNamedFunction - This method returns the address of the specified
838/// function by using the dynamic loader interface. As such it is only useful
839/// for resolving library symbols, not code generated symbols.
840///
841void *DefaultJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000842 bool AbortOnFailure) {
Danil Malyshevbfee5422012-03-28 21:46:36 +0000843 // Check to see if this is one of the functions we want to intercept. Note,
844 // we cast to intptr_t here to silence a -pedantic warning that complains
845 // about casting a function pointer to a normal pointer.
846 if (Name == "exit") return (void*)(intptr_t)&jit_exit;
847 if (Name == "atexit") return (void*)(intptr_t)&jit_atexit;
848
849 // We should not invoke parent's ctors/dtors from generated main()!
850 // On Mingw and Cygwin, the symbol __main is resolved to
851 // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
852 // (and register wrong callee's dtors with atexit(3)).
853 // We expect ExecutionEngine::runStaticConstructorsDestructors()
854 // is called before ExecutionEngine::runFunctionAsMain() is called.
855 if (Name == "__main") return (void*)(intptr_t)&jit_noop;
856
857 const char *NameStr = Name.c_str();
858 // If this is an asm specifier, skip the sentinal.
859 if (NameStr[0] == 1) ++NameStr;
860
861 // If it's an external function, look it up in the process image...
862 void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
863 if (Ptr) return Ptr;
864
865 // If it wasn't found and if it starts with an underscore ('_') character,
866 // try again without the underscore.
867 if (NameStr[0] == '_') {
868 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
869 if (Ptr) return Ptr;
870 }
871
872 // Darwin/PPC adds $LDBLStub suffixes to various symbols like printf. These
873 // are references to hidden visibility symbols that dlsym cannot resolve.
874 // If we have one of these, strip off $LDBLStub and try again.
875#if defined(__APPLE__) && defined(__ppc__)
876 if (Name.size() > 9 && Name[Name.size()-9] == '$' &&
877 memcmp(&Name[Name.size()-8], "LDBLStub", 8) == 0) {
878 // First try turning $LDBLStub into $LDBL128. If that fails, strip it off.
879 // This mirrors logic in libSystemStubs.a.
880 std::string Prefix = std::string(Name.begin(), Name.end()-9);
881 if (void *Ptr = getPointerToNamedFunction(Prefix+"$LDBL128", false))
882 return Ptr;
883 if (void *Ptr = getPointerToNamedFunction(Prefix, false))
884 return Ptr;
885 }
886#endif
887
888 if (AbortOnFailure) {
889 report_fatal_error("Program used external function '"+Name+
890 "' which could not be resolved!");
891 }
892 return 0;
893}
894
895
896
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000897JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
898 return new DefaultJITMemoryManager();
899}
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000900
Chandler Carruthead0f762014-03-28 08:53:08 +0000901const size_t DefaultJITMemoryManager::DefaultCodeSlabSize;
902const size_t DefaultJITMemoryManager::DefaultSlabSize;
903const size_t DefaultJITMemoryManager::DefaultSizeThreshold;