Silence VS warnings.
[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/CodeGen/MachineCodeEmitter.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineRelocation.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetJITInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/System/Memory.h"
28 using namespace llvm;
29
30 namespace {
31   Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
32   JIT *TheJIT = 0;
33 }
34
35
36 //===----------------------------------------------------------------------===//
37 // JITMemoryManager code.
38 //
39 namespace {
40   /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
41   /// sane way.  This splits a large block of MAP_NORESERVE'd memory into two
42   /// sections, one for function stubs, one for the functions themselves.  We
43   /// have to do this because we may need to emit a function stub while in the
44   /// middle of emitting a function, and we don't know how large the function we
45   /// are emitting is.  This never bothers to release the memory, because when
46   /// we are ready to destroy the JIT, the program exits.
47   class JITMemoryManager {
48     sys::MemoryBlock  MemBlock;  // Virtual memory block allocated RWX
49     unsigned char *MemBase;      // Base of block of memory, start of stub mem
50     unsigned char *FunctionBase; // Start of the function body area
51     unsigned char *CurStubPtr, *CurFunctionPtr;
52   public:
53     JITMemoryManager();
54     ~JITMemoryManager();
55     
56     inline unsigned char *allocateStub(unsigned StubSize);
57     inline unsigned char *startFunctionBody();
58     inline void endFunctionBody(unsigned char *FunctionEnd);    
59   };
60 }
61
62 JITMemoryManager::JITMemoryManager() {
63   // Allocate a 16M block of memory...
64   MemBlock = sys::Memory::AllocateRWX((16 << 20));
65   MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
66   FunctionBase = MemBase + 512*1024; // Use 512k for stubs
67
68   // Allocate stubs backwards from the function base, allocate functions forward
69   // from the function base.
70   CurStubPtr = CurFunctionPtr = FunctionBase;
71 }
72
73 JITMemoryManager::~JITMemoryManager() {
74   sys::Memory::ReleaseRWX(MemBlock);
75 }
76
77 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
78   CurStubPtr -= StubSize;
79   if (CurStubPtr < MemBase) {
80     std::cerr << "JIT ran out of memory for function stubs!\n";
81     abort();
82   }
83   return CurStubPtr;
84 }
85
86 unsigned char *JITMemoryManager::startFunctionBody() {
87   // Round up to an even multiple of 8 bytes, this should eventually be target
88   // specific.
89   return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
90 }
91
92 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
93   assert(FunctionEnd > CurFunctionPtr);
94   CurFunctionPtr = FunctionEnd;
95 }
96
97 //===----------------------------------------------------------------------===//
98 // JIT lazy compilation code.
99 //
100 namespace {
101   /// JITResolver - Keep track of, and resolve, call sites for functions that
102   /// have not yet been compiled.
103   class JITResolver {
104     /// MCE - The MachineCodeEmitter to use to emit stubs with.
105     MachineCodeEmitter &MCE;
106
107     /// LazyResolverFn - The target lazy resolver function that we actually
108     /// rewrite instructions to use.
109     TargetJITInfo::LazyResolverFn LazyResolverFn;
110
111     // FunctionToStubMap - Keep track of the stub created for a particular
112     // function so that we can reuse them if necessary.
113     std::map<Function*, void*> FunctionToStubMap;
114
115     // StubToFunctionMap - Keep track of the function that each stub corresponds
116     // to.
117     std::map<void*, Function*> StubToFunctionMap;
118
119   public:
120     JITResolver(MachineCodeEmitter &mce) : MCE(mce) {
121       LazyResolverFn =
122         TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
123     }
124
125     /// getFunctionStub - This returns a pointer to a function stub, creating
126     /// one on demand as needed.
127     void *getFunctionStub(Function *F);
128
129     /// AddCallbackAtLocation - If the target is capable of rewriting an
130     /// instruction without the use of a stub, record the location of the use so
131     /// we know which function is being used at the location.
132     void *AddCallbackAtLocation(Function *F, void *Location) {
133       /// Get the target-specific JIT resolver function.
134       StubToFunctionMap[Location] = F;
135       return (void*)LazyResolverFn;
136     }
137
138     /// JITCompilerFn - This function is called to resolve a stub to a compiled
139     /// address.  If the LLVM Function corresponding to the stub has not yet
140     /// been compiled, this function compiles it first.
141     static void *JITCompilerFn(void *Stub);
142   };
143 }
144
145 /// getJITResolver - This function returns the one instance of the JIT resolver.
146 ///
147 static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
148   static JITResolver TheJITResolver(*MCE);
149   return TheJITResolver;
150 }
151
152 /// getFunctionStub - This returns a pointer to a function stub, creating
153 /// one on demand as needed.
154 void *JITResolver::getFunctionStub(Function *F) {
155   // If we already have a stub for this function, recycle it.
156   void *&Stub = FunctionToStubMap[F];
157   if (Stub) return Stub;
158
159   // Call the lazy resolver function unless we already KNOW it is an external
160   // function, in which case we just skip the lazy resolution step.
161   void *Actual = (void*)LazyResolverFn;
162   if (F->hasExternalLinkage())
163     Actual = TheJIT->getPointerToFunction(F);
164     
165   // Otherwise, codegen a new stub.  For now, the stub will call the lazy
166   // resolver function.
167   Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
168
169   if (F->hasExternalLinkage()) {
170     // If we are getting the stub for an external function, we really want the
171     // address of the stub in the GlobalAddressMap for the JIT, not the address
172     // of the external function.
173     TheJIT->updateGlobalMapping(F, Stub);
174   }
175
176   DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
177                   << F->getName() << "'\n");
178
179   // Finally, keep track of the stub-to-Function mapping so that the
180   // JITCompilerFn knows which function to compile!
181   StubToFunctionMap[Stub] = F;
182   return Stub;
183 }
184
185 /// JITCompilerFn - This function is called when a lazy compilation stub has
186 /// been entered.  It looks up which function this stub corresponds to, compiles
187 /// it if necessary, then returns the resultant function pointer.
188 void *JITResolver::JITCompilerFn(void *Stub) {
189   JITResolver &JR = getJITResolver();
190   
191   // The address given to us for the stub may not be exactly right, it might be
192   // a little bit after the stub.  As such, use upper_bound to find it.
193   std::map<void*, Function*>::iterator I =
194     JR.StubToFunctionMap.upper_bound(Stub);
195   assert(I != JR.StubToFunctionMap.begin() && "This is not a known stub!");
196   Function *F = (--I)->second;
197
198   // The target function will rewrite the stub so that the compilation callback
199   // function is no longer called from this stub.
200   JR.StubToFunctionMap.erase(I);
201
202   DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
203                   << "' In stub ptr = " << Stub << " actual ptr = "
204                   << I->first << "\n");
205
206   void *Result = TheJIT->getPointerToFunction(F);
207
208   // We don't need to reuse this stub in the future, as F is now compiled.
209   JR.FunctionToStubMap.erase(F);
210
211   // FIXME: We could rewrite all references to this stub if we knew them.
212   return Result;
213 }
214
215
216 // getPointerToFunctionOrStub - If the specified function has been
217 // code-gen'd, return a pointer to the function.  If not, compile it, or use
218 // a stub to implement lazy compilation if available.
219 //
220 void *JIT::getPointerToFunctionOrStub(Function *F) {
221   // If we have already code generated the function, just return the address.
222   if (void *Addr = getPointerToGlobalIfAvailable(F))
223     return Addr;
224
225   // Get a stub if the target supports it
226   return getJITResolver(MCE).getFunctionStub(F);
227 }
228
229
230
231 //===----------------------------------------------------------------------===//
232 // JITEmitter code.
233 //
234 namespace {
235   /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
236   /// used to output functions to memory for execution.
237   class JITEmitter : public MachineCodeEmitter {
238     JITMemoryManager MemMgr;
239
240     // CurBlock - The start of the current block of memory.  CurByte - The
241     // current byte being emitted to.
242     unsigned char *CurBlock, *CurByte;
243
244     // When outputting a function stub in the context of some other function, we
245     // save CurBlock and CurByte here.
246     unsigned char *SavedCurBlock, *SavedCurByte;
247
248     // ConstantPoolAddresses - Contains the location for each entry in the
249     // constant pool.
250     std::vector<void*> ConstantPoolAddresses;
251
252     /// Relocations - These are the relocations that the function needs, as
253     /// emitted.
254     std::vector<MachineRelocation> Relocations;
255   public:
256     JITEmitter(JIT &jit) { TheJIT = &jit; }
257
258     virtual void startFunction(MachineFunction &F);
259     virtual void finishFunction(MachineFunction &F);
260     virtual void emitConstantPool(MachineConstantPool *MCP);
261     virtual void startFunctionStub(unsigned StubSize);
262     virtual void* finishFunctionStub(const Function *F);
263     virtual void emitByte(unsigned char B);
264     virtual void emitWord(unsigned W);
265     virtual void emitWordAt(unsigned W, unsigned *Ptr);
266
267     virtual void addRelocation(const MachineRelocation &MR) {
268       Relocations.push_back(MR);
269     }
270
271     virtual uint64_t getCurrentPCValue();
272     virtual uint64_t getCurrentPCOffset();
273     virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
274
275   private:
276     void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
277   };
278 }
279
280 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
281   return new JITEmitter(jit);
282 }
283
284 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
285                                      bool DoesntNeedStub) {
286   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
287     /// FIXME: If we straightened things out, this could actually emit the
288     /// global immediately instead of queuing it for codegen later!
289     return TheJIT->getOrEmitGlobalVariable(GV);
290   }
291
292   // If we have already compiled the function, return a pointer to its body.
293   Function *F = cast<Function>(V);
294   void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
295   if (ResultPtr) return ResultPtr;
296
297   if (F->hasExternalLinkage() && F->isExternal()) {
298     // If this is an external function pointer, we can force the JIT to
299     // 'compile' it, which really just adds it to the map.
300     if (DoesntNeedStub)
301       return TheJIT->getPointerToFunction(F);
302
303     return getJITResolver(this).getFunctionStub(F);
304   }
305
306   // Okay, the function has not been compiled yet, if the target callback
307   // mechanism is capable of rewriting the instruction directly, prefer to do
308   // that instead of emitting a stub.
309   if (DoesntNeedStub)
310     return getJITResolver(this).AddCallbackAtLocation(F, Reference);
311
312   // Otherwise, we have to emit a lazy resolving stub.
313   return getJITResolver(this).getFunctionStub(F);
314 }
315
316 void JITEmitter::startFunction(MachineFunction &F) {
317   CurByte = CurBlock = MemMgr.startFunctionBody();
318   TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
319 }
320
321 void JITEmitter::finishFunction(MachineFunction &F) {
322   MemMgr.endFunctionBody(CurByte);
323   ConstantPoolAddresses.clear();
324   NumBytes += CurByte-CurBlock;
325
326   if (!Relocations.empty()) {
327     // Resolve the relocations to concrete pointers.
328     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
329       MachineRelocation &MR = Relocations[i];
330       void *ResultPtr;
331       if (MR.isString())
332         ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
333       else
334         ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
335                                        CurBlock+MR.getMachineCodeOffset(),
336                                        MR.doesntNeedFunctionStub());
337       MR.setResultPointer(ResultPtr);
338     }
339
340     TheJIT->getJITInfo().relocate(CurBlock, &Relocations[0],
341                                   Relocations.size());
342   }
343
344   DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)CurBlock
345                   << "] Function: " << F.getFunction()->getName()
346                   << ": " << CurByte-CurBlock << " bytes of text, "
347                   << Relocations.size() << " relocations\n");
348   Relocations.clear();
349 }
350
351 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
352   const std::vector<Constant*> &Constants = MCP->getConstants();
353   if (Constants.empty()) return;
354
355   std::vector<unsigned> ConstantOffset;
356   ConstantOffset.reserve(Constants.size());
357
358   // Calculate how much space we will need for all the constants, and the offset
359   // each one will live in.
360   unsigned TotalSize = 0;
361   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
362     const Type *Ty = Constants[i]->getType();
363     unsigned Size      = (unsigned)TheJIT->getTargetData().getTypeSize(Ty);
364     unsigned Alignment = TheJIT->getTargetData().getTypeAlignment(Ty);
365     // Make sure to take into account the alignment requirements of the type.
366     TotalSize = (TotalSize + Alignment-1) & ~(Alignment-1);
367
368     // Remember the offset this element lives at.
369     ConstantOffset.push_back(TotalSize);
370     TotalSize += Size;   // Reserve space for the constant.
371   }
372
373   // Now that we know how much memory to allocate, do so.
374   char *Pool = new char[TotalSize];
375
376   // Actually output all of the constants, and remember their addresses.
377   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
378     void *Addr = Pool + ConstantOffset[i];
379     TheJIT->InitializeMemory(Constants[i], Addr);
380     ConstantPoolAddresses.push_back(Addr);
381   }
382 }
383
384 void JITEmitter::startFunctionStub(unsigned StubSize) {
385   SavedCurBlock = CurBlock;  SavedCurByte = CurByte;
386   CurByte = CurBlock = MemMgr.allocateStub(StubSize);
387 }
388
389 void *JITEmitter::finishFunctionStub(const Function *F) {
390   NumBytes += CurByte-CurBlock;
391   std::swap(CurBlock, SavedCurBlock);
392   CurByte = SavedCurByte;
393   return SavedCurBlock;
394 }
395
396 void JITEmitter::emitByte(unsigned char B) {
397   *CurByte++ = B;   // Write the byte to memory
398 }
399
400 void JITEmitter::emitWord(unsigned W) {
401   // This won't work if the endianness of the host and target don't agree!  (For
402   // a JIT this can't happen though.  :)
403   *(unsigned*)CurByte = W;
404   CurByte += sizeof(unsigned);
405 }
406
407 void JITEmitter::emitWordAt(unsigned W, unsigned *Ptr) {
408   *Ptr = W;
409 }
410
411 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
412 // in the constant pool that was last emitted with the 'emitConstantPool'
413 // method.
414 //
415 uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
416   assert(ConstantNum < ConstantPoolAddresses.size() &&
417          "Invalid ConstantPoolIndex!");
418   return (intptr_t)ConstantPoolAddresses[ConstantNum];
419 }
420
421 // getCurrentPCValue - This returns the address that the next emitted byte
422 // will be output to.
423 //
424 uint64_t JITEmitter::getCurrentPCValue() {
425   return (intptr_t)CurByte;
426 }
427
428 uint64_t JITEmitter::getCurrentPCOffset() {
429   return (intptr_t)CurByte-(intptr_t)CurBlock;
430 }
431
432 // getPointerToNamedFunction - This function is used as a global wrapper to
433 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
434 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
435 // need to resolve function(s) that are being mis-codegenerated, so we need to
436 // resolve their addresses at runtime, and this is the way to do it.
437 extern "C" {
438   void *getPointerToNamedFunction(const char *Name) {
439     Module &M = TheJIT->getModule();
440     if (Function *F = M.getNamedFunction(Name))
441       return TheJIT->getPointerToFunction(F);
442     return TheJIT->getPointerToNamedFunction(Name);
443   }
444 }