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