Under unusual circumstances (jitting a function that causes the creation of
[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->getTypePaddedSize(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()->getTypePaddedSize(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   if (!Relocations.empty()) {
1055     CurFn = F.getFunction();
1056     NumRelos += Relocations.size();
1057
1058     // Resolve the relocations to concrete pointers.
1059     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1060       MachineRelocation &MR = Relocations[i];
1061       void *ResultPtr = 0;
1062       if (!MR.letTargetResolve()) {
1063         if (MR.isExternalSymbol()) {
1064           ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1065                                                         false);
1066           DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1067                << ResultPtr << "]\n";  
1068
1069           // If the target REALLY wants a stub for this function, emit it now.
1070           if (!MR.doesntNeedStub()) {
1071             if (!TheJIT->areDlsymStubsEnabled()) {
1072               ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1073             } else {
1074               void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1075               if (!Stub) {
1076                 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1077                 AddStubToCurrentFunction(Stub);
1078               }
1079               ResultPtr = Stub;
1080             }
1081           }
1082         } else if (MR.isGlobalValue()) {
1083           ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1084                                          BufferBegin+MR.getMachineCodeOffset(),
1085                                          MR.doesntNeedStub());
1086         } else if (MR.isIndirectSymbol()) {
1087           ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
1088                                           BufferBegin+MR.getMachineCodeOffset(),
1089                                           MR.doesntNeedStub());
1090         } else if (MR.isBasicBlock()) {
1091           ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1092         } else if (MR.isConstantPoolIndex()) {
1093           ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1094         } else {
1095           assert(MR.isJumpTableIndex());
1096           ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1097         }
1098
1099         MR.setResultPointer(ResultPtr);
1100       }
1101
1102       // if we are managing the GOT and the relocation wants an index,
1103       // give it one
1104       if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
1105         unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
1106         MR.setGOTIndex(idx);
1107         if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
1108           DOUT << "JIT: GOT was out of date for " << ResultPtr
1109                << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1110                << "\n";
1111           ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
1112         }
1113       }
1114     }
1115
1116     CurFn = 0;
1117     TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
1118                                   Relocations.size(), MemMgr->getGOTBase());
1119   }
1120
1121   // Update the GOT entry for F to point to the new code.
1122   if (MemMgr->isManagingGOT()) {
1123     unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
1124     if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
1125       DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
1126            << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1127       ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
1128     }
1129   }
1130
1131   unsigned char *FnEnd = CurBufferPtr;
1132
1133   MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
1134
1135   if (CurBufferPtr == BufferEnd) {
1136     // FIXME: Allocate more space, then try again.
1137     cerr << "JIT: Ran out of space for generated machine code!\n";
1138     abort();
1139   }
1140
1141   BufferBegin = CurBufferPtr = 0;
1142   NumBytes += FnEnd-FnStart;
1143
1144   // Invalidate the icache if necessary.
1145   sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
1146   
1147   // Add it to the JIT symbol table if the host wants it.
1148   AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1149                            FnStart, FnEnd-FnStart);
1150
1151   DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1152        << "] Function: " << F.getFunction()->getName()
1153        << ": " << (FnEnd-FnStart) << " bytes of text, "
1154        << Relocations.size() << " relocations\n";
1155   Relocations.clear();
1156   ConstPoolAddresses.clear();
1157
1158   // Mark code region readable and executable if it's not so already.
1159   MemMgr->setMemoryExecutable();
1160
1161 #ifndef NDEBUG
1162   {
1163     if (sys::hasDisassembler()) {
1164       DOUT << "JIT: Disassembled code:\n";
1165       DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
1166     } else {
1167       DOUT << "JIT: Binary code:\n";
1168       DOUT << std::hex;
1169       unsigned char* q = FnStart;
1170       for (int i = 0; q < FnEnd; q += 4, ++i) {
1171         if (i == 4)
1172           i = 0;
1173         if (i == 0)
1174           DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1175                << (long)(q - FnStart) << ": ";
1176         bool Done = false;
1177         for (int j = 3; j >= 0; --j) {
1178           if (q + j >= FnEnd)
1179             Done = true;
1180           else
1181             DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1182         }
1183         if (Done)
1184           break;
1185         DOUT << ' ';
1186         if (i == 3)
1187           DOUT << '\n';
1188       }
1189       DOUT << std::dec;
1190       DOUT<< '\n';
1191     }
1192   }
1193 #endif
1194   if (ExceptionHandling) {
1195     uintptr_t ActualSize = 0;
1196     SavedBufferBegin = BufferBegin;
1197     SavedBufferEnd = BufferEnd;
1198     SavedCurBufferPtr = CurBufferPtr;
1199     
1200     if (MemMgr->NeedsExactSize()) {
1201       ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1202     }
1203
1204     BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1205                                                              ActualSize);
1206     BufferEnd = BufferBegin+ActualSize;
1207     unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
1208     MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1209                               FrameRegister);
1210     BufferBegin = SavedBufferBegin;
1211     BufferEnd = SavedBufferEnd;
1212     CurBufferPtr = SavedCurBufferPtr;
1213
1214     TheJIT->RegisterTable(FrameRegister);
1215   }
1216
1217   if (MMI)
1218     MMI->EndFunction();
1219  
1220   return false;
1221 }
1222
1223 /// deallocateMemForFunction - Deallocate all memory for the specified
1224 /// function body.  Also drop any references the function has to stubs.
1225 void JITEmitter::deallocateMemForFunction(Function *F) {
1226   MemMgr->deallocateMemForFunction(F);
1227
1228   // If the function did not reference any stubs, return.
1229   if (CurFnStubUses.find(F) == CurFnStubUses.end())
1230     return;
1231   
1232   // For each referenced stub, erase the reference to this function, and then
1233   // erase the list of referenced stubs.
1234   SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1235   for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1236     void *Stub = StubList[i];
1237     
1238     // If we already invalidated this stub for this function, continue.
1239     if (StubFnRefs.count(Stub) == 0)
1240       continue;
1241       
1242     SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1243     FnRefs.erase(F);
1244     
1245     // If this function was the last reference to the stub, invalidate the stub
1246     // in the JITResolver.  Were there a memory manager deallocateStub routine,
1247     // we could call that at this point too.
1248     if (FnRefs.empty()) {
1249       DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
1250       StubFnRefs.erase(Stub);
1251
1252       // Invalidate the stub.  If it is a GV stub, update the JIT's global
1253       // mapping for that GV to zero, otherwise, search the string map of
1254       // external function names to stubs and remove the entry for this stub.
1255       GlobalValue *GV = Resolver.invalidateStub(Stub);
1256       if (GV) {
1257         TheJIT->updateGlobalMapping(GV, 0);
1258       } else {
1259         for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1260              e = ExtFnStubs.end(); i != e; ++i) {
1261           if (i->second == Stub) {
1262             ExtFnStubs.erase(i);
1263             break;
1264           }
1265         }
1266       }
1267     }
1268   }
1269   CurFnStubUses.erase(F);
1270 }
1271
1272
1273 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1274   if (BufferBegin)
1275     return MachineCodeEmitter::allocateSpace(Size, Alignment);
1276
1277   // create a new memory block if there is no active one.
1278   // care must be taken so that BufferBegin is invalidated when a
1279   // block is trimmed
1280   BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1281   BufferEnd = BufferBegin+Size;
1282   return CurBufferPtr;
1283 }
1284
1285 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1286   if (TheJIT->getJITInfo().hasCustomConstantPool())
1287     return;
1288
1289   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1290   if (Constants.empty()) return;
1291
1292   unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1293   unsigned Align = MCP->getConstantPoolAlignment();
1294   ConstantPoolBase = allocateSpace(Size, Align);
1295   ConstantPool = MCP;
1296
1297   if (ConstantPoolBase == 0) return;  // Buffer overflow.
1298
1299   DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1300        << "] (size: " << Size << ", alignment: " << Align << ")\n";
1301
1302   // Initialize the memory for all of the constant pool entries.
1303   unsigned Offset = 0;
1304   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1305     MachineConstantPoolEntry CPE = Constants[i];
1306     unsigned AlignMask = CPE.getAlignment() - 1;
1307     Offset = (Offset + AlignMask) & ~AlignMask;
1308
1309     uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1310     ConstPoolAddresses.push_back(CAddr);
1311     if (CPE.isMachineConstantPoolEntry()) {
1312       // FIXME: add support to lower machine constant pool values into bytes!
1313       cerr << "Initialize memory with machine specific constant pool entry"
1314            << " has not been implemented!\n";
1315       abort();
1316     }
1317     TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1318     DOUT << "JIT:   CP" << i << " at [0x"
1319          << std::hex << CAddr << std::dec << "]\n";
1320
1321     const Type *Ty = CPE.Val.ConstVal->getType();
1322     Offset += TheJIT->getTargetData()->getTypePaddedSize(Ty);
1323   }
1324 }
1325
1326 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1327   if (TheJIT->getJITInfo().hasCustomJumpTables())
1328     return;
1329
1330   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1331   if (JT.empty()) return;
1332   
1333   unsigned NumEntries = 0;
1334   for (unsigned i = 0, e = JT.size(); i != e; ++i)
1335     NumEntries += JT[i].MBBs.size();
1336
1337   unsigned EntrySize = MJTI->getEntrySize();
1338
1339   // Just allocate space for all the jump tables now.  We will fix up the actual
1340   // MBB entries in the tables after we emit the code for each block, since then
1341   // we will know the final locations of the MBBs in memory.
1342   JumpTable = MJTI;
1343   JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1344 }
1345
1346 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1347   if (TheJIT->getJITInfo().hasCustomJumpTables())
1348     return;
1349
1350   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1351   if (JT.empty() || JumpTableBase == 0) return;
1352   
1353   if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1354     assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1355     // For each jump table, place the offset from the beginning of the table
1356     // to the target address.
1357     int *SlotPtr = (int*)JumpTableBase;
1358
1359     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1360       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1361       // Store the offset of the basic block for this jump table slot in the
1362       // memory we allocated for the jump table in 'initJumpTableInfo'
1363       uintptr_t Base = (uintptr_t)SlotPtr;
1364       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1365         uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1366         *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1367       }
1368     }
1369   } else {
1370     assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1371     
1372     // For each jump table, map each target in the jump table to the address of 
1373     // an emitted MachineBasicBlock.
1374     intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1375
1376     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1377       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1378       // Store the address of the basic block for this jump table slot in the
1379       // memory we allocated for the jump table in 'initJumpTableInfo'
1380       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1381         *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1382     }
1383   }
1384 }
1385
1386 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1387                              unsigned Alignment) {
1388   SavedBufferBegin = BufferBegin;
1389   SavedBufferEnd = BufferEnd;
1390   SavedCurBufferPtr = CurBufferPtr;
1391   
1392   BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1393   BufferEnd = BufferBegin+StubSize+1;
1394 }
1395
1396 void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1397                              unsigned StubSize) {
1398   SavedBufferBegin = BufferBegin;
1399   SavedBufferEnd = BufferEnd;
1400   SavedCurBufferPtr = CurBufferPtr;
1401   
1402   BufferBegin = CurBufferPtr = (unsigned char *)Buffer;
1403   BufferEnd = BufferBegin+StubSize+1;
1404 }
1405
1406 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1407   NumBytes += getCurrentPCOffset();
1408   std::swap(SavedBufferBegin, BufferBegin);
1409   BufferEnd = SavedBufferEnd;
1410   CurBufferPtr = SavedCurBufferPtr;
1411   return SavedBufferBegin;
1412 }
1413
1414 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1415 // in the constant pool that was last emitted with the 'emitConstantPool'
1416 // method.
1417 //
1418 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1419   assert(ConstantNum < ConstantPool->getConstants().size() &&
1420          "Invalid ConstantPoolIndex!");
1421   return ConstPoolAddresses[ConstantNum];
1422 }
1423
1424 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1425 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1426 //
1427 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1428   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1429   assert(Index < JT.size() && "Invalid jump table index!");
1430   
1431   unsigned Offset = 0;
1432   unsigned EntrySize = JumpTable->getEntrySize();
1433   
1434   for (unsigned i = 0; i < Index; ++i)
1435     Offset += JT[i].MBBs.size();
1436   
1437    Offset *= EntrySize;
1438   
1439   return (uintptr_t)((char *)JumpTableBase + Offset);
1440 }
1441
1442 //===----------------------------------------------------------------------===//
1443 //  Public interface to this file
1444 //===----------------------------------------------------------------------===//
1445
1446 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1447   return new JITEmitter(jit, JMM);
1448 }
1449
1450 // getPointerToNamedFunction - This function is used as a global wrapper to
1451 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1452 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1453 // need to resolve function(s) that are being mis-codegenerated, so we need to
1454 // resolve their addresses at runtime, and this is the way to do it.
1455 extern "C" {
1456   void *getPointerToNamedFunction(const char *Name) {
1457     if (Function *F = TheJIT->FindFunctionNamed(Name))
1458       return TheJIT->getPointerToFunction(F);
1459     return TheJIT->getPointerToNamedFunction(Name);
1460   }
1461 }
1462
1463 // getPointerToFunctionOrStub - If the specified function has been
1464 // code-gen'd, return a pointer to the function.  If not, compile it, or use
1465 // a stub to implement lazy compilation if available.
1466 //
1467 void *JIT::getPointerToFunctionOrStub(Function *F) {
1468   // If we have already code generated the function, just return the address.
1469   if (void *Addr = getPointerToGlobalIfAvailable(F))
1470     return Addr;
1471   
1472   // Get a stub if the target supports it.
1473   assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1474   JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1475   return JE->getJITResolver().getFunctionStub(F);
1476 }
1477
1478 void JIT::updateFunctionStub(Function *F) {
1479   // Get the empty stub we generated earlier.
1480   assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1481   JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1482   void *Stub = JE->getJITResolver().getFunctionStub(F);
1483
1484   // Tell the target jit info to rewrite the stub at the specified address,
1485   // rather than creating a new one.
1486   void *Addr = getPointerToGlobalIfAvailable(F);
1487   getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1488 }
1489
1490 /// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1491 /// that were emitted during code generation.
1492 ///
1493 void JIT::updateDlsymStubTable() {
1494   assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1495   JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1496   
1497   SmallVector<GlobalValue*, 8> GVs;
1498   SmallVector<void*, 8> Ptrs;
1499   const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
1500
1501   JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1502
1503   unsigned nStubs = GVs.size() + ExtFns.size();
1504   
1505   // If there are no relocatable stubs, return.
1506   if (nStubs == 0)
1507     return;
1508
1509   // If there are no new relocatable stubs, return.
1510   void *CurTable = JE->getMemMgr()->getDlsymTable();
1511   if (CurTable && (*(unsigned *)CurTable == nStubs))
1512     return;
1513   
1514   // Calculate the size of the stub info
1515   unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
1516   
1517   SmallVector<unsigned, 8> Offsets;
1518   for (unsigned i = 0; i != GVs.size(); ++i) {
1519     Offsets.push_back(offset);
1520     offset += GVs[i]->getName().length() + 1;
1521   }
1522   for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end(); 
1523        i != e; ++i) {
1524     Offsets.push_back(offset);
1525     offset += strlen(i->first()) + 1;
1526   }
1527   
1528   // Allocate space for the new "stub", which contains the dlsym table.
1529   JE->startGVStub(0, offset, 4);
1530   
1531   // Emit the number of records
1532   MCE->emitInt32(nStubs);
1533   
1534   // Emit the string offsets
1535   for (unsigned i = 0; i != nStubs; ++i)
1536     MCE->emitInt32(Offsets[i]);
1537   
1538   // Emit the pointers.  Verify that they are at least 2-byte aligned, and set
1539   // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1540   // relocation can write the relocated pointer at the appropriate place in
1541   // the stub.
1542   for (unsigned i = 0; i != GVs.size(); ++i) {
1543     intptr_t Ptr = (intptr_t)Ptrs[i];
1544     assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1545     
1546     if (isa<Function>(GVs[i]))
1547       Ptr |= (intptr_t)1;
1548            
1549     if (sizeof(Ptr) == 8)
1550       MCE->emitInt64(Ptr);
1551     else
1552       MCE->emitInt32(Ptr);
1553   }
1554   for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end(); 
1555        i != e; ++i) {
1556     intptr_t Ptr = (intptr_t)i->second | 1;
1557
1558     if (sizeof(Ptr) == 8)
1559       MCE->emitInt64(Ptr);
1560     else
1561       MCE->emitInt32(Ptr);
1562   }
1563   
1564   // Emit the strings.
1565   for (unsigned i = 0; i != GVs.size(); ++i)
1566     MCE->emitString(GVs[i]->getName());
1567   for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end(); 
1568        i != e; ++i)
1569     MCE->emitString(i->first());
1570   
1571   // Tell the JIT memory manager where it is.  The JIT Memory Manager will
1572   // deallocate space for the old one, if one existed.
1573   JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1574 }
1575
1576 /// freeMachineCodeForFunction - release machine code memory for given Function.
1577 ///
1578 void JIT::freeMachineCodeForFunction(Function *F) {
1579
1580   // Delete translation for this from the ExecutionEngine, so it will get
1581   // retranslated next time it is used.
1582   void *OldPtr = updateGlobalMapping(F, 0);
1583
1584   if (OldPtr)
1585     RemoveFunctionFromSymbolTable(OldPtr);
1586
1587   // Free the actual memory for the function body and related stuff.
1588   assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1589   cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
1590 }
1591