Rename PaddedSize to AllocSize, in the hope that this
[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 is distributed under the University of Illinois Open Source
6 // 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 "JITDwarfEmitter.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/CodeGen/MachineCodeEmitter.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRelocation.h"
27 #include "llvm/ExecutionEngine/JITMemoryManager.h"
28 #include "llvm/ExecutionEngine/GenericValue.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetJITInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/MutexGuard.h"
35 #include "llvm/Support/ValueHandle.h"
36 #include "llvm/System/Disassembler.h"
37 #include "llvm/System/Memory.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/Statistic.h"
42 #include <algorithm>
43 #ifndef NDEBUG
44 #include <iomanip>
45 #endif
46 using namespace llvm;
47
48 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
49 STATISTIC(NumRelos, "Number of relocations applied");
50 static JIT *TheJIT = 0;
51
52
53 //===----------------------------------------------------------------------===//
54 // JIT lazy compilation code.
55 //
56 namespace {
57   class JITResolverState {
58   public:
59     typedef std::map<AssertingVH<Function>, void*> FunctionToStubMapTy;
60     typedef std::map<void*, Function*> StubToFunctionMapTy;
61     typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
62   private:
63     /// FunctionToStubMap - Keep track of the stub created for a particular
64     /// function so that we can reuse them if necessary.
65     FunctionToStubMapTy FunctionToStubMap;
66
67     /// StubToFunctionMap - Keep track of the function that each stub
68     /// corresponds to.
69     StubToFunctionMapTy StubToFunctionMap;
70
71     /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
72     /// particular GlobalVariable so that we can reuse them if necessary.
73     GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
74
75   public:
76     FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
77       assert(locked.holds(TheJIT->lock));
78       return FunctionToStubMap;
79     }
80
81     StubToFunctionMapTy& getStubToFunctionMap(const MutexGuard& locked) {
82       assert(locked.holds(TheJIT->lock));
83       return StubToFunctionMap;
84     }
85
86     GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
87       assert(locked.holds(TheJIT->lock));
88       return GlobalToIndirectSymMap;
89     }
90   };
91
92   /// JITResolver - Keep track of, and resolve, call sites for functions that
93   /// have not yet been compiled.
94   class JITResolver {
95     typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
96     typedef JITResolverState::StubToFunctionMapTy StubToFunctionMapTy;
97     typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
98
99     /// LazyResolverFn - The target lazy resolver function that we actually
100     /// rewrite instructions to use.
101     TargetJITInfo::LazyResolverFn LazyResolverFn;
102
103     JITResolverState state;
104
105     /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
106     /// external functions.
107     std::map<void*, void*> ExternalFnToStubMap;
108
109     /// revGOTMap - map addresses to indexes in the GOT
110     std::map<void*, unsigned> revGOTMap;
111     unsigned nextGOTIndex;
112
113     static JITResolver *TheJITResolver;
114   public:
115     explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
116       TheJIT = &jit;
117
118       LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
119       assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
120       TheJITResolver = this;
121     }
122     
123     ~JITResolver() {
124       TheJITResolver = 0;
125     }
126
127     /// getFunctionStubIfAvailable - This returns a pointer to a function stub
128     /// if it has already been created.
129     void *getFunctionStubIfAvailable(Function *F);
130
131     /// getFunctionStub - This returns a pointer to a function stub, creating
132     /// one on demand as needed.  If empty is true, create a function stub
133     /// pointing at address 0, to be filled in later.
134     void *getFunctionStub(Function *F);
135
136     /// getExternalFunctionStub - Return a stub for the function at the
137     /// specified address, created lazily on demand.
138     void *getExternalFunctionStub(void *FnAddr);
139
140     /// getGlobalValueIndirectSym - Return an indirect symbol containing the
141     /// specified GV address.
142     void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
143
144     /// AddCallbackAtLocation - If the target is capable of rewriting an
145     /// instruction without the use of a stub, record the location of the use so
146     /// we know which function is being used at the location.
147     void *AddCallbackAtLocation(Function *F, void *Location) {
148       MutexGuard locked(TheJIT->lock);
149       /// Get the target-specific JIT resolver function.
150       state.getStubToFunctionMap(locked)[Location] = F;
151       return (void*)(intptr_t)LazyResolverFn;
152     }
153     
154     void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
155                            SmallVectorImpl<void*> &Ptrs);
156     
157     GlobalValue *invalidateStub(void *Stub);
158
159     /// getGOTIndexForAddress - Return a new or existing index in the GOT for
160     /// an address.  This function only manages slots, it does not manage the
161     /// contents of the slots or the memory associated with the GOT.
162     unsigned getGOTIndexForAddr(void *addr);
163
164     /// JITCompilerFn - This function is called to resolve a stub to a compiled
165     /// address.  If the LLVM Function corresponding to the stub has not yet
166     /// been compiled, this function compiles it first.
167     static void *JITCompilerFn(void *Stub);
168   };
169 }
170
171 JITResolver *JITResolver::TheJITResolver = 0;
172
173 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
174 /// if it has already been created.
175 void *JITResolver::getFunctionStubIfAvailable(Function *F) {
176   MutexGuard locked(TheJIT->lock);
177
178   // If we already have a stub for this function, recycle it.
179   void *&Stub = state.getFunctionToStubMap(locked)[F];
180   return Stub;
181 }
182
183 /// getFunctionStub - This returns a pointer to a function stub, creating
184 /// one on demand as needed.
185 void *JITResolver::getFunctionStub(Function *F) {
186   MutexGuard locked(TheJIT->lock);
187
188   // If we already have a stub for this function, recycle it.
189   void *&Stub = state.getFunctionToStubMap(locked)[F];
190   if (Stub) return Stub;
191
192   // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
193   // case we must resolve the symbol now.
194   void *Actual =  TheJIT->isLazyCompilationDisabled() 
195     ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
196    
197   // If this is an external declaration, attempt to resolve the address now
198   // to place in the stub.
199   if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
200     Actual = TheJIT->getPointerToFunction(F);
201
202     // If we resolved the symbol to a null address (eg. a weak external)
203     // don't emit a stub. Return a null pointer to the application.  If dlsym
204     // stubs are enabled, not being able to resolve the address is not
205     // meaningful.
206     if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
207   }
208
209   // Codegen a new stub, calling the lazy resolver or the actual address of the
210   // external function, if it was resolved.
211   Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
212                                                *TheJIT->getCodeEmitter());
213
214   if (Actual != (void*)(intptr_t)LazyResolverFn) {
215     // If we are getting the stub for an external function, we really want the
216     // address of the stub in the GlobalAddressMap for the JIT, not the address
217     // of the external function.
218     TheJIT->updateGlobalMapping(F, Stub);
219   }
220
221   DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
222        << F->getName() << "'\n";
223
224   // Finally, keep track of the stub-to-Function mapping so that the
225   // JITCompilerFn knows which function to compile!
226   state.getStubToFunctionMap(locked)[Stub] = F;
227   
228   // If we are JIT'ing non-lazily but need to call a function that does not
229   // exist yet, add it to the JIT's work list so that we can fill in the stub
230   // address later.
231   if (!Actual && TheJIT->isLazyCompilationDisabled())
232     if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
233       TheJIT->addPendingFunction(F);
234   
235   return Stub;
236 }
237
238 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
239 /// GV address.
240 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
241   MutexGuard locked(TheJIT->lock);
242
243   // If we already have a stub for this global variable, recycle it.
244   void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
245   if (IndirectSym) return IndirectSym;
246
247   // Otherwise, codegen a new indirect symbol.
248   IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
249                                                      *TheJIT->getCodeEmitter());
250
251   DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
252        << GV->getName() << "'\n";
253
254   return IndirectSym;
255 }
256
257 /// getExternalFunctionStub - Return a stub for the function at the
258 /// specified address, created lazily on demand.
259 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
260   // If we already have a stub for this function, recycle it.
261   void *&Stub = ExternalFnToStubMap[FnAddr];
262   if (Stub) return Stub;
263
264   Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
265                                                *TheJIT->getCodeEmitter());
266
267   DOUT << "JIT: Stub emitted at [" << Stub
268        << "] for external function at '" << FnAddr << "'\n";
269   return Stub;
270 }
271
272 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
273   unsigned idx = revGOTMap[addr];
274   if (!idx) {
275     idx = ++nextGOTIndex;
276     revGOTMap[addr] = idx;
277     DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
278   }
279   return idx;
280 }
281
282 void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
283                                     SmallVectorImpl<void*> &Ptrs) {
284   MutexGuard locked(TheJIT->lock);
285   
286   FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
287   GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
288   
289   for (FunctionToStubMapTy::iterator i = FM.begin(), e = FM.end(); i != e; ++i){
290     Function *F = i->first;
291     if (F->isDeclaration() && F->hasExternalLinkage()) {
292       GVs.push_back(i->first);
293       Ptrs.push_back(i->second);
294     }
295   }
296   for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
297        i != e; ++i) {
298     GVs.push_back(i->first);
299     Ptrs.push_back(i->second);
300   }
301 }
302
303 GlobalValue *JITResolver::invalidateStub(void *Stub) {
304   MutexGuard locked(TheJIT->lock);
305   
306   FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
307   StubToFunctionMapTy &SM = state.getStubToFunctionMap(locked);
308   GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
309   
310   // Look up the cheap way first, to see if it's a function stub we are
311   // invalidating.  If so, remove it from both the forward and reverse maps.
312   if (SM.find(Stub) != SM.end()) {
313     Function *F = SM[Stub];
314     SM.erase(Stub);
315     FM.erase(F);
316     return F;
317   }
318   
319   // Otherwise, it might be an indirect symbol stub.  Find it and remove it.
320   for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
321        i != e; ++i) {
322     if (i->second != Stub)
323       continue;
324     GlobalValue *GV = i->first;
325     GM.erase(i);
326     return GV;
327   }
328   
329   // Lastly, check to see if it's in the ExternalFnToStubMap.
330   for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
331        e = ExternalFnToStubMap.end(); i != e; ++i) {
332     if (i->second != Stub)
333       continue;
334     ExternalFnToStubMap.erase(i);
335     break;
336   }
337   
338   return 0;
339 }
340
341 /// JITCompilerFn - This function is called when a lazy compilation stub has
342 /// been entered.  It looks up which function this stub corresponds to, compiles
343 /// it if necessary, then returns the resultant function pointer.
344 void *JITResolver::JITCompilerFn(void *Stub) {
345   JITResolver &JR = *TheJITResolver;
346   
347   Function* F = 0;
348   void* ActualPtr = 0;
349
350   {
351     // Only lock for getting the Function. The call getPointerToFunction made
352     // in this function might trigger function materializing, which requires
353     // JIT lock to be unlocked.
354     MutexGuard locked(TheJIT->lock);
355
356     // The address given to us for the stub may not be exactly right, it might be
357     // a little bit after the stub.  As such, use upper_bound to find it.
358     StubToFunctionMapTy::iterator I =
359       JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
360     assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
361            "This is not a known stub!");
362     F = (--I)->second;
363     ActualPtr = I->first;
364   }
365
366   // If we have already code generated the function, just return the address.
367   void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
368   
369   if (!Result) {
370     // Otherwise we don't have it, do lazy compilation now.
371     
372     // If lazy compilation is disabled, emit a useful error message and abort.
373     if (TheJIT->isLazyCompilationDisabled()) {
374       cerr << "LLVM JIT requested to do lazy compilation of function '"
375       << F->getName() << "' when lazy compiles are disabled!\n";
376       abort();
377     }
378   
379     // We might like to remove the stub from the StubToFunction map.
380     // We can't do that! Multiple threads could be stuck, waiting to acquire the
381     // lock above. As soon as the 1st function finishes compiling the function,
382     // the next one will be released, and needs to be able to find the function
383     // it needs to call.
384     //JR.state.getStubToFunctionMap(locked).erase(I);
385
386     DOUT << "JIT: Lazily resolving function '" << F->getName()
387          << "' In stub ptr = " << Stub << " actual ptr = "
388          << ActualPtr << "\n";
389
390     Result = TheJIT->getPointerToFunction(F);
391   }
392   
393   // Reacquire the lock to erase the stub in the map.
394   MutexGuard locked(TheJIT->lock);
395
396   // We don't need to reuse this stub in the future, as F is now compiled.
397   JR.state.getFunctionToStubMap(locked).erase(F);
398
399   // FIXME: We could rewrite all references to this stub if we knew them.
400
401   // What we will do is set the compiled function address to map to the
402   // same GOT entry as the stub so that later clients may update the GOT
403   // if they see it still using the stub address.
404   // Note: this is done so the Resolver doesn't have to manage GOT memory
405   // Do this without allocating map space if the target isn't using a GOT
406   if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
407     JR.revGOTMap[Result] = JR.revGOTMap[Stub];
408
409   return Result;
410 }
411
412 //===----------------------------------------------------------------------===//
413 // Function Index Support
414
415 // On MacOS we generate an index of currently JIT'd functions so that
416 // performance tools can determine a symbol name and accurate code range for a
417 // PC value.  Because performance tools are generally asynchronous, the code
418 // below is written with the hope that it could be interrupted at any time and
419 // have useful answers.  However, we don't go crazy with atomic operations, we
420 // just do a "reasonable effort".
421 #ifdef __APPLE__ 
422 #define ENABLE_JIT_SYMBOL_TABLE 0
423 #endif
424
425 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
426 /// being added to an array of symbols.  This indicates the name of the function
427 /// as well as the address range it occupies.  This allows the client to map
428 /// from a PC value to the name of the function.
429 struct JitSymbolEntry {
430   const char *FnName;   // FnName - a strdup'd string.
431   void *FnStart;
432   intptr_t FnSize;
433 };
434
435
436 struct JitSymbolTable {
437   /// NextPtr - This forms a linked list of JitSymbolTable entries.  This
438   /// pointer is not used right now, but might be used in the future.  Consider
439   /// it reserved for future use.
440   JitSymbolTable *NextPtr;
441   
442   /// Symbols - This is an array of JitSymbolEntry entries.  Only the first
443   /// 'NumSymbols' symbols are valid.
444   JitSymbolEntry *Symbols;
445   
446   /// NumSymbols - This indicates the number entries in the Symbols array that
447   /// are valid.
448   unsigned NumSymbols;
449   
450   /// NumAllocated - This indicates the amount of space we have in the Symbols
451   /// array.  This is a private field that should not be read by external tools.
452   unsigned NumAllocated;
453 };
454
455 #if ENABLE_JIT_SYMBOL_TABLE 
456 JitSymbolTable *__jitSymbolTable;
457 #endif
458
459 static void AddFunctionToSymbolTable(const char *FnName, 
460                                      void *FnStart, intptr_t FnSize) {
461   assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
462   JitSymbolTable **SymTabPtrPtr = 0;
463 #if !ENABLE_JIT_SYMBOL_TABLE
464   return;
465 #else
466   SymTabPtrPtr = &__jitSymbolTable;
467 #endif
468   
469   // If this is the first entry in the symbol table, add the JitSymbolTable
470   // index.
471   if (*SymTabPtrPtr == 0) {
472     JitSymbolTable *New = new JitSymbolTable();
473     New->NextPtr = 0;
474     New->Symbols = 0;
475     New->NumSymbols = 0;
476     New->NumAllocated = 0;
477     *SymTabPtrPtr = New;
478   }
479   
480   JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
481   
482   // If we have space in the table, reallocate the table.
483   if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
484     // If we don't have space, reallocate the table.
485     unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
486     JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
487     JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
488     
489     // Copy the old entries over.
490     memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
491     
492     // Swap the new symbols in, delete the old ones.
493     SymTabPtr->Symbols = NewSymbols;
494     SymTabPtr->NumAllocated = NewSize;
495     delete [] OldSymbols;
496   }
497   
498   // Otherwise, we have enough space, just tack it onto the end of the array.
499   JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
500   Entry.FnName = strdup(FnName);
501   Entry.FnStart = FnStart;
502   Entry.FnSize = FnSize;
503   ++SymTabPtr->NumSymbols;
504 }
505
506 static void RemoveFunctionFromSymbolTable(void *FnStart) {
507   assert(FnStart && "Invalid function pointer");
508   JitSymbolTable **SymTabPtrPtr = 0;
509 #if !ENABLE_JIT_SYMBOL_TABLE
510   return;
511 #else
512   SymTabPtrPtr = &__jitSymbolTable;
513 #endif
514   
515   JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
516   JitSymbolEntry *Symbols = SymTabPtr->Symbols;
517   
518   // Scan the table to find its index.  The table is not sorted, so do a linear
519   // scan.
520   unsigned Index;
521   for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
522     assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
523   
524   // Once we have an index, we know to nuke this entry, overwrite it with the
525   // entry at the end of the array, making the last entry redundant.
526   const char *OldName = Symbols[Index].FnName;
527   Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
528   free((void*)OldName);
529   
530   // Drop the number of symbols in the table.
531   --SymTabPtr->NumSymbols;
532
533   // Finally, if we deleted the final symbol, deallocate the table itself.
534   if (SymTabPtr->NumSymbols != 0) 
535     return;
536   
537   *SymTabPtrPtr = 0;
538   delete [] Symbols;
539   delete SymTabPtr;
540 }
541
542 //===----------------------------------------------------------------------===//
543 // JITEmitter code.
544 //
545 namespace {
546   /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
547   /// used to output functions to memory for execution.
548   class JITEmitter : public MachineCodeEmitter {
549     JITMemoryManager *MemMgr;
550
551     // When outputting a function stub in the context of some other function, we
552     // save BufferBegin/BufferEnd/CurBufferPtr here.
553     unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
554
555     /// Relocations - These are the relocations that the function needs, as
556     /// emitted.
557     std::vector<MachineRelocation> Relocations;
558     
559     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
560     /// It is filled in by the StartMachineBasicBlock callback and queried by
561     /// the getMachineBasicBlockAddress callback.
562     std::vector<uintptr_t> MBBLocations;
563
564     /// ConstantPool - The constant pool for the current function.
565     ///
566     MachineConstantPool *ConstantPool;
567
568     /// ConstantPoolBase - A pointer to the first entry in the constant pool.
569     ///
570     void *ConstantPoolBase;
571
572     /// ConstPoolAddresses - Addresses of individual constant pool entries.
573     ///
574     SmallVector<uintptr_t, 8> ConstPoolAddresses;
575
576     /// JumpTable - The jump tables for the current function.
577     ///
578     MachineJumpTableInfo *JumpTable;
579     
580     /// JumpTableBase - A pointer to the first entry in the jump table.
581     ///
582     void *JumpTableBase;
583
584     /// Resolver - This contains info about the currently resolved functions.
585     JITResolver Resolver;
586     
587     /// DE - The dwarf emitter for the jit.
588     JITDwarfEmitter *DE;
589
590     /// LabelLocations - This vector is a mapping from Label ID's to their 
591     /// address.
592     std::vector<uintptr_t> LabelLocations;
593
594     /// MMI - Machine module info for exception informations
595     MachineModuleInfo* MMI;
596
597     // GVSet - a set to keep track of which globals have been seen
598     SmallPtrSet<const GlobalVariable*, 8> GVSet;
599
600     // CurFn - The llvm function being emitted.  Only valid during 
601     // finishFunction().
602     const Function *CurFn;
603     
604     // CurFnStubUses - For a given Function, a vector of stubs that it
605     // references.  This facilitates the JIT detecting that a stub is no
606     // longer used, so that it may be deallocated.
607     DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
608     
609     // StubFnRefs - For a given pointer to a stub, a set of Functions which
610     // reference the stub.  When the count of a stub's references drops to zero,
611     // the stub is unused.
612     DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
613     
614     // ExtFnStubs - A map of external function names to stubs which have entries
615     // in the JITResolver's ExternalFnToStubMap.
616     StringMap<void *> ExtFnStubs;
617     
618   public:
619     JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0) {
620       MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
621       if (jit.getJITInfo().needsGOT()) {
622         MemMgr->AllocateGOT();
623         DOUT << "JIT is managing a GOT\n";
624       }
625
626       if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
627     }
628     ~JITEmitter() { 
629       delete MemMgr;
630       if (ExceptionHandling) delete DE;
631     }
632
633     /// classof - Methods for support type inquiry through isa, cast, and
634     /// dyn_cast:
635     ///
636     static inline bool classof(const JITEmitter*) { return true; }
637     static inline bool classof(const MachineCodeEmitter*) { return true; }
638     
639     JITResolver &getJITResolver() { return Resolver; }
640
641     virtual void startFunction(MachineFunction &F);
642     virtual bool finishFunction(MachineFunction &F);
643     
644     void emitConstantPool(MachineConstantPool *MCP);
645     void initJumpTableInfo(MachineJumpTableInfo *MJTI);
646     void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
647     
648     virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
649                                    unsigned Alignment = 1);
650     virtual void startGVStub(const GlobalValue* GV, void *Buffer,
651                              unsigned StubSize);
652     virtual void* finishGVStub(const GlobalValue *GV);
653
654     /// allocateSpace - Reserves space in the current block if any, or
655     /// allocate a new one of the given size.
656     virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
657
658     virtual void addRelocation(const MachineRelocation &MR) {
659       Relocations.push_back(MR);
660     }
661     
662     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
663       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
664         MBBLocations.resize((MBB->getNumber()+1)*2);
665       MBBLocations[MBB->getNumber()] = getCurrentPCValue();
666       DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
667            << (void*) getCurrentPCValue() << "]\n";
668     }
669
670     virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
671     virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
672
673     virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
674       assert(MBBLocations.size() > (unsigned)MBB->getNumber() && 
675              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
676       return MBBLocations[MBB->getNumber()];
677     }
678
679     /// deallocateMemForFunction - Deallocate all memory for the specified
680     /// function body.
681     void deallocateMemForFunction(Function *F);
682
683     /// AddStubToCurrentFunction - Mark the current function being JIT'd as
684     /// using the stub at the specified address. Allows
685     /// deallocateMemForFunction to also remove stubs no longer referenced.
686     void AddStubToCurrentFunction(void *Stub);
687     
688     /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
689     /// MachineRelocations that reference external functions by name.
690     const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
691     
692     virtual void emitLabel(uint64_t LabelID) {
693       if (LabelLocations.size() <= LabelID)
694         LabelLocations.resize((LabelID+1)*2);
695       LabelLocations[LabelID] = getCurrentPCValue();
696     }
697
698     virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
699       assert(LabelLocations.size() > (unsigned)LabelID && 
700              LabelLocations[LabelID] && "Label not emitted!");
701       return LabelLocations[LabelID];
702     }
703  
704     virtual void setModuleInfo(MachineModuleInfo* Info) {
705       MMI = Info;
706       if (ExceptionHandling) DE->setModuleInfo(Info);
707     }
708
709     void setMemoryExecutable(void) {
710       MemMgr->setMemoryExecutable();
711     }
712     
713     JITMemoryManager *getMemMgr(void) const { return MemMgr; }
714
715   private:
716     void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
717     void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
718                                     bool NoNeedStub);
719     unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
720     unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
721     unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
722     unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
723   };
724 }
725
726 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
727                                      bool DoesntNeedStub) {
728   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
729     return TheJIT->getOrEmitGlobalVariable(GV);
730
731   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
732     return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
733
734   // If we have already compiled the function, return a pointer to its body.
735   Function *F = cast<Function>(V);
736   void *ResultPtr;
737   if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
738     // Return the function stub if it's already created.
739     ResultPtr = Resolver.getFunctionStubIfAvailable(F);
740     if (ResultPtr)
741       AddStubToCurrentFunction(ResultPtr);
742   } else {
743     ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
744   }
745   if (ResultPtr) return ResultPtr;
746
747   // If this is an external function pointer, we can force the JIT to
748   // 'compile' it, which really just adds it to the map.  In dlsym mode, 
749   // external functions are forced through a stub, regardless of reloc type.
750   if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
751       DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
752     return TheJIT->getPointerToFunction(F);
753
754   // Okay, the function has not been compiled yet, if the target callback
755   // mechanism is capable of rewriting the instruction directly, prefer to do
756   // that instead of emitting a stub.  This uses the lazy resolver, so is not
757   // legal if lazy compilation is disabled.
758   if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
759     return Resolver.AddCallbackAtLocation(F, Reference);
760
761   // Otherwise, we have to emit a stub.
762   void *StubAddr = Resolver.getFunctionStub(F);
763
764   // Add the stub to the current function's list of referenced stubs, so we can
765   // deallocate them if the current function is ever freed.  It's possible to
766   // return null from getFunctionStub in the case of a weak extern that fails
767   // to resolve.
768   if (StubAddr)
769     AddStubToCurrentFunction(StubAddr);
770
771   return StubAddr;
772 }
773
774 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
775                                             bool NoNeedStub) {
776   // Make sure GV is emitted first, and create a stub containing the fully
777   // resolved address.
778   void *GVAddress = getPointerToGlobal(V, Reference, true);
779   void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
780   
781   // Add the stub to the current function's list of referenced stubs, so we can
782   // deallocate them if the current function is ever freed.
783   AddStubToCurrentFunction(StubAddr);
784   
785   return StubAddr;
786 }
787
788 void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
789   if (!TheJIT->areDlsymStubsEnabled())
790     return;
791   
792   assert(CurFn && "Stub added to current function, but current function is 0!");
793   
794   SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
795   StubsUsed.push_back(StubAddr);
796
797   SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
798   FnRefs.insert(CurFn);
799 }
800
801 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
802                                            const TargetData *TD) {
803   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
804   if (Constants.empty()) return 0;
805
806   unsigned Size = 0;
807   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
808     MachineConstantPoolEntry CPE = Constants[i];
809     unsigned AlignMask = CPE.getAlignment() - 1;
810     Size = (Size + AlignMask) & ~AlignMask;
811     const Type *Ty = CPE.getType();
812     Size += TD->getTypeAllocSize(Ty);
813   }
814   return Size;
815 }
816
817 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
818   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
819   if (JT.empty()) return 0;
820   
821   unsigned NumEntries = 0;
822   for (unsigned i = 0, e = JT.size(); i != e; ++i)
823     NumEntries += JT[i].MBBs.size();
824
825   unsigned EntrySize = MJTI->getEntrySize();
826
827   return NumEntries * EntrySize;
828 }
829
830 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
831   if (Alignment == 0) Alignment = 1;
832   // Since we do not know where the buffer will be allocated, be pessimistic. 
833   return Size + Alignment;
834 }
835
836 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
837 /// into the running total Size.
838
839 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
840   const Type *ElTy = GV->getType()->getElementType();
841   size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
842   size_t GVAlign = 
843       (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
844   DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
845   DEBUG(GV->dump());
846   // Assume code section ends with worst possible alignment, so first
847   // variable needs maximal padding.
848   if (Size==0)
849     Size = 1;
850   Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
851   Size += GVSize;
852   return Size;
853 }
854
855 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
856 /// but are referenced from the constant; put them in GVSet and add their
857 /// size into the running total Size.
858
859 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C, 
860                                               unsigned Size) {
861   // If its undefined, return the garbage.
862   if (isa<UndefValue>(C))
863     return Size;
864
865   // If the value is a ConstantExpr
866   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
867     Constant *Op0 = CE->getOperand(0);
868     switch (CE->getOpcode()) {
869     case Instruction::GetElementPtr:
870     case Instruction::Trunc:
871     case Instruction::ZExt:
872     case Instruction::SExt:
873     case Instruction::FPTrunc:
874     case Instruction::FPExt:
875     case Instruction::UIToFP:
876     case Instruction::SIToFP:
877     case Instruction::FPToUI:
878     case Instruction::FPToSI:
879     case Instruction::PtrToInt:
880     case Instruction::IntToPtr:
881     case Instruction::BitCast: {
882       Size = addSizeOfGlobalsInConstantVal(Op0, Size);
883       break;
884     }
885     case Instruction::Add:
886     case Instruction::Sub:
887     case Instruction::Mul:
888     case Instruction::UDiv:
889     case Instruction::SDiv:
890     case Instruction::URem:
891     case Instruction::SRem:
892     case Instruction::And:
893     case Instruction::Or:
894     case Instruction::Xor: {
895       Size = addSizeOfGlobalsInConstantVal(Op0, Size);
896       Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
897       break;
898     }
899     default: {
900        cerr << "ConstantExpr not handled: " << *CE << "\n";
901       abort();
902     }
903     }
904   }
905
906   if (C->getType()->getTypeID() == Type::PointerTyID)
907     if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
908       if (GVSet.insert(GV))
909         Size = addSizeOfGlobal(GV, Size);
910
911   return Size;
912 }
913
914 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
915 /// but are referenced from the given initializer.
916
917 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init, 
918                                               unsigned Size) {
919   if (!isa<UndefValue>(Init) &&
920       !isa<ConstantVector>(Init) &&
921       !isa<ConstantAggregateZero>(Init) &&
922       !isa<ConstantArray>(Init) &&
923       !isa<ConstantStruct>(Init) &&
924       Init->getType()->isFirstClassType())
925     Size = addSizeOfGlobalsInConstantVal(Init, Size);
926   return Size;
927 }
928
929 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
930 /// globals; then walk the initializers of those globals looking for more.
931 /// If their size has not been considered yet, add it into the running total
932 /// Size.
933
934 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
935   unsigned Size = 0;
936   GVSet.clear();
937
938   for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
939        MBB != E; ++MBB) {
940     for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
941          I != E; ++I) {
942       const TargetInstrDesc &Desc = I->getDesc();
943       const MachineInstr &MI = *I;
944       unsigned NumOps = Desc.getNumOperands();
945       for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
946         const MachineOperand &MO = MI.getOperand(CurOp);
947         if (MO.isGlobal()) {
948           GlobalValue* V = MO.getGlobal();
949           const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
950           if (!GV)
951             continue;
952           // If seen in previous function, it will have an entry here.
953           if (TheJIT->getPointerToGlobalIfAvailable(GV))
954             continue;
955           // If seen earlier in this function, it will have an entry here.
956           // FIXME: it should be possible to combine these tables, by
957           // assuming the addresses of the new globals in this module
958           // start at 0 (or something) and adjusting them after codegen
959           // complete.  Another possibility is to grab a marker bit in GV.
960           if (GVSet.insert(GV))
961             // A variable as yet unseen.  Add in its size.
962             Size = addSizeOfGlobal(GV, Size);
963         }
964       }
965     }
966   }
967   DOUT << "JIT: About to look through initializers\n";
968   // Look for more globals that are referenced only from initializers.
969   // GVSet.end is computed each time because the set can grow as we go.
970   for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin(); 
971        I != GVSet.end(); I++) {
972     const GlobalVariable* GV = *I;
973     if (GV->hasInitializer())
974       Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
975   }
976
977   return Size;
978 }
979
980 void JITEmitter::startFunction(MachineFunction &F) {
981   DOUT << "JIT: Starting CodeGen of Function "
982        << F.getFunction()->getName() << "\n";
983
984   uintptr_t ActualSize = 0;
985   // Set the memory writable, if it's not already
986   MemMgr->setMemoryWritable();
987   if (MemMgr->NeedsExactSize()) {
988     DOUT << "JIT: ExactSize\n";
989     const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
990     MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
991     MachineConstantPool *MCP = F.getConstantPool();
992     
993     // Ensure the constant pool/jump table info is at least 4-byte aligned.
994     ActualSize = RoundUpToAlign(ActualSize, 16);
995     
996     // Add the alignment of the constant pool
997     ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
998
999     // Add the constant pool size
1000     ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1001
1002     // Add the aligment of the jump table info
1003     ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
1004
1005     // Add the jump table size
1006     ActualSize += GetJumpTableSizeInBytes(MJTI);
1007     
1008     // Add the alignment for the function
1009     ActualSize = RoundUpToAlign(ActualSize,
1010                                 std::max(F.getFunction()->getAlignment(), 8U));
1011
1012     // Add the function size
1013     ActualSize += TII->GetFunctionSizeInBytes(F);
1014
1015     DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
1016     // Add the size of the globals that will be allocated after this function.
1017     // These are all the ones referenced from this function that were not
1018     // previously allocated.
1019     ActualSize += GetSizeOfGlobalsInBytes(F);
1020     DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
1021   }
1022
1023   BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1024                                                          ActualSize);
1025   BufferEnd = BufferBegin+ActualSize;
1026   
1027   // Ensure the constant pool/jump table info is at least 4-byte aligned.
1028   emitAlignment(16);
1029
1030   emitConstantPool(F.getConstantPool());
1031   initJumpTableInfo(F.getJumpTableInfo());
1032
1033   // About to start emitting the machine code for the function.
1034   emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
1035   TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
1036
1037   MBBLocations.clear();
1038 }
1039
1040 bool JITEmitter::finishFunction(MachineFunction &F) {
1041   if (CurBufferPtr == BufferEnd) {
1042     // FIXME: Allocate more space, then try again.
1043     cerr << "JIT: Ran out of space for generated machine code!\n";
1044     abort();
1045   }
1046   
1047   emitJumpTableInfo(F.getJumpTableInfo());
1048   
1049   // FnStart is the start of the text, not the start of the constant pool and
1050   // other per-function data.
1051   unsigned char *FnStart =
1052     (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
1053
1054   // FnEnd is the end of the function's machine code.
1055   unsigned char *FnEnd = CurBufferPtr;
1056
1057   if (!Relocations.empty()) {
1058     CurFn = F.getFunction();
1059     NumRelos += Relocations.size();
1060
1061     // Resolve the relocations to concrete pointers.
1062     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1063       MachineRelocation &MR = Relocations[i];
1064       void *ResultPtr = 0;
1065       if (!MR.letTargetResolve()) {
1066         if (MR.isExternalSymbol()) {
1067           ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1068                                                         false);
1069           DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1070                << ResultPtr << "]\n";  
1071
1072           // If the target REALLY wants a stub for this function, emit it now.
1073           if (!MR.doesntNeedStub()) {
1074             if (!TheJIT->areDlsymStubsEnabled()) {
1075               ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1076             } else {
1077               void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1078               if (!Stub) {
1079                 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1080                 AddStubToCurrentFunction(Stub);
1081               }
1082               ResultPtr = Stub;
1083             }
1084           }
1085         } else if (MR.isGlobalValue()) {
1086           ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1087                                          BufferBegin+MR.getMachineCodeOffset(),
1088                                          MR.doesntNeedStub());
1089         } else if (MR.isIndirectSymbol()) {
1090           ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
1091                                           BufferBegin+MR.getMachineCodeOffset(),
1092                                           MR.doesntNeedStub());
1093         } else if (MR.isBasicBlock()) {
1094           ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1095         } else if (MR.isConstantPoolIndex()) {
1096           ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1097         } else {
1098           assert(MR.isJumpTableIndex());
1099           ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1100         }
1101
1102         MR.setResultPointer(ResultPtr);
1103       }
1104
1105       // if we are managing the GOT and the relocation wants an index,
1106       // give it one
1107       if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
1108         unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
1109         MR.setGOTIndex(idx);
1110         if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
1111           DOUT << "JIT: GOT was out of date for " << ResultPtr
1112                << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1113                << "\n";
1114           ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
1115         }
1116       }
1117     }
1118
1119     CurFn = 0;
1120     TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
1121                                   Relocations.size(), MemMgr->getGOTBase());
1122   }
1123
1124   // Update the GOT entry for F to point to the new code.
1125   if (MemMgr->isManagingGOT()) {
1126     unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
1127     if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
1128       DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
1129            << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1130       ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
1131     }
1132   }
1133
1134   // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1135   // global variables that were referenced in the relocations.
1136   MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
1137
1138   if (CurBufferPtr == BufferEnd) {
1139     // FIXME: Allocate more space, then try again.
1140     cerr << "JIT: Ran out of space for generated machine code!\n";
1141     abort();
1142   }
1143
1144   BufferBegin = CurBufferPtr = 0;
1145   NumBytes += FnEnd-FnStart;
1146
1147   // Invalidate the icache if necessary.
1148   sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
1149   
1150   // Add it to the JIT symbol table if the host wants it.
1151   AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1152                            FnStart, FnEnd-FnStart);
1153
1154   DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1155        << "] Function: " << F.getFunction()->getName()
1156        << ": " << (FnEnd-FnStart) << " bytes of text, "
1157        << Relocations.size() << " relocations\n";
1158   Relocations.clear();
1159   ConstPoolAddresses.clear();
1160
1161   // Mark code region readable and executable if it's not so already.
1162   MemMgr->setMemoryExecutable();
1163
1164 #ifndef NDEBUG
1165   {
1166     if (sys::hasDisassembler()) {
1167       DOUT << "JIT: Disassembled code:\n";
1168       DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
1169     } else {
1170       DOUT << "JIT: Binary code:\n";
1171       DOUT << std::hex;
1172       unsigned char* q = FnStart;
1173       for (int i = 0; q < FnEnd; q += 4, ++i) {
1174         if (i == 4)
1175           i = 0;
1176         if (i == 0)
1177           DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1178                << (long)(q - FnStart) << ": ";
1179         bool Done = false;
1180         for (int j = 3; j >= 0; --j) {
1181           if (q + j >= FnEnd)
1182             Done = true;
1183           else
1184             DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1185         }
1186         if (Done)
1187           break;
1188         DOUT << ' ';
1189         if (i == 3)
1190           DOUT << '\n';
1191       }
1192       DOUT << std::dec;
1193       DOUT<< '\n';
1194     }
1195   }
1196 #endif
1197   if (ExceptionHandling) {
1198     uintptr_t ActualSize = 0;
1199     SavedBufferBegin = BufferBegin;
1200     SavedBufferEnd = BufferEnd;
1201     SavedCurBufferPtr = CurBufferPtr;
1202     
1203     if (MemMgr->NeedsExactSize()) {
1204       ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1205     }
1206
1207     BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1208                                                              ActualSize);
1209     BufferEnd = BufferBegin+ActualSize;
1210     unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
1211     MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1212                               FrameRegister);
1213     BufferBegin = SavedBufferBegin;
1214     BufferEnd = SavedBufferEnd;
1215     CurBufferPtr = SavedCurBufferPtr;
1216
1217     TheJIT->RegisterTable(FrameRegister);
1218   }
1219
1220   if (MMI)
1221     MMI->EndFunction();
1222  
1223   return false;
1224 }
1225
1226 /// deallocateMemForFunction - Deallocate all memory for the specified
1227 /// function body.  Also drop any references the function has to stubs.
1228 void JITEmitter::deallocateMemForFunction(Function *F) {
1229   MemMgr->deallocateMemForFunction(F);
1230
1231   // If the function did not reference any stubs, return.
1232   if (CurFnStubUses.find(F) == CurFnStubUses.end())
1233     return;
1234   
1235   // For each referenced stub, erase the reference to this function, and then
1236   // erase the list of referenced stubs.
1237   SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1238   for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1239     void *Stub = StubList[i];
1240     
1241     // If we already invalidated this stub for this function, continue.
1242     if (StubFnRefs.count(Stub) == 0)
1243       continue;
1244       
1245     SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1246     FnRefs.erase(F);
1247     
1248     // If this function was the last reference to the stub, invalidate the stub
1249     // in the JITResolver.  Were there a memory manager deallocateStub routine,
1250     // we could call that at this point too.
1251     if (FnRefs.empty()) {
1252       DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
1253       StubFnRefs.erase(Stub);
1254
1255       // Invalidate the stub.  If it is a GV stub, update the JIT's global
1256       // mapping for that GV to zero, otherwise, search the string map of
1257       // external function names to stubs and remove the entry for this stub.
1258       GlobalValue *GV = Resolver.invalidateStub(Stub);
1259       if (GV) {
1260         TheJIT->updateGlobalMapping(GV, 0);
1261       } else {
1262         for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1263              e = ExtFnStubs.end(); i != e; ++i) {
1264           if (i->second == Stub) {
1265             ExtFnStubs.erase(i);
1266             break;
1267           }
1268         }
1269       }
1270     }
1271   }
1272   CurFnStubUses.erase(F);
1273 }
1274
1275
1276 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1277   if (BufferBegin)
1278     return MachineCodeEmitter::allocateSpace(Size, Alignment);
1279
1280   // create a new memory block if there is no active one.
1281   // care must be taken so that BufferBegin is invalidated when a
1282   // block is trimmed
1283   BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1284   BufferEnd = BufferBegin+Size;
1285   return CurBufferPtr;
1286 }
1287
1288 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1289   if (TheJIT->getJITInfo().hasCustomConstantPool())
1290     return;
1291
1292   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1293   if (Constants.empty()) return;
1294
1295   unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1296   unsigned Align = MCP->getConstantPoolAlignment();
1297   ConstantPoolBase = allocateSpace(Size, Align);
1298   ConstantPool = MCP;
1299
1300   if (ConstantPoolBase == 0) return;  // Buffer overflow.
1301
1302   DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1303        << "] (size: " << Size << ", alignment: " << Align << ")\n";
1304
1305   // Initialize the memory for all of the constant pool entries.
1306   unsigned Offset = 0;
1307   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1308     MachineConstantPoolEntry CPE = Constants[i];
1309     unsigned AlignMask = CPE.getAlignment() - 1;
1310     Offset = (Offset + AlignMask) & ~AlignMask;
1311
1312     uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1313     ConstPoolAddresses.push_back(CAddr);
1314     if (CPE.isMachineConstantPoolEntry()) {
1315       // FIXME: add support to lower machine constant pool values into bytes!
1316       cerr << "Initialize memory with machine specific constant pool entry"
1317            << " has not been implemented!\n";
1318       abort();
1319     }
1320     TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1321     DOUT << "JIT:   CP" << i << " at [0x"
1322          << std::hex << CAddr << std::dec << "]\n";
1323
1324     const Type *Ty = CPE.Val.ConstVal->getType();
1325     Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
1326   }
1327 }
1328
1329 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1330   if (TheJIT->getJITInfo().hasCustomJumpTables())
1331     return;
1332
1333   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1334   if (JT.empty()) return;
1335   
1336   unsigned NumEntries = 0;
1337   for (unsigned i = 0, e = JT.size(); i != e; ++i)
1338     NumEntries += JT[i].MBBs.size();
1339
1340   unsigned EntrySize = MJTI->getEntrySize();
1341
1342   // Just allocate space for all the jump tables now.  We will fix up the actual
1343   // MBB entries in the tables after we emit the code for each block, since then
1344   // we will know the final locations of the MBBs in memory.
1345   JumpTable = MJTI;
1346   JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1347 }
1348
1349 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1350   if (TheJIT->getJITInfo().hasCustomJumpTables())
1351     return;
1352
1353   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1354   if (JT.empty() || JumpTableBase == 0) return;
1355   
1356   if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1357     assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1358     // For each jump table, place the offset from the beginning of the table
1359     // to the target address.
1360     int *SlotPtr = (int*)JumpTableBase;
1361
1362     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1363       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1364       // Store the offset of the basic block for this jump table slot in the
1365       // memory we allocated for the jump table in 'initJumpTableInfo'
1366       uintptr_t Base = (uintptr_t)SlotPtr;
1367       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1368         uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1369         *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1370       }
1371     }
1372   } else {
1373     assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1374     
1375     // For each jump table, map each target in the jump table to the address of 
1376     // an emitted MachineBasicBlock.
1377     intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1378
1379     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1380       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1381       // Store the address of the basic block for this jump table slot in the
1382       // memory we allocated for the jump table in 'initJumpTableInfo'
1383       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1384         *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1385     }
1386   }
1387 }
1388
1389 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1390                              unsigned Alignment) {
1391   SavedBufferBegin = BufferBegin;
1392   SavedBufferEnd = BufferEnd;
1393   SavedCurBufferPtr = CurBufferPtr;
1394   
1395   BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1396   BufferEnd = BufferBegin+StubSize+1;
1397 }
1398
1399 void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1400                              unsigned StubSize) {
1401   SavedBufferBegin = BufferBegin;
1402   SavedBufferEnd = BufferEnd;
1403   SavedCurBufferPtr = CurBufferPtr;
1404   
1405   BufferBegin = CurBufferPtr = (unsigned char *)Buffer;
1406   BufferEnd = BufferBegin+StubSize+1;
1407 }
1408
1409 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1410   NumBytes += getCurrentPCOffset();
1411   std::swap(SavedBufferBegin, BufferBegin);
1412   BufferEnd = SavedBufferEnd;
1413   CurBufferPtr = SavedCurBufferPtr;
1414   return SavedBufferBegin;
1415 }
1416
1417 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1418 // in the constant pool that was last emitted with the 'emitConstantPool'
1419 // method.
1420 //
1421 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1422   assert(ConstantNum < ConstantPool->getConstants().size() &&
1423          "Invalid ConstantPoolIndex!");
1424   return ConstPoolAddresses[ConstantNum];
1425 }
1426
1427 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1428 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1429 //
1430 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1431   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1432   assert(Index < JT.size() && "Invalid jump table index!");
1433   
1434   unsigned Offset = 0;
1435   unsigned EntrySize = JumpTable->getEntrySize();
1436   
1437   for (unsigned i = 0; i < Index; ++i)
1438     Offset += JT[i].MBBs.size();
1439   
1440    Offset *= EntrySize;
1441   
1442   return (uintptr_t)((char *)JumpTableBase + Offset);
1443 }
1444
1445 //===----------------------------------------------------------------------===//
1446 //  Public interface to this file
1447 //===----------------------------------------------------------------------===//
1448
1449 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1450   return new JITEmitter(jit, JMM);
1451 }
1452
1453 // getPointerToNamedFunction - This function is used as a global wrapper to
1454 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1455 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1456 // need to resolve function(s) that are being mis-codegenerated, so we need to
1457 // resolve their addresses at runtime, and this is the way to do it.
1458 extern "C" {
1459   void *getPointerToNamedFunction(const char *Name) {
1460     if (Function *F = TheJIT->FindFunctionNamed(Name))
1461       return TheJIT->getPointerToFunction(F);
1462     return TheJIT->getPointerToNamedFunction(Name);
1463   }
1464 }
1465
1466 // getPointerToFunctionOrStub - If the specified function has been
1467 // code-gen'd, return a pointer to the function.  If not, compile it, or use
1468 // a stub to implement lazy compilation if available.
1469 //
1470 void *JIT::getPointerToFunctionOrStub(Function *F) {
1471   // If we have already code generated the function, just return the address.
1472   if (void *Addr = getPointerToGlobalIfAvailable(F))
1473     return Addr;
1474   
1475   // Get a stub if the target supports it.
1476   assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1477   JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1478   return JE->getJITResolver().getFunctionStub(F);
1479 }
1480
1481 void JIT::updateFunctionStub(Function *F) {
1482   // Get the empty stub we generated earlier.
1483   assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1484   JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1485   void *Stub = JE->getJITResolver().getFunctionStub(F);
1486
1487   // Tell the target jit info to rewrite the stub at the specified address,
1488   // rather than creating a new one.
1489   void *Addr = getPointerToGlobalIfAvailable(F);
1490   getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1491 }
1492
1493 /// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1494 /// that were emitted during code generation.
1495 ///
1496 void JIT::updateDlsymStubTable() {
1497   assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1498   JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1499   
1500   SmallVector<GlobalValue*, 8> GVs;
1501   SmallVector<void*, 8> Ptrs;
1502   const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
1503
1504   JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1505
1506   unsigned nStubs = GVs.size() + ExtFns.size();
1507   
1508   // If there are no relocatable stubs, return.
1509   if (nStubs == 0)
1510     return;
1511
1512   // If there are no new relocatable stubs, return.
1513   void *CurTable = JE->getMemMgr()->getDlsymTable();
1514   if (CurTable && (*(unsigned *)CurTable == nStubs))
1515     return;
1516   
1517   // Calculate the size of the stub info
1518   unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
1519   
1520   SmallVector<unsigned, 8> Offsets;
1521   for (unsigned i = 0; i != GVs.size(); ++i) {
1522     Offsets.push_back(offset);
1523     offset += GVs[i]->getName().length() + 1;
1524   }
1525   for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end(); 
1526        i != e; ++i) {
1527     Offsets.push_back(offset);
1528     offset += strlen(i->first()) + 1;
1529   }
1530   
1531   // Allocate space for the new "stub", which contains the dlsym table.
1532   JE->startGVStub(0, offset, 4);
1533   
1534   // Emit the number of records
1535   MCE->emitInt32(nStubs);
1536   
1537   // Emit the string offsets
1538   for (unsigned i = 0; i != nStubs; ++i)
1539     MCE->emitInt32(Offsets[i]);
1540   
1541   // Emit the pointers.  Verify that they are at least 2-byte aligned, and set
1542   // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1543   // relocation can write the relocated pointer at the appropriate place in
1544   // the stub.
1545   for (unsigned i = 0; i != GVs.size(); ++i) {
1546     intptr_t Ptr = (intptr_t)Ptrs[i];
1547     assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1548     
1549     if (isa<Function>(GVs[i]))
1550       Ptr |= (intptr_t)1;
1551            
1552     if (sizeof(Ptr) == 8)
1553       MCE->emitInt64(Ptr);
1554     else
1555       MCE->emitInt32(Ptr);
1556   }
1557   for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end(); 
1558        i != e; ++i) {
1559     intptr_t Ptr = (intptr_t)i->second | 1;
1560
1561     if (sizeof(Ptr) == 8)
1562       MCE->emitInt64(Ptr);
1563     else
1564       MCE->emitInt32(Ptr);
1565   }
1566   
1567   // Emit the strings.
1568   for (unsigned i = 0; i != GVs.size(); ++i)
1569     MCE->emitString(GVs[i]->getName());
1570   for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end(); 
1571        i != e; ++i)
1572     MCE->emitString(i->first());
1573   
1574   // Tell the JIT memory manager where it is.  The JIT Memory Manager will
1575   // deallocate space for the old one, if one existed.
1576   JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1577 }
1578
1579 /// freeMachineCodeForFunction - release machine code memory for given Function.
1580 ///
1581 void JIT::freeMachineCodeForFunction(Function *F) {
1582
1583   // Delete translation for this from the ExecutionEngine, so it will get
1584   // retranslated next time it is used.
1585   void *OldPtr = updateGlobalMapping(F, 0);
1586
1587   if (OldPtr)
1588     RemoveFunctionFromSymbolTable(OldPtr);
1589
1590   // Free the actual memory for the function body and related stuff.
1591   assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1592   cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
1593 }
1594