af17405c8e789641fbff37058f1b2b1a6746bdb2
[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 "llvm/Constant.h"
18 #include "llvm/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineRelocation.h"
25 #include "llvm/ExecutionEngine/JITMemoryManager.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetJITInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MutexGuard.h"
31 #include "llvm/System/Disassembler.h"
32 #include "llvm/ADT/Statistic.h"
33 #include <algorithm>
34 using namespace llvm;
35
36 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
37 STATISTIC(NumRelos, "Number of relocations applied");
38 static JIT *TheJIT = 0;
39
40
41 //===----------------------------------------------------------------------===//
42 // JIT lazy compilation code.
43 //
44 namespace {
45   class JITResolverState {
46   private:
47     /// FunctionToStubMap - Keep track of the stub created for a particular
48     /// function so that we can reuse them if necessary.
49     std::map<Function*, void*> FunctionToStubMap;
50
51     /// StubToFunctionMap - Keep track of the function that each stub
52     /// corresponds to.
53     std::map<void*, Function*> StubToFunctionMap;
54
55   public:
56     std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
57       assert(locked.holds(TheJIT->lock));
58       return FunctionToStubMap;
59     }
60
61     std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
62       assert(locked.holds(TheJIT->lock));
63       return StubToFunctionMap;
64     }
65   };
66
67   /// JITResolver - Keep track of, and resolve, call sites for functions that
68   /// have not yet been compiled.
69   class JITResolver {
70     /// LazyResolverFn - The target lazy resolver function that we actually
71     /// rewrite instructions to use.
72     TargetJITInfo::LazyResolverFn LazyResolverFn;
73
74     JITResolverState state;
75
76     /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
77     /// external functions.
78     std::map<void*, void*> ExternalFnToStubMap;
79
80     //map addresses to indexes in the GOT
81     std::map<void*, unsigned> revGOTMap;
82     unsigned nextGOTIndex;
83
84     static JITResolver *TheJITResolver;
85   public:
86     JITResolver(JIT &jit) : nextGOTIndex(0) {
87       TheJIT = &jit;
88
89       LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
90       assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
91       TheJITResolver = this;
92     }
93     
94     ~JITResolver() {
95       TheJITResolver = 0;
96     }
97
98     /// getFunctionStub - This returns a pointer to a function stub, creating
99     /// one on demand as needed.
100     void *getFunctionStub(Function *F);
101
102     /// getExternalFunctionStub - Return a stub for the function at the
103     /// specified address, created lazily on demand.
104     void *getExternalFunctionStub(void *FnAddr);
105
106     /// AddCallbackAtLocation - If the target is capable of rewriting an
107     /// instruction without the use of a stub, record the location of the use so
108     /// we know which function is being used at the location.
109     void *AddCallbackAtLocation(Function *F, void *Location) {
110       MutexGuard locked(TheJIT->lock);
111       /// Get the target-specific JIT resolver function.
112       state.getStubToFunctionMap(locked)[Location] = F;
113       return (void*)(intptr_t)LazyResolverFn;
114     }
115
116     /// getGOTIndexForAddress - Return a new or existing index in the GOT for
117     /// an address.  This function only manages slots, it does not manage the
118     /// contents of the slots or the memory associated with the GOT.
119     unsigned getGOTIndexForAddr(void *addr);
120
121     /// JITCompilerFn - This function is called to resolve a stub to a compiled
122     /// address.  If the LLVM Function corresponding to the stub has not yet
123     /// been compiled, this function compiles it first.
124     static void *JITCompilerFn(void *Stub);
125   };
126 }
127
128 JITResolver *JITResolver::TheJITResolver = 0;
129
130 #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
131     defined(__APPLE__)
132 extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
133 #endif
134
135 /// synchronizeICache - On some targets, the JIT emitted code must be
136 /// explicitly refetched to ensure correct execution.
137 static void synchronizeICache(const void *Addr, size_t len) {
138 #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
139     defined(__APPLE__)
140   sys_icache_invalidate(Addr, len);
141 #endif
142 }
143
144 /// getFunctionStub - This returns a pointer to a function stub, creating
145 /// one on demand as needed.
146 void *JITResolver::getFunctionStub(Function *F) {
147   MutexGuard locked(TheJIT->lock);
148
149   // If we already have a stub for this function, recycle it.
150   void *&Stub = state.getFunctionToStubMap(locked)[F];
151   if (Stub) return Stub;
152
153   // Call the lazy resolver function unless we already KNOW it is an external
154   // function, in which case we just skip the lazy resolution step.
155   void *Actual = (void*)(intptr_t)LazyResolverFn;
156   if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
157     Actual = TheJIT->getPointerToFunction(F);
158
159   // Otherwise, codegen a new stub.  For now, the stub will call the lazy
160   // resolver function.
161   Stub = TheJIT->getJITInfo().emitFunctionStub(Actual,
162                                                *TheJIT->getCodeEmitter());
163
164   if (Actual != (void*)(intptr_t)LazyResolverFn) {
165     // If we are getting the stub for an external function, we really want the
166     // address of the stub in the GlobalAddressMap for the JIT, not the address
167     // of the external function.
168     TheJIT->updateGlobalMapping(F, Stub);
169   }
170
171   // Invalidate the icache if necessary.
172   synchronizeICache(Stub, TheJIT->getCodeEmitter()->getCurrentPCValue() -
173                           (intptr_t)Stub);
174
175   DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
176        << F->getName() << "'\n";
177
178   // Finally, keep track of the stub-to-Function mapping so that the
179   // JITCompilerFn knows which function to compile!
180   state.getStubToFunctionMap(locked)[Stub] = F;
181   return Stub;
182 }
183
184 /// getExternalFunctionStub - Return a stub for the function at the
185 /// specified address, created lazily on demand.
186 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
187   // If we already have a stub for this function, recycle it.
188   void *&Stub = ExternalFnToStubMap[FnAddr];
189   if (Stub) return Stub;
190
191   Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr,
192                                                *TheJIT->getCodeEmitter());
193
194   // Invalidate the icache if necessary.
195   synchronizeICache(Stub, TheJIT->getCodeEmitter()->getCurrentPCValue() -
196                     (intptr_t)Stub);
197
198   DOUT << "JIT: Stub emitted at [" << Stub
199        << "] for external function at '" << FnAddr << "'\n";
200   return Stub;
201 }
202
203 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
204   unsigned idx = revGOTMap[addr];
205   if (!idx) {
206     idx = ++nextGOTIndex;
207     revGOTMap[addr] = idx;
208     DOUT << "Adding GOT entry " << idx
209          << " for addr " << addr << "\n";
210   }
211   return idx;
212 }
213
214 /// JITCompilerFn - This function is called when a lazy compilation stub has
215 /// been entered.  It looks up which function this stub corresponds to, compiles
216 /// it if necessary, then returns the resultant function pointer.
217 void *JITResolver::JITCompilerFn(void *Stub) {
218   JITResolver &JR = *TheJITResolver;
219
220   MutexGuard locked(TheJIT->lock);
221
222   // The address given to us for the stub may not be exactly right, it might be
223   // a little bit after the stub.  As such, use upper_bound to find it.
224   std::map<void*, Function*>::iterator I =
225     JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
226   assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
227          "This is not a known stub!");
228   Function *F = (--I)->second;
229
230   // If we have already code generated the function, just return the address.
231   void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
232   
233   if (!Result) {
234     // Otherwise we don't have it, do lazy compilation now.
235     
236     // If lazy compilation is disabled, emit a useful error message and abort.
237     if (TheJIT->isLazyCompilationDisabled()) {
238       cerr << "LLVM JIT requested to do lazy compilation of function '"
239       << F->getName() << "' when lazy compiles are disabled!\n";
240       abort();
241     }
242   
243     // We might like to remove the stub from the StubToFunction map.
244     // We can't do that! Multiple threads could be stuck, waiting to acquire the
245     // lock above. As soon as the 1st function finishes compiling the function,
246     // the next one will be released, and needs to be able to find the function
247     // it needs to call.
248     //JR.state.getStubToFunctionMap(locked).erase(I);
249
250     DOUT << "JIT: Lazily resolving function '" << F->getName()
251          << "' In stub ptr = " << Stub << " actual ptr = "
252          << I->first << "\n";
253
254     Result = TheJIT->getPointerToFunction(F);
255   }
256
257   // We don't need to reuse this stub in the future, as F is now compiled.
258   JR.state.getFunctionToStubMap(locked).erase(F);
259
260   // FIXME: We could rewrite all references to this stub if we knew them.
261
262   // What we will do is set the compiled function address to map to the
263   // same GOT entry as the stub so that later clients may update the GOT
264   // if they see it still using the stub address.
265   // Note: this is done so the Resolver doesn't have to manage GOT memory
266   // Do this without allocating map space if the target isn't using a GOT
267   if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
268     JR.revGOTMap[Result] = JR.revGOTMap[Stub];
269
270   return Result;
271 }
272
273
274 //===----------------------------------------------------------------------===//
275 // JITEmitter code.
276 //
277 namespace {
278   /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
279   /// used to output functions to memory for execution.
280   class JITEmitter : public MachineCodeEmitter {
281     JITMemoryManager *MemMgr;
282
283     // When outputting a function stub in the context of some other function, we
284     // save BufferBegin/BufferEnd/CurBufferPtr here.
285     unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
286
287     /// Relocations - These are the relocations that the function needs, as
288     /// emitted.
289     std::vector<MachineRelocation> Relocations;
290     
291     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
292     /// It is filled in by the StartMachineBasicBlock callback and queried by
293     /// the getMachineBasicBlockAddress callback.
294     std::vector<intptr_t> MBBLocations;
295
296     /// ConstantPool - The constant pool for the current function.
297     ///
298     MachineConstantPool *ConstantPool;
299
300     /// ConstantPoolBase - A pointer to the first entry in the constant pool.
301     ///
302     void *ConstantPoolBase;
303
304     /// JumpTable - The jump tables for the current function.
305     ///
306     MachineJumpTableInfo *JumpTable;
307     
308     /// JumpTableBase - A pointer to the first entry in the jump table.
309     ///
310     void *JumpTableBase;
311     
312     /// Resolver - This contains info about the currently resolved functions.
313     JITResolver Resolver;
314   public:
315     JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
316       MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
317       if (jit.getJITInfo().needsGOT()) {
318         MemMgr->AllocateGOT();
319         DOUT << "JIT is managing a GOT\n";
320       }
321     }
322     ~JITEmitter() { 
323       delete MemMgr;
324     }
325     
326     JITResolver &getJITResolver() { return Resolver; }
327
328     virtual void startFunction(MachineFunction &F);
329     virtual bool finishFunction(MachineFunction &F);
330     
331     void emitConstantPool(MachineConstantPool *MCP);
332     void initJumpTableInfo(MachineJumpTableInfo *MJTI);
333     void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
334     
335     virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1);
336     virtual void* finishFunctionStub(const Function *F);
337
338     virtual void addRelocation(const MachineRelocation &MR) {
339       Relocations.push_back(MR);
340     }
341     
342     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
343       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
344         MBBLocations.resize((MBB->getNumber()+1)*2);
345       MBBLocations[MBB->getNumber()] = getCurrentPCValue();
346     }
347
348     virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
349     virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
350     
351     virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
352       assert(MBBLocations.size() > (unsigned)MBB->getNumber() && 
353              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
354       return MBBLocations[MBB->getNumber()];
355     }
356
357     /// deallocateMemForFunction - Deallocate all memory for the specified
358     /// function body.
359     void deallocateMemForFunction(Function *F) {
360       MemMgr->deallocateMemForFunction(F);
361     }
362   private:
363     void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
364   };
365 }
366
367 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
368                                      bool DoesntNeedStub) {
369   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
370     /// FIXME: If we straightened things out, this could actually emit the
371     /// global immediately instead of queuing it for codegen later!
372     return TheJIT->getOrEmitGlobalVariable(GV);
373   }
374
375   // If we have already compiled the function, return a pointer to its body.
376   Function *F = cast<Function>(V);
377   void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
378   if (ResultPtr) return ResultPtr;
379
380   if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
381     // If this is an external function pointer, we can force the JIT to
382     // 'compile' it, which really just adds it to the map.
383     if (DoesntNeedStub)
384       return TheJIT->getPointerToFunction(F);
385
386     return Resolver.getFunctionStub(F);
387   }
388
389   // Okay, the function has not been compiled yet, if the target callback
390   // mechanism is capable of rewriting the instruction directly, prefer to do
391   // that instead of emitting a stub.
392   if (DoesntNeedStub)
393     return Resolver.AddCallbackAtLocation(F, Reference);
394
395   // Otherwise, we have to emit a lazy resolving stub.
396   return Resolver.getFunctionStub(F);
397 }
398
399 void JITEmitter::startFunction(MachineFunction &F) {
400   uintptr_t ActualSize;
401   BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
402                                                          ActualSize);
403   BufferEnd = BufferBegin+ActualSize;
404   
405   // Ensure the constant pool/jump table info is at least 4-byte aligned.
406   emitAlignment(16);
407
408   emitConstantPool(F.getConstantPool());
409   initJumpTableInfo(F.getJumpTableInfo());
410
411   // About to start emitting the machine code for the function.
412   emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
413   TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
414
415   MBBLocations.clear();
416 }
417
418 bool JITEmitter::finishFunction(MachineFunction &F) {
419   if (CurBufferPtr == BufferEnd) {
420     // FIXME: Allocate more space, then try again.
421     cerr << "JIT: Ran out of space for generated machine code!\n";
422     abort();
423   }
424   
425   emitJumpTableInfo(F.getJumpTableInfo());
426   
427   // FnStart is the start of the text, not the start of the constant pool and
428   // other per-function data.
429   unsigned char *FnStart =
430     (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
431   unsigned char *FnEnd   = CurBufferPtr;
432   
433   MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
434   NumBytes += FnEnd-FnStart;
435
436   if (!Relocations.empty()) {
437     NumRelos += Relocations.size();
438
439     // Resolve the relocations to concrete pointers.
440     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
441       MachineRelocation &MR = Relocations[i];
442       void *ResultPtr;
443       if (MR.isString()) {
444         ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
445
446         // If the target REALLY wants a stub for this function, emit it now.
447         if (!MR.doesntNeedFunctionStub())
448           ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
449       } else if (MR.isGlobalValue()) {
450         ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
451                                        BufferBegin+MR.getMachineCodeOffset(),
452                                        MR.doesntNeedFunctionStub());
453       } else if (MR.isBasicBlock()) {
454         ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
455       } else if (MR.isConstantPoolIndex()) {
456         ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
457       } else {
458         assert(MR.isJumpTableIndex());
459         ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
460       }
461
462       MR.setResultPointer(ResultPtr);
463
464       // if we are managing the GOT and the relocation wants an index,
465       // give it one
466       if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
467         unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
468         MR.setGOTIndex(idx);
469         if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
470           DOUT << "GOT was out of date for " << ResultPtr
471                << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
472                << "\n";
473           ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
474         }
475       }
476     }
477
478     TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
479                                   Relocations.size(), MemMgr->getGOTBase());
480   }
481
482   // Update the GOT entry for F to point to the new code.
483   if (MemMgr->isManagingGOT()) {
484     unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
485     if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
486       DOUT << "GOT was out of date for " << (void*)BufferBegin
487            << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
488       ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
489     }
490   }
491
492   // Invalidate the icache if necessary.
493   synchronizeICache(FnStart, FnEnd-FnStart);
494
495   DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
496        << "] Function: " << F.getFunction()->getName()
497        << ": " << (FnEnd-FnStart) << " bytes of text, "
498        << Relocations.size() << " relocations\n";
499   Relocations.clear();
500
501 #ifndef NDEBUG
502   if (sys::hasDisassembler())
503     DOUT << "Disassembled code:\n"
504          << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
505 #endif
506   
507   return false;
508 }
509
510 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
511   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
512   if (Constants.empty()) return;
513
514   MachineConstantPoolEntry CPE = Constants.back();
515   unsigned Size = CPE.Offset;
516   const Type *Ty = CPE.isMachineConstantPoolEntry()
517     ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
518   Size += TheJIT->getTargetData()->getABITypeSize(Ty);
519
520   ConstantPoolBase = allocateSpace(Size, 1 << MCP->getConstantPoolAlignment());
521   ConstantPool = MCP;
522
523   if (ConstantPoolBase == 0) return;  // Buffer overflow.
524
525   // Initialize the memory for all of the constant pool entries.
526   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
527     void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
528     if (Constants[i].isMachineConstantPoolEntry()) {
529       // FIXME: add support to lower machine constant pool values into bytes!
530       cerr << "Initialize memory with machine specific constant pool entry"
531            << " has not been implemented!\n";
532       abort();
533     }
534     TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
535   }
536 }
537
538 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
539   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
540   if (JT.empty()) return;
541   
542   unsigned NumEntries = 0;
543   for (unsigned i = 0, e = JT.size(); i != e; ++i)
544     NumEntries += JT[i].MBBs.size();
545
546   unsigned EntrySize = MJTI->getEntrySize();
547
548   // Just allocate space for all the jump tables now.  We will fix up the actual
549   // MBB entries in the tables after we emit the code for each block, since then
550   // we will know the final locations of the MBBs in memory.
551   JumpTable = MJTI;
552   JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
553 }
554
555 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
556   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
557   if (JT.empty() || JumpTableBase == 0) return;
558   
559   if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
560     assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
561     // For each jump table, place the offset from the beginning of the table
562     // to the target address.
563     int *SlotPtr = (int*)JumpTableBase;
564
565     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
566       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
567       // Store the offset of the basic block for this jump table slot in the
568       // memory we allocated for the jump table in 'initJumpTableInfo'
569       intptr_t Base = (intptr_t)SlotPtr;
570       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
571         *SlotPtr++ = (intptr_t)getMachineBasicBlockAddress(MBBs[mi]) - Base;
572     }
573   } else {
574     assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
575     
576     // For each jump table, map each target in the jump table to the address of 
577     // an emitted MachineBasicBlock.
578     intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
579
580     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
581       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
582       // Store the address of the basic block for this jump table slot in the
583       // memory we allocated for the jump table in 'initJumpTableInfo'
584       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
585         *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
586     }
587   }
588 }
589
590 void JITEmitter::startFunctionStub(unsigned StubSize, unsigned Alignment) {
591   SavedBufferBegin = BufferBegin;
592   SavedBufferEnd = BufferEnd;
593   SavedCurBufferPtr = CurBufferPtr;
594   
595   BufferBegin = CurBufferPtr = MemMgr->allocateStub(StubSize, Alignment);
596   BufferEnd = BufferBegin+StubSize+1;
597 }
598
599 void *JITEmitter::finishFunctionStub(const Function *F) {
600   NumBytes += getCurrentPCOffset();
601   std::swap(SavedBufferBegin, BufferBegin);
602   BufferEnd = SavedBufferEnd;
603   CurBufferPtr = SavedCurBufferPtr;
604   return SavedBufferBegin;
605 }
606
607 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
608 // in the constant pool that was last emitted with the 'emitConstantPool'
609 // method.
610 //
611 intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
612   assert(ConstantNum < ConstantPool->getConstants().size() &&
613          "Invalid ConstantPoolIndex!");
614   return (intptr_t)ConstantPoolBase +
615          ConstantPool->getConstants()[ConstantNum].Offset;
616 }
617
618 // getJumpTableEntryAddress - Return the address of the JumpTable with index
619 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
620 //
621 intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
622   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
623   assert(Index < JT.size() && "Invalid jump table index!");
624   
625   unsigned Offset = 0;
626   unsigned EntrySize = JumpTable->getEntrySize();
627   
628   for (unsigned i = 0; i < Index; ++i)
629     Offset += JT[i].MBBs.size();
630   
631    Offset *= EntrySize;
632   
633   return (intptr_t)((char *)JumpTableBase + Offset);
634 }
635
636 //===----------------------------------------------------------------------===//
637 //  Public interface to this file
638 //===----------------------------------------------------------------------===//
639
640 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
641   return new JITEmitter(jit, JMM);
642 }
643
644 // getPointerToNamedFunction - This function is used as a global wrapper to
645 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
646 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
647 // need to resolve function(s) that are being mis-codegenerated, so we need to
648 // resolve their addresses at runtime, and this is the way to do it.
649 extern "C" {
650   void *getPointerToNamedFunction(const char *Name) {
651     if (Function *F = TheJIT->FindFunctionNamed(Name))
652       return TheJIT->getPointerToFunction(F);
653     return TheJIT->getPointerToNamedFunction(Name);
654   }
655 }
656
657 // getPointerToFunctionOrStub - If the specified function has been
658 // code-gen'd, return a pointer to the function.  If not, compile it, or use
659 // a stub to implement lazy compilation if available.
660 //
661 void *JIT::getPointerToFunctionOrStub(Function *F) {
662   // If we have already code generated the function, just return the address.
663   if (void *Addr = getPointerToGlobalIfAvailable(F))
664     return Addr;
665   
666   // Get a stub if the target supports it.
667   assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
668   JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
669   return JE->getJITResolver().getFunctionStub(F);
670 }
671
672 /// freeMachineCodeForFunction - release machine code memory for given Function.
673 ///
674 void JIT::freeMachineCodeForFunction(Function *F) {
675   // Delete translation for this from the ExecutionEngine, so it will get
676   // retranslated next time it is used.
677   updateGlobalMapping(F, 0);
678
679   // Free the actual memory for the function body and related stuff.
680   assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
681   static_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);
682 }
683