Add getCurrentPCOffset() and addRelocation() methods.
[oota-llvm.git] / lib / ExecutionEngine / JIT / JITEmitter.cpp
1 //===-- Emitter.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
29 using namespace llvm;
30
31 namespace {
32   Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
33   JIT *TheJIT = 0;
34
35   /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
36   /// sane way.  This splits a large block of MAP_NORESERVE'd memory into two
37   /// sections, one for function stubs, one for the functions themselves.  We
38   /// have to do this because we may need to emit a function stub while in the
39   /// middle of emitting a function, and we don't know how large the function we
40   /// are emitting is.  This never bothers to release the memory, because when
41   /// we are ready to destroy the JIT, the program exits.
42   class JITMemoryManager {
43     sys::MemoryBlock  MemBlock;  // Virtual memory block allocated RWX
44     unsigned char *MemBase;      // Base of block of memory, start of stub mem
45     unsigned char *FunctionBase; // Start of the function body area
46     unsigned char *CurStubPtr, *CurFunctionPtr;
47   public:
48     JITMemoryManager();
49     
50     inline unsigned char *allocateStub(unsigned StubSize);
51     inline unsigned char *startFunctionBody();
52     inline void endFunctionBody(unsigned char *FunctionEnd);    
53   };
54 }
55
56 JITMemoryManager::JITMemoryManager() {
57   // Allocate a 16M block of memory...
58   MemBlock = sys::Memory::AllocateRWX((16 << 20));
59   MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
60   FunctionBase = MemBase + 512*1024; // Use 512k for stubs
61
62   // Allocate stubs backwards from the function base, allocate functions forward
63   // from the function base.
64   CurStubPtr = CurFunctionPtr = FunctionBase;
65 }
66
67 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
68   CurStubPtr -= StubSize;
69   if (CurStubPtr < MemBase) {
70     std::cerr << "JIT ran out of memory for function stubs!\n";
71     abort();
72   }
73   return CurStubPtr;
74 }
75
76 unsigned char *JITMemoryManager::startFunctionBody() {
77   // Round up to an even multiple of 8 bytes, this should eventually be target
78   // specific.
79   return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
80 }
81
82 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
83   assert(FunctionEnd > CurFunctionPtr);
84   CurFunctionPtr = FunctionEnd;
85 }
86
87
88
89 namespace {
90   /// Emitter - The JIT implementation of the MachineCodeEmitter, which is used
91   /// to output functions to memory for execution.
92   class Emitter : public MachineCodeEmitter {
93     JITMemoryManager MemMgr;
94
95     // CurBlock - The start of the current block of memory.  CurByte - The
96     // current byte being emitted to.
97     unsigned char *CurBlock, *CurByte;
98
99     // When outputting a function stub in the context of some other function, we
100     // save CurBlock and CurByte here.
101     unsigned char *SavedCurBlock, *SavedCurByte;
102
103     // ConstantPoolAddresses - Contains the location for each entry in the
104     // constant pool.
105     std::vector<void*> ConstantPoolAddresses;
106
107     /// Relocations - These are the relocations that the function needs, as
108     /// emitted.
109     std::vector<MachineRelocation> Relocations;
110   public:
111     Emitter(JIT &jit) { TheJIT = &jit; }
112
113     virtual void startFunction(MachineFunction &F);
114     virtual void finishFunction(MachineFunction &F);
115     virtual void emitConstantPool(MachineConstantPool *MCP);
116     virtual void startFunctionStub(const Function &F, unsigned StubSize);
117     virtual void* finishFunctionStub(const Function &F);
118     virtual void emitByte(unsigned char B);
119     virtual void emitWord(unsigned W);
120     virtual void emitWordAt(unsigned W, unsigned *Ptr);
121
122     virtual void addRelocation(const MachineRelocation &MR) {
123       Relocations.push_back(MR);
124     }
125
126     virtual uint64_t getCurrentPCValue();
127     virtual uint64_t getCurrentPCOffset();
128     virtual uint64_t getGlobalValueAddress(GlobalValue *V);
129     virtual uint64_t getGlobalValueAddress(const char *Name);
130     virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
131
132     // forceCompilationOf - Force the compilation of the specified function, and
133     // return its address, because we REALLY need the address now.
134     //
135     // FIXME: This is JIT specific!
136     //
137     virtual uint64_t forceCompilationOf(Function *F);
138   };
139 }
140
141 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
142   return new Emitter(jit);
143 }
144
145 void Emitter::startFunction(MachineFunction &F) {
146   CurByte = CurBlock = MemMgr.startFunctionBody();
147   TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
148 }
149
150 void Emitter::finishFunction(MachineFunction &F) {
151   MemMgr.endFunctionBody(CurByte);
152   ConstantPoolAddresses.clear();
153   NumBytes += CurByte-CurBlock;
154
155   if (!Relocations.empty()) {
156     // Resolve the relocations to concrete pointers.
157     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
158       MachineRelocation &MR = Relocations[i];
159       void *ResultPtr;
160       if (MR.isGlobalValue()) {
161         assert(0 && "Unimplemented!\n");
162       } else {
163         ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
164       }
165       MR.setResultPointer(ResultPtr);
166     }
167
168     TheJIT->getJITInfo().relocate(CurBlock, &Relocations[0],
169                                   Relocations.size());
170   }
171
172   DEBUG(std::cerr << "Finished CodeGen of [" << (void*)CurBlock
173                   << "] Function: " << F.getFunction()->getName()
174                   << ": " << CurByte-CurBlock << " bytes of text, "
175                   << Relocations.size() << " relocations\n");
176   Relocations.clear();
177 }
178
179 void Emitter::emitConstantPool(MachineConstantPool *MCP) {
180   const std::vector<Constant*> &Constants = MCP->getConstants();
181   if (Constants.empty()) return;
182
183   std::vector<unsigned> ConstantOffset;
184   ConstantOffset.reserve(Constants.size());
185
186   // Calculate how much space we will need for all the constants, and the offset
187   // each one will live in.
188   unsigned TotalSize = 0;
189   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
190     const Type *Ty = Constants[i]->getType();
191     unsigned Size      = TheJIT->getTargetData().getTypeSize(Ty);
192     unsigned Alignment = TheJIT->getTargetData().getTypeAlignment(Ty);
193     // Make sure to take into account the alignment requirements of the type.
194     TotalSize = (TotalSize + Alignment-1) & ~(Alignment-1);
195
196     // Remember the offset this element lives at.
197     ConstantOffset.push_back(TotalSize);
198     TotalSize += Size;   // Reserve space for the constant.
199   }
200
201   // Now that we know how much memory to allocate, do so.
202   char *Pool = new char[TotalSize];
203
204   // Actually output all of the constants, and remember their addresses.
205   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
206     void *Addr = Pool + ConstantOffset[i];
207     TheJIT->InitializeMemory(Constants[i], Addr);
208     ConstantPoolAddresses.push_back(Addr);
209   }
210 }
211
212 void Emitter::startFunctionStub(const Function &F, unsigned StubSize) {
213   SavedCurBlock = CurBlock;  SavedCurByte = CurByte;
214   CurByte = CurBlock = MemMgr.allocateStub(StubSize);
215 }
216
217 void *Emitter::finishFunctionStub(const Function &F) {
218   NumBytes += CurByte-CurBlock;
219   DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
220                   << (uintptr_t)CurBlock
221                   << std::dec << "] Function stub for: " << F.getName()
222                   << ": " << CurByte-CurBlock << " bytes of text\n");
223   std::swap(CurBlock, SavedCurBlock);
224   CurByte = SavedCurByte;
225   return SavedCurBlock;
226 }
227
228 void Emitter::emitByte(unsigned char B) {
229   *CurByte++ = B;   // Write the byte to memory
230 }
231
232 void Emitter::emitWord(unsigned W) {
233   // This won't work if the endianness of the host and target don't agree!  (For
234   // a JIT this can't happen though.  :)
235   *(unsigned*)CurByte = W;
236   CurByte += sizeof(unsigned);
237 }
238
239 void Emitter::emitWordAt(unsigned W, unsigned *Ptr) {
240   *Ptr = W;
241 }
242
243 uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) {
244   // Try looking up the function to see if it is already compiled, if not return
245   // 0.
246   if (Function *F = dyn_cast<Function>(V)) {
247     void *Addr = TheJIT->getPointerToGlobalIfAvailable(F);
248     if (Addr == 0 && F->hasExternalLinkage()) {
249       // Do not output stubs for external functions.
250       Addr = TheJIT->getPointerToFunction(F);
251     }
252     return (intptr_t)Addr;
253   } else {
254     return (intptr_t)TheJIT->getOrEmitGlobalVariable(cast<GlobalVariable>(V));
255   }
256 }
257 uint64_t Emitter::getGlobalValueAddress(const char *Name) {
258   return (intptr_t)TheJIT->getPointerToNamedFunction(Name);
259 }
260
261 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
262 // in the constant pool that was last emitted with the 'emitConstantPool'
263 // method.
264 //
265 uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
266   assert(ConstantNum < ConstantPoolAddresses.size() &&
267          "Invalid ConstantPoolIndex!");
268   return (intptr_t)ConstantPoolAddresses[ConstantNum];
269 }
270
271 // getCurrentPCValue - This returns the address that the next emitted byte
272 // will be output to.
273 //
274 uint64_t Emitter::getCurrentPCValue() {
275   return (intptr_t)CurByte;
276 }
277
278 uint64_t Emitter::getCurrentPCOffset() {
279   return (intptr_t)CurByte-(intptr_t)CurBlock;
280 }
281
282 uint64_t Emitter::forceCompilationOf(Function *F) {
283   return (intptr_t)TheJIT->getPointerToFunction(F);
284 }
285
286 // getPointerToNamedFunction - This function is used as a global wrapper to
287 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
288 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
289 // need to resolve function(s) that are being mis-codegenerated, so we need to
290 // resolve their addresses at runtime, and this is the way to do it.
291 extern "C" {
292   void *getPointerToNamedFunction(const char *Name) {
293     Module &M = TheJIT->getModule();
294     if (Function *F = M.getNamedFunction(Name))
295       return TheJIT->getPointerToFunction(F);
296     return TheJIT->getPointerToNamedFunction(Name);
297   }
298 }