blob: 3c54b581cb3ad443e3fbf1ce67e9e2096ce426b1 [file] [log] [blame]
Chris Lattner166f2262004-11-22 22:00:25 +00001//===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbd199fb2002-12-24 00:01:05 +00009//
Chris Lattner5be478f2004-11-20 03:46:14 +000010// This file defines a MachineCodeEmitter object that is used by the JIT to
11// write machine code to memory and remember where relocatable values are.
Chris Lattnerbd199fb2002-12-24 00:01:05 +000012//
13//===----------------------------------------------------------------------===//
14
Chris Lattner3785fad2003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Chris Lattner4d326fa2003-12-20 01:46:27 +000016#include "JIT.h"
Chris Lattner2c0a6a12003-11-30 04:23:21 +000017#include "llvm/Constant.h"
18#include "llvm/Module.h"
Chris Lattner5b3a4552005-03-17 15:38:16 +000019#include "llvm/Type.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000020#include "llvm/CodeGen/MachineCodeEmitter.h"
21#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000022#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman37efe672006-04-22 18:53:45 +000023#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000024#include "llvm/CodeGen/MachineRelocation.h"
Nate Begeman37efe672006-04-22 18:53:45 +000025#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000026#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000027#include "llvm/Target/TargetJITInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/Support/Debug.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000029#include "llvm/Support/MutexGuard.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000030#include "llvm/ADT/Statistic.h"
Reid Spencer52b0ba62004-09-11 04:31:03 +000031#include "llvm/System/Memory.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000032#include <algorithm>
Chris Lattnerc19aade2003-12-08 08:06:28 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Chris Lattnerbd199fb2002-12-24 00:01:05 +000035namespace {
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000036 Statistic NumBytes("jit", "Number of bytes of machine code compiled");
37 Statistic NumRelos("jit", "Number of relocations applied");
Chris Lattner4d326fa2003-12-20 01:46:27 +000038 JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000039}
Chris Lattnerbd199fb2002-12-24 00:01:05 +000040
Chris Lattner54266522004-11-20 23:57:07 +000041
42//===----------------------------------------------------------------------===//
43// JITMemoryManager code.
44//
45namespace {
Chris Lattnere993cc22006-05-11 23:08:08 +000046 /// MemoryRangeHeader - For a range of memory, this is the header that we put
47 /// on the block of memory. It is carefully crafted to be one word of memory.
48 /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
49 /// which starts with this.
50 struct FreeRangeHeader;
51 struct MemoryRangeHeader {
52 /// ThisAllocated - This is true if this block is currently allocated. If
53 /// not, this can be converted to a FreeRangeHeader.
54 intptr_t ThisAllocated : 1;
55
56 /// PrevAllocated - Keep track of whether the block immediately before us is
57 /// allocated. If not, the word immediately before this header is the size
58 /// of the previous block.
59 intptr_t PrevAllocated : 1;
60
61 /// BlockSize - This is the size in bytes of this memory block,
62 /// including this header.
63 uintptr_t BlockSize : (sizeof(intptr_t)*8 - 2);
64
65
66 /// getBlockAfter - Return the memory block immediately after this one.
67 ///
68 MemoryRangeHeader &getBlockAfter() const {
69 return *(MemoryRangeHeader*)((char*)this+BlockSize);
70 }
71
72 /// getFreeBlockBefore - If the block before this one is free, return it,
73 /// otherwise return null.
74 FreeRangeHeader *getFreeBlockBefore() const {
75 if (PrevAllocated) return 0;
76 intptr_t PrevSize = ((intptr_t *)this)[-1];
77 return (FreeRangeHeader*)((char*)this-PrevSize);
78 }
79
Chris Lattner9f3d1ba2006-05-11 23:56:57 +000080 /// FreeBlock - Turn an allocated block into a free block, adjusting
Chris Lattnere993cc22006-05-11 23:08:08 +000081 /// bits in the object headers, and adding an end of region memory block.
Chris Lattner9f3d1ba2006-05-11 23:56:57 +000082 FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
Chris Lattnere993cc22006-05-11 23:08:08 +000083
84 /// TrimAllocationToSize - If this allocated block is significantly larger
85 /// than NewSize, split it into two pieces (where the former is NewSize
86 /// bytes, including the header), and add the new block to the free list.
87 FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
88 uint64_t NewSize);
89 };
90
91 /// FreeRangeHeader - For a memory block that isn't already allocated, this
92 /// keeps track of the current block and has a pointer to the next free block.
93 /// Free blocks are kept on a circularly linked list.
94 struct FreeRangeHeader : public MemoryRangeHeader {
95 FreeRangeHeader *Prev;
96 FreeRangeHeader *Next;
97
98 /// getMinBlockSize - Get the minimum size for a memory block. Blocks
99 /// smaller than this size cannot be created.
100 static unsigned getMinBlockSize() {
101 return sizeof(FreeRangeHeader)+sizeof(intptr_t);
102 }
103
104 /// SetEndOfBlockSizeMarker - The word at the end of every free block is
105 /// known to be the size of the free block. Set it for this block.
106 void SetEndOfBlockSizeMarker() {
107 void *EndOfBlock = (char*)this + BlockSize;
108 ((intptr_t *)EndOfBlock)[-1] = BlockSize;
109 }
110
111 FreeRangeHeader *RemoveFromFreeList() {
112 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
113 Next->Prev = Prev;
114 return Prev->Next = Next;
115 }
116
117 void AddToFreeList(FreeRangeHeader *FreeList) {
118 Next = FreeList;
119 Prev = FreeList->Prev;
120 Prev->Next = this;
121 Next->Prev = this;
122 }
123
124 /// GrowBlock - The block after this block just got deallocated. Merge it
125 /// into the current block.
126 void GrowBlock(uintptr_t NewSize);
127
128 /// AllocateBlock - Mark this entire block allocated, updating freelists
129 /// etc. This returns a pointer to the circular free-list.
130 FreeRangeHeader *AllocateBlock();
131 };
132}
133
134
135/// AllocateBlock - Mark this entire block allocated, updating freelists
136/// etc. This returns a pointer to the circular free-list.
137FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
138 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
139 "Cannot allocate an allocated block!");
140 // Mark this block allocated.
141 ThisAllocated = 1;
142 getBlockAfter().PrevAllocated = 1;
143
144 // Remove it from the free list.
145 return RemoveFromFreeList();
146}
147
Chris Lattner9f3d1ba2006-05-11 23:56:57 +0000148/// FreeBlock - Turn an allocated block into a free block, adjusting
Chris Lattnere993cc22006-05-11 23:08:08 +0000149/// bits in the object headers, and adding an end of region memory block.
150/// If possible, coallesce this block with neighboring blocks. Return the
Chris Lattner9f3d1ba2006-05-11 23:56:57 +0000151/// FreeRangeHeader to allocate from.
152FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000153 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
154 assert(ThisAllocated && "This block is already allocated!");
155 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
156
Chris Lattner9f3d1ba2006-05-11 23:56:57 +0000157 FreeRangeHeader *FreeListToReturn = FreeList;
158
Chris Lattnere993cc22006-05-11 23:08:08 +0000159 // If the block after this one is free, merge it into this block.
160 if (!FollowingBlock->ThisAllocated) {
161 FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
Chris Lattner9f3d1ba2006-05-11 23:56:57 +0000162 // "FreeList" always needs to be a valid free block. If we're about to
163 // coallesce with it, update our notion of what the free list is.
164 if (&FollowingFreeBlock == FreeList) {
165 FreeList = FollowingFreeBlock.Next;
166 FreeListToReturn = 0;
167 assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
168 }
Chris Lattnere993cc22006-05-11 23:08:08 +0000169 FollowingFreeBlock.RemoveFromFreeList();
170
171 // Include the following block into this one.
172 BlockSize += FollowingFreeBlock.BlockSize;
173 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
174
175 // Tell the block after the block we are coallescing that this block is
176 // allocated.
177 FollowingBlock->PrevAllocated = 1;
178 }
179
180 assert(FollowingBlock->ThisAllocated && "Missed coallescing?");
181
182 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
183 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
Chris Lattner9f3d1ba2006-05-11 23:56:57 +0000184 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
Chris Lattnere993cc22006-05-11 23:08:08 +0000185 }
186
187 // Otherwise, mark this block free.
188 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
189 FollowingBlock->PrevAllocated = 0;
190 FreeBlock.ThisAllocated = 0;
191
192 // Link this into the linked list of free blocks.
193 FreeBlock.AddToFreeList(FreeList);
194
195 // Add a marker at the end of the block, indicating the size of this free
196 // block.
197 FreeBlock.SetEndOfBlockSizeMarker();
Chris Lattner9f3d1ba2006-05-11 23:56:57 +0000198 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
Chris Lattnere993cc22006-05-11 23:08:08 +0000199}
200
201/// GrowBlock - The block after this block just got deallocated. Merge it
202/// into the current block.
203void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
204 assert(NewSize > BlockSize && "Not growing block?");
205 BlockSize = NewSize;
206 SetEndOfBlockSizeMarker();
Chris Lattner9f3d1ba2006-05-11 23:56:57 +0000207 getBlockAfter().PrevAllocated = 0;
Chris Lattnere993cc22006-05-11 23:08:08 +0000208}
209
210/// TrimAllocationToSize - If this allocated block is significantly larger
211/// than NewSize, split it into two pieces (where the former is NewSize
212/// bytes, including the header), and add the new block to the free list.
213FreeRangeHeader *MemoryRangeHeader::
214TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
215 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
216 "Cannot deallocate part of an allocated block!");
217
218 // Round up size for alignment of header.
219 unsigned HeaderAlign = __alignof(FreeRangeHeader);
220 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
221
222 // Size is now the size of the block we will remove from the start of the
223 // current block.
224 assert(NewSize <= BlockSize &&
225 "Allocating more space from this block than exists!");
226
227 // If splitting this block will cause the remainder to be too small, do not
228 // split the block.
229 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
230 return FreeList;
231
232 // Otherwise, we splice the required number of bytes out of this block, form
233 // a new block immediately after it, then mark this block allocated.
234 MemoryRangeHeader &FormerNextBlock = getBlockAfter();
235
236 // Change the size of this block.
237 BlockSize = NewSize;
238
239 // Get the new block we just sliced out and turn it into a free block.
240 FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
241 NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
242 NewNextBlock.ThisAllocated = 0;
243 NewNextBlock.PrevAllocated = 1;
244 NewNextBlock.SetEndOfBlockSizeMarker();
245 FormerNextBlock.PrevAllocated = 0;
246 NewNextBlock.AddToFreeList(FreeList);
247 return &NewNextBlock;
248}
249
250
251namespace {
Chris Lattner688506d2003-08-14 18:35:27 +0000252 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
253 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
254 /// sections, one for function stubs, one for the functions themselves. We
255 /// have to do this because we may need to emit a function stub while in the
256 /// middle of emitting a function, and we don't know how large the function we
257 /// are emitting is. This never bothers to release the memory, because when
258 /// we are ready to destroy the JIT, the program exits.
259 class JITMemoryManager {
Chris Lattnere6fdcbf2006-05-03 00:54:49 +0000260 std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
Chris Lattnere993cc22006-05-11 23:08:08 +0000261 FreeRangeHeader *FreeMemoryList; // Circular list of free blocks.
262
263 // When emitting code into a memory block, this is the block.
264 MemoryRangeHeader *CurBlock;
265
266 unsigned char *CurStubPtr, *StubBase;
Chris Lattnera726c7f2006-05-02 21:44:14 +0000267 unsigned char *GOTBase; // Target Specific reserved memory
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000268
Chris Lattnere993cc22006-05-11 23:08:08 +0000269 // Centralize memory block allocation.
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000270 sys::MemoryBlock getNewMemoryBlock(unsigned size);
Chris Lattnere993cc22006-05-11 23:08:08 +0000271
272 std::map<const Function*, MemoryRangeHeader*> FunctionBlocks;
Chris Lattner688506d2003-08-14 18:35:27 +0000273 public:
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000274 JITMemoryManager(bool useGOT);
Reid Spencer4af3da62004-12-13 16:04:04 +0000275 ~JITMemoryManager();
Misha Brukmanf976c852005-04-21 22:55:34 +0000276
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000277 inline unsigned char *allocateStub(unsigned StubSize, unsigned Alignment);
Chris Lattnere993cc22006-05-11 23:08:08 +0000278
279 /// startFunctionBody - When a function starts, allocate a block of free
280 /// executable memory, returning a pointer to it and its actual size.
281 unsigned char *startFunctionBody(uintptr_t &ActualSize) {
282 CurBlock = FreeMemoryList;
283
284 // Allocate the entire memory block.
285 FreeMemoryList = FreeMemoryList->AllocateBlock();
286 ActualSize = CurBlock->BlockSize-sizeof(MemoryRangeHeader);
287 return (unsigned char *)(CurBlock+1);
288 }
289
290 /// endFunctionBody - The function F is now allocated, and takes the memory
291 /// in the range [FunctionStart,FunctionEnd).
292 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
293 unsigned char *FunctionEnd) {
294 assert(FunctionEnd > FunctionStart);
295 assert(FunctionStart == (unsigned char *)(CurBlock+1) &&
296 "Mismatched function start/end!");
297
298 uintptr_t BlockSize = FunctionEnd - (unsigned char *)CurBlock;
299 FunctionBlocks[F] = CurBlock;
300
301 // Release the memory at the end of this block that isn't needed.
302 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
303 }
Chris Lattnera726c7f2006-05-02 21:44:14 +0000304
305 unsigned char *getGOTBase() const {
306 return GOTBase;
307 }
308 bool isManagingGOT() const {
309 return GOTBase != NULL;
310 }
Chris Lattnere993cc22006-05-11 23:08:08 +0000311
312 /// deallocateMemForFunction - Deallocate all memory for the specified
313 /// function body.
314 void deallocateMemForFunction(const Function *F) {
Chris Lattner9f3d1ba2006-05-11 23:56:57 +0000315 std::map<const Function*, MemoryRangeHeader*>::iterator
316 I = FunctionBlocks.find(F);
317 if (I == FunctionBlocks.end()) return;
Chris Lattnere993cc22006-05-11 23:08:08 +0000318
Chris Lattner9f3d1ba2006-05-11 23:56:57 +0000319 // Find the block that is allocated for this function.
320 MemoryRangeHeader *MemRange = I->second;
321 assert(MemRange->ThisAllocated && "Block isn't allocated!");
322
Chris Lattnera5f04192006-05-12 00:03:12 +0000323 // Fill the buffer with garbage!
324 DEBUG(memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange)));
325
Chris Lattner9f3d1ba2006-05-11 23:56:57 +0000326 // Free the memory.
327 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
328
329 // Finally, remove this entry from FunctionBlocks.
330 FunctionBlocks.erase(I);
Chris Lattnere993cc22006-05-11 23:08:08 +0000331 }
Chris Lattner688506d2003-08-14 18:35:27 +0000332 };
333}
334
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000335JITMemoryManager::JITMemoryManager(bool useGOT) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000336 // Allocate a 16M block of memory for functions.
337 sys::MemoryBlock MemBlock = getNewMemoryBlock(16 << 20);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000338
Chris Lattnere993cc22006-05-11 23:08:08 +0000339 unsigned char *MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
Chris Lattner281a6012005-01-10 18:23:22 +0000340
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000341 // Allocate stubs backwards from the base, allocate functions forward
342 // from the base.
Chris Lattnere993cc22006-05-11 23:08:08 +0000343 StubBase = MemBase;
344 CurStubPtr = MemBase + 512*1024; // Use 512k for stubs, working backwards.
345
346 // We set up the memory chunk with 4 mem regions, like this:
347 // [ START
348 // [ Free #0 ] -> Large space to allocate functions from.
349 // [ Allocated #1 ] -> Tiny space to separate regions.
350 // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
351 // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
352 // END ]
353 //
354 // The last three blocks are never deallocated or touched.
355
356 // Add MemoryRangeHeader to the end of the memory region, indicating that
357 // the space after the block of memory is allocated. This is block #3.
358 MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
359 Mem3->ThisAllocated = 1;
360 Mem3->PrevAllocated = 0;
361 Mem3->BlockSize = 0;
362
363 /// Add a tiny free region so that the free list always has one entry.
364 FreeRangeHeader *Mem2 =
365 (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
366 Mem2->ThisAllocated = 0;
367 Mem2->PrevAllocated = 1;
368 Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
369 Mem2->SetEndOfBlockSizeMarker();
370 Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
371 Mem2->Next = Mem2;
372
373 /// Add a tiny allocated region so that Mem2 is never coallesced away.
374 MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
Chris Lattner9f3d1ba2006-05-11 23:56:57 +0000375 Mem1->ThisAllocated = 1;
376 Mem1->PrevAllocated = 0;
377 Mem1->BlockSize = (char*)Mem2 - (char*)Mem1;
Chris Lattnere993cc22006-05-11 23:08:08 +0000378
379 // Add a FreeRangeHeader to the start of the function body region, indicating
380 // that the space is free. Mark the previous block allocated so we never look
381 // at it.
382 FreeRangeHeader *Mem0 = (FreeRangeHeader*)CurStubPtr;
383 Mem0->ThisAllocated = 0;
384 Mem0->PrevAllocated = 1;
Chris Lattner9f3d1ba2006-05-11 23:56:57 +0000385 Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
Chris Lattnere993cc22006-05-11 23:08:08 +0000386 Mem0->SetEndOfBlockSizeMarker();
387 Mem0->AddToFreeList(Mem2);
388
389 // Start out with the freelist pointing to Mem0.
390 FreeMemoryList = Mem0;
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000391
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000392 // Allocate the GOT.
Andrew Lenharth2b3b89c2005-08-01 17:35:40 +0000393 GOTBase = NULL;
Chris Lattnerbbea1242006-05-12 18:10:12 +0000394 if (useGOT) GOTBase = new unsigned char[sizeof(void*) * 8192];
Chris Lattner688506d2003-08-14 18:35:27 +0000395}
396
Reid Spencer4af3da62004-12-13 16:04:04 +0000397JITMemoryManager::~JITMemoryManager() {
Chris Lattnere6fdcbf2006-05-03 00:54:49 +0000398 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
399 sys::Memory::ReleaseRWX(Blocks[i]);
Chris Lattnerbbea1242006-05-12 18:10:12 +0000400
401 delete[] GOTBase;
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000402 Blocks.clear();
Reid Spencer4af3da62004-12-13 16:04:04 +0000403}
404
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000405unsigned char *JITMemoryManager::allocateStub(unsigned StubSize,
406 unsigned Alignment) {
Chris Lattner688506d2003-08-14 18:35:27 +0000407 CurStubPtr -= StubSize;
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000408 CurStubPtr = (unsigned char*)(((intptr_t)CurStubPtr) &
409 ~(intptr_t)(Alignment-1));
Chris Lattnere993cc22006-05-11 23:08:08 +0000410 if (CurStubPtr < StubBase) {
Chris Lattnera726c7f2006-05-02 21:44:14 +0000411 // FIXME: allocate a new block
Bill Wendling832171c2006-12-07 20:04:42 +0000412 cerr << "JIT ran out of memory for function stubs!\n";
Chris Lattner688506d2003-08-14 18:35:27 +0000413 abort();
414 }
415 return CurStubPtr;
416}
417
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000418sys::MemoryBlock JITMemoryManager::getNewMemoryBlock(unsigned size) {
Chris Lattnerc1780d22006-07-07 17:31:41 +0000419 // Allocate a new block close to the last one.
420 const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.front();
421 std::string ErrMsg;
422 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld, &ErrMsg);
423 if (B.base() == 0) {
Bill Wendling832171c2006-12-07 20:04:42 +0000424 cerr << "Allocation failed when allocating new memory in the JIT\n";
425 cerr << ErrMsg << "\n";
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000426 abort();
427 }
Chris Lattnerc1780d22006-07-07 17:31:41 +0000428 Blocks.push_back(B);
429 return B;
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000430}
431
Chris Lattner54266522004-11-20 23:57:07 +0000432//===----------------------------------------------------------------------===//
433// JIT lazy compilation code.
434//
435namespace {
Reid Spenceree448632005-07-12 15:51:55 +0000436 class JITResolverState {
437 private:
438 /// FunctionToStubMap - Keep track of the stub created for a particular
439 /// function so that we can reuse them if necessary.
440 std::map<Function*, void*> FunctionToStubMap;
441
442 /// StubToFunctionMap - Keep track of the function that each stub
443 /// corresponds to.
444 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +0000445
Reid Spenceree448632005-07-12 15:51:55 +0000446 public:
447 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
448 assert(locked.holds(TheJIT->lock));
449 return FunctionToStubMap;
450 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000451
Reid Spenceree448632005-07-12 15:51:55 +0000452 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
453 assert(locked.holds(TheJIT->lock));
454 return StubToFunctionMap;
455 }
456 };
Jeff Cohen00b168892005-07-27 06:12:32 +0000457
Chris Lattner54266522004-11-20 23:57:07 +0000458 /// JITResolver - Keep track of, and resolve, call sites for functions that
459 /// have not yet been compiled.
460 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +0000461 /// MCE - The MachineCodeEmitter to use to emit stubs with.
Chris Lattner54266522004-11-20 23:57:07 +0000462 MachineCodeEmitter &MCE;
463
Chris Lattner5e225582004-11-21 03:37:42 +0000464 /// LazyResolverFn - The target lazy resolver function that we actually
465 /// rewrite instructions to use.
466 TargetJITInfo::LazyResolverFn LazyResolverFn;
467
Reid Spenceree448632005-07-12 15:51:55 +0000468 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000469
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000470 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
471 /// external functions.
472 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000473
474 //map addresses to indexes in the GOT
475 std::map<void*, unsigned> revGOTMap;
476 unsigned nextGOTIndex;
477
Chris Lattner54266522004-11-20 23:57:07 +0000478 public:
Andrew Lenharth6a974612005-07-28 12:44:13 +0000479 JITResolver(MachineCodeEmitter &mce) : MCE(mce), nextGOTIndex(0) {
Chris Lattner5e225582004-11-21 03:37:42 +0000480 LazyResolverFn =
481 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
482 }
Chris Lattner54266522004-11-20 23:57:07 +0000483
484 /// getFunctionStub - This returns a pointer to a function stub, creating
485 /// one on demand as needed.
486 void *getFunctionStub(Function *F);
487
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000488 /// getExternalFunctionStub - Return a stub for the function at the
489 /// specified address, created lazily on demand.
490 void *getExternalFunctionStub(void *FnAddr);
491
Chris Lattner5e225582004-11-21 03:37:42 +0000492 /// AddCallbackAtLocation - If the target is capable of rewriting an
493 /// instruction without the use of a stub, record the location of the use so
494 /// we know which function is being used at the location.
495 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000496 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000497 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000498 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000499 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000500 }
501
Andrew Lenharth6a974612005-07-28 12:44:13 +0000502 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
503 /// and address. This function only manages slots, it does not manage the
504 /// contents of the slots or the memory associated with the GOT.
505 unsigned getGOTIndexForAddr(void* addr);
506
Chris Lattner54266522004-11-20 23:57:07 +0000507 /// JITCompilerFn - This function is called to resolve a stub to a compiled
508 /// address. If the LLVM Function corresponding to the stub has not yet
509 /// been compiled, this function compiles it first.
510 static void *JITCompilerFn(void *Stub);
511 };
512}
513
514/// getJITResolver - This function returns the one instance of the JIT resolver.
515///
516static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
517 static JITResolver TheJITResolver(*MCE);
518 return TheJITResolver;
519}
520
Evan Cheng55b50532006-07-27 06:33:55 +0000521#if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
522 defined(__APPLE__)
523extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
524#endif
525
526/// synchronizeICache - On some targets, the JIT emitted code must be
527/// explicitly refetched to ensure correct execution.
528static void synchronizeICache(const void *Addr, size_t len) {
529#if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
530 defined(__APPLE__)
Jim Laskey2e9f3682006-07-27 13:40:34 +0000531 sys_icache_invalidate(Addr, len);
Evan Cheng55b50532006-07-27 06:33:55 +0000532#endif
533}
534
Chris Lattner54266522004-11-20 23:57:07 +0000535/// getFunctionStub - This returns a pointer to a function stub, creating
536/// one on demand as needed.
537void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000538 MutexGuard locked(TheJIT->lock);
539
Chris Lattner54266522004-11-20 23:57:07 +0000540 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000541 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000542 if (Stub) return Stub;
543
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000544 // Call the lazy resolver function unless we already KNOW it is an external
545 // function, in which case we just skip the lazy resolution step.
Chris Lattner870286a2006-06-01 17:29:22 +0000546 void *Actual = (void*)(intptr_t)LazyResolverFn;
Chris Lattnerc6336272006-09-15 04:56:11 +0000547 if (F->isExternal() && !F->hasNotBeenReadFromBytecode())
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000548 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000549
Chris Lattner54266522004-11-20 23:57:07 +0000550 // Otherwise, codegen a new stub. For now, the stub will call the lazy
551 // resolver function.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000552 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
553
Chris Lattner870286a2006-06-01 17:29:22 +0000554 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000555 // If we are getting the stub for an external function, we really want the
556 // address of the stub in the GlobalAddressMap for the JIT, not the address
557 // of the external function.
558 TheJIT->updateGlobalMapping(F, Stub);
559 }
Chris Lattner54266522004-11-20 23:57:07 +0000560
Evan Cheng55fc2802006-07-25 20:40:54 +0000561 // Invalidate the icache if necessary.
Evan Cheng55b50532006-07-27 06:33:55 +0000562 synchronizeICache(Stub, MCE.getCurrentPCValue()-(intptr_t)Stub);
Evan Cheng55fc2802006-07-25 20:40:54 +0000563
Bill Wendling832171c2006-12-07 20:04:42 +0000564 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
565 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000566
Chris Lattner54266522004-11-20 23:57:07 +0000567 // Finally, keep track of the stub-to-Function mapping so that the
568 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000569 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000570 return Stub;
571}
572
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000573/// getExternalFunctionStub - Return a stub for the function at the
574/// specified address, created lazily on demand.
575void *JITResolver::getExternalFunctionStub(void *FnAddr) {
576 // If we already have a stub for this function, recycle it.
577 void *&Stub = ExternalFnToStubMap[FnAddr];
578 if (Stub) return Stub;
579
580 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
Evan Cheng55fc2802006-07-25 20:40:54 +0000581
582 // Invalidate the icache if necessary.
Evan Cheng55b50532006-07-27 06:33:55 +0000583 synchronizeICache(Stub, MCE.getCurrentPCValue()-(intptr_t)Stub);
Evan Cheng55fc2802006-07-25 20:40:54 +0000584
Bill Wendling832171c2006-12-07 20:04:42 +0000585 DOUT << "JIT: Stub emitted at [" << Stub
586 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000587 return Stub;
588}
589
Andrew Lenharth6a974612005-07-28 12:44:13 +0000590unsigned JITResolver::getGOTIndexForAddr(void* addr) {
591 unsigned idx = revGOTMap[addr];
592 if (!idx) {
593 idx = ++nextGOTIndex;
594 revGOTMap[addr] = idx;
Bill Wendling832171c2006-12-07 20:04:42 +0000595 DOUT << "Adding GOT entry " << idx
596 << " for addr " << addr << "\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000597 // ((void**)MemMgr.getGOTBase())[idx] = addr;
598 }
599 return idx;
600}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000601
Chris Lattner54266522004-11-20 23:57:07 +0000602/// JITCompilerFn - This function is called when a lazy compilation stub has
603/// been entered. It looks up which function this stub corresponds to, compiles
604/// it if necessary, then returns the resultant function pointer.
605void *JITResolver::JITCompilerFn(void *Stub) {
606 JITResolver &JR = getJITResolver();
Misha Brukmanf976c852005-04-21 22:55:34 +0000607
Reid Spenceree448632005-07-12 15:51:55 +0000608 MutexGuard locked(TheJIT->lock);
609
Chris Lattner54266522004-11-20 23:57:07 +0000610 // The address given to us for the stub may not be exactly right, it might be
611 // a little bit after the stub. As such, use upper_bound to find it.
612 std::map<void*, Function*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000613 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
Chris Lattner21998772006-01-07 06:20:51 +0000614 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
615 "This is not a known stub!");
Chris Lattner54266522004-11-20 23:57:07 +0000616 Function *F = (--I)->second;
617
Chris Lattner9cab56d2006-11-09 19:32:13 +0000618 // If disabled, emit a useful error message and abort.
619 if (TheJIT->isLazyCompilationDisabled()) {
Bill Wendling832171c2006-12-07 20:04:42 +0000620 cerr << "LLVM JIT requested to do lazy compilation of function '"
621 << F->getName() << "' when lazy compiles are disabled!\n";
Chris Lattner9cab56d2006-11-09 19:32:13 +0000622 abort();
623 }
624
Reid Spenceree448632005-07-12 15:51:55 +0000625 // We might like to remove the stub from the StubToFunction map.
626 // We can't do that! Multiple threads could be stuck, waiting to acquire the
627 // lock above. As soon as the 1st function finishes compiling the function,
Chris Lattner21998772006-01-07 06:20:51 +0000628 // the next one will be released, and needs to be able to find the function it
629 // needs to call.
Reid Spenceree448632005-07-12 15:51:55 +0000630 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000631
Bill Wendling832171c2006-12-07 20:04:42 +0000632 DOUT << "JIT: Lazily resolving function '" << F->getName()
633 << "' In stub ptr = " << Stub << " actual ptr = "
634 << I->first << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000635
636 void *Result = TheJIT->getPointerToFunction(F);
637
638 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000639 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000640
641 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000642
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000643 // What we will do is set the compiled function address to map to the
644 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000645 // if they see it still using the stub address.
646 // Note: this is done so the Resolver doesn't have to manage GOT memory
647 // Do this without allocating map space if the target isn't using a GOT
648 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
649 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
650
Chris Lattner54266522004-11-20 23:57:07 +0000651 return Result;
652}
Chris Lattner688506d2003-08-14 18:35:27 +0000653
654
Chris Lattner54266522004-11-20 23:57:07 +0000655//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000656// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000657//
Chris Lattner688506d2003-08-14 18:35:27 +0000658namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000659 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
660 /// used to output functions to memory for execution.
661 class JITEmitter : public MachineCodeEmitter {
Chris Lattner688506d2003-08-14 18:35:27 +0000662 JITMemoryManager MemMgr;
663
Chris Lattner6125fdd2003-05-09 03:30:07 +0000664 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000665 // save BufferBegin/BufferEnd/CurBufferPtr here.
666 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000667
Chris Lattner5be478f2004-11-20 03:46:14 +0000668 /// Relocations - These are the relocations that the function needs, as
669 /// emitted.
670 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000671
672 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
673 /// It is filled in by the StartMachineBasicBlock callback and queried by
674 /// the getMachineBasicBlockAddress callback.
675 std::vector<intptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000676
Chris Lattner239862c2006-02-09 04:49:59 +0000677 /// ConstantPool - The constant pool for the current function.
678 ///
679 MachineConstantPool *ConstantPool;
680
681 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
682 ///
683 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000684
Nate Begeman019f8512006-09-10 23:03:44 +0000685 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000686 ///
687 MachineJumpTableInfo *JumpTable;
688
689 /// JumpTableBase - A pointer to the first entry in the jump table.
690 ///
691 void *JumpTableBase;
692public:
Chris Lattner239862c2006-02-09 04:49:59 +0000693 JITEmitter(JIT &jit) : MemMgr(jit.getJITInfo().needsGOT()) {
Jeff Cohen00b168892005-07-27 06:12:32 +0000694 TheJIT = &jit;
Bill Wendling832171c2006-12-07 20:04:42 +0000695 if (MemMgr.isManagingGOT()) DOUT << "JIT is managing a GOT\n";
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000696 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000697
698 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000699 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000700
701 void emitConstantPool(MachineConstantPool *MCP);
702 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerb4432f32006-05-03 17:10:41 +0000703 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000704
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000705 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1);
Chris Lattner54266522004-11-20 23:57:07 +0000706 virtual void* finishFunctionStub(const Function *F);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000707
Chris Lattner5be478f2004-11-20 03:46:14 +0000708 virtual void addRelocation(const MachineRelocation &MR) {
709 Relocations.push_back(MR);
710 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000711
712 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
713 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
714 MBBLocations.resize((MBB->getNumber()+1)*2);
715 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
716 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000717
Chris Lattnerb4432f32006-05-03 17:10:41 +0000718 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
719 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
720
721 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
722 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
723 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
724 return MBBLocations[MBB->getNumber()];
725 }
726
Chris Lattnere993cc22006-05-11 23:08:08 +0000727 /// deallocateMemForFunction - Deallocate all memory for the specified
728 /// function body.
729 void deallocateMemForFunction(Function *F) {
730 MemMgr.deallocateMemForFunction(F);
731 }
Chris Lattner54266522004-11-20 23:57:07 +0000732 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000733 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000734 };
735}
736
Chris Lattner166f2262004-11-22 22:00:25 +0000737void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
738 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000739 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
740 /// FIXME: If we straightened things out, this could actually emit the
741 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000742 return TheJIT->getOrEmitGlobalVariable(GV);
743 }
744
745 // If we have already compiled the function, return a pointer to its body.
746 Function *F = cast<Function>(V);
747 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
748 if (ResultPtr) return ResultPtr;
749
Chris Lattnerc6336272006-09-15 04:56:11 +0000750 if (F->isExternal() && !F->hasNotBeenReadFromBytecode()) {
Chris Lattner54266522004-11-20 23:57:07 +0000751 // If this is an external function pointer, we can force the JIT to
752 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000753 if (DoesntNeedStub)
754 return TheJIT->getPointerToFunction(F);
755
756 return getJITResolver(this).getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000757 }
758
Chris Lattner5e225582004-11-21 03:37:42 +0000759 // Okay, the function has not been compiled yet, if the target callback
760 // mechanism is capable of rewriting the instruction directly, prefer to do
761 // that instead of emitting a stub.
762 if (DoesntNeedStub)
763 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
764
Chris Lattner54266522004-11-20 23:57:07 +0000765 // Otherwise, we have to emit a lazy resolving stub.
766 return getJITResolver(this).getFunctionStub(F);
767}
768
Chris Lattner166f2262004-11-22 22:00:25 +0000769void JITEmitter::startFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000770 uintptr_t ActualSize;
771 BufferBegin = CurBufferPtr = MemMgr.startFunctionBody(ActualSize);
772 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000773
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000774 // Ensure the constant pool/jump table info is at least 4-byte aligned.
775 emitAlignment(16);
776
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000777 emitConstantPool(F.getConstantPool());
778 initJumpTableInfo(F.getJumpTableInfo());
779
780 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000781 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000782 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +0000783
Chris Lattnerb4432f32006-05-03 17:10:41 +0000784 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000785}
786
Chris Lattner43b429b2006-05-02 18:27:26 +0000787bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000788 if (CurBufferPtr == BufferEnd) {
789 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +0000790 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +0000791 abort();
792 }
793
Chris Lattnerb4432f32006-05-03 17:10:41 +0000794 emitJumpTableInfo(F.getJumpTableInfo());
795
Chris Lattnera8279532006-06-16 18:09:26 +0000796 // FnStart is the start of the text, not the start of the constant pool and
797 // other per-function data.
798 unsigned char *FnStart =
799 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
800 unsigned char *FnEnd = CurBufferPtr;
801
802 MemMgr.endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
803 NumBytes += FnEnd-FnStart;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000804
Chris Lattner5be478f2004-11-20 03:46:14 +0000805 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000806 NumRelos += Relocations.size();
807
Chris Lattner5be478f2004-11-20 03:46:14 +0000808 // Resolve the relocations to concrete pointers.
809 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
810 MachineRelocation &MR = Relocations[i];
811 void *ResultPtr;
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000812 if (MR.isString()) {
Chris Lattner5be478f2004-11-20 03:46:14 +0000813 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000814
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000815 // If the target REALLY wants a stub for this function, emit it now.
816 if (!MR.doesntNeedFunctionStub())
817 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000818 } else if (MR.isGlobalValue()) {
Chris Lattner5e225582004-11-21 03:37:42 +0000819 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
Chris Lattner43b429b2006-05-02 18:27:26 +0000820 BufferBegin+MR.getMachineCodeOffset(),
Chris Lattner5e225582004-11-21 03:37:42 +0000821 MR.doesntNeedFunctionStub());
Evan Chengf141cc42006-07-27 18:21:10 +0000822 } else if (MR.isBasicBlock()) {
823 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
Evan Cheng52b510b2006-06-23 01:02:37 +0000824 } else if (MR.isConstantPoolIndex()){
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000825 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Evan Cheng52b510b2006-06-23 01:02:37 +0000826 } else {
827 assert(MR.isJumpTableIndex());
828 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000829 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000830
Chris Lattner5be478f2004-11-20 03:46:14 +0000831 MR.setResultPointer(ResultPtr);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000832
Andrew Lenharth6a974612005-07-28 12:44:13 +0000833 // if we are managing the GOT and the relocation wants an index,
834 // give it one
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000835 if (MemMgr.isManagingGOT() && MR.isGOTRelative()) {
Andrew Lenharth6a974612005-07-28 12:44:13 +0000836 unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
837 MR.setGOTIndex(idx);
838 if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
Bill Wendling832171c2006-12-07 20:04:42 +0000839 DOUT << "GOT was out of date for " << ResultPtr
840 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx]
841 << "\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000842 ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
843 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000844 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000845 }
846
Chris Lattner43b429b2006-05-02 18:27:26 +0000847 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000848 Relocations.size(), MemMgr.getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000849 }
850
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000851 // Update the GOT entry for F to point to the new code.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000852 if(MemMgr.isManagingGOT()) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000853 unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)BufferBegin);
854 if (((void**)MemMgr.getGOTBase())[idx] != (void*)BufferBegin) {
Bill Wendling832171c2006-12-07 20:04:42 +0000855 DOUT << "GOT was out of date for " << (void*)BufferBegin
856 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n";
Chris Lattner43b429b2006-05-02 18:27:26 +0000857 ((void**)MemMgr.getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000858 }
859 }
860
Evan Cheng55fc2802006-07-25 20:40:54 +0000861 // Invalidate the icache if necessary.
Evan Cheng55b50532006-07-27 06:33:55 +0000862 synchronizeICache(FnStart, FnEnd-FnStart);
Evan Cheng55fc2802006-07-25 20:40:54 +0000863
Bill Wendling832171c2006-12-07 20:04:42 +0000864 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
865 << "] Function: " << F.getFunction()->getName()
866 << ": " << (FnEnd-FnStart) << " bytes of text, "
867 << Relocations.size() << " relocations\n";
Chris Lattner5be478f2004-11-20 03:46:14 +0000868 Relocations.clear();
Chris Lattner43b429b2006-05-02 18:27:26 +0000869 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000870}
871
Chris Lattner166f2262004-11-22 22:00:25 +0000872void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Chris Lattnerfa77d432006-02-09 04:22:52 +0000873 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000874 if (Constants.empty()) return;
875
Evan Chengcd5731d2006-09-12 20:59:59 +0000876 MachineConstantPoolEntry CPE = Constants.back();
877 unsigned Size = CPE.Offset;
878 const Type *Ty = CPE.isMachineConstantPoolEntry()
Chris Lattner8a650092006-09-13 16:21:10 +0000879 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Evan Chengcd5731d2006-09-12 20:59:59 +0000880 Size += TheJIT->getTargetData()->getTypeSize(Ty);
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000881
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000882 ConstantPoolBase = allocateSpace(Size, 1 << MCP->getConstantPoolAlignment());
Chris Lattner239862c2006-02-09 04:49:59 +0000883 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000884
885 if (ConstantPoolBase == 0) return; // Buffer overflow.
886
Chris Lattner239862c2006-02-09 04:49:59 +0000887 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +0000888 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +0000889 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Evan Chengcd5731d2006-09-12 20:59:59 +0000890 if (Constants[i].isMachineConstantPoolEntry()) {
891 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +0000892 cerr << "Initialize memory with machine specific constant pool entry"
893 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +0000894 abort();
895 }
896 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000897 }
898}
899
Nate Begeman37efe672006-04-22 18:53:45 +0000900void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
901 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
902 if (JT.empty()) return;
903
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000904 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +0000905 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000906 NumEntries += JT[i].MBBs.size();
907
908 unsigned EntrySize = MJTI->getEntrySize();
909
Nate Begeman37efe672006-04-22 18:53:45 +0000910 // Just allocate space for all the jump tables now. We will fix up the actual
911 // MBB entries in the tables after we emit the code for each block, since then
912 // we will know the final locations of the MBBs in memory.
913 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000914 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +0000915}
916
Chris Lattnerb4432f32006-05-03 17:10:41 +0000917void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Nate Begeman37efe672006-04-22 18:53:45 +0000918 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000919 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +0000920
Chris Lattner32ca55f2006-05-03 00:13:06 +0000921 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
Nate Begeman37efe672006-04-22 18:53:45 +0000922
923 // For each jump table, map each target in the jump table to the address of
924 // an emitted MachineBasicBlock.
Chris Lattner32ca55f2006-05-03 00:13:06 +0000925 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
926
Nate Begeman37efe672006-04-22 18:53:45 +0000927 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
928 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Chris Lattner32ca55f2006-05-03 00:13:06 +0000929 // Store the address of the basic block for this jump table slot in the
930 // memory we allocated for the jump table in 'initJumpTableInfo'
931 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
Chris Lattnerb4432f32006-05-03 17:10:41 +0000932 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
Nate Begeman37efe672006-04-22 18:53:45 +0000933 }
934}
935
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000936void JITEmitter::startFunctionStub(unsigned StubSize, unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000937 SavedBufferBegin = BufferBegin;
938 SavedBufferEnd = BufferEnd;
939 SavedCurBufferPtr = CurBufferPtr;
940
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000941 BufferBegin = CurBufferPtr = MemMgr.allocateStub(StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +0000942 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +0000943}
944
Chris Lattner166f2262004-11-22 22:00:25 +0000945void *JITEmitter::finishFunctionStub(const Function *F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000946 NumBytes += getCurrentPCOffset();
947 std::swap(SavedBufferBegin, BufferBegin);
948 BufferEnd = SavedBufferEnd;
949 CurBufferPtr = SavedCurBufferPtr;
950 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000951}
952
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000953// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
954// in the constant pool that was last emitted with the 'emitConstantPool'
955// method.
956//
Chris Lattnerb4432f32006-05-03 17:10:41 +0000957intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +0000958 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +0000959 "Invalid ConstantPoolIndex!");
Chris Lattner239862c2006-02-09 04:49:59 +0000960 return (intptr_t)ConstantPoolBase +
961 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000962}
963
Nate Begeman37efe672006-04-22 18:53:45 +0000964// getJumpTableEntryAddress - Return the address of the JumpTable with index
965// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
966//
Chris Lattnerb4432f32006-05-03 17:10:41 +0000967intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +0000968 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
969 assert(Index < JT.size() && "Invalid jump table index!");
970
971 unsigned Offset = 0;
972 unsigned EntrySize = JumpTable->getEntrySize();
973
974 for (unsigned i = 0; i < Index; ++i)
975 Offset += JT[i].MBBs.size() * EntrySize;
976
Nate Begemanc34b2272006-04-25 17:46:32 +0000977 return (intptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +0000978}
979
Chris Lattnere993cc22006-05-11 23:08:08 +0000980//===----------------------------------------------------------------------===//
981// Public interface to this file
982//===----------------------------------------------------------------------===//
983
984MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
985 return new JITEmitter(jit);
986}
987
Misha Brukmand69c1e62003-07-28 19:09:06 +0000988// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000989// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000990// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
991// need to resolve function(s) that are being mis-codegenerated, so we need to
992// resolve their addresses at runtime, and this is the way to do it.
993extern "C" {
994 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000995 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000996 return TheJIT->getPointerToFunction(F);
997 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000998 }
999}
Chris Lattnere993cc22006-05-11 23:08:08 +00001000
1001// getPointerToFunctionOrStub - If the specified function has been
1002// code-gen'd, return a pointer to the function. If not, compile it, or use
1003// a stub to implement lazy compilation if available.
1004//
1005void *JIT::getPointerToFunctionOrStub(Function *F) {
1006 // If we have already code generated the function, just return the address.
1007 if (void *Addr = getPointerToGlobalIfAvailable(F))
1008 return Addr;
1009
1010 // Get a stub if the target supports it
1011 return getJITResolver(MCE).getFunctionStub(F);
1012}
1013
1014/// freeMachineCodeForFunction - release machine code memory for given Function.
1015///
1016void JIT::freeMachineCodeForFunction(Function *F) {
1017 // Delete translation for this from the ExecutionEngine, so it will get
1018 // retranslated next time it is used.
1019 updateGlobalMapping(F, 0);
1020
1021 // Free the actual memory for the function body and related stuff.
1022 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
1023 dynamic_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);
1024}
1025