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