JumpTable support! What this represents is working asm and jit support for
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/GenericValue.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetJITInfo.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/System/Memory.h"
31 #include <algorithm>
32 #include <iostream>
33 #include <list>
34 using namespace llvm;
35
36 namespace {
37   Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
38   Statistic<> NumRelos("jit", "Number of relocations applied");
39   JIT *TheJIT = 0;
40 }
41
42
43 //===----------------------------------------------------------------------===//
44 // JITMemoryManager code.
45 //
46 namespace {
47   /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
48   /// sane way.  This splits a large block of MAP_NORESERVE'd memory into two
49   /// sections, one for function stubs, one for the functions themselves.  We
50   /// have to do this because we may need to emit a function stub while in the
51   /// middle of emitting a function, and we don't know how large the function we
52   /// are emitting is.  This never bothers to release the memory, because when
53   /// we are ready to destroy the JIT, the program exits.
54   class JITMemoryManager {
55     std::list<sys::MemoryBlock> Blocks; // List of blocks allocated by the JIT
56     unsigned char *FunctionBase; // Start of the function body area
57     unsigned char *GlobalBase; // Start of the Global area
58     unsigned char *ConstantBase; // Memory allocated for constant pools
59     unsigned char *CurStubPtr, *CurFunctionPtr, *CurConstantPtr, *CurGlobalPtr;
60     unsigned char *GOTBase; //Target Specific reserved memory
61
62     // centralize memory block allocation
63     sys::MemoryBlock getNewMemoryBlock(unsigned size);
64   public:
65     JITMemoryManager(bool useGOT);
66     ~JITMemoryManager();
67
68     inline unsigned char *allocateStub(unsigned StubSize);
69     inline unsigned char *allocateConstant(unsigned ConstantSize,
70                                            unsigned Alignment);
71     inline unsigned char* allocateGlobal(unsigned Size,
72                                          unsigned Alignment);
73     inline unsigned char *startFunctionBody();
74     inline void endFunctionBody(unsigned char *FunctionEnd);
75     inline unsigned char* getGOTBase() const;
76
77     inline bool isManagingGOT() const;
78   };
79 }
80
81 JITMemoryManager::JITMemoryManager(bool useGOT) {
82   // Allocate a 16M block of memory for functions
83   sys::MemoryBlock FunBlock = getNewMemoryBlock(16 << 20);
84   // Allocate a 1M block of memory for Constants
85   sys::MemoryBlock ConstBlock = getNewMemoryBlock(1 << 20);
86   // Allocate a 1M Block of memory for Globals
87   sys::MemoryBlock GVBlock = getNewMemoryBlock(1 << 20);
88
89   Blocks.push_front(FunBlock);
90   Blocks.push_front(ConstBlock);
91   Blocks.push_front(GVBlock);
92
93   FunctionBase = reinterpret_cast<unsigned char*>(FunBlock.base());
94   ConstantBase = reinterpret_cast<unsigned char*>(ConstBlock.base());
95   GlobalBase = reinterpret_cast<unsigned char*>(GVBlock.base());
96
97   // Allocate stubs backwards from the base, allocate functions forward
98   // from the base.
99   CurStubPtr = CurFunctionPtr = FunctionBase + 512*1024;// Use 512k for stubs
100
101   CurConstantPtr = ConstantBase + ConstBlock.size();
102   CurGlobalPtr = GlobalBase + GVBlock.size();
103
104   //Allocate the GOT just like a global array
105   GOTBase = NULL;
106   if (useGOT)
107     GOTBase = allocateGlobal(sizeof(void*) * 8192, 8);
108 }
109
110 JITMemoryManager::~JITMemoryManager() {
111   for (std::list<sys::MemoryBlock>::iterator ib = Blocks.begin(),
112        ie = Blocks.end(); ib != ie; ++ib)
113     sys::Memory::ReleaseRWX(*ib);
114   Blocks.clear();
115 }
116
117 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
118   CurStubPtr -= StubSize;
119   if (CurStubPtr < FunctionBase) {
120     //FIXME: allocate a new block
121     std::cerr << "JIT ran out of memory for function stubs!\n";
122     abort();
123   }
124   return CurStubPtr;
125 }
126
127 unsigned char *JITMemoryManager::allocateConstant(unsigned ConstantSize,
128                                                   unsigned Alignment) {
129   // Reserve space and align pointer.
130   CurConstantPtr -= ConstantSize;
131   CurConstantPtr =
132     (unsigned char *)((intptr_t)CurConstantPtr & ~((intptr_t)Alignment - 1));
133
134   if (CurConstantPtr < ConstantBase) {
135     //Either allocate another MB or 2xConstantSize
136     sys::MemoryBlock ConstBlock = getNewMemoryBlock(2 * ConstantSize);
137     ConstantBase = reinterpret_cast<unsigned char*>(ConstBlock.base());
138     CurConstantPtr = ConstantBase + ConstBlock.size();
139     return allocateConstant(ConstantSize, Alignment);
140   }
141   return CurConstantPtr;
142 }
143
144 unsigned char *JITMemoryManager::allocateGlobal(unsigned Size,
145                                                 unsigned Alignment) {
146  // Reserve space and align pointer.
147   CurGlobalPtr -= Size;
148   CurGlobalPtr =
149     (unsigned char *)((intptr_t)CurGlobalPtr & ~((intptr_t)Alignment - 1));
150
151   if (CurGlobalPtr < GlobalBase) {
152     //Either allocate another MB or 2xSize
153     sys::MemoryBlock GVBlock =  getNewMemoryBlock(2 * Size);
154     GlobalBase = reinterpret_cast<unsigned char*>(GVBlock.base());
155     CurGlobalPtr = GlobalBase + GVBlock.size();
156     return allocateGlobal(Size, Alignment);
157   }
158   return CurGlobalPtr;
159 }
160
161 unsigned char *JITMemoryManager::startFunctionBody() {
162   // Round up to an even multiple of 8 bytes, this should eventually be target
163   // specific.
164   return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
165 }
166
167 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
168   assert(FunctionEnd > CurFunctionPtr);
169   CurFunctionPtr = FunctionEnd;
170 }
171
172 unsigned char* JITMemoryManager::getGOTBase() const {
173   return GOTBase;
174 }
175
176 bool JITMemoryManager::isManagingGOT() const {
177   return GOTBase != NULL;
178 }
179
180 sys::MemoryBlock JITMemoryManager::getNewMemoryBlock(unsigned size) {
181   const sys::MemoryBlock* BOld = 0;
182   if (Blocks.size())
183     BOld = &Blocks.front();
184   //never allocate less than 1 MB
185   sys::MemoryBlock B;
186   try {
187     B = sys::Memory::AllocateRWX(std::max(((unsigned)1 << 20), size), BOld);
188   } catch (std::string& err) {
189     std::cerr << "Allocation failed when allocating new memory in the JIT\n";
190     std::cerr << err << "\n";
191     abort();
192   }
193   Blocks.push_front(B);
194   return B;
195 }
196
197 //===----------------------------------------------------------------------===//
198 // JIT lazy compilation code.
199 //
200 namespace {
201   class JITResolverState {
202   private:
203     /// FunctionToStubMap - Keep track of the stub created for a particular
204     /// function so that we can reuse them if necessary.
205     std::map<Function*, void*> FunctionToStubMap;
206
207     /// StubToFunctionMap - Keep track of the function that each stub
208     /// corresponds to.
209     std::map<void*, Function*> StubToFunctionMap;
210
211   public:
212     std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
213       assert(locked.holds(TheJIT->lock));
214       return FunctionToStubMap;
215     }
216
217     std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
218       assert(locked.holds(TheJIT->lock));
219       return StubToFunctionMap;
220     }
221   };
222
223   /// JITResolver - Keep track of, and resolve, call sites for functions that
224   /// have not yet been compiled.
225   class JITResolver {
226     /// MCE - The MachineCodeEmitter to use to emit stubs with.
227     MachineCodeEmitter &MCE;
228
229     /// LazyResolverFn - The target lazy resolver function that we actually
230     /// rewrite instructions to use.
231     TargetJITInfo::LazyResolverFn LazyResolverFn;
232
233     JITResolverState state;
234
235     /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
236     /// external functions.
237     std::map<void*, void*> ExternalFnToStubMap;
238
239     //map addresses to indexes in the GOT
240     std::map<void*, unsigned> revGOTMap;
241     unsigned nextGOTIndex;
242
243   public:
244     JITResolver(MachineCodeEmitter &mce) : MCE(mce), nextGOTIndex(0) {
245       LazyResolverFn =
246         TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
247     }
248
249     /// getFunctionStub - This returns a pointer to a function stub, creating
250     /// one on demand as needed.
251     void *getFunctionStub(Function *F);
252
253     /// getExternalFunctionStub - Return a stub for the function at the
254     /// specified address, created lazily on demand.
255     void *getExternalFunctionStub(void *FnAddr);
256
257     /// AddCallbackAtLocation - If the target is capable of rewriting an
258     /// instruction without the use of a stub, record the location of the use so
259     /// we know which function is being used at the location.
260     void *AddCallbackAtLocation(Function *F, void *Location) {
261       MutexGuard locked(TheJIT->lock);
262       /// Get the target-specific JIT resolver function.
263       state.getStubToFunctionMap(locked)[Location] = F;
264       return (void*)LazyResolverFn;
265     }
266
267     /// getGOTIndexForAddress - Return a new or existing index in the GOT for
268     /// and address.  This function only manages slots, it does not manage the
269     /// contents of the slots or the memory associated with the GOT.
270     unsigned getGOTIndexForAddr(void* addr);
271
272     /// JITCompilerFn - This function is called to resolve a stub to a compiled
273     /// address.  If the LLVM Function corresponding to the stub has not yet
274     /// been compiled, this function compiles it first.
275     static void *JITCompilerFn(void *Stub);
276   };
277 }
278
279 /// getJITResolver - This function returns the one instance of the JIT resolver.
280 ///
281 static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
282   static JITResolver TheJITResolver(*MCE);
283   return TheJITResolver;
284 }
285
286 /// getFunctionStub - This returns a pointer to a function stub, creating
287 /// one on demand as needed.
288 void *JITResolver::getFunctionStub(Function *F) {
289   MutexGuard locked(TheJIT->lock);
290
291   // If we already have a stub for this function, recycle it.
292   void *&Stub = state.getFunctionToStubMap(locked)[F];
293   if (Stub) return Stub;
294
295   // Call the lazy resolver function unless we already KNOW it is an external
296   // function, in which case we just skip the lazy resolution step.
297   void *Actual = (void*)LazyResolverFn;
298   if (F->isExternal() && F->hasExternalLinkage())
299     Actual = TheJIT->getPointerToFunction(F);
300
301   // Otherwise, codegen a new stub.  For now, the stub will call the lazy
302   // resolver function.
303   Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
304
305   if (Actual != (void*)LazyResolverFn) {
306     // If we are getting the stub for an external function, we really want the
307     // address of the stub in the GlobalAddressMap for the JIT, not the address
308     // of the external function.
309     TheJIT->updateGlobalMapping(F, Stub);
310   }
311
312   DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
313                   << F->getName() << "'\n");
314
315   // Finally, keep track of the stub-to-Function mapping so that the
316   // JITCompilerFn knows which function to compile!
317   state.getStubToFunctionMap(locked)[Stub] = F;
318   return Stub;
319 }
320
321 /// getExternalFunctionStub - Return a stub for the function at the
322 /// specified address, created lazily on demand.
323 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
324   // If we already have a stub for this function, recycle it.
325   void *&Stub = ExternalFnToStubMap[FnAddr];
326   if (Stub) return Stub;
327
328   Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
329   DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
330         << "] for external function at '" << FnAddr << "'\n");
331   return Stub;
332 }
333
334 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
335   unsigned idx = revGOTMap[addr];
336   if (!idx) {
337     idx = ++nextGOTIndex;
338     revGOTMap[addr] = idx;
339     DEBUG(std::cerr << "Adding GOT entry " << idx
340           << " for addr " << addr << "\n");
341     //    ((void**)MemMgr.getGOTBase())[idx] = addr;
342   }
343   return idx;
344 }
345
346 /// JITCompilerFn - This function is called when a lazy compilation stub has
347 /// been entered.  It looks up which function this stub corresponds to, compiles
348 /// it if necessary, then returns the resultant function pointer.
349 void *JITResolver::JITCompilerFn(void *Stub) {
350   JITResolver &JR = getJITResolver();
351
352   MutexGuard locked(TheJIT->lock);
353
354   // The address given to us for the stub may not be exactly right, it might be
355   // a little bit after the stub.  As such, use upper_bound to find it.
356   std::map<void*, Function*>::iterator I =
357     JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
358   assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
359          "This is not a known stub!");
360   Function *F = (--I)->second;
361
362   // We might like to remove the stub from the StubToFunction map.
363   // We can't do that! Multiple threads could be stuck, waiting to acquire the
364   // lock above. As soon as the 1st function finishes compiling the function,
365   // the next one will be released, and needs to be able to find the function it
366   // needs to call.
367   //JR.state.getStubToFunctionMap(locked).erase(I);
368
369   DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
370                   << "' In stub ptr = " << Stub << " actual ptr = "
371                   << I->first << "\n");
372
373   void *Result = TheJIT->getPointerToFunction(F);
374
375   // We don't need to reuse this stub in the future, as F is now compiled.
376   JR.state.getFunctionToStubMap(locked).erase(F);
377
378   // FIXME: We could rewrite all references to this stub if we knew them.
379
380   // What we will do is set the compiled function address to map to the
381   // same GOT entry as the stub so that later clients may update the GOT
382   // if they see it still using the stub address.
383   // Note: this is done so the Resolver doesn't have to manage GOT memory
384   // Do this without allocating map space if the target isn't using a GOT
385   if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
386     JR.revGOTMap[Result] = JR.revGOTMap[Stub];
387
388   return Result;
389 }
390
391
392 // getPointerToFunctionOrStub - If the specified function has been
393 // code-gen'd, return a pointer to the function.  If not, compile it, or use
394 // a stub to implement lazy compilation if available.
395 //
396 void *JIT::getPointerToFunctionOrStub(Function *F) {
397   // If we have already code generated the function, just return the address.
398   if (void *Addr = getPointerToGlobalIfAvailable(F))
399     return Addr;
400
401   // Get a stub if the target supports it
402   return getJITResolver(MCE).getFunctionStub(F);
403 }
404
405
406
407 //===----------------------------------------------------------------------===//
408 // JITEmitter code.
409 //
410 namespace {
411   /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
412   /// used to output functions to memory for execution.
413   class JITEmitter : public MachineCodeEmitter {
414     JITMemoryManager MemMgr;
415
416     // CurBlock - The start of the current block of memory.  CurByte - The
417     // current byte being emitted to.
418     unsigned char *CurBlock, *CurByte;
419
420     // When outputting a function stub in the context of some other function, we
421     // save CurBlock and CurByte here.
422     unsigned char *SavedCurBlock, *SavedCurByte;
423
424     /// Relocations - These are the relocations that the function needs, as
425     /// emitted.
426     std::vector<MachineRelocation> Relocations;
427
428     /// ConstantPool - The constant pool for the current function.
429     ///
430     MachineConstantPool *ConstantPool;
431
432     /// ConstantPoolBase - A pointer to the first entry in the constant pool.
433     ///
434     void *ConstantPoolBase;
435
436     /// ConstantPool - The constant pool for the current function.
437     ///
438     MachineJumpTableInfo *JumpTable;
439     
440     /// JumpTableBase - A pointer to the first entry in the jump table.
441     ///
442     void *JumpTableBase;
443 public:
444     JITEmitter(JIT &jit) : MemMgr(jit.getJITInfo().needsGOT()) {
445       TheJIT = &jit;
446       DEBUG(std::cerr <<
447             (MemMgr.isManagingGOT() ? "JIT is managing GOT\n"
448              : "JIT is not managing GOT\n"));
449     }
450
451     virtual void startFunction(MachineFunction &F);
452     virtual void finishFunction(MachineFunction &F);
453     virtual void emitConstantPool(MachineConstantPool *MCP);
454     virtual void initJumpTableInfo(MachineJumpTableInfo *MJTI);
455     virtual void emitJumpTableInfo(MachineJumpTableInfo *MJTI,
456                                    std::map<MachineBasicBlock*,uint64_t> &MBBM);
457     virtual void startFunctionStub(unsigned StubSize);
458     virtual void* finishFunctionStub(const Function *F);
459     virtual void emitByte(unsigned char B);
460     virtual void emitWord(unsigned W);
461     virtual void emitWordAt(unsigned W, unsigned *Ptr);
462
463     virtual void addRelocation(const MachineRelocation &MR) {
464       Relocations.push_back(MR);
465     }
466
467     virtual uint64_t getCurrentPCValue();
468     virtual uint64_t getCurrentPCOffset();
469     virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
470     virtual uint64_t getJumpTableEntryAddress(unsigned Entry);
471     virtual unsigned char* allocateGlobal(unsigned size, unsigned alignment);
472
473   private:
474     void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
475   };
476 }
477
478 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
479   return new JITEmitter(jit);
480 }
481
482 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
483                                      bool DoesntNeedStub) {
484   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
485     /// FIXME: If we straightened things out, this could actually emit the
486     /// global immediately instead of queuing it for codegen later!
487     return TheJIT->getOrEmitGlobalVariable(GV);
488   }
489
490   // If we have already compiled the function, return a pointer to its body.
491   Function *F = cast<Function>(V);
492   void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
493   if (ResultPtr) return ResultPtr;
494
495   if (F->hasExternalLinkage() && F->isExternal()) {
496     // If this is an external function pointer, we can force the JIT to
497     // 'compile' it, which really just adds it to the map.
498     if (DoesntNeedStub)
499       return TheJIT->getPointerToFunction(F);
500
501     return getJITResolver(this).getFunctionStub(F);
502   }
503
504   // Okay, the function has not been compiled yet, if the target callback
505   // mechanism is capable of rewriting the instruction directly, prefer to do
506   // that instead of emitting a stub.
507   if (DoesntNeedStub)
508     return getJITResolver(this).AddCallbackAtLocation(F, Reference);
509
510   // Otherwise, we have to emit a lazy resolving stub.
511   return getJITResolver(this).getFunctionStub(F);
512 }
513
514 void JITEmitter::startFunction(MachineFunction &F) {
515   CurByte = CurBlock = MemMgr.startFunctionBody();
516   TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
517 }
518
519 void JITEmitter::finishFunction(MachineFunction &F) {
520   MemMgr.endFunctionBody(CurByte);
521   NumBytes += CurByte-CurBlock;
522
523   if (!Relocations.empty()) {
524     NumRelos += Relocations.size();
525
526     // Resolve the relocations to concrete pointers.
527     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
528       MachineRelocation &MR = Relocations[i];
529       void *ResultPtr;
530       if (MR.isString()) {
531         ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
532
533         // If the target REALLY wants a stub for this function, emit it now.
534         if (!MR.doesntNeedFunctionStub())
535           ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
536       } else if (MR.isGlobalValue())
537         ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
538                                        CurBlock+MR.getMachineCodeOffset(),
539                                        MR.doesntNeedFunctionStub());
540       else //ConstantPoolIndex
541         ResultPtr =
542        (void*)(intptr_t)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
543
544       MR.setResultPointer(ResultPtr);
545
546       // if we are managing the GOT and the relocation wants an index,
547       // give it one
548       if (MemMgr.isManagingGOT() && !MR.isConstantPoolIndex() &&
549           MR.isGOTRelative()) {
550         unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
551         MR.setGOTIndex(idx);
552         if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
553           DEBUG(std::cerr << "GOT was out of date for " << ResultPtr
554                 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx]
555                 << "\n");
556           ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
557         }
558       }
559     }
560
561     TheJIT->getJITInfo().relocate(CurBlock, &Relocations[0],
562                                   Relocations.size(), MemMgr.getGOTBase());
563   }
564
565   //Update the GOT entry for F to point to the new code.
566   if(MemMgr.isManagingGOT()) {
567     unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)CurBlock);
568     if (((void**)MemMgr.getGOTBase())[idx] != (void*)CurBlock) {
569       DEBUG(std::cerr << "GOT was out of date for " << (void*)CurBlock
570             << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n");
571       ((void**)MemMgr.getGOTBase())[idx] = (void*)CurBlock;
572     }
573   }
574
575   DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)CurBlock
576                   << "] Function: " << F.getFunction()->getName()
577                   << ": " << CurByte-CurBlock << " bytes of text, "
578                   << Relocations.size() << " relocations\n");
579   Relocations.clear();
580 }
581
582 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
583   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
584   if (Constants.empty()) return;
585
586   unsigned Size = Constants.back().Offset;
587   Size += TheJIT->getTargetData().getTypeSize(Constants.back().Val->getType());
588
589   ConstantPoolBase = MemMgr.allocateConstant(Size, 
590                                        1 << MCP->getConstantPoolAlignment());
591   ConstantPool = MCP;
592   
593   // Initialize the memory for all of the constant pool entries.
594   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
595     void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
596     TheJIT->InitializeMemory(Constants[i].Val, CAddr);
597   }
598 }
599
600 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
601   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
602   if (JT.empty()) return;
603   
604   unsigned Size = 0;
605   unsigned EntrySize = MJTI->getEntrySize();
606   for (unsigned i = 0, e = JT.size(); i != e; ++i)
607     Size += JT[i].MBBs.size() * EntrySize;
608   
609   // Just allocate space for all the jump tables now.  We will fix up the actual
610   // MBB entries in the tables after we emit the code for each block, since then
611   // we will know the final locations of the MBBs in memory.
612   JumpTable = MJTI;
613   JumpTableBase = MemMgr.allocateConstant(Size, MJTI->getAlignment());
614 }
615
616 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI,
617                                    std::map<MachineBasicBlock*,uint64_t> &MBBM){
618   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
619   if (JT.empty()) return;
620
621   unsigned Offset = 0;
622   unsigned EntrySize = MJTI->getEntrySize();
623   
624   // For each jump table, map each target in the jump table to the address of 
625   // an emitted MachineBasicBlock.
626   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
627     const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
628     for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
629       uint64_t addr = MBBM[MBBs[mi]];
630       GenericValue addrgv;
631       const Type *Ty;
632       if (EntrySize == 4) {
633         addrgv.UIntVal = addr;
634         Ty = Type::UIntTy;
635       } else if (EntrySize == 8) {
636         addrgv.ULongVal = addr;
637         Ty = Type::ULongTy;
638       } else {
639         assert(0 && "Unhandled jump table entry size!");
640         abort();
641       }
642       // Store the address of the basic block for this jump table slot in the
643       // memory we allocated for the jump table in 'initJumpTableInfo'
644       void *ptr = (void *)((char *)JumpTableBase + Offset);
645       TheJIT->StoreValueToMemory(addrgv, (GenericValue *)ptr, Ty);
646       Offset += EntrySize;
647     }
648   }
649 }
650
651 void JITEmitter::startFunctionStub(unsigned StubSize) {
652   SavedCurBlock = CurBlock;  SavedCurByte = CurByte;
653   CurByte = CurBlock = MemMgr.allocateStub(StubSize);
654 }
655
656 void *JITEmitter::finishFunctionStub(const Function *F) {
657   NumBytes += CurByte-CurBlock;
658   std::swap(CurBlock, SavedCurBlock);
659   CurByte = SavedCurByte;
660   return SavedCurBlock;
661 }
662
663 void JITEmitter::emitByte(unsigned char B) {
664   *CurByte++ = B;   // Write the byte to memory
665 }
666
667 void JITEmitter::emitWord(unsigned W) {
668   // This won't work if the endianness of the host and target don't agree!  (For
669   // a JIT this can't happen though.  :)
670   *(unsigned*)CurByte = W;
671   CurByte += sizeof(unsigned);
672 }
673
674 void JITEmitter::emitWordAt(unsigned W, unsigned *Ptr) {
675   *Ptr = W;
676 }
677
678 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
679 // in the constant pool that was last emitted with the 'emitConstantPool'
680 // method.
681 //
682 uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
683   assert(ConstantNum < ConstantPool->getConstants().size() &&
684          "Invalid ConstantPoolIndex!");
685   return (intptr_t)ConstantPoolBase +
686          ConstantPool->getConstants()[ConstantNum].Offset;
687 }
688
689 // getJumpTableEntryAddress - Return the address of the JumpTable with index
690 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
691 //
692 uint64_t JITEmitter::getJumpTableEntryAddress(unsigned Index) {
693   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
694   assert(Index < JT.size() && "Invalid jump table index!");
695   
696   unsigned Offset = 0;
697   unsigned EntrySize = JumpTable->getEntrySize();
698   
699   for (unsigned i = 0; i < Index; ++i)
700     Offset += JT[i].MBBs.size() * EntrySize;
701   
702   return (uint64_t)((char *)JumpTableBase + Offset);
703 }
704
705 unsigned char* JITEmitter::allocateGlobal(unsigned size, unsigned alignment)
706 {
707   return MemMgr.allocateGlobal(size, alignment);
708 }
709
710 // getCurrentPCValue - This returns the address that the next emitted byte
711 // will be output to.
712 //
713 uint64_t JITEmitter::getCurrentPCValue() {
714   return (intptr_t)CurByte;
715 }
716
717 uint64_t JITEmitter::getCurrentPCOffset() {
718   return (intptr_t)CurByte-(intptr_t)CurBlock;
719 }
720
721 // getPointerToNamedFunction - This function is used as a global wrapper to
722 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
723 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
724 // need to resolve function(s) that are being mis-codegenerated, so we need to
725 // resolve their addresses at runtime, and this is the way to do it.
726 extern "C" {
727   void *getPointerToNamedFunction(const char *Name) {
728     Module &M = TheJIT->getModule();
729     if (Function *F = M.getNamedFunction(Name))
730       return TheJIT->getPointerToFunction(F);
731     return TheJIT->getPointerToNamedFunction(Name);
732   }
733 }