remove static ctors from Statistic objects
[oota-llvm.git] / lib / ExecutionEngine / JIT / JITEmitter.cpp
1 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
2 //
3 //                     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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // 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.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "jit"
16 #include "JIT.h"
17 #include "llvm/Constant.h"
18 #include "llvm/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineRelocation.h"
25 #include "llvm/ExecutionEngine/GenericValue.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetJITInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MutexGuard.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/System/Memory.h"
33 #include <algorithm>
34 using namespace llvm;
35
36 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
37 STATISTIC(NumRelos, "Number of relocations applied");
38 static JIT *TheJIT = 0;
39
40 //===----------------------------------------------------------------------===//
41 // JITMemoryManager code.
42 //
43 namespace {
44   /// MemoryRangeHeader - For a range of memory, this is the header that we put
45   /// on the block of memory.  It is carefully crafted to be one word of memory.
46   /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
47   /// which starts with this.
48   struct FreeRangeHeader;
49   struct MemoryRangeHeader {
50     /// ThisAllocated - This is true if this block is currently allocated.  If
51     /// not, this can be converted to a FreeRangeHeader.
52     intptr_t ThisAllocated : 1;
53     
54     /// PrevAllocated - Keep track of whether the block immediately before us is
55     /// allocated.  If not, the word immediately before this header is the size
56     /// of the previous block.
57     intptr_t PrevAllocated : 1;
58     
59     /// BlockSize - This is the size in bytes of this memory block,
60     /// including this header.
61     uintptr_t BlockSize : (sizeof(intptr_t)*8 - 2);
62     
63
64     /// getBlockAfter - Return the memory block immediately after this one.
65     ///
66     MemoryRangeHeader &getBlockAfter() const {
67       return *(MemoryRangeHeader*)((char*)this+BlockSize);
68     }
69     
70     /// getFreeBlockBefore - If the block before this one is free, return it,
71     /// otherwise return null.
72     FreeRangeHeader *getFreeBlockBefore() const {
73       if (PrevAllocated) return 0;
74       intptr_t PrevSize = ((intptr_t *)this)[-1];
75       return (FreeRangeHeader*)((char*)this-PrevSize);
76     }
77     
78     /// FreeBlock - Turn an allocated block into a free block, adjusting
79     /// bits in the object headers, and adding an end of region memory block.
80     FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
81     
82     /// TrimAllocationToSize - If this allocated block is significantly larger
83     /// than NewSize, split it into two pieces (where the former is NewSize
84     /// bytes, including the header), and add the new block to the free list.
85     FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList, 
86                                           uint64_t NewSize);
87   };
88
89   /// FreeRangeHeader - For a memory block that isn't already allocated, this
90   /// keeps track of the current block and has a pointer to the next free block.
91   /// Free blocks are kept on a circularly linked list.
92   struct FreeRangeHeader : public MemoryRangeHeader {
93     FreeRangeHeader *Prev;
94     FreeRangeHeader *Next;
95     
96     /// getMinBlockSize - Get the minimum size for a memory block.  Blocks
97     /// smaller than this size cannot be created.
98     static unsigned getMinBlockSize() {
99       return sizeof(FreeRangeHeader)+sizeof(intptr_t);
100     }
101     
102     /// SetEndOfBlockSizeMarker - The word at the end of every free block is
103     /// known to be the size of the free block.  Set it for this block.
104     void SetEndOfBlockSizeMarker() {
105       void *EndOfBlock = (char*)this + BlockSize;
106       ((intptr_t *)EndOfBlock)[-1] = BlockSize;
107     }
108
109     FreeRangeHeader *RemoveFromFreeList() {
110       assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
111       Next->Prev = Prev;
112       return Prev->Next = Next;
113     }
114     
115     void AddToFreeList(FreeRangeHeader *FreeList) {
116       Next = FreeList;
117       Prev = FreeList->Prev;
118       Prev->Next = this;
119       Next->Prev = this;
120     }
121
122     /// GrowBlock - The block after this block just got deallocated.  Merge it
123     /// into the current block.
124     void GrowBlock(uintptr_t NewSize);
125     
126     /// AllocateBlock - Mark this entire block allocated, updating freelists
127     /// etc.  This returns a pointer to the circular free-list.
128     FreeRangeHeader *AllocateBlock();
129   };
130 }
131
132
133 /// AllocateBlock - Mark this entire block allocated, updating freelists
134 /// etc.  This returns a pointer to the circular free-list.
135 FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
136   assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
137          "Cannot allocate an allocated block!");
138   // Mark this block allocated.
139   ThisAllocated = 1;
140   getBlockAfter().PrevAllocated = 1;
141  
142   // Remove it from the free list.
143   return RemoveFromFreeList();
144 }
145
146 /// FreeBlock - Turn an allocated block into a free block, adjusting
147 /// bits in the object headers, and adding an end of region memory block.
148 /// If possible, coallesce this block with neighboring blocks.  Return the
149 /// FreeRangeHeader to allocate from.
150 FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
151   MemoryRangeHeader *FollowingBlock = &getBlockAfter();
152   assert(ThisAllocated && "This block is already allocated!");
153   assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
154   
155   FreeRangeHeader *FreeListToReturn = FreeList;
156   
157   // If the block after this one is free, merge it into this block.
158   if (!FollowingBlock->ThisAllocated) {
159     FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
160     // "FreeList" always needs to be a valid free block.  If we're about to
161     // coallesce with it, update our notion of what the free list is.
162     if (&FollowingFreeBlock == FreeList) {
163       FreeList = FollowingFreeBlock.Next;
164       FreeListToReturn = 0;
165       assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
166     }
167     FollowingFreeBlock.RemoveFromFreeList();
168     
169     // Include the following block into this one.
170     BlockSize += FollowingFreeBlock.BlockSize;
171     FollowingBlock = &FollowingFreeBlock.getBlockAfter();
172     
173     // Tell the block after the block we are coallescing that this block is
174     // allocated.
175     FollowingBlock->PrevAllocated = 1;
176   }
177   
178   assert(FollowingBlock->ThisAllocated && "Missed coallescing?");
179   
180   if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
181     PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
182     return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
183   }
184
185   // Otherwise, mark this block free.
186   FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
187   FollowingBlock->PrevAllocated = 0;
188   FreeBlock.ThisAllocated = 0;
189
190   // Link this into the linked list of free blocks.
191   FreeBlock.AddToFreeList(FreeList);
192
193   // Add a marker at the end of the block, indicating the size of this free
194   // block.
195   FreeBlock.SetEndOfBlockSizeMarker();
196   return FreeListToReturn ? FreeListToReturn : &FreeBlock;
197 }
198
199 /// GrowBlock - The block after this block just got deallocated.  Merge it
200 /// into the current block.
201 void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
202   assert(NewSize > BlockSize && "Not growing block?");
203   BlockSize = NewSize;
204   SetEndOfBlockSizeMarker();
205   getBlockAfter().PrevAllocated = 0;
206 }
207
208 /// TrimAllocationToSize - If this allocated block is significantly larger
209 /// than NewSize, split it into two pieces (where the former is NewSize
210 /// bytes, including the header), and add the new block to the free list.
211 FreeRangeHeader *MemoryRangeHeader::
212 TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
213   assert(ThisAllocated && getBlockAfter().PrevAllocated &&
214          "Cannot deallocate part of an allocated block!");
215
216   // Round up size for alignment of header.
217   unsigned HeaderAlign = __alignof(FreeRangeHeader);
218   NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
219   
220   // Size is now the size of the block we will remove from the start of the
221   // current block.
222   assert(NewSize <= BlockSize &&
223          "Allocating more space from this block than exists!");
224   
225   // If splitting this block will cause the remainder to be too small, do not
226   // split the block.
227   if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
228     return FreeList;
229   
230   // Otherwise, we splice the required number of bytes out of this block, form
231   // a new block immediately after it, then mark this block allocated.
232   MemoryRangeHeader &FormerNextBlock = getBlockAfter();
233   
234   // Change the size of this block.
235   BlockSize = NewSize;
236   
237   // Get the new block we just sliced out and turn it into a free block.
238   FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
239   NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
240   NewNextBlock.ThisAllocated = 0;
241   NewNextBlock.PrevAllocated = 1;
242   NewNextBlock.SetEndOfBlockSizeMarker();
243   FormerNextBlock.PrevAllocated = 0;
244   NewNextBlock.AddToFreeList(FreeList);
245   return &NewNextBlock;
246 }
247
248  
249 namespace {  
250   /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
251   /// sane way.  This splits a large block of MAP_NORESERVE'd memory into two
252   /// sections, one for function stubs, one for the functions themselves.  We
253   /// have to do this because we may need to emit a function stub while in the
254   /// middle of emitting a function, and we don't know how large the function we
255   /// are emitting is.  This never bothers to release the memory, because when
256   /// we are ready to destroy the JIT, the program exits.
257   class JITMemoryManager {
258     std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
259     FreeRangeHeader *FreeMemoryList;      // Circular list of free blocks.
260     
261     // When emitting code into a memory block, this is the block.
262     MemoryRangeHeader *CurBlock;
263     
264     unsigned char *CurStubPtr, *StubBase;
265     unsigned char *GOTBase;      // Target Specific reserved memory
266
267     // Centralize memory block allocation.
268     sys::MemoryBlock getNewMemoryBlock(unsigned size);
269     
270     std::map<const Function*, MemoryRangeHeader*> FunctionBlocks;
271   public:
272     JITMemoryManager(bool useGOT);
273     ~JITMemoryManager();
274
275     inline unsigned char *allocateStub(unsigned StubSize, unsigned Alignment);
276     
277     /// startFunctionBody - When a function starts, allocate a block of free
278     /// executable memory, returning a pointer to it and its actual size.
279     unsigned char *startFunctionBody(uintptr_t &ActualSize) {
280       CurBlock = FreeMemoryList;
281       
282       // Allocate the entire memory block.
283       FreeMemoryList = FreeMemoryList->AllocateBlock();
284       ActualSize = CurBlock->BlockSize-sizeof(MemoryRangeHeader);
285       return (unsigned char *)(CurBlock+1);
286     }
287     
288     /// endFunctionBody - The function F is now allocated, and takes the memory
289     /// in the range [FunctionStart,FunctionEnd).
290     void endFunctionBody(const Function *F, unsigned char *FunctionStart,
291                          unsigned char *FunctionEnd) {
292       assert(FunctionEnd > FunctionStart);
293       assert(FunctionStart == (unsigned char *)(CurBlock+1) &&
294              "Mismatched function start/end!");
295       
296       uintptr_t BlockSize = FunctionEnd - (unsigned char *)CurBlock;
297       FunctionBlocks[F] = CurBlock;
298
299       // Release the memory at the end of this block that isn't needed.
300       FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
301     }
302     
303     unsigned char *getGOTBase() const {
304       return GOTBase;
305     }
306     bool isManagingGOT() const {
307       return GOTBase != NULL;
308     }
309     
310     /// deallocateMemForFunction - Deallocate all memory for the specified
311     /// function body.
312     void deallocateMemForFunction(const Function *F) {
313       std::map<const Function*, MemoryRangeHeader*>::iterator
314         I = FunctionBlocks.find(F);
315       if (I == FunctionBlocks.end()) return;
316       
317       // Find the block that is allocated for this function.
318       MemoryRangeHeader *MemRange = I->second;
319       assert(MemRange->ThisAllocated && "Block isn't allocated!");
320       
321       // Fill the buffer with garbage!
322       DEBUG(memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange)));
323       
324       // Free the memory.
325       FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
326       
327       // Finally, remove this entry from FunctionBlocks.
328       FunctionBlocks.erase(I);
329     }
330   };
331 }
332
333 JITMemoryManager::JITMemoryManager(bool useGOT) {
334   // Allocate a 16M block of memory for functions.
335   sys::MemoryBlock MemBlock = getNewMemoryBlock(16 << 20);
336
337   unsigned char *MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
338
339   // Allocate stubs backwards from the base, allocate functions forward
340   // from the base.
341   StubBase   = MemBase;
342   CurStubPtr = MemBase + 512*1024; // Use 512k for stubs, working backwards.
343   
344   // We set up the memory chunk with 4 mem regions, like this:
345   //  [ START
346   //    [ Free      #0 ] -> Large space to allocate functions from.
347   //    [ Allocated #1 ] -> Tiny space to separate regions.
348   //    [ Free      #2 ] -> Tiny space so there is always at least 1 free block.
349   //    [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
350   //  END ]
351   //
352   // The last three blocks are never deallocated or touched.
353   
354   // Add MemoryRangeHeader to the end of the memory region, indicating that
355   // the space after the block of memory is allocated.  This is block #3.
356   MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
357   Mem3->ThisAllocated = 1;
358   Mem3->PrevAllocated = 0;
359   Mem3->BlockSize     = 0;
360   
361   /// Add a tiny free region so that the free list always has one entry.
362   FreeRangeHeader *Mem2 = 
363     (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
364   Mem2->ThisAllocated = 0;
365   Mem2->PrevAllocated = 1;
366   Mem2->BlockSize     = FreeRangeHeader::getMinBlockSize();
367   Mem2->SetEndOfBlockSizeMarker();
368   Mem2->Prev = Mem2;   // Mem2 *is* the free list for now.
369   Mem2->Next = Mem2;
370
371   /// Add a tiny allocated region so that Mem2 is never coallesced away.
372   MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
373   Mem1->ThisAllocated = 1;
374   Mem1->PrevAllocated = 0;
375   Mem1->BlockSize     = (char*)Mem2 - (char*)Mem1;
376   
377   // Add a FreeRangeHeader to the start of the function body region, indicating
378   // that the space is free.  Mark the previous block allocated so we never look
379   // at it.
380   FreeRangeHeader *Mem0 = (FreeRangeHeader*)CurStubPtr;
381   Mem0->ThisAllocated = 0;
382   Mem0->PrevAllocated = 1;
383   Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
384   Mem0->SetEndOfBlockSizeMarker();
385   Mem0->AddToFreeList(Mem2);
386   
387   // Start out with the freelist pointing to Mem0.
388   FreeMemoryList = Mem0;
389
390   // Allocate the GOT.
391   GOTBase = NULL;
392   if (useGOT) GOTBase = new unsigned char[sizeof(void*) * 8192];
393 }
394
395 JITMemoryManager::~JITMemoryManager() {
396   for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
397     sys::Memory::ReleaseRWX(Blocks[i]);
398   
399   delete[] GOTBase;
400   Blocks.clear();
401 }
402
403 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize,
404                                               unsigned Alignment) {
405   CurStubPtr -= StubSize;
406   CurStubPtr = (unsigned char*)(((intptr_t)CurStubPtr) &
407                                 ~(intptr_t)(Alignment-1));
408   if (CurStubPtr < StubBase) {
409     // FIXME: allocate a new block
410     cerr << "JIT ran out of memory for function stubs!\n";
411     abort();
412   }
413   return CurStubPtr;
414 }
415
416 sys::MemoryBlock JITMemoryManager::getNewMemoryBlock(unsigned size) {
417   // Allocate a new block close to the last one.
418   const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.front();
419   std::string ErrMsg;
420   sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld, &ErrMsg);
421   if (B.base() == 0) {
422     cerr << "Allocation failed when allocating new memory in the JIT\n";
423     cerr << ErrMsg << "\n";
424     abort();
425   }
426   Blocks.push_back(B);
427   return B;
428 }
429
430 //===----------------------------------------------------------------------===//
431 // JIT lazy compilation code.
432 //
433 namespace {
434   class JITResolverState {
435   private:
436     /// FunctionToStubMap - Keep track of the stub created for a particular
437     /// function so that we can reuse them if necessary.
438     std::map<Function*, void*> FunctionToStubMap;
439
440     /// StubToFunctionMap - Keep track of the function that each stub
441     /// corresponds to.
442     std::map<void*, Function*> StubToFunctionMap;
443
444   public:
445     std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
446       assert(locked.holds(TheJIT->lock));
447       return FunctionToStubMap;
448     }
449
450     std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
451       assert(locked.holds(TheJIT->lock));
452       return StubToFunctionMap;
453     }
454   };
455
456   /// JITResolver - Keep track of, and resolve, call sites for functions that
457   /// have not yet been compiled.
458   class JITResolver {
459     /// MCE - The MachineCodeEmitter to use to emit stubs with.
460     MachineCodeEmitter &MCE;
461
462     /// LazyResolverFn - The target lazy resolver function that we actually
463     /// rewrite instructions to use.
464     TargetJITInfo::LazyResolverFn LazyResolverFn;
465
466     JITResolverState state;
467
468     /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
469     /// external functions.
470     std::map<void*, void*> ExternalFnToStubMap;
471
472     //map addresses to indexes in the GOT
473     std::map<void*, unsigned> revGOTMap;
474     unsigned nextGOTIndex;
475
476   public:
477     JITResolver(MachineCodeEmitter &mce) : MCE(mce), nextGOTIndex(0) {
478       LazyResolverFn =
479         TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
480     }
481
482     /// getFunctionStub - This returns a pointer to a function stub, creating
483     /// one on demand as needed.
484     void *getFunctionStub(Function *F);
485
486     /// getExternalFunctionStub - Return a stub for the function at the
487     /// specified address, created lazily on demand.
488     void *getExternalFunctionStub(void *FnAddr);
489
490     /// AddCallbackAtLocation - If the target is capable of rewriting an
491     /// instruction without the use of a stub, record the location of the use so
492     /// we know which function is being used at the location.
493     void *AddCallbackAtLocation(Function *F, void *Location) {
494       MutexGuard locked(TheJIT->lock);
495       /// Get the target-specific JIT resolver function.
496       state.getStubToFunctionMap(locked)[Location] = F;
497       return (void*)(intptr_t)LazyResolverFn;
498     }
499
500     /// getGOTIndexForAddress - Return a new or existing index in the GOT for
501     /// and address.  This function only manages slots, it does not manage the
502     /// contents of the slots or the memory associated with the GOT.
503     unsigned getGOTIndexForAddr(void* addr);
504
505     /// JITCompilerFn - This function is called to resolve a stub to a compiled
506     /// address.  If the LLVM Function corresponding to the stub has not yet
507     /// been compiled, this function compiles it first.
508     static void *JITCompilerFn(void *Stub);
509   };
510 }
511
512 /// getJITResolver - This function returns the one instance of the JIT resolver.
513 ///
514 static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
515   static JITResolver TheJITResolver(*MCE);
516   return TheJITResolver;
517 }
518
519 #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
520     defined(__APPLE__)
521 extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
522 #endif
523
524 /// synchronizeICache - On some targets, the JIT emitted code must be
525 /// explicitly refetched to ensure correct execution.
526 static void synchronizeICache(const void *Addr, size_t len) {
527 #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
528     defined(__APPLE__)
529   sys_icache_invalidate(Addr, len);
530 #endif
531 }
532
533 /// getFunctionStub - This returns a pointer to a function stub, creating
534 /// one on demand as needed.
535 void *JITResolver::getFunctionStub(Function *F) {
536   MutexGuard locked(TheJIT->lock);
537
538   // If we already have a stub for this function, recycle it.
539   void *&Stub = state.getFunctionToStubMap(locked)[F];
540   if (Stub) return Stub;
541
542   // Call the lazy resolver function unless we already KNOW it is an external
543   // function, in which case we just skip the lazy resolution step.
544   void *Actual = (void*)(intptr_t)LazyResolverFn;
545   if (F->isExternal() && !F->hasNotBeenReadFromBytecode())
546     Actual = TheJIT->getPointerToFunction(F);
547
548   // Otherwise, codegen a new stub.  For now, the stub will call the lazy
549   // resolver function.
550   Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
551
552   if (Actual != (void*)(intptr_t)LazyResolverFn) {
553     // If we are getting the stub for an external function, we really want the
554     // address of the stub in the GlobalAddressMap for the JIT, not the address
555     // of the external function.
556     TheJIT->updateGlobalMapping(F, Stub);
557   }
558
559   // Invalidate the icache if necessary.
560   synchronizeICache(Stub, MCE.getCurrentPCValue()-(intptr_t)Stub);
561
562   DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
563        << F->getName() << "'\n";
564
565   // Finally, keep track of the stub-to-Function mapping so that the
566   // JITCompilerFn knows which function to compile!
567   state.getStubToFunctionMap(locked)[Stub] = F;
568   return Stub;
569 }
570
571 /// getExternalFunctionStub - Return a stub for the function at the
572 /// specified address, created lazily on demand.
573 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
574   // If we already have a stub for this function, recycle it.
575   void *&Stub = ExternalFnToStubMap[FnAddr];
576   if (Stub) return Stub;
577
578   Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
579
580   // Invalidate the icache if necessary.
581   synchronizeICache(Stub, MCE.getCurrentPCValue()-(intptr_t)Stub);
582
583   DOUT << "JIT: Stub emitted at [" << Stub
584        << "] for external function at '" << FnAddr << "'\n";
585   return Stub;
586 }
587
588 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
589   unsigned idx = revGOTMap[addr];
590   if (!idx) {
591     idx = ++nextGOTIndex;
592     revGOTMap[addr] = idx;
593     DOUT << "Adding GOT entry " << idx
594          << " for addr " << addr << "\n";
595     //    ((void**)MemMgr.getGOTBase())[idx] = addr;
596   }
597   return idx;
598 }
599
600 /// JITCompilerFn - This function is called when a lazy compilation stub has
601 /// been entered.  It looks up which function this stub corresponds to, compiles
602 /// it if necessary, then returns the resultant function pointer.
603 void *JITResolver::JITCompilerFn(void *Stub) {
604   JITResolver &JR = getJITResolver();
605
606   MutexGuard locked(TheJIT->lock);
607
608   // The address given to us for the stub may not be exactly right, it might be
609   // a little bit after the stub.  As such, use upper_bound to find it.
610   std::map<void*, Function*>::iterator I =
611     JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
612   assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
613          "This is not a known stub!");
614   Function *F = (--I)->second;
615
616   // If disabled, emit a useful error message and abort.
617   if (TheJIT->isLazyCompilationDisabled()) {
618     cerr << "LLVM JIT requested to do lazy compilation of function '"
619          << F->getName() << "' when lazy compiles are disabled!\n";
620     abort();
621   }
622   
623   // We might like to remove the stub from the StubToFunction map.
624   // We can't do that! Multiple threads could be stuck, waiting to acquire the
625   // lock above. As soon as the 1st function finishes compiling the function,
626   // the next one will be released, and needs to be able to find the function it
627   // needs to call.
628   //JR.state.getStubToFunctionMap(locked).erase(I);
629
630   DOUT << "JIT: Lazily resolving function '" << F->getName()
631        << "' In stub ptr = " << Stub << " actual ptr = "
632        << I->first << "\n";
633
634   void *Result = TheJIT->getPointerToFunction(F);
635
636   // We don't need to reuse this stub in the future, as F is now compiled.
637   JR.state.getFunctionToStubMap(locked).erase(F);
638
639   // FIXME: We could rewrite all references to this stub if we knew them.
640
641   // What we will do is set the compiled function address to map to the
642   // same GOT entry as the stub so that later clients may update the GOT
643   // if they see it still using the stub address.
644   // Note: this is done so the Resolver doesn't have to manage GOT memory
645   // Do this without allocating map space if the target isn't using a GOT
646   if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
647     JR.revGOTMap[Result] = JR.revGOTMap[Stub];
648
649   return Result;
650 }
651
652
653 //===----------------------------------------------------------------------===//
654 // JITEmitter code.
655 //
656 namespace {
657   /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
658   /// used to output functions to memory for execution.
659   class JITEmitter : public MachineCodeEmitter {
660     JITMemoryManager MemMgr;
661
662     // When outputting a function stub in the context of some other function, we
663     // save BufferBegin/BufferEnd/CurBufferPtr here.
664     unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
665
666     /// Relocations - These are the relocations that the function needs, as
667     /// emitted.
668     std::vector<MachineRelocation> Relocations;
669     
670     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
671     /// It is filled in by the StartMachineBasicBlock callback and queried by
672     /// the getMachineBasicBlockAddress callback.
673     std::vector<intptr_t> MBBLocations;
674
675     /// ConstantPool - The constant pool for the current function.
676     ///
677     MachineConstantPool *ConstantPool;
678
679     /// ConstantPoolBase - A pointer to the first entry in the constant pool.
680     ///
681     void *ConstantPoolBase;
682
683     /// JumpTable - The jump tables for the current function.
684     ///
685     MachineJumpTableInfo *JumpTable;
686     
687     /// JumpTableBase - A pointer to the first entry in the jump table.
688     ///
689     void *JumpTableBase;
690 public:
691     JITEmitter(JIT &jit) : MemMgr(jit.getJITInfo().needsGOT()) {
692       TheJIT = &jit;
693       if (MemMgr.isManagingGOT()) DOUT << "JIT is managing a GOT\n";
694     }
695
696     virtual void startFunction(MachineFunction &F);
697     virtual bool finishFunction(MachineFunction &F);
698     
699     void emitConstantPool(MachineConstantPool *MCP);
700     void initJumpTableInfo(MachineJumpTableInfo *MJTI);
701     void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
702     
703     virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1);
704     virtual void* finishFunctionStub(const Function *F);
705
706     virtual void addRelocation(const MachineRelocation &MR) {
707       Relocations.push_back(MR);
708     }
709     
710     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
711       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
712         MBBLocations.resize((MBB->getNumber()+1)*2);
713       MBBLocations[MBB->getNumber()] = getCurrentPCValue();
714     }
715
716     virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
717     virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
718     
719     virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
720       assert(MBBLocations.size() > (unsigned)MBB->getNumber() && 
721              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
722       return MBBLocations[MBB->getNumber()];
723     }
724
725     /// deallocateMemForFunction - Deallocate all memory for the specified
726     /// function body.
727     void deallocateMemForFunction(Function *F) {
728       MemMgr.deallocateMemForFunction(F);
729     }
730   private:
731     void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
732   };
733 }
734
735 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
736                                      bool DoesntNeedStub) {
737   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
738     /// FIXME: If we straightened things out, this could actually emit the
739     /// global immediately instead of queuing it for codegen later!
740     return TheJIT->getOrEmitGlobalVariable(GV);
741   }
742
743   // If we have already compiled the function, return a pointer to its body.
744   Function *F = cast<Function>(V);
745   void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
746   if (ResultPtr) return ResultPtr;
747
748   if (F->isExternal() && !F->hasNotBeenReadFromBytecode()) {
749     // If this is an external function pointer, we can force the JIT to
750     // 'compile' it, which really just adds it to the map.
751     if (DoesntNeedStub)
752       return TheJIT->getPointerToFunction(F);
753
754     return getJITResolver(this).getFunctionStub(F);
755   }
756
757   // Okay, the function has not been compiled yet, if the target callback
758   // mechanism is capable of rewriting the instruction directly, prefer to do
759   // that instead of emitting a stub.
760   if (DoesntNeedStub)
761     return getJITResolver(this).AddCallbackAtLocation(F, Reference);
762
763   // Otherwise, we have to emit a lazy resolving stub.
764   return getJITResolver(this).getFunctionStub(F);
765 }
766
767 void JITEmitter::startFunction(MachineFunction &F) {
768   uintptr_t ActualSize;
769   BufferBegin = CurBufferPtr = MemMgr.startFunctionBody(ActualSize);
770   BufferEnd = BufferBegin+ActualSize;
771   
772   // Ensure the constant pool/jump table info is at least 4-byte aligned.
773   emitAlignment(16);
774
775   emitConstantPool(F.getConstantPool());
776   initJumpTableInfo(F.getJumpTableInfo());
777
778   // About to start emitting the machine code for the function.
779   emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
780   TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
781
782   MBBLocations.clear();
783 }
784
785 bool JITEmitter::finishFunction(MachineFunction &F) {
786   if (CurBufferPtr == BufferEnd) {
787     // FIXME: Allocate more space, then try again.
788     cerr << "JIT: Ran out of space for generated machine code!\n";
789     abort();
790   }
791   
792   emitJumpTableInfo(F.getJumpTableInfo());
793   
794   // FnStart is the start of the text, not the start of the constant pool and
795   // other per-function data.
796   unsigned char *FnStart =
797     (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
798   unsigned char *FnEnd   = CurBufferPtr;
799   
800   MemMgr.endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
801   NumBytes += FnEnd-FnStart;
802
803   if (!Relocations.empty()) {
804     NumRelos += Relocations.size();
805
806     // Resolve the relocations to concrete pointers.
807     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
808       MachineRelocation &MR = Relocations[i];
809       void *ResultPtr;
810       if (MR.isString()) {
811         ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
812
813         // If the target REALLY wants a stub for this function, emit it now.
814         if (!MR.doesntNeedFunctionStub())
815           ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
816       } else if (MR.isGlobalValue()) {
817         ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
818                                        BufferBegin+MR.getMachineCodeOffset(),
819                                        MR.doesntNeedFunctionStub());
820       } else if (MR.isBasicBlock()) {
821         ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
822       } else if (MR.isConstantPoolIndex()) {
823         ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
824       } else {
825         assert(MR.isJumpTableIndex());
826         ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
827       }
828
829       MR.setResultPointer(ResultPtr);
830
831       // if we are managing the GOT and the relocation wants an index,
832       // give it one
833       if (MemMgr.isManagingGOT() && MR.isGOTRelative()) {
834         unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
835         MR.setGOTIndex(idx);
836         if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
837           DOUT << "GOT was out of date for " << ResultPtr
838                << " pointing at " << ((void**)MemMgr.getGOTBase())[idx]
839                << "\n";
840           ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
841         }
842       }
843     }
844
845     TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
846                                   Relocations.size(), MemMgr.getGOTBase());
847   }
848
849   // Update the GOT entry for F to point to the new code.
850   if(MemMgr.isManagingGOT()) {
851     unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)BufferBegin);
852     if (((void**)MemMgr.getGOTBase())[idx] != (void*)BufferBegin) {
853       DOUT << "GOT was out of date for " << (void*)BufferBegin
854            << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n";
855       ((void**)MemMgr.getGOTBase())[idx] = (void*)BufferBegin;
856     }
857   }
858
859   // Invalidate the icache if necessary.
860   synchronizeICache(FnStart, FnEnd-FnStart);
861
862   DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
863        << "] Function: " << F.getFunction()->getName()
864        << ": " << (FnEnd-FnStart) << " bytes of text, "
865        << Relocations.size() << " relocations\n";
866   Relocations.clear();
867   return false;
868 }
869
870 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
871   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
872   if (Constants.empty()) return;
873
874   MachineConstantPoolEntry CPE = Constants.back();
875   unsigned Size = CPE.Offset;
876   const Type *Ty = CPE.isMachineConstantPoolEntry()
877     ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
878   Size += TheJIT->getTargetData()->getTypeSize(Ty);
879
880   ConstantPoolBase = allocateSpace(Size, 1 << MCP->getConstantPoolAlignment());
881   ConstantPool = MCP;
882
883   if (ConstantPoolBase == 0) return;  // Buffer overflow.
884
885   // Initialize the memory for all of the constant pool entries.
886   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
887     void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
888     if (Constants[i].isMachineConstantPoolEntry()) {
889       // FIXME: add support to lower machine constant pool values into bytes!
890       cerr << "Initialize memory with machine specific constant pool entry"
891            << " has not been implemented!\n";
892       abort();
893     }
894     TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
895   }
896 }
897
898 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
899   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
900   if (JT.empty()) return;
901   
902   unsigned NumEntries = 0;
903   for (unsigned i = 0, e = JT.size(); i != e; ++i)
904     NumEntries += JT[i].MBBs.size();
905
906   unsigned EntrySize = MJTI->getEntrySize();
907
908   // Just allocate space for all the jump tables now.  We will fix up the actual
909   // MBB entries in the tables after we emit the code for each block, since then
910   // we will know the final locations of the MBBs in memory.
911   JumpTable = MJTI;
912   JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
913 }
914
915 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
916   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
917   if (JT.empty() || JumpTableBase == 0) return;
918   
919   if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
920     assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
921     // For each jump table, place the offset from the beginning of the table
922     // to the target address.
923     int *SlotPtr = (int*)JumpTableBase;
924
925     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
926       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
927       // Store the offset of the basic block for this jump table slot in the
928       // memory we allocated for the jump table in 'initJumpTableInfo'
929       intptr_t Base = (intptr_t)SlotPtr;
930       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
931         *SlotPtr++ = (intptr_t)getMachineBasicBlockAddress(MBBs[mi]) - Base;
932     }
933   } else {
934     assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
935     
936     // For each jump table, map each target in the jump table to the address of 
937     // an emitted MachineBasicBlock.
938     intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
939
940     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
941       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
942       // Store the address of the basic block for this jump table slot in the
943       // memory we allocated for the jump table in 'initJumpTableInfo'
944       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
945         *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
946     }
947   }
948 }
949
950 void JITEmitter::startFunctionStub(unsigned StubSize, unsigned Alignment) {
951   SavedBufferBegin = BufferBegin;
952   SavedBufferEnd = BufferEnd;
953   SavedCurBufferPtr = CurBufferPtr;
954   
955   BufferBegin = CurBufferPtr = MemMgr.allocateStub(StubSize, Alignment);
956   BufferEnd = BufferBegin+StubSize+1;
957 }
958
959 void *JITEmitter::finishFunctionStub(const Function *F) {
960   NumBytes += getCurrentPCOffset();
961   std::swap(SavedBufferBegin, BufferBegin);
962   BufferEnd = SavedBufferEnd;
963   CurBufferPtr = SavedCurBufferPtr;
964   return SavedBufferBegin;
965 }
966
967 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
968 // in the constant pool that was last emitted with the 'emitConstantPool'
969 // method.
970 //
971 intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
972   assert(ConstantNum < ConstantPool->getConstants().size() &&
973          "Invalid ConstantPoolIndex!");
974   return (intptr_t)ConstantPoolBase +
975          ConstantPool->getConstants()[ConstantNum].Offset;
976 }
977
978 // getJumpTableEntryAddress - Return the address of the JumpTable with index
979 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
980 //
981 intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
982   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
983   assert(Index < JT.size() && "Invalid jump table index!");
984   
985   unsigned Offset = 0;
986   unsigned EntrySize = JumpTable->getEntrySize();
987   
988   for (unsigned i = 0; i < Index; ++i)
989     Offset += JT[i].MBBs.size();
990   
991    Offset *= EntrySize;
992   
993   return (intptr_t)((char *)JumpTableBase + Offset);
994 }
995
996 //===----------------------------------------------------------------------===//
997 //  Public interface to this file
998 //===----------------------------------------------------------------------===//
999
1000 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
1001   return new JITEmitter(jit);
1002 }
1003
1004 // getPointerToNamedFunction - This function is used as a global wrapper to
1005 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1006 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1007 // need to resolve function(s) that are being mis-codegenerated, so we need to
1008 // resolve their addresses at runtime, and this is the way to do it.
1009 extern "C" {
1010   void *getPointerToNamedFunction(const char *Name) {
1011     if (Function *F = TheJIT->FindFunctionNamed(Name))
1012       return TheJIT->getPointerToFunction(F);
1013     return TheJIT->getPointerToNamedFunction(Name);
1014   }
1015 }
1016
1017 // getPointerToFunctionOrStub - If the specified function has been
1018 // code-gen'd, return a pointer to the function.  If not, compile it, or use
1019 // a stub to implement lazy compilation if available.
1020 //
1021 void *JIT::getPointerToFunctionOrStub(Function *F) {
1022   // If we have already code generated the function, just return the address.
1023   if (void *Addr = getPointerToGlobalIfAvailable(F))
1024     return Addr;
1025   
1026   // Get a stub if the target supports it
1027   return getJITResolver(MCE).getFunctionStub(F);
1028 }
1029
1030 /// freeMachineCodeForFunction - release machine code memory for given Function.
1031 ///
1032 void JIT::freeMachineCodeForFunction(Function *F) {
1033   // Delete translation for this from the ExecutionEngine, so it will get
1034   // retranslated next time it is used.
1035   updateGlobalMapping(F, 0);
1036
1037   // Free the actual memory for the function body and related stuff.
1038   assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
1039   dynamic_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);
1040 }
1041