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