blob: 584b93f81502a367012540f8eef2d366c8d9960e [file] [log] [blame]
Chris Lattner8907b4b2007-12-05 23:39:57 +00001//===-- JITMemoryManager.cpp - Memory Allocator for JIT'd code ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner8907b4b2007-12-05 23:39:57 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the DefaultJITMemoryManager class.
11//
12//===----------------------------------------------------------------------===//
13
Reid Kleckner4bf37062009-07-23 01:40:54 +000014#include "llvm/ExecutionEngine/JITMemoryManager.h"
Reid Kleckner10b4fc52009-07-23 21:46:56 +000015#include "llvm/ADT/SmallPtrSet.h"
16#include "llvm/ADT/Statistic.h"
Benjamin Kramer1bd73352010-04-08 10:44:28 +000017#include "llvm/ADT/Twine.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Config/config.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000019#include "llvm/IR/GlobalValue.h"
Reid Kleckner10b4fc52009-07-23 21:46:56 +000020#include "llvm/Support/Allocator.h"
Chris Lattner8907b4b2007-12-05 23:39:57 +000021#include "llvm/Support/Compiler.h"
Reid Kleckner10b4fc52009-07-23 21:46:56 +000022#include "llvm/Support/Debug.h"
Danil Malyshev30b9e322012-03-28 21:46:36 +000023#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000024#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000025#include "llvm/Support/Memory.h"
26#include "llvm/Support/raw_ostream.h"
Chuck Rose III3012ac62007-12-06 02:03:01 +000027#include <cassert>
Dan Gohmande551f92009-04-01 18:45:54 +000028#include <climits>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000029#include <cstring>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000030#include <vector>
Danil Malyshev30b9e322012-03-28 21:46:36 +000031
32#if defined(__linux__)
33#if defined(HAVE_SYS_STAT_H)
34#include <sys/stat.h>
35#endif
36#include <fcntl.h>
37#include <unistd.h>
38#endif
39
Chris Lattner8907b4b2007-12-05 23:39:57 +000040using namespace llvm;
41
Stephen Hinesdce4a402014-05-29 02:49:00 -070042#define DEBUG_TYPE "jit"
43
Reid Kleckner10b4fc52009-07-23 21:46:56 +000044STATISTIC(NumSlabs, "Number of slabs of memory allocated by the JIT");
Chris Lattner8907b4b2007-12-05 23:39:57 +000045
46JITMemoryManager::~JITMemoryManager() {}
47
48//===----------------------------------------------------------------------===//
49// Memory Block Implementation.
50//===----------------------------------------------------------------------===//
51
52namespace {
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;
Eric Christopher5cf0aed2009-11-12 01:06:08 +000062
Chris Lattner8907b4b2007-12-05 23:39:57 +000063 /// 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;
Eric Christopher5cf0aed2009-11-12 01:06:08 +000067
Chris Lattner8907b4b2007-12-05 23:39:57 +000068 /// BlockSize - This is the size in bytes of this memory block,
69 /// including this header.
Dan Gohmande551f92009-04-01 18:45:54 +000070 uintptr_t BlockSize : (sizeof(intptr_t)*CHAR_BIT - 2);
Eric Christopher5cf0aed2009-11-12 01:06:08 +000071
Chris Lattner8907b4b2007-12-05 23:39:57 +000072
73 /// getBlockAfter - Return the memory block immediately after this one.
74 ///
75 MemoryRangeHeader &getBlockAfter() const {
David Greenefe1215e2013-01-14 21:04:44 +000076 return *reinterpret_cast<MemoryRangeHeader *>(
77 reinterpret_cast<char*>(
78 const_cast<MemoryRangeHeader *>(this))+BlockSize);
Chris Lattner8907b4b2007-12-05 23:39:57 +000079 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +000080
Chris Lattner8907b4b2007-12-05 23:39:57 +000081 /// getFreeBlockBefore - If the block before this one is free, return it,
82 /// otherwise return null.
83 FreeRangeHeader *getFreeBlockBefore() const {
Stephen Hinesdce4a402014-05-29 02:49:00 -070084 if (PrevAllocated) return nullptr;
David Greenefe1215e2013-01-14 21:04:44 +000085 intptr_t PrevSize = reinterpret_cast<intptr_t *>(
86 const_cast<MemoryRangeHeader *>(this))[-1];
87 return reinterpret_cast<FreeRangeHeader *>(
88 reinterpret_cast<char*>(
89 const_cast<MemoryRangeHeader *>(this))-PrevSize);
Chris Lattner8907b4b2007-12-05 23:39:57 +000090 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +000091
Chris Lattner8907b4b2007-12-05 23:39:57 +000092 /// FreeBlock - Turn an allocated block into a free block, adjusting
93 /// bits in the object headers, and adding an end of region memory block.
94 FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
Eric Christopher5cf0aed2009-11-12 01:06:08 +000095
Chris Lattner8907b4b2007-12-05 23:39:57 +000096 /// TrimAllocationToSize - If this allocated block is significantly larger
97 /// than NewSize, split it into two pieces (where the former is NewSize
98 /// bytes, including the header), and add the new block to the free list.
Eric Christopher5cf0aed2009-11-12 01:06:08 +000099 FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
Chris Lattner8907b4b2007-12-05 23:39:57 +0000100 uint64_t NewSize);
101 };
102
103 /// FreeRangeHeader - For a memory block that isn't already allocated, this
104 /// keeps track of the current block and has a pointer to the next free block.
105 /// Free blocks are kept on a circularly linked list.
106 struct FreeRangeHeader : public MemoryRangeHeader {
107 FreeRangeHeader *Prev;
108 FreeRangeHeader *Next;
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000109
Chris Lattner8907b4b2007-12-05 23:39:57 +0000110 /// getMinBlockSize - Get the minimum size for a memory block. Blocks
111 /// smaller than this size cannot be created.
112 static unsigned getMinBlockSize() {
113 return sizeof(FreeRangeHeader)+sizeof(intptr_t);
114 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000115
Chris Lattner8907b4b2007-12-05 23:39:57 +0000116 /// SetEndOfBlockSizeMarker - The word at the end of every free block is
117 /// known to be the size of the free block. Set it for this block.
118 void SetEndOfBlockSizeMarker() {
119 void *EndOfBlock = (char*)this + BlockSize;
120 ((intptr_t *)EndOfBlock)[-1] = BlockSize;
121 }
122
123 FreeRangeHeader *RemoveFromFreeList() {
124 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
125 Next->Prev = Prev;
126 return Prev->Next = Next;
127 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000128
Chris Lattner8907b4b2007-12-05 23:39:57 +0000129 void AddToFreeList(FreeRangeHeader *FreeList) {
130 Next = FreeList;
131 Prev = FreeList->Prev;
132 Prev->Next = this;
133 Next->Prev = this;
134 }
135
136 /// GrowBlock - The block after this block just got deallocated. Merge it
137 /// into the current block.
138 void GrowBlock(uintptr_t NewSize);
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000139
Chris Lattner8907b4b2007-12-05 23:39:57 +0000140 /// AllocateBlock - Mark this entire block allocated, updating freelists
141 /// etc. This returns a pointer to the circular free-list.
142 FreeRangeHeader *AllocateBlock();
143 };
144}
145
146
147/// AllocateBlock - Mark this entire block allocated, updating freelists
148/// etc. This returns a pointer to the circular free-list.
149FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
150 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
151 "Cannot allocate an allocated block!");
152 // Mark this block allocated.
153 ThisAllocated = 1;
154 getBlockAfter().PrevAllocated = 1;
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000155
Chris Lattner8907b4b2007-12-05 23:39:57 +0000156 // Remove it from the free list.
157 return RemoveFromFreeList();
158}
159
160/// FreeBlock - Turn an allocated block into a free block, adjusting
161/// bits in the object headers, and adding an end of region memory block.
162/// If possible, coalesce this block with neighboring blocks. Return the
163/// FreeRangeHeader to allocate from.
164FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
165 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000166 assert(ThisAllocated && "This block is already free!");
Chris Lattner8907b4b2007-12-05 23:39:57 +0000167 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000168
Chris Lattner8907b4b2007-12-05 23:39:57 +0000169 FreeRangeHeader *FreeListToReturn = FreeList;
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000170
Chris Lattner8907b4b2007-12-05 23:39:57 +0000171 // If the block after this one is free, merge it into this block.
172 if (!FollowingBlock->ThisAllocated) {
173 FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
174 // "FreeList" always needs to be a valid free block. If we're about to
175 // coalesce with it, update our notion of what the free list is.
176 if (&FollowingFreeBlock == FreeList) {
177 FreeList = FollowingFreeBlock.Next;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700178 FreeListToReturn = nullptr;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000179 assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
180 }
181 FollowingFreeBlock.RemoveFromFreeList();
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000182
Chris Lattner8907b4b2007-12-05 23:39:57 +0000183 // Include the following block into this one.
184 BlockSize += FollowingFreeBlock.BlockSize;
185 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000186
Chris Lattner8907b4b2007-12-05 23:39:57 +0000187 // Tell the block after the block we are coalescing that this block is
188 // allocated.
189 FollowingBlock->PrevAllocated = 1;
190 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000191
Chris Lattner8907b4b2007-12-05 23:39:57 +0000192 assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000193
Chris Lattner8907b4b2007-12-05 23:39:57 +0000194 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
195 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
196 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
197 }
198
199 // Otherwise, mark this block free.
200 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
201 FollowingBlock->PrevAllocated = 0;
202 FreeBlock.ThisAllocated = 0;
203
204 // Link this into the linked list of free blocks.
205 FreeBlock.AddToFreeList(FreeList);
206
207 // Add a marker at the end of the block, indicating the size of this free
208 // block.
209 FreeBlock.SetEndOfBlockSizeMarker();
210 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
211}
212
213/// GrowBlock - The block after this block just got deallocated. Merge it
214/// into the current block.
215void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
216 assert(NewSize > BlockSize && "Not growing block?");
217 BlockSize = NewSize;
218 SetEndOfBlockSizeMarker();
219 getBlockAfter().PrevAllocated = 0;
220}
221
222/// TrimAllocationToSize - If this allocated block is significantly larger
223/// than NewSize, split it into two pieces (where the former is NewSize
224/// bytes, including the header), and add the new block to the free list.
225FreeRangeHeader *MemoryRangeHeader::
226TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
227 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
228 "Cannot deallocate part of an allocated block!");
229
Evan Cheng60b75f42008-07-29 07:38:32 +0000230 // Don't allow blocks to be trimmed below minimum required size
231 NewSize = std::max<uint64_t>(FreeRangeHeader::getMinBlockSize(), NewSize);
232
Chris Lattner8907b4b2007-12-05 23:39:57 +0000233 // Round up size for alignment of header.
234 unsigned HeaderAlign = __alignof(FreeRangeHeader);
235 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000236
Chris Lattner8907b4b2007-12-05 23:39:57 +0000237 // Size is now the size of the block we will remove from the start of the
238 // current block.
239 assert(NewSize <= BlockSize &&
240 "Allocating more space from this block than exists!");
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000241
Chris Lattner8907b4b2007-12-05 23:39:57 +0000242 // If splitting this block will cause the remainder to be too small, do not
243 // split the block.
244 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
245 return FreeList;
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000246
Chris Lattner8907b4b2007-12-05 23:39:57 +0000247 // Otherwise, we splice the required number of bytes out of this block, form
248 // a new block immediately after it, then mark this block allocated.
249 MemoryRangeHeader &FormerNextBlock = getBlockAfter();
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000250
Chris Lattner8907b4b2007-12-05 23:39:57 +0000251 // Change the size of this block.
252 BlockSize = NewSize;
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000253
Chris Lattner8907b4b2007-12-05 23:39:57 +0000254 // Get the new block we just sliced out and turn it into a free block.
255 FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
256 NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
257 NewNextBlock.ThisAllocated = 0;
258 NewNextBlock.PrevAllocated = 1;
259 NewNextBlock.SetEndOfBlockSizeMarker();
260 FormerNextBlock.PrevAllocated = 0;
261 NewNextBlock.AddToFreeList(FreeList);
262 return &NewNextBlock;
263}
264
265//===----------------------------------------------------------------------===//
266// Memory Block Implementation.
267//===----------------------------------------------------------------------===//
268
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000269namespace {
270
271 class DefaultJITMemoryManager;
272
Stephen Hinesdce4a402014-05-29 02:49:00 -0700273 class JITAllocator {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000274 DefaultJITMemoryManager &JMM;
275 public:
Stephen Hinesdce4a402014-05-29 02:49:00 -0700276 JITAllocator(DefaultJITMemoryManager &jmm) : JMM(jmm) { }
277 void *Allocate(size_t Size, size_t /*Alignment*/);
278 void Deallocate(void *Slab, size_t Size);
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000279 };
280
Chris Lattner8907b4b2007-12-05 23:39:57 +0000281 /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
282 /// This splits a large block of MAP_NORESERVE'd memory into two
283 /// sections, one for function stubs, one for the functions themselves. We
284 /// have to do this because we may need to emit a function stub while in the
285 /// middle of emitting a function, and we don't know how large the function we
286 /// are emitting is.
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000287 class DefaultJITMemoryManager : public JITMemoryManager {
Stephen Hines36b56882014-04-23 16:57:46 -0700288 public:
289 /// DefaultCodeSlabSize - When we have to go map more memory, we allocate at
290 /// least this much unless more is requested. Currently, in 512k slabs.
291 static const size_t DefaultCodeSlabSize = 512 * 1024;
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000292
Stephen Hines36b56882014-04-23 16:57:46 -0700293 /// DefaultSlabSize - Allocate globals and stubs into slabs of 64K (probably
294 /// 16 pages) unless we get an allocation above SizeThreshold.
295 static const size_t DefaultSlabSize = 64 * 1024;
296
297 /// DefaultSizeThreshold - For any allocation larger than 16K (probably
298 /// 4 pages), we should allocate a separate slab to avoid wasted space at
299 /// the end of a normal slab.
300 static const size_t DefaultSizeThreshold = 16 * 1024;
301
302 private:
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000303 // Whether to poison freed memory.
304 bool PoisonMemory;
305
306 /// LastSlab - This points to the last slab allocated and is used as the
307 /// NearBlock parameter to AllocateRWX so that we can attempt to lay out all
308 /// stubs, data, and code contiguously in memory. In general, however, this
309 /// is not possible because the NearBlock parameter is ignored on Windows
310 /// platforms and even on Unix it works on a best-effort pasis.
311 sys::MemoryBlock LastSlab;
312
313 // Memory slabs allocated by the JIT. We refer to them as slabs so we don't
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000314 // confuse them with the blocks of memory described above.
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000315 std::vector<sys::MemoryBlock> CodeSlabs;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700316 BumpPtrAllocatorImpl<JITAllocator, DefaultSlabSize,
317 DefaultSizeThreshold> StubAllocator;
318 BumpPtrAllocatorImpl<JITAllocator, DefaultSlabSize,
319 DefaultSizeThreshold> DataAllocator;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000320
321 // Circular list of free blocks.
322 FreeRangeHeader *FreeMemoryList;
323
Chris Lattner8907b4b2007-12-05 23:39:57 +0000324 // When emitting code into a memory block, this is the block.
325 MemoryRangeHeader *CurBlock;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000326
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000327 uint8_t *GOTBase; // Target Specific reserved memory
Chris Lattner8907b4b2007-12-05 23:39:57 +0000328 public:
329 DefaultJITMemoryManager();
330 ~DefaultJITMemoryManager();
331
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000332 /// allocateNewSlab - Allocates a new MemoryBlock and remembers it as the
333 /// last slab it allocated, so that subsequent allocations follow it.
334 sys::MemoryBlock allocateNewSlab(size_t size);
335
Danil Malyshev30b9e322012-03-28 21:46:36 +0000336 /// getPointerToNamedFunction - This method returns the address of the
337 /// specified function by using the dlsym function call.
Stephen Hines36b56882014-04-23 16:57:46 -0700338 void *getPointerToNamedFunction(const std::string &Name,
339 bool AbortOnFailure = true) override;
Danil Malyshev30b9e322012-03-28 21:46:36 +0000340
Stephen Hines36b56882014-04-23 16:57:46 -0700341 void AllocateGOT() override;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000342
343 // Testing methods.
Stephen Hines36b56882014-04-23 16:57:46 -0700344 bool CheckInvariants(std::string &ErrorStr) override;
345 size_t GetDefaultCodeSlabSize() override { return DefaultCodeSlabSize; }
346 size_t GetDefaultDataSlabSize() override { return DefaultSlabSize; }
347 size_t GetDefaultStubSlabSize() override { return DefaultSlabSize; }
348 unsigned GetNumCodeSlabs() override { return CodeSlabs.size(); }
349 unsigned GetNumDataSlabs() override { return DataAllocator.GetNumSlabs(); }
350 unsigned GetNumStubSlabs() override { return StubAllocator.GetNumSlabs(); }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000351
Chris Lattner8907b4b2007-12-05 23:39:57 +0000352 /// startFunctionBody - When a function starts, allocate a block of free
353 /// executable memory, returning a pointer to it and its actual size.
Stephen Hines36b56882014-04-23 16:57:46 -0700354 uint8_t *startFunctionBody(const Function *F,
355 uintptr_t &ActualSize) override {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000356
Chris Lattner96c96b42009-03-09 21:34:10 +0000357 FreeRangeHeader* candidateBlock = FreeMemoryList;
358 FreeRangeHeader* head = FreeMemoryList;
359 FreeRangeHeader* iter = head->Next;
360
361 uintptr_t largest = candidateBlock->BlockSize;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000362
Chris Lattner96c96b42009-03-09 21:34:10 +0000363 // Search for the largest free block
364 while (iter != head) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000365 if (iter->BlockSize > largest) {
366 largest = iter->BlockSize;
367 candidateBlock = iter;
368 }
369 iter = iter->Next;
Chris Lattner96c96b42009-03-09 21:34:10 +0000370 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000371
Nicolas Geoffray1b10d792009-07-29 22:55:02 +0000372 largest = largest - sizeof(MemoryRangeHeader);
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000373
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000374 // If this block isn't big enough for the allocation desired, allocate
375 // another block of memory and add it to the free list.
Nicolas Geoffray1b10d792009-07-29 22:55:02 +0000376 if (largest < ActualSize ||
377 largest <= FreeRangeHeader::getMinBlockSize()) {
David Greenebd8c8af2010-01-05 01:23:38 +0000378 DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000379 candidateBlock = allocateNewCodeSlab((size_t)ActualSize);
380 }
381
Chris Lattner96c96b42009-03-09 21:34:10 +0000382 // Select this candidate block for allocation
383 CurBlock = candidateBlock;
384
Chris Lattner8907b4b2007-12-05 23:39:57 +0000385 // Allocate the entire memory block.
Chris Lattner96c96b42009-03-09 21:34:10 +0000386 FreeMemoryList = candidateBlock->AllocateBlock();
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000387 ActualSize = CurBlock->BlockSize - sizeof(MemoryRangeHeader);
388 return (uint8_t *)(CurBlock + 1);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000389 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000390
391 /// allocateNewCodeSlab - Helper method to allocate a new slab of code
392 /// memory from the OS and add it to the free list. Returns the new
393 /// FreeRangeHeader at the base of the slab.
394 FreeRangeHeader *allocateNewCodeSlab(size_t MinSize) {
395 // If the user needs at least MinSize free memory, then we account for
396 // two MemoryRangeHeaders: the one in the user's block, and the one at the
397 // end of the slab.
398 size_t PaddedMin = MinSize + 2 * sizeof(MemoryRangeHeader);
399 size_t SlabSize = std::max(DefaultCodeSlabSize, PaddedMin);
400 sys::MemoryBlock B = allocateNewSlab(SlabSize);
401 CodeSlabs.push_back(B);
402 char *MemBase = (char*)(B.base());
403
404 // Put a tiny allocated block at the end of the memory chunk, so when
405 // FreeBlock calls getBlockAfter it doesn't fall off the end.
406 MemoryRangeHeader *EndBlock =
407 (MemoryRangeHeader*)(MemBase + B.size()) - 1;
408 EndBlock->ThisAllocated = 1;
409 EndBlock->PrevAllocated = 0;
410 EndBlock->BlockSize = sizeof(MemoryRangeHeader);
411
412 // Start out with a vast new block of free memory.
413 FreeRangeHeader *NewBlock = (FreeRangeHeader*)MemBase;
414 NewBlock->ThisAllocated = 0;
415 // Make sure getFreeBlockBefore doesn't look into unmapped memory.
416 NewBlock->PrevAllocated = 1;
417 NewBlock->BlockSize = (uintptr_t)EndBlock - (uintptr_t)NewBlock;
418 NewBlock->SetEndOfBlockSizeMarker();
419 NewBlock->AddToFreeList(FreeMemoryList);
420
421 assert(NewBlock->BlockSize - sizeof(MemoryRangeHeader) >= MinSize &&
422 "The block was too small!");
423 return NewBlock;
424 }
425
Chris Lattner8907b4b2007-12-05 23:39:57 +0000426 /// endFunctionBody - The function F is now allocated, and takes the memory
427 /// in the range [FunctionStart,FunctionEnd).
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000428 void endFunctionBody(const Function *F, uint8_t *FunctionStart,
Stephen Hines36b56882014-04-23 16:57:46 -0700429 uint8_t *FunctionEnd) override {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000430 assert(FunctionEnd > FunctionStart);
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000431 assert(FunctionStart == (uint8_t *)(CurBlock+1) &&
Chris Lattner8907b4b2007-12-05 23:39:57 +0000432 "Mismatched function start/end!");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000433
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000434 uintptr_t BlockSize = FunctionEnd - (uint8_t *)CurBlock;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000435
436 // Release the memory at the end of this block that isn't needed.
437 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
438 }
Nuno Lopescef75272008-10-21 11:42:16 +0000439
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000440 /// allocateSpace - Allocate a memory block of the given size. This method
441 /// cannot be called between calls to startFunctionBody and endFunctionBody.
Stephen Hines36b56882014-04-23 16:57:46 -0700442 uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) override {
Nuno Lopescef75272008-10-21 11:42:16 +0000443 CurBlock = FreeMemoryList;
444 FreeMemoryList = FreeMemoryList->AllocateBlock();
445
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000446 uint8_t *result = (uint8_t *)(CurBlock + 1);
Nuno Lopescef75272008-10-21 11:42:16 +0000447
448 if (Alignment == 0) Alignment = 1;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000449 result = (uint8_t*)(((intptr_t)result+Alignment-1) &
Nuno Lopescef75272008-10-21 11:42:16 +0000450 ~(intptr_t)(Alignment-1));
451
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000452 uintptr_t BlockSize = result + Size - (uint8_t *)CurBlock;
Nuno Lopescef75272008-10-21 11:42:16 +0000453 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
454
455 return result;
456 }
457
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000458 /// allocateStub - Allocate memory for a function stub.
459 uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
Stephen Hines36b56882014-04-23 16:57:46 -0700460 unsigned Alignment) override {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000461 return (uint8_t*)StubAllocator.Allocate(StubSize, Alignment);
462 }
463
464 /// allocateGlobal - Allocate memory for a global.
Stephen Hines36b56882014-04-23 16:57:46 -0700465 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) override {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000466 return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000467 }
468
Jim Grosbach61425c02012-01-16 22:26:39 +0000469 /// allocateCodeSection - Allocate memory for a code section.
470 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Stephen Hines36b56882014-04-23 16:57:46 -0700471 unsigned SectionID,
472 StringRef SectionName) override {
Sean Callananf92bbcd2012-08-15 20:53:52 +0000473 // Grow the required block size to account for the block header
474 Size += sizeof(*CurBlock);
475
Elena Demikhovskye5cb25f2013-07-02 12:24:22 +0000476 // Alignment handling.
477 if (!Alignment)
478 Alignment = 16;
479 Size += Alignment - 1;
480
Jim Grosbach61425c02012-01-16 22:26:39 +0000481 FreeRangeHeader* candidateBlock = FreeMemoryList;
482 FreeRangeHeader* head = FreeMemoryList;
483 FreeRangeHeader* iter = head->Next;
484
485 uintptr_t largest = candidateBlock->BlockSize;
486
487 // Search for the largest free block.
488 while (iter != head) {
489 if (iter->BlockSize > largest) {
490 largest = iter->BlockSize;
491 candidateBlock = iter;
492 }
493 iter = iter->Next;
494 }
495
496 largest = largest - sizeof(MemoryRangeHeader);
497
498 // If this block isn't big enough for the allocation desired, allocate
499 // another block of memory and add it to the free list.
500 if (largest < Size || largest <= FreeRangeHeader::getMinBlockSize()) {
501 DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
502 candidateBlock = allocateNewCodeSlab((size_t)Size);
503 }
504
505 // Select this candidate block for allocation
506 CurBlock = candidateBlock;
507
508 // Allocate the entire memory block.
509 FreeMemoryList = candidateBlock->AllocateBlock();
510 // Release the memory at the end of this block that isn't needed.
511 FreeMemoryList = CurBlock->TrimAllocationToSize(FreeMemoryList, Size);
Elena Demikhovskye5cb25f2013-07-02 12:24:22 +0000512 uintptr_t unalignedAddr = (uintptr_t)CurBlock + sizeof(*CurBlock);
513 return (uint8_t*)RoundUpToAlignment((uint64_t)unalignedAddr, Alignment);
Jim Grosbach61425c02012-01-16 22:26:39 +0000514 }
515
516 /// allocateDataSection - Allocate memory for a data section.
517 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo6eb43d22013-10-02 00:59:25 +0000518 unsigned SectionID, StringRef SectionName,
Stephen Hines36b56882014-04-23 16:57:46 -0700519 bool IsReadOnly) override {
Jim Grosbach61425c02012-01-16 22:26:39 +0000520 return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
521 }
522
Stephen Hines36b56882014-04-23 16:57:46 -0700523 bool finalizeMemory(std::string *ErrMsg) override {
Andrew Kaylor53608a32012-11-15 23:50:01 +0000524 return false;
525 }
526
Stephen Hines36b56882014-04-23 16:57:46 -0700527 uint8_t *getGOTBase() const override {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000528 return GOTBase;
529 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000530
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000531 void deallocateBlock(void *Block) {
532 // Find the block that is allocated for this function.
533 MemoryRangeHeader *MemRange = static_cast<MemoryRangeHeader*>(Block) - 1;
534 assert(MemRange->ThisAllocated && "Block isn't allocated!");
535
536 // Fill the buffer with garbage!
537 if (PoisonMemory) {
538 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
539 }
540
541 // Free the memory.
542 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
543 }
544
545 /// deallocateFunctionBody - Deallocate all memory for the specified
Chris Lattner8907b4b2007-12-05 23:39:57 +0000546 /// function body.
Stephen Hines36b56882014-04-23 16:57:46 -0700547 void deallocateFunctionBody(void *Body) override {
Nicolas Geoffray71e0b7c2009-10-22 14:35:57 +0000548 if (Body) deallocateBlock(Body);
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000549 }
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000550
Jim Grosbachcce6c292008-10-03 16:17:20 +0000551 /// setMemoryWritable - When code generation is in progress,
552 /// the code pages may need permissions changed.
Stephen Hines36b56882014-04-23 16:57:46 -0700553 void setMemoryWritable() override {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000554 for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
555 sys::Memory::setWritable(CodeSlabs[i]);
Jim Grosbachcce6c292008-10-03 16:17:20 +0000556 }
557 /// setMemoryExecutable - When code generation is done and we're ready to
558 /// start execution, the code pages may need permissions changed.
Stephen Hines36b56882014-04-23 16:57:46 -0700559 void setMemoryExecutable() override {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000560 for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
561 sys::Memory::setExecutable(CodeSlabs[i]);
Jim Grosbachcce6c292008-10-03 16:17:20 +0000562 }
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000563
564 /// setPoisonMemory - Controls whether we write garbage over freed memory.
565 ///
Stephen Hines36b56882014-04-23 16:57:46 -0700566 void setPoisonMemory(bool poison) override {
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000567 PoisonMemory = poison;
568 }
Chris Lattner8907b4b2007-12-05 23:39:57 +0000569 };
570}
571
Stephen Hinesdce4a402014-05-29 02:49:00 -0700572void *JITAllocator::Allocate(size_t Size, size_t /*Alignment*/) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000573 sys::MemoryBlock B = JMM.allocateNewSlab(Size);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700574 return B.base();
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000575}
576
Stephen Hinesdce4a402014-05-29 02:49:00 -0700577void JITAllocator::Deallocate(void *Slab, size_t Size) {
578 sys::MemoryBlock B(Slab, Size);
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000579 sys::Memory::ReleaseRWX(B);
580}
581
582DefaultJITMemoryManager::DefaultJITMemoryManager()
Stephen Hinesdce4a402014-05-29 02:49:00 -0700583 :
Dan Gohman5b78d502009-08-27 01:25:57 +0000584#ifdef NDEBUG
Stephen Hinesdce4a402014-05-29 02:49:00 -0700585 PoisonMemory(false),
Dan Gohman5b78d502009-08-27 01:25:57 +0000586#else
Stephen Hinesdce4a402014-05-29 02:49:00 -0700587 PoisonMemory(true),
Dan Gohman5b78d502009-08-27 01:25:57 +0000588#endif
Stephen Hinesdce4a402014-05-29 02:49:00 -0700589 LastSlab(nullptr, 0), StubAllocator(*this), DataAllocator(*this) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000590
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000591 // Allocate space for code.
592 sys::MemoryBlock MemBlock = allocateNewSlab(DefaultCodeSlabSize);
593 CodeSlabs.push_back(MemBlock);
594 uint8_t *MemBase = (uint8_t*)MemBlock.base();
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000595
Chris Lattner8907b4b2007-12-05 23:39:57 +0000596 // We set up the memory chunk with 4 mem regions, like this:
597 // [ START
598 // [ Free #0 ] -> Large space to allocate functions from.
599 // [ Allocated #1 ] -> Tiny space to separate regions.
600 // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
601 // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
602 // END ]
603 //
604 // The last three blocks are never deallocated or touched.
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000605
Chris Lattner8907b4b2007-12-05 23:39:57 +0000606 // Add MemoryRangeHeader to the end of the memory region, indicating that
607 // the space after the block of memory is allocated. This is block #3.
608 MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
609 Mem3->ThisAllocated = 1;
610 Mem3->PrevAllocated = 0;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000611 Mem3->BlockSize = sizeof(MemoryRangeHeader);
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000612
Chris Lattner8907b4b2007-12-05 23:39:57 +0000613 /// Add a tiny free region so that the free list always has one entry.
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000614 FreeRangeHeader *Mem2 =
Chris Lattner8907b4b2007-12-05 23:39:57 +0000615 (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
616 Mem2->ThisAllocated = 0;
617 Mem2->PrevAllocated = 1;
618 Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
619 Mem2->SetEndOfBlockSizeMarker();
620 Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
621 Mem2->Next = Mem2;
622
623 /// Add a tiny allocated region so that Mem2 is never coalesced away.
624 MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
625 Mem1->ThisAllocated = 1;
626 Mem1->PrevAllocated = 0;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000627 Mem1->BlockSize = sizeof(MemoryRangeHeader);
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000628
Chris Lattner8907b4b2007-12-05 23:39:57 +0000629 // Add a FreeRangeHeader to the start of the function body region, indicating
630 // that the space is free. Mark the previous block allocated so we never look
631 // at it.
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000632 FreeRangeHeader *Mem0 = (FreeRangeHeader*)MemBase;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000633 Mem0->ThisAllocated = 0;
634 Mem0->PrevAllocated = 1;
635 Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
636 Mem0->SetEndOfBlockSizeMarker();
637 Mem0->AddToFreeList(Mem2);
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000638
Chris Lattner8907b4b2007-12-05 23:39:57 +0000639 // Start out with the freelist pointing to Mem0.
640 FreeMemoryList = Mem0;
641
Stephen Hinesdce4a402014-05-29 02:49:00 -0700642 GOTBase = nullptr;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000643}
644
645void DefaultJITMemoryManager::AllocateGOT() {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700646 assert(!GOTBase && "Cannot allocate the got multiple times");
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000647 GOTBase = new uint8_t[sizeof(void*) * 8192];
Chris Lattner8907b4b2007-12-05 23:39:57 +0000648 HasGOT = true;
649}
650
Chris Lattner8907b4b2007-12-05 23:39:57 +0000651DefaultJITMemoryManager::~DefaultJITMemoryManager() {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000652 for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
653 sys::Memory::ReleaseRWX(CodeSlabs[i]);
654
Chris Lattner8907b4b2007-12-05 23:39:57 +0000655 delete[] GOTBase;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000656}
657
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000658sys::MemoryBlock DefaultJITMemoryManager::allocateNewSlab(size_t size) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000659 // Allocate a new block close to the last one.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000660 std::string ErrMsg;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700661 sys::MemoryBlock *LastSlabPtr = LastSlab.base() ? &LastSlab : nullptr;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000662 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, LastSlabPtr, &ErrMsg);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700663 if (!B.base()) {
Chris Lattner75361b62010-04-07 22:58:41 +0000664 report_fatal_error("Allocation failed when allocating new memory in the"
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000665 " JIT\n" + Twine(ErrMsg));
Chris Lattner8907b4b2007-12-05 23:39:57 +0000666 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000667 LastSlab = B;
668 ++NumSlabs;
Reid Kleckner01248e62009-08-21 21:03:57 +0000669 // Initialize the slab to garbage when debugging.
670 if (PoisonMemory) {
671 memset(B.base(), 0xCD, B.size());
672 }
Chris Lattner8907b4b2007-12-05 23:39:57 +0000673 return B;
674}
675
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000676/// CheckInvariants - For testing only. Return "" if all internal invariants
677/// are preserved, and a helpful error message otherwise. For free and
678/// allocated blocks, make sure that adding BlockSize gives a valid block.
679/// For free blocks, make sure they're in the free list and that their end of
680/// block size marker is correct. This function should return an error before
681/// accessing bad memory. This function is defined here instead of in
682/// JITMemoryManagerTest.cpp so that we don't have to expose all of the
683/// implementation details of DefaultJITMemoryManager.
684bool DefaultJITMemoryManager::CheckInvariants(std::string &ErrorStr) {
685 raw_string_ostream Err(ErrorStr);
686
687 // Construct a the set of FreeRangeHeader pointers so we can query it
688 // efficiently.
689 llvm::SmallPtrSet<MemoryRangeHeader*, 16> FreeHdrSet;
690 FreeRangeHeader* FreeHead = FreeMemoryList;
691 FreeRangeHeader* FreeRange = FreeHead;
692
693 do {
694 // Check that the free range pointer is in the blocks we've allocated.
695 bool Found = false;
696 for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
697 E = CodeSlabs.end(); I != E && !Found; ++I) {
698 char *Start = (char*)I->base();
699 char *End = Start + I->size();
700 Found = (Start <= (char*)FreeRange && (char*)FreeRange < End);
701 }
702 if (!Found) {
703 Err << "Corrupt free list; points to " << FreeRange;
704 return false;
705 }
706
707 if (FreeRange->Next->Prev != FreeRange) {
708 Err << "Next and Prev pointers do not match.";
709 return false;
710 }
711
712 // Otherwise, add it to the set.
713 FreeHdrSet.insert(FreeRange);
714 FreeRange = FreeRange->Next;
715 } while (FreeRange != FreeHead);
716
717 // Go over each block, and look at each MemoryRangeHeader.
718 for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
719 E = CodeSlabs.end(); I != E; ++I) {
720 char *Start = (char*)I->base();
721 char *End = Start + I->size();
722
723 // Check each memory range.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700724 for (MemoryRangeHeader *Hdr = (MemoryRangeHeader*)Start, *LastHdr = nullptr;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000725 Start <= (char*)Hdr && (char*)Hdr < End;
726 Hdr = &Hdr->getBlockAfter()) {
727 if (Hdr->ThisAllocated == 0) {
728 // Check that this range is in the free list.
729 if (!FreeHdrSet.count(Hdr)) {
730 Err << "Found free header at " << Hdr << " that is not in free list.";
731 return false;
732 }
733
734 // Now make sure the size marker at the end of the block is correct.
735 uintptr_t *Marker = ((uintptr_t*)&Hdr->getBlockAfter()) - 1;
736 if (!(Start <= (char*)Marker && (char*)Marker < End)) {
737 Err << "Block size in header points out of current MemoryBlock.";
738 return false;
739 }
740 if (Hdr->BlockSize != *Marker) {
741 Err << "End of block size marker (" << *Marker << ") "
742 << "and BlockSize (" << Hdr->BlockSize << ") don't match.";
743 return false;
744 }
745 }
746
747 if (LastHdr && LastHdr->ThisAllocated != Hdr->PrevAllocated) {
748 Err << "Hdr->PrevAllocated (" << Hdr->PrevAllocated << ") != "
749 << "LastHdr->ThisAllocated (" << LastHdr->ThisAllocated << ")";
750 return false;
751 } else if (!LastHdr && !Hdr->PrevAllocated) {
752 Err << "The first header should have PrevAllocated true.";
753 return false;
754 }
755
756 // Remember the last header.
757 LastHdr = Hdr;
758 }
759 }
760
761 // All invariants are preserved.
762 return true;
763}
Chris Lattner8907b4b2007-12-05 23:39:57 +0000764
Danil Malyshev30b9e322012-03-28 21:46:36 +0000765//===----------------------------------------------------------------------===//
766// getPointerToNamedFunction() implementation.
767//===----------------------------------------------------------------------===//
768
769// AtExitHandlers - List of functions to call when the program exits,
770// registered with the atexit() library function.
771static std::vector<void (*)()> AtExitHandlers;
772
773/// runAtExitHandlers - Run any functions registered by the program's
774/// calls to atexit(3), which we intercept and store in
775/// AtExitHandlers.
776///
777static void runAtExitHandlers() {
778 while (!AtExitHandlers.empty()) {
779 void (*Fn)() = AtExitHandlers.back();
780 AtExitHandlers.pop_back();
781 Fn();
782 }
783}
784
785//===----------------------------------------------------------------------===//
786// Function stubs that are invoked instead of certain library calls
787//
788// Force the following functions to be linked in to anything that uses the
789// JIT. This is a hack designed to work around the all-too-clever Glibc
790// strategy of making these functions work differently when inlined vs. when
791// not inlined, and hiding their real definitions in a separate archive file
792// that the dynamic linker can't see. For more info, search for
793// 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
Andrew Kaylor1ab60842013-11-15 17:59:43 +0000794#if defined(__linux__) && defined(__GLIBC__)
Danil Malyshev30b9e322012-03-28 21:46:36 +0000795/* stat functions are redirecting to __xstat with a version number. On x86-64
796 * linking with libc_nonshared.a and -Wl,--export-dynamic doesn't make 'stat'
797 * available as an exported symbol, so we have to add it explicitly.
798 */
799namespace {
800class StatSymbols {
801public:
802 StatSymbols() {
803 sys::DynamicLibrary::AddSymbol("stat", (void*)(intptr_t)stat);
804 sys::DynamicLibrary::AddSymbol("fstat", (void*)(intptr_t)fstat);
805 sys::DynamicLibrary::AddSymbol("lstat", (void*)(intptr_t)lstat);
806 sys::DynamicLibrary::AddSymbol("stat64", (void*)(intptr_t)stat64);
807 sys::DynamicLibrary::AddSymbol("\x1stat64", (void*)(intptr_t)stat64);
808 sys::DynamicLibrary::AddSymbol("\x1open64", (void*)(intptr_t)open64);
809 sys::DynamicLibrary::AddSymbol("\x1lseek64", (void*)(intptr_t)lseek64);
810 sys::DynamicLibrary::AddSymbol("fstat64", (void*)(intptr_t)fstat64);
811 sys::DynamicLibrary::AddSymbol("lstat64", (void*)(intptr_t)lstat64);
812 sys::DynamicLibrary::AddSymbol("atexit", (void*)(intptr_t)atexit);
813 sys::DynamicLibrary::AddSymbol("mknod", (void*)(intptr_t)mknod);
814 }
815};
816}
817static StatSymbols initStatSymbols;
818#endif // __linux__
819
820// jit_exit - Used to intercept the "exit" library call.
821static void jit_exit(int Status) {
822 runAtExitHandlers(); // Run atexit handlers...
823 exit(Status);
824}
825
826// jit_atexit - Used to intercept the "atexit" library call.
827static int jit_atexit(void (*Fn)()) {
828 AtExitHandlers.push_back(Fn); // Take note of atexit handler...
829 return 0; // Always successful
830}
831
832static int jit_noop() {
833 return 0;
834}
835
836//===----------------------------------------------------------------------===//
837//
838/// getPointerToNamedFunction - This method returns the address of the specified
839/// function by using the dynamic loader interface. As such it is only useful
840/// for resolving library symbols, not code generated symbols.
841///
842void *DefaultJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky5fe01982012-04-29 12:40:47 +0000843 bool AbortOnFailure) {
Danil Malyshev30b9e322012-03-28 21:46:36 +0000844 // Check to see if this is one of the functions we want to intercept. Note,
845 // we cast to intptr_t here to silence a -pedantic warning that complains
846 // about casting a function pointer to a normal pointer.
847 if (Name == "exit") return (void*)(intptr_t)&jit_exit;
848 if (Name == "atexit") return (void*)(intptr_t)&jit_atexit;
849
850 // We should not invoke parent's ctors/dtors from generated main()!
851 // On Mingw and Cygwin, the symbol __main is resolved to
852 // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
853 // (and register wrong callee's dtors with atexit(3)).
854 // We expect ExecutionEngine::runStaticConstructorsDestructors()
855 // is called before ExecutionEngine::runFunctionAsMain() is called.
856 if (Name == "__main") return (void*)(intptr_t)&jit_noop;
857
858 const char *NameStr = Name.c_str();
859 // If this is an asm specifier, skip the sentinal.
860 if (NameStr[0] == 1) ++NameStr;
861
862 // If it's an external function, look it up in the process image...
863 void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
864 if (Ptr) return Ptr;
865
866 // If it wasn't found and if it starts with an underscore ('_') character,
867 // try again without the underscore.
868 if (NameStr[0] == '_') {
869 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
870 if (Ptr) return Ptr;
871 }
872
873 // Darwin/PPC adds $LDBLStub suffixes to various symbols like printf. These
874 // are references to hidden visibility symbols that dlsym cannot resolve.
875 // If we have one of these, strip off $LDBLStub and try again.
876#if defined(__APPLE__) && defined(__ppc__)
877 if (Name.size() > 9 && Name[Name.size()-9] == '$' &&
878 memcmp(&Name[Name.size()-8], "LDBLStub", 8) == 0) {
879 // First try turning $LDBLStub into $LDBL128. If that fails, strip it off.
880 // This mirrors logic in libSystemStubs.a.
881 std::string Prefix = std::string(Name.begin(), Name.end()-9);
882 if (void *Ptr = getPointerToNamedFunction(Prefix+"$LDBL128", false))
883 return Ptr;
884 if (void *Ptr = getPointerToNamedFunction(Prefix, false))
885 return Ptr;
886 }
887#endif
888
889 if (AbortOnFailure) {
890 report_fatal_error("Program used external function '"+Name+
891 "' which could not be resolved!");
892 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700893 return nullptr;
Danil Malyshev30b9e322012-03-28 21:46:36 +0000894}
895
896
897
Chris Lattner8907b4b2007-12-05 23:39:57 +0000898JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
899 return new DefaultJITMemoryManager();
900}
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000901
Stephen Hines36b56882014-04-23 16:57:46 -0700902const size_t DefaultJITMemoryManager::DefaultCodeSlabSize;
903const size_t DefaultJITMemoryManager::DefaultSlabSize;
904const size_t DefaultJITMemoryManager::DefaultSizeThreshold;