blob: 15ea90d84bdbe5a7c6948098a5607f36b00faa2b [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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"
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000017#include "JITDwarfEmitter.h"
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000018#include "llvm/Constants.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019#include "llvm/Module.h"
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000020#include "llvm/DerivedTypes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/CodeGen/MachineCodeEmitter.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000026#include "llvm/CodeGen/MachineRelocation.h"
Chris Lattnerc8ad39c2007-12-05 23:39:57 +000027#include "llvm/ExecutionEngine/JITMemoryManager.h"
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000028#include "llvm/ExecutionEngine/GenericValue.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/Target/TargetData.h"
30#include "llvm/Target/TargetJITInfo.h"
31#include "llvm/Target/TargetMachine.h"
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000032#include "llvm/Target/TargetOptions.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/Support/Debug.h"
34#include "llvm/Support/MutexGuard.h"
35#include "llvm/System/Disassembler.h"
Chris Lattner88f51632008-06-25 17:18:44 +000036#include "llvm/System/Memory.h"
Nicolas Geoffray68847972008-04-18 20:59:31 +000037#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng68e5fc32008-11-07 09:02:17 +000038#include "llvm/ADT/SmallPtrSet.h"
Nate Begeman7b1a8472009-02-18 08:31:02 +000039#include "llvm/ADT/SmallVector.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/ADT/Statistic.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041#include <algorithm>
Evan Cheng23dbb902008-11-05 23:44:08 +000042#ifndef NDEBUG
43#include <iomanip>
44#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +000045using namespace llvm;
46
47STATISTIC(NumBytes, "Number of bytes of machine code compiled");
48STATISTIC(NumRelos, "Number of relocations applied");
49static JIT *TheJIT = 0;
50
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051
52//===----------------------------------------------------------------------===//
53// JIT lazy compilation code.
54//
55namespace {
56 class JITResolverState {
57 private:
58 /// FunctionToStubMap - Keep track of the stub created for a particular
59 /// function so that we can reuse them if necessary.
60 std::map<Function*, void*> FunctionToStubMap;
61
62 /// StubToFunctionMap - Keep track of the function that each stub
63 /// corresponds to.
64 std::map<void*, Function*> StubToFunctionMap;
65
Evan Chengb0ebcb42008-11-10 01:52:24 +000066 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Cheng28e7e162008-01-04 10:46:51 +000067 /// particular GlobalVariable so that we can reuse them if necessary.
Evan Chengb0ebcb42008-11-10 01:52:24 +000068 std::map<GlobalValue*, void*> GlobalToIndirectSymMap;
Evan Cheng28e7e162008-01-04 10:46:51 +000069
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070 public:
71 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
72 assert(locked.holds(TheJIT->lock));
73 return FunctionToStubMap;
74 }
75
76 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
77 assert(locked.holds(TheJIT->lock));
78 return StubToFunctionMap;
79 }
Evan Cheng28e7e162008-01-04 10:46:51 +000080
81 std::map<GlobalValue*, void*>&
Evan Chengb0ebcb42008-11-10 01:52:24 +000082 getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Cheng28e7e162008-01-04 10:46:51 +000083 assert(locked.holds(TheJIT->lock));
Evan Chengb0ebcb42008-11-10 01:52:24 +000084 return GlobalToIndirectSymMap;
Evan Cheng28e7e162008-01-04 10:46:51 +000085 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086 };
87
88 /// JITResolver - Keep track of, and resolve, call sites for functions that
89 /// have not yet been compiled.
90 class JITResolver {
91 /// LazyResolverFn - The target lazy resolver function that we actually
92 /// rewrite instructions to use.
93 TargetJITInfo::LazyResolverFn LazyResolverFn;
94
95 JITResolverState state;
96
97 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
98 /// external functions.
99 std::map<void*, void*> ExternalFnToStubMap;
100
101 //map addresses to indexes in the GOT
102 std::map<void*, unsigned> revGOTMap;
103 unsigned nextGOTIndex;
104
105 static JITResolver *TheJITResolver;
106 public:
Dan Gohman40bd38e2008-03-25 22:06:05 +0000107 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 TheJIT = &jit;
109
110 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
111 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
112 TheJITResolver = this;
113 }
114
115 ~JITResolver() {
116 TheJITResolver = 0;
117 }
118
Evan Cheng6e4b7632008-11-13 21:50:50 +0000119 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
120 /// if it has already been created.
121 void *getFunctionStubIfAvailable(Function *F);
122
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begeman7b1a8472009-02-18 08:31:02 +0000124 /// one on demand as needed. If empty is true, create a function stub
125 /// pointing at address 0, to be filled in later.
126 void *getFunctionStub(Function *F, bool empty = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127
128 /// getExternalFunctionStub - Return a stub for the function at the
129 /// specified address, created lazily on demand.
130 void *getExternalFunctionStub(void *FnAddr);
131
Evan Chengb0ebcb42008-11-10 01:52:24 +0000132 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Cheng23c6b642008-11-05 01:50:32 +0000133 /// specified GV address.
Evan Chengb0ebcb42008-11-10 01:52:24 +0000134 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Cheng28e7e162008-01-04 10:46:51 +0000135
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136 /// AddCallbackAtLocation - If the target is capable of rewriting an
137 /// instruction without the use of a stub, record the location of the use so
138 /// we know which function is being used at the location.
139 void *AddCallbackAtLocation(Function *F, void *Location) {
140 MutexGuard locked(TheJIT->lock);
141 /// Get the target-specific JIT resolver function.
142 state.getStubToFunctionMap(locked)[Location] = F;
143 return (void*)(intptr_t)LazyResolverFn;
144 }
Nate Begeman7b1a8472009-02-18 08:31:02 +0000145
146 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
Nate Begemana5645962009-03-05 06:34:37 +0000147 SmallVectorImpl<void*> &Ptrs);
148
149 GlobalValue *invalidateStub(void *Stub);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150
151 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000152 /// an address. This function only manages slots, it does not manage the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 /// contents of the slots or the memory associated with the GOT.
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000154 unsigned getGOTIndexForAddr(void *addr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155
156 /// JITCompilerFn - This function is called to resolve a stub to a compiled
157 /// address. If the LLVM Function corresponding to the stub has not yet
158 /// been compiled, this function compiles it first.
159 static void *JITCompilerFn(void *Stub);
160 };
161}
162
163JITResolver *JITResolver::TheJITResolver = 0;
164
Evan Cheng6e4b7632008-11-13 21:50:50 +0000165/// getFunctionStubIfAvailable - This returns a pointer to a function stub
166/// if it has already been created.
167void *JITResolver::getFunctionStubIfAvailable(Function *F) {
168 MutexGuard locked(TheJIT->lock);
169
170 // If we already have a stub for this function, recycle it.
171 void *&Stub = state.getFunctionToStubMap(locked)[F];
172 return Stub;
173}
174
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175/// getFunctionStub - This returns a pointer to a function stub, creating
176/// one on demand as needed.
Nate Begeman7b1a8472009-02-18 08:31:02 +0000177void *JITResolver::getFunctionStub(Function *F, bool empty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 MutexGuard locked(TheJIT->lock);
179
180 // If we already have a stub for this function, recycle it.
181 void *&Stub = state.getFunctionToStubMap(locked)[F];
182 if (Stub) return Stub;
183
184 // Call the lazy resolver function unless we already KNOW it is an external
185 // function, in which case we just skip the lazy resolution step.
Nate Begeman7b1a8472009-02-18 08:31:02 +0000186 void *Actual = empty ? (void*)0 : (void*)(intptr_t)LazyResolverFn;
Dan Gohman0ae39622009-01-05 05:32:42 +0000187 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 Actual = TheJIT->getPointerToFunction(F);
189
Dan Gohman0ae39622009-01-05 05:32:42 +0000190 // If we resolved the symbol to a null address (eg. a weak external)
191 // don't emit a stub. Return a null pointer to the application.
192 if (!Actual) return 0;
193 }
194
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 // Otherwise, codegen a new stub. For now, the stub will call the lazy
196 // resolver function.
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000197 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 *TheJIT->getCodeEmitter());
199
200 if (Actual != (void*)(intptr_t)LazyResolverFn) {
201 // If we are getting the stub for an external function, we really want the
202 // address of the stub in the GlobalAddressMap for the JIT, not the address
203 // of the external function.
204 TheJIT->updateGlobalMapping(F, Stub);
205 }
206
Nate Begemana5645962009-03-05 06:34:37 +0000207 cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 << F->getName() << "'\n";
209
210 // Finally, keep track of the stub-to-Function mapping so that the
211 // JITCompilerFn knows which function to compile!
212 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begeman7b1a8472009-02-18 08:31:02 +0000213
214 // If this is an "empty" stub, then inform the JIT that it will need to
215 // JIT the function so an address can be provided.
216 if (empty)
217 TheJIT->addPendingFunction(F);
218
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 return Stub;
220}
221
Evan Chengb0ebcb42008-11-10 01:52:24 +0000222/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Cheng28e7e162008-01-04 10:46:51 +0000223/// GV address.
Evan Chengb0ebcb42008-11-10 01:52:24 +0000224void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Cheng28e7e162008-01-04 10:46:51 +0000225 MutexGuard locked(TheJIT->lock);
226
227 // If we already have a stub for this global variable, recycle it.
Evan Chengb0ebcb42008-11-10 01:52:24 +0000228 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
229 if (IndirectSym) return IndirectSym;
Evan Cheng28e7e162008-01-04 10:46:51 +0000230
Evan Cheng221548c2008-11-10 23:26:16 +0000231 // Otherwise, codegen a new indirect symbol.
Evan Chengb0ebcb42008-11-10 01:52:24 +0000232 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Cheng23c6b642008-11-05 01:50:32 +0000233 *TheJIT->getCodeEmitter());
Evan Cheng28e7e162008-01-04 10:46:51 +0000234
Evan Chengb0ebcb42008-11-10 01:52:24 +0000235 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
Evan Cheng28e7e162008-01-04 10:46:51 +0000236 << GV->getName() << "'\n";
237
Evan Chengb0ebcb42008-11-10 01:52:24 +0000238 return IndirectSym;
Evan Cheng28e7e162008-01-04 10:46:51 +0000239}
240
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241/// getExternalFunctionStub - Return a stub for the function at the
242/// specified address, created lazily on demand.
243void *JITResolver::getExternalFunctionStub(void *FnAddr) {
244 // If we already have a stub for this function, recycle it.
245 void *&Stub = ExternalFnToStubMap[FnAddr];
246 if (Stub) return Stub;
247
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000248 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 *TheJIT->getCodeEmitter());
250
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 DOUT << "JIT: Stub emitted at [" << Stub
252 << "] for external function at '" << FnAddr << "'\n";
253 return Stub;
254}
255
256unsigned JITResolver::getGOTIndexForAddr(void* addr) {
257 unsigned idx = revGOTMap[addr];
258 if (!idx) {
259 idx = ++nextGOTIndex;
260 revGOTMap[addr] = idx;
Evan Cheng7323eb52008-11-07 22:30:29 +0000261 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 }
263 return idx;
264}
265
Nate Begeman7b1a8472009-02-18 08:31:02 +0000266void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
267 SmallVectorImpl<void*> &Ptrs) {
268 MutexGuard locked(TheJIT->lock);
269
270 std::map<Function*,void*> &FM = state.getFunctionToStubMap(locked);
271 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
272
273 for (std::map<Function*,void*>::iterator i = FM.begin(), e = FM.end();
274 i != e; ++i) {
275 Function *F = i->first;
276 if (F->isDeclaration() && F->hasExternalLinkage()) {
277 GVs.push_back(i->first);
278 Ptrs.push_back(i->second);
279 }
280 }
281 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
282 i != e; ++i) {
283 GVs.push_back(i->first);
284 Ptrs.push_back(i->second);
285 }
286}
287
Nate Begemana5645962009-03-05 06:34:37 +0000288GlobalValue *JITResolver::invalidateStub(void *Stub) {
289 MutexGuard locked(TheJIT->lock);
290
291 std::map<Function*,void*> &FM = state.getFunctionToStubMap(locked);
292 std::map<void*,Function*> &SM = state.getStubToFunctionMap(locked);
293 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
294
295 // Look up the cheap way first, to see if it's a function stub we are
296 // invalidating. If so, remove it from both the forward and reverse maps.
297 if (SM.find(Stub) != SM.end()) {
298 Function *F = SM[Stub];
299 SM.erase(Stub);
300 FM.erase(F);
301 return F;
302 }
303
304 // Otherwise, it must be an indirect symbol stub. Find it and remove it.
305 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
306 i != e; ++i) {
307 if (i->second != Stub)
308 continue;
309 GlobalValue *GV = i->first;
310 GM.erase(i);
311 return GV;
312 }
313
314 return 0;
315}
316
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317/// JITCompilerFn - This function is called when a lazy compilation stub has
318/// been entered. It looks up which function this stub corresponds to, compiles
319/// it if necessary, then returns the resultant function pointer.
320void *JITResolver::JITCompilerFn(void *Stub) {
321 JITResolver &JR = *TheJITResolver;
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000322
323 Function* F = 0;
324 void* ActualPtr = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000326 {
327 // Only lock for getting the Function. The call getPointerToFunction made
328 // in this function might trigger function materializing, which requires
329 // JIT lock to be unlocked.
330 MutexGuard locked(TheJIT->lock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000332 // The address given to us for the stub may not be exactly right, it might be
333 // a little bit after the stub. As such, use upper_bound to find it.
334 std::map<void*, Function*>::iterator I =
335 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
336 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
337 "This is not a known stub!");
338 F = (--I)->second;
339 ActualPtr = I->first;
340 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341
342 // If we have already code generated the function, just return the address.
343 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
344
345 if (!Result) {
346 // Otherwise we don't have it, do lazy compilation now.
347
348 // If lazy compilation is disabled, emit a useful error message and abort.
349 if (TheJIT->isLazyCompilationDisabled()) {
350 cerr << "LLVM JIT requested to do lazy compilation of function '"
351 << F->getName() << "' when lazy compiles are disabled!\n";
352 abort();
353 }
354
355 // We might like to remove the stub from the StubToFunction map.
356 // We can't do that! Multiple threads could be stuck, waiting to acquire the
357 // lock above. As soon as the 1st function finishes compiling the function,
358 // the next one will be released, and needs to be able to find the function
359 // it needs to call.
360 //JR.state.getStubToFunctionMap(locked).erase(I);
361
362 DOUT << "JIT: Lazily resolving function '" << F->getName()
363 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000364 << ActualPtr << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365
366 Result = TheJIT->getPointerToFunction(F);
367 }
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000368
369 // Reacquire the lock to erase the stub in the map.
370 MutexGuard locked(TheJIT->lock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371
372 // We don't need to reuse this stub in the future, as F is now compiled.
373 JR.state.getFunctionToStubMap(locked).erase(F);
374
375 // FIXME: We could rewrite all references to this stub if we knew them.
376
377 // What we will do is set the compiled function address to map to the
378 // same GOT entry as the stub so that later clients may update the GOT
379 // if they see it still using the stub address.
380 // Note: this is done so the Resolver doesn't have to manage GOT memory
381 // Do this without allocating map space if the target isn't using a GOT
382 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
383 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
384
385 return Result;
386}
387
Chris Lattnerf50e3572008-04-04 05:51:42 +0000388//===----------------------------------------------------------------------===//
389// Function Index Support
390
391// On MacOS we generate an index of currently JIT'd functions so that
392// performance tools can determine a symbol name and accurate code range for a
393// PC value. Because performance tools are generally asynchronous, the code
394// below is written with the hope that it could be interrupted at any time and
395// have useful answers. However, we don't go crazy with atomic operations, we
396// just do a "reasonable effort".
397#ifdef __APPLE__
Evan Cheng4481f762008-05-15 17:31:35 +0000398#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattnerf50e3572008-04-04 05:51:42 +0000399#endif
400
401/// JitSymbolEntry - Each function that is JIT compiled results in one of these
402/// being added to an array of symbols. This indicates the name of the function
403/// as well as the address range it occupies. This allows the client to map
404/// from a PC value to the name of the function.
405struct JitSymbolEntry {
406 const char *FnName; // FnName - a strdup'd string.
407 void *FnStart;
408 intptr_t FnSize;
409};
410
411
412struct JitSymbolTable {
413 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
414 /// pointer is not used right now, but might be used in the future. Consider
415 /// it reserved for future use.
416 JitSymbolTable *NextPtr;
417
418 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
419 /// 'NumSymbols' symbols are valid.
420 JitSymbolEntry *Symbols;
421
422 /// NumSymbols - This indicates the number entries in the Symbols array that
423 /// are valid.
424 unsigned NumSymbols;
425
426 /// NumAllocated - This indicates the amount of space we have in the Symbols
427 /// array. This is a private field that should not be read by external tools.
428 unsigned NumAllocated;
429};
430
431#if ENABLE_JIT_SYMBOL_TABLE
432JitSymbolTable *__jitSymbolTable;
433#endif
434
435static void AddFunctionToSymbolTable(const char *FnName,
436 void *FnStart, intptr_t FnSize) {
437 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
438 JitSymbolTable **SymTabPtrPtr = 0;
439#if !ENABLE_JIT_SYMBOL_TABLE
440 return;
441#else
442 SymTabPtrPtr = &__jitSymbolTable;
443#endif
444
445 // If this is the first entry in the symbol table, add the JitSymbolTable
446 // index.
447 if (*SymTabPtrPtr == 0) {
448 JitSymbolTable *New = new JitSymbolTable();
449 New->NextPtr = 0;
450 New->Symbols = 0;
451 New->NumSymbols = 0;
452 New->NumAllocated = 0;
453 *SymTabPtrPtr = New;
454 }
455
456 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
457
458 // If we have space in the table, reallocate the table.
459 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
460 // If we don't have space, reallocate the table.
Chris Lattnerea0cb7c2008-04-13 07:04:56 +0000461 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattnerf50e3572008-04-04 05:51:42 +0000462 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
463 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
464
465 // Copy the old entries over.
Nate Begeman7b1a8472009-02-18 08:31:02 +0000466 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattnerf50e3572008-04-04 05:51:42 +0000467
468 // Swap the new symbols in, delete the old ones.
469 SymTabPtr->Symbols = NewSymbols;
Chris Lattnerea0cb7c2008-04-13 07:04:56 +0000470 SymTabPtr->NumAllocated = NewSize;
Chris Lattnerf50e3572008-04-04 05:51:42 +0000471 delete [] OldSymbols;
472 }
473
474 // Otherwise, we have enough space, just tack it onto the end of the array.
475 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
476 Entry.FnName = strdup(FnName);
477 Entry.FnStart = FnStart;
478 Entry.FnSize = FnSize;
479 ++SymTabPtr->NumSymbols;
480}
481
482static void RemoveFunctionFromSymbolTable(void *FnStart) {
483 assert(FnStart && "Invalid function pointer");
484 JitSymbolTable **SymTabPtrPtr = 0;
485#if !ENABLE_JIT_SYMBOL_TABLE
486 return;
487#else
488 SymTabPtrPtr = &__jitSymbolTable;
489#endif
490
491 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
492 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
493
494 // Scan the table to find its index. The table is not sorted, so do a linear
495 // scan.
496 unsigned Index;
497 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
498 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
499
500 // Once we have an index, we know to nuke this entry, overwrite it with the
501 // entry at the end of the array, making the last entry redundant.
502 const char *OldName = Symbols[Index].FnName;
503 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
504 free((void*)OldName);
505
506 // Drop the number of symbols in the table.
507 --SymTabPtr->NumSymbols;
508
509 // Finally, if we deleted the final symbol, deallocate the table itself.
Nate Begeman0751db22008-05-18 19:09:10 +0000510 if (SymTabPtr->NumSymbols != 0)
Chris Lattnerf50e3572008-04-04 05:51:42 +0000511 return;
512
513 *SymTabPtrPtr = 0;
514 delete [] Symbols;
515 delete SymTabPtr;
516}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517
518//===----------------------------------------------------------------------===//
519// JITEmitter code.
520//
521namespace {
522 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
523 /// used to output functions to memory for execution.
524 class JITEmitter : public MachineCodeEmitter {
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000525 JITMemoryManager *MemMgr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000526
527 // When outputting a function stub in the context of some other function, we
528 // save BufferBegin/BufferEnd/CurBufferPtr here.
529 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
530
531 /// Relocations - These are the relocations that the function needs, as
532 /// emitted.
533 std::vector<MachineRelocation> Relocations;
534
535 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
536 /// It is filled in by the StartMachineBasicBlock callback and queried by
537 /// the getMachineBasicBlockAddress callback.
Evan Cheng6e561c72008-12-10 02:32:19 +0000538 std::vector<uintptr_t> MBBLocations;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539
540 /// ConstantPool - The constant pool for the current function.
541 ///
542 MachineConstantPool *ConstantPool;
543
544 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
545 ///
546 void *ConstantPoolBase;
547
548 /// JumpTable - The jump tables for the current function.
549 ///
550 MachineJumpTableInfo *JumpTable;
551
552 /// JumpTableBase - A pointer to the first entry in the jump table.
553 ///
554 void *JumpTableBase;
Evan Chengaf743252008-01-05 02:26:58 +0000555
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000556 /// Resolver - This contains info about the currently resolved functions.
557 JITResolver Resolver;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000558
559 /// DE - The dwarf emitter for the jit.
560 JITDwarfEmitter *DE;
561
562 /// LabelLocations - This vector is a mapping from Label ID's to their
563 /// address.
Evan Cheng6e561c72008-12-10 02:32:19 +0000564 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000565
566 /// MMI - Machine module info for exception informations
567 MachineModuleInfo* MMI;
568
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000569 // GVSet - a set to keep track of which globals have been seen
Evan Cheng68e5fc32008-11-07 09:02:17 +0000570 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000571
Nate Begemana5645962009-03-05 06:34:37 +0000572 // CurFn - The llvm function being emitted. Only valid during
573 // finishFunction().
574 const Function *CurFn;
575
576 // CurFnStubUses - For a given Function, a vector of stubs that it
577 // references. This facilitates the JIT detecting that a stub is no
578 // longer used, so that it may be deallocated.
579 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
580
581 // StubFnRefs - For a given pointer to a stub, a set of Functions which
582 // reference the stub. When the count of a stub's references drops to zero,
583 // the stub is unused.
584 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
585
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 public:
Nate Begemana5645962009-03-05 06:34:37 +0000587 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0) {
Chris Lattnere44be002007-12-06 01:08:09 +0000588 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000589 if (jit.getJITInfo().needsGOT()) {
590 MemMgr->AllocateGOT();
591 DOUT << "JIT is managing a GOT\n";
592 }
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000593
594 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000595 }
596 ~JITEmitter() {
597 delete MemMgr;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000598 if (ExceptionHandling) delete DE;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000599 }
Evan Cheng89b29a12008-08-20 00:28:12 +0000600
601 /// classof - Methods for support type inquiry through isa, cast, and
602 /// dyn_cast:
603 ///
604 static inline bool classof(const JITEmitter*) { return true; }
605 static inline bool classof(const MachineCodeEmitter*) { return true; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606
607 JITResolver &getJITResolver() { return Resolver; }
608
609 virtual void startFunction(MachineFunction &F);
610 virtual bool finishFunction(MachineFunction &F);
611
612 void emitConstantPool(MachineConstantPool *MCP);
613 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
614 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
615
Evan Cheng2c3267a2008-11-08 08:02:53 +0000616 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000617 unsigned Alignment = 1);
Nate Begeman7b1a8472009-02-18 08:31:02 +0000618 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
619 unsigned StubSize);
Evan Cheng2c3267a2008-11-08 08:02:53 +0000620 virtual void* finishGVStub(const GlobalValue *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621
Nuno Lopes1ab7adc2008-10-21 11:42:16 +0000622 /// allocateSpace - Reserves space in the current block if any, or
623 /// allocate a new one of the given size.
Evan Cheng6e561c72008-12-10 02:32:19 +0000624 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopes1ab7adc2008-10-21 11:42:16 +0000625
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 virtual void addRelocation(const MachineRelocation &MR) {
627 Relocations.push_back(MR);
628 }
629
630 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
631 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
632 MBBLocations.resize((MBB->getNumber()+1)*2);
633 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Evan Cheng7323eb52008-11-07 22:30:29 +0000634 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
635 << (void*) getCurrentPCValue() << "]\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636 }
637
Evan Cheng6e561c72008-12-10 02:32:19 +0000638 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
639 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Chengaf743252008-01-05 02:26:58 +0000640
Evan Cheng6e561c72008-12-10 02:32:19 +0000641 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
643 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
644 return MBBLocations[MBB->getNumber()];
645 }
646
Nate Begemana5645962009-03-05 06:34:37 +0000647 void AddStubToCurrentFunction(void *Stub);
648
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000649 /// deallocateMemForFunction - Deallocate all memory for the specified
650 /// function body.
Nate Begemana5645962009-03-05 06:34:37 +0000651 void deallocateMemForFunction(Function *F);
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000652
653 virtual void emitLabel(uint64_t LabelID) {
654 if (LabelLocations.size() <= LabelID)
655 LabelLocations.resize((LabelID+1)*2);
656 LabelLocations[LabelID] = getCurrentPCValue();
657 }
658
Evan Cheng6e561c72008-12-10 02:32:19 +0000659 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000660 assert(LabelLocations.size() > (unsigned)LabelID &&
661 LabelLocations[LabelID] && "Label not emitted!");
662 return LabelLocations[LabelID];
663 }
664
665 virtual void setModuleInfo(MachineModuleInfo* Info) {
666 MMI = Info;
667 if (ExceptionHandling) DE->setModuleInfo(Info);
668 }
669
Jim Grosbach724b1812008-10-03 16:17:20 +0000670 void setMemoryExecutable(void) {
671 MemMgr->setMemoryExecutable();
672 }
Nate Begeman7b1a8472009-02-18 08:31:02 +0000673
674 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
Jim Grosbach724b1812008-10-03 16:17:20 +0000675
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676 private:
677 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Chengb0ebcb42008-11-10 01:52:24 +0000678 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Cheng221548c2008-11-10 23:26:16 +0000679 bool NoNeedStub);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000680 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
681 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
682 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
683 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 };
685}
686
687void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
688 bool DoesntNeedStub) {
Nate Begeman7b1a8472009-02-18 08:31:02 +0000689 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begeman7b1a8472009-02-18 08:31:02 +0000691
Chris Lattner44d8ea72008-06-25 20:21:35 +0000692 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikovc7b90912008-09-09 20:05:04 +0000693 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694
695 // If we have already compiled the function, return a pointer to its body.
696 Function *F = cast<Function>(V);
Evan Cheng6e4b7632008-11-13 21:50:50 +0000697 void *ResultPtr;
Nate Begemana5645962009-03-05 06:34:37 +0000698 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
Evan Cheng6e4b7632008-11-13 21:50:50 +0000699 // Return the function stub if it's already created.
700 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begemana5645962009-03-05 06:34:37 +0000701 if (ResultPtr)
702 AddStubToCurrentFunction(ResultPtr);
703 } else {
Evan Cheng6e4b7632008-11-13 21:50:50 +0000704 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begemana5645962009-03-05 06:34:37 +0000705 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 if (ResultPtr) return ResultPtr;
707
Nate Begeman7b1a8472009-02-18 08:31:02 +0000708 // If this is an external function pointer, we can force the JIT to
709 // 'compile' it, which really just adds it to the map.
710 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() && DoesntNeedStub)
711 return TheJIT->getPointerToFunction(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000712
Nate Begeman7b1a8472009-02-18 08:31:02 +0000713 // If we are jitting non-lazily but encounter a function that has not been
714 // jitted yet, we need to allocate a blank stub to call the function
715 // once we JIT it and its address is known.
716 if (TheJIT->isLazyCompilationDisabled())
717 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
718 return Resolver.getFunctionStub(F, true);
719
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720 // Okay, the function has not been compiled yet, if the target callback
721 // mechanism is capable of rewriting the instruction directly, prefer to do
722 // that instead of emitting a stub.
723 if (DoesntNeedStub)
724 return Resolver.AddCallbackAtLocation(F, Reference);
725
726 // Otherwise, we have to emit a lazy resolving stub.
Nate Begemana5645962009-03-05 06:34:37 +0000727 void *StubAddr = Resolver.getFunctionStub(F);
728
729 // Add the stub to the current function's list of referenced stubs, so we can
730 // deallocate them if the current function is ever freed.
731 AddStubToCurrentFunction(StubAddr);
732
733 return StubAddr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734}
735
Evan Chengb0ebcb42008-11-10 01:52:24 +0000736void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Cheng221548c2008-11-10 23:26:16 +0000737 bool NoNeedStub) {
Nate Begemana5645962009-03-05 06:34:37 +0000738 // Make sure GV is emitted first, and create a stub containing the fully
739 // resolved address.
Evan Cheng28e7e162008-01-04 10:46:51 +0000740 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begemana5645962009-03-05 06:34:37 +0000741 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
742
743 // Add the stub to the current function's list of referenced stubs, so we can
744 // deallocate them if the current function is ever freed.
745 AddStubToCurrentFunction(StubAddr);
746
747 return StubAddr;
748}
749
750void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
751 if (!TheJIT->areDlsymStubsEnabled())
752 return;
753
754 assert(CurFn && "Stub added to current function, but current function is 0!");
755
756 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
757 StubsUsed.push_back(StubAddr);
758
759 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
760 FnRefs.insert(CurFn);
Evan Cheng28e7e162008-01-04 10:46:51 +0000761}
762
Nicolas Geoffray68847972008-04-18 20:59:31 +0000763static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
764 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
765 if (Constants.empty()) return 0;
766
767 MachineConstantPoolEntry CPE = Constants.back();
768 unsigned Size = CPE.Offset;
769 const Type *Ty = CPE.isMachineConstantPoolEntry()
770 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000771 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
Nicolas Geoffray68847972008-04-18 20:59:31 +0000772 return Size;
773}
774
775static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
776 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
777 if (JT.empty()) return 0;
778
779 unsigned NumEntries = 0;
780 for (unsigned i = 0, e = JT.size(); i != e; ++i)
781 NumEntries += JT[i].MBBs.size();
782
783 unsigned EntrySize = MJTI->getEntrySize();
784
785 return NumEntries * EntrySize;
786}
787
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000788static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffray68847972008-04-18 20:59:31 +0000789 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000790 // Since we do not know where the buffer will be allocated, be pessimistic.
791 return Size + Alignment;
Nicolas Geoffray68847972008-04-18 20:59:31 +0000792}
Evan Cheng28e7e162008-01-04 10:46:51 +0000793
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000794/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
795/// into the running total Size.
796
797unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
798 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000799 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypePaddedSize(ElTy);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000800 size_t GVAlign =
801 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengd6599362008-11-06 17:46:04 +0000802 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000803 DEBUG(GV->dump());
804 // Assume code section ends with worst possible alignment, so first
805 // variable needs maximal padding.
806 if (Size==0)
807 Size = 1;
808 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
809 Size += GVSize;
810 return Size;
811}
812
813/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
814/// but are referenced from the constant; put them in GVSet and add their
815/// size into the running total Size.
816
817unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
818 unsigned Size) {
819 // If its undefined, return the garbage.
820 if (isa<UndefValue>(C))
821 return Size;
822
823 // If the value is a ConstantExpr
824 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
825 Constant *Op0 = CE->getOperand(0);
826 switch (CE->getOpcode()) {
827 case Instruction::GetElementPtr:
828 case Instruction::Trunc:
829 case Instruction::ZExt:
830 case Instruction::SExt:
831 case Instruction::FPTrunc:
832 case Instruction::FPExt:
833 case Instruction::UIToFP:
834 case Instruction::SIToFP:
835 case Instruction::FPToUI:
836 case Instruction::FPToSI:
837 case Instruction::PtrToInt:
838 case Instruction::IntToPtr:
839 case Instruction::BitCast: {
840 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
841 break;
842 }
843 case Instruction::Add:
844 case Instruction::Sub:
845 case Instruction::Mul:
846 case Instruction::UDiv:
847 case Instruction::SDiv:
848 case Instruction::URem:
849 case Instruction::SRem:
850 case Instruction::And:
851 case Instruction::Or:
852 case Instruction::Xor: {
853 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
854 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
855 break;
856 }
857 default: {
858 cerr << "ConstantExpr not handled: " << *CE << "\n";
859 abort();
860 }
861 }
862 }
863
864 if (C->getType()->getTypeID() == Type::PointerTyID)
865 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng68e5fc32008-11-07 09:02:17 +0000866 if (GVSet.insert(GV))
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000867 Size = addSizeOfGlobal(GV, Size);
868
869 return Size;
870}
871
872/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
873/// but are referenced from the given initializer.
874
875unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
876 unsigned Size) {
877 if (!isa<UndefValue>(Init) &&
878 !isa<ConstantVector>(Init) &&
879 !isa<ConstantAggregateZero>(Init) &&
880 !isa<ConstantArray>(Init) &&
881 !isa<ConstantStruct>(Init) &&
882 Init->getType()->isFirstClassType())
883 Size = addSizeOfGlobalsInConstantVal(Init, Size);
884 return Size;
885}
886
887/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
888/// globals; then walk the initializers of those globals looking for more.
889/// If their size has not been considered yet, add it into the running total
890/// Size.
891
892unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
893 unsigned Size = 0;
894 GVSet.clear();
895
896 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
897 MBB != E; ++MBB) {
898 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
899 I != E; ++I) {
900 const TargetInstrDesc &Desc = I->getDesc();
901 const MachineInstr &MI = *I;
902 unsigned NumOps = Desc.getNumOperands();
903 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
904 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000905 if (MO.isGlobal()) {
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000906 GlobalValue* V = MO.getGlobal();
907 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
908 if (!GV)
909 continue;
910 // If seen in previous function, it will have an entry here.
911 if (TheJIT->getPointerToGlobalIfAvailable(GV))
912 continue;
913 // If seen earlier in this function, it will have an entry here.
914 // FIXME: it should be possible to combine these tables, by
915 // assuming the addresses of the new globals in this module
916 // start at 0 (or something) and adjusting them after codegen
917 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng68e5fc32008-11-07 09:02:17 +0000918 if (GVSet.insert(GV))
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000919 // A variable as yet unseen. Add in its size.
920 Size = addSizeOfGlobal(GV, Size);
921 }
922 }
923 }
924 }
Evan Chengd6599362008-11-06 17:46:04 +0000925 DOUT << "JIT: About to look through initializers\n";
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000926 // Look for more globals that are referenced only from initializers.
927 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng68e5fc32008-11-07 09:02:17 +0000928 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000929 I != GVSet.end(); I++) {
930 const GlobalVariable* GV = *I;
931 if (GV->hasInitializer())
932 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
933 }
934
935 return Size;
936}
937
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938void JITEmitter::startFunction(MachineFunction &F) {
Evan Chengd6599362008-11-06 17:46:04 +0000939 DOUT << "JIT: Starting CodeGen of Function "
940 << F.getFunction()->getName() << "\n";
941
Nicolas Geoffray68847972008-04-18 20:59:31 +0000942 uintptr_t ActualSize = 0;
Jim Grosbach724b1812008-10-03 16:17:20 +0000943 // Set the memory writable, if it's not already
944 MemMgr->setMemoryWritable();
Nicolas Geoffrayf748af22008-04-20 17:44:19 +0000945 if (MemMgr->NeedsExactSize()) {
Evan Chengd6599362008-11-06 17:46:04 +0000946 DOUT << "JIT: ExactSize\n";
Nicolas Geoffray68847972008-04-18 20:59:31 +0000947 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
948 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
949 MachineConstantPool *MCP = F.getConstantPool();
950
951 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000952 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffray68847972008-04-18 20:59:31 +0000953
954 // Add the alignment of the constant pool
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000955 ActualSize = RoundUpToAlign(ActualSize,
956 1 << MCP->getConstantPoolAlignment());
Nicolas Geoffray68847972008-04-18 20:59:31 +0000957
958 // Add the constant pool size
959 ActualSize += GetConstantPoolSizeInBytes(MCP);
960
961 // Add the aligment of the jump table info
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000962 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffray68847972008-04-18 20:59:31 +0000963
964 // Add the jump table size
965 ActualSize += GetJumpTableSizeInBytes(MJTI);
966
967 // Add the alignment for the function
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000968 ActualSize = RoundUpToAlign(ActualSize,
969 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffray68847972008-04-18 20:59:31 +0000970
971 // Add the function size
972 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000973
Evan Chengd6599362008-11-06 17:46:04 +0000974 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000975 // Add the size of the globals that will be allocated after this function.
976 // These are all the ones referenced from this function that were not
977 // previously allocated.
978 ActualSize += GetSizeOfGlobalsInBytes(F);
Evan Chengd6599362008-11-06 17:46:04 +0000979 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffray68847972008-04-18 20:59:31 +0000980 }
981
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000982 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
983 ActualSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984 BufferEnd = BufferBegin+ActualSize;
985
986 // Ensure the constant pool/jump table info is at least 4-byte aligned.
987 emitAlignment(16);
988
989 emitConstantPool(F.getConstantPool());
990 initJumpTableInfo(F.getJumpTableInfo());
991
992 // About to start emitting the machine code for the function.
993 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
994 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
995
996 MBBLocations.clear();
997}
998
999bool JITEmitter::finishFunction(MachineFunction &F) {
1000 if (CurBufferPtr == BufferEnd) {
1001 // FIXME: Allocate more space, then try again.
1002 cerr << "JIT: Ran out of space for generated machine code!\n";
1003 abort();
1004 }
1005
1006 emitJumpTableInfo(F.getJumpTableInfo());
1007
1008 // FnStart is the start of the text, not the start of the constant pool and
1009 // other per-function data.
1010 unsigned char *FnStart =
1011 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012
1013 if (!Relocations.empty()) {
Nate Begemana5645962009-03-05 06:34:37 +00001014 CurFn = F.getFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 NumRelos += Relocations.size();
1016
1017 // Resolve the relocations to concrete pointers.
1018 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1019 MachineRelocation &MR = Relocations[i];
Evan Cheng1cf55bb2008-11-03 07:14:02 +00001020 void *ResultPtr = 0;
Evan Chengc5fe01b2008-10-29 23:54:46 +00001021 if (!MR.letTargetResolve()) {
Evan Cheng2976cd12008-11-08 07:37:34 +00001022 if (MR.isExternalSymbol()) {
Dan Gohman0ae39622009-01-05 05:32:42 +00001023 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1024 false);
Evan Cheng2976cd12008-11-08 07:37:34 +00001025 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Evan Cheng56d1b582008-11-08 07:22:53 +00001026 << ResultPtr << "]\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027
Evan Chengc5fe01b2008-10-29 23:54:46 +00001028 // If the target REALLY wants a stub for this function, emit it now.
1029 if (!MR.doesntNeedStub())
1030 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1031 } else if (MR.isGlobalValue()) {
1032 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1033 BufferBegin+MR.getMachineCodeOffset(),
1034 MR.doesntNeedStub());
Evan Chengb0ebcb42008-11-10 01:52:24 +00001035 } else if (MR.isIndirectSymbol()) {
1036 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Cheng28e7e162008-01-04 10:46:51 +00001037 BufferBegin+MR.getMachineCodeOffset(),
1038 MR.doesntNeedStub());
Evan Chengc5fe01b2008-10-29 23:54:46 +00001039 } else if (MR.isBasicBlock()) {
1040 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1041 } else if (MR.isConstantPoolIndex()) {
1042 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1043 } else {
1044 assert(MR.isJumpTableIndex());
1045 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1046 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047
Evan Chengc5fe01b2008-10-29 23:54:46 +00001048 MR.setResultPointer(ResultPtr);
1049 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050
1051 // if we are managing the GOT and the relocation wants an index,
1052 // give it one
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001053 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
1055 MR.setGOTIndex(idx);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001056 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengd6599362008-11-06 17:46:04 +00001057 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001058 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 << "\n";
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001060 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001061 }
1062 }
1063 }
1064
Nate Begemana5645962009-03-05 06:34:37 +00001065 CurFn = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001067 Relocations.size(), MemMgr->getGOTBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068 }
1069
1070 // Update the GOT entry for F to point to the new code.
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001071 if (MemMgr->isManagingGOT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001073 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengd6599362008-11-06 17:46:04 +00001074 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001075 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1076 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001077 }
1078 }
1079
Nuno Lopes1ab7adc2008-10-21 11:42:16 +00001080 unsigned char *FnEnd = CurBufferPtr;
1081
1082 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
Evan Cheng6e561c72008-12-10 02:32:19 +00001083
1084 if (CurBufferPtr == BufferEnd) {
1085 // FIXME: Allocate more space, then try again.
1086 cerr << "JIT: Ran out of space for generated machine code!\n";
1087 abort();
1088 }
1089
Nuno Lopes1ab7adc2008-10-21 11:42:16 +00001090 BufferBegin = CurBufferPtr = 0;
1091 NumBytes += FnEnd-FnStart;
1092
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001093 // Invalidate the icache if necessary.
Chris Lattner88f51632008-06-25 17:18:44 +00001094 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattnerf50e3572008-04-04 05:51:42 +00001095
1096 // Add it to the JIT symbol table if the host wants it.
1097 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1098 FnStart, FnEnd-FnStart);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099
1100 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1101 << "] Function: " << F.getFunction()->getName()
1102 << ": " << (FnEnd-FnStart) << " bytes of text, "
1103 << Relocations.size() << " relocations\n";
1104 Relocations.clear();
1105
Evan Chengb83f6972008-09-18 07:54:21 +00001106 // Mark code region readable and executable if it's not so already.
Jim Grosbach724b1812008-10-03 16:17:20 +00001107 MemMgr->setMemoryExecutable();
Evan Chengb83f6972008-09-18 07:54:21 +00001108
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109#ifndef NDEBUG
Evan Cheng23dbb902008-11-05 23:44:08 +00001110 {
Evan Chengb81ef082008-11-12 08:22:43 +00001111 if (sys::hasDisassembler()) {
1112 DOUT << "JIT: Disassembled code:\n";
Evan Chengd6599362008-11-06 17:46:04 +00001113 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chengb81ef082008-11-12 08:22:43 +00001114 } else {
1115 DOUT << "JIT: Binary code:\n";
Evan Cheng23dbb902008-11-05 23:44:08 +00001116 DOUT << std::hex;
Evan Cheng23dbb902008-11-05 23:44:08 +00001117 unsigned char* q = FnStart;
Evan Chengb81ef082008-11-12 08:22:43 +00001118 for (int i = 0; q < FnEnd; q += 4, ++i) {
1119 if (i == 4)
1120 i = 0;
1121 if (i == 0)
1122 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1123 << (long)(q - FnStart) << ": ";
1124 bool Done = false;
1125 for (int j = 3; j >= 0; --j) {
1126 if (q + j >= FnEnd)
1127 Done = true;
1128 else
1129 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1130 }
1131 if (Done)
1132 break;
1133 DOUT << ' ';
1134 if (i == 3)
Evan Chengca323d72008-11-06 01:18:29 +00001135 DOUT << '\n';
Evan Cheng23dbb902008-11-05 23:44:08 +00001136 }
1137 DOUT << std::dec;
Evan Chengca323d72008-11-06 01:18:29 +00001138 DOUT<< '\n';
Evan Cheng23dbb902008-11-05 23:44:08 +00001139 }
1140 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141#endif
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001142 if (ExceptionHandling) {
Nicolas Geoffray68847972008-04-18 20:59:31 +00001143 uintptr_t ActualSize = 0;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001144 SavedBufferBegin = BufferBegin;
1145 SavedBufferEnd = BufferEnd;
1146 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffray68847972008-04-18 20:59:31 +00001147
Nicolas Geoffrayf748af22008-04-20 17:44:19 +00001148 if (MemMgr->NeedsExactSize()) {
1149 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffray68847972008-04-18 20:59:31 +00001150 }
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001151
1152 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1153 ActualSize);
1154 BufferEnd = BufferBegin+ActualSize;
1155 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner3d46fe02008-03-07 20:05:43 +00001156 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1157 FrameRegister);
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001158 BufferBegin = SavedBufferBegin;
1159 BufferEnd = SavedBufferEnd;
1160 CurBufferPtr = SavedCurBufferPtr;
1161
1162 TheJIT->RegisterTable(FrameRegister);
1163 }
Evan Chengca346e62008-09-02 08:14:01 +00001164
1165 if (MMI)
1166 MMI->EndFunction();
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001167
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001168 return false;
1169}
1170
Nate Begemana5645962009-03-05 06:34:37 +00001171/// deallocateMemForFunction - Deallocate all memory for the specified
1172/// function body. Also drop any references the function has to stubs.
1173void JITEmitter::deallocateMemForFunction(Function *F) {
1174 MemMgr->deallocateMemForFunction(F);
1175
1176 // If the function did not reference any stubs, return.
1177 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1178 return;
1179
1180 // For each referenced stub, erase the reference to this function, and then
1181 // erase the list of referenced stubs.
1182 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1183 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1184 void *Stub = StubList[i];
1185 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1186 FnRefs.erase(F);
1187
1188 // If this function was the last reference to the stub, invalidate the stub
1189 // in the JITResolver. Were there a memory manager deallocateStub routine,
1190 // we could call that at this point too.
1191 if (FnRefs.empty()) {
1192 Resolver.invalidateStub(Stub);
1193 StubFnRefs.erase(F);
1194 }
1195 }
1196 CurFnStubUses.erase(F);
1197}
1198
1199
Evan Cheng6e561c72008-12-10 02:32:19 +00001200void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopes1ab7adc2008-10-21 11:42:16 +00001201 if (BufferBegin)
1202 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1203
1204 // create a new memory block if there is no active one.
1205 // care must be taken so that BufferBegin is invalidated when a
1206 // block is trimmed
1207 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1208 BufferEnd = BufferBegin+Size;
1209 return CurBufferPtr;
1210}
1211
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001212void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng68e5fc32008-11-07 09:02:17 +00001213 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbachbad01432008-10-30 23:44:39 +00001214 return;
Evan Cheng68e5fc32008-11-07 09:02:17 +00001215
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001216 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1217 if (Constants.empty()) return;
1218
1219 MachineConstantPoolEntry CPE = Constants.back();
1220 unsigned Size = CPE.Offset;
1221 const Type *Ty = CPE.isMachineConstantPoolEntry()
1222 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001223 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224
Evan Cheng71c58872008-04-12 00:22:01 +00001225 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1226 ConstantPoolBase = allocateSpace(Size, Align);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 ConstantPool = MCP;
1228
1229 if (ConstantPoolBase == 0) return; // Buffer overflow.
1230
Evan Cheng71c58872008-04-12 00:22:01 +00001231 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1232 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1233
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234 // Initialize the memory for all of the constant pool entries.
1235 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1236 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
1237 if (Constants[i].isMachineConstantPoolEntry()) {
1238 // FIXME: add support to lower machine constant pool values into bytes!
1239 cerr << "Initialize memory with machine specific constant pool entry"
1240 << " has not been implemented!\n";
1241 abort();
1242 }
1243 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
Evan Cheng71c58872008-04-12 00:22:01 +00001244 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 }
1246}
1247
1248void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng68e5fc32008-11-07 09:02:17 +00001249 if (TheJIT->getJITInfo().hasCustomJumpTables())
1250 return;
1251
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1253 if (JT.empty()) return;
1254
1255 unsigned NumEntries = 0;
1256 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1257 NumEntries += JT[i].MBBs.size();
1258
1259 unsigned EntrySize = MJTI->getEntrySize();
1260
1261 // Just allocate space for all the jump tables now. We will fix up the actual
1262 // MBB entries in the tables after we emit the code for each block, since then
1263 // we will know the final locations of the MBBs in memory.
1264 JumpTable = MJTI;
1265 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1266}
1267
1268void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng68e5fc32008-11-07 09:02:17 +00001269 if (TheJIT->getJITInfo().hasCustomJumpTables())
1270 return;
1271
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1273 if (JT.empty() || JumpTableBase == 0) return;
1274
1275 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1276 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1277 // For each jump table, place the offset from the beginning of the table
1278 // to the target address.
1279 int *SlotPtr = (int*)JumpTableBase;
1280
1281 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1282 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1283 // Store the offset of the basic block for this jump table slot in the
1284 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng6e561c72008-12-10 02:32:19 +00001285 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Chengaf743252008-01-05 02:26:58 +00001286 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng6e561c72008-12-10 02:32:19 +00001287 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Chengaf743252008-01-05 02:26:58 +00001288 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1289 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290 }
1291 } else {
1292 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1293
1294 // For each jump table, map each target in the jump table to the address of
1295 // an emitted MachineBasicBlock.
1296 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1297
1298 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1299 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1300 // Store the address of the basic block for this jump table slot in the
1301 // memory we allocated for the jump table in 'initJumpTableInfo'
1302 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1303 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1304 }
1305 }
1306}
1307
Evan Cheng2c3267a2008-11-08 08:02:53 +00001308void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1309 unsigned Alignment) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310 SavedBufferBegin = BufferBegin;
1311 SavedBufferEnd = BufferEnd;
1312 SavedCurBufferPtr = CurBufferPtr;
1313
Evan Cheng2c3267a2008-11-08 08:02:53 +00001314 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001315 BufferEnd = BufferBegin+StubSize+1;
1316}
1317
Nate Begeman7b1a8472009-02-18 08:31:02 +00001318void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1319 unsigned StubSize) {
1320 SavedBufferBegin = BufferBegin;
1321 SavedBufferEnd = BufferEnd;
1322 SavedCurBufferPtr = CurBufferPtr;
1323
1324 BufferBegin = CurBufferPtr = (unsigned char *)Buffer;
1325 BufferEnd = BufferBegin+StubSize+1;
1326}
1327
Evan Cheng2c3267a2008-11-08 08:02:53 +00001328void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001329 NumBytes += getCurrentPCOffset();
1330 std::swap(SavedBufferBegin, BufferBegin);
1331 BufferEnd = SavedBufferEnd;
1332 CurBufferPtr = SavedCurBufferPtr;
1333 return SavedBufferBegin;
1334}
1335
1336// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1337// in the constant pool that was last emitted with the 'emitConstantPool'
1338// method.
1339//
Evan Cheng6e561c72008-12-10 02:32:19 +00001340uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 assert(ConstantNum < ConstantPool->getConstants().size() &&
1342 "Invalid ConstantPoolIndex!");
Evan Cheng6e561c72008-12-10 02:32:19 +00001343 return (uintptr_t)ConstantPoolBase +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 ConstantPool->getConstants()[ConstantNum].Offset;
1345}
1346
1347// getJumpTableEntryAddress - Return the address of the JumpTable with index
1348// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1349//
Evan Cheng6e561c72008-12-10 02:32:19 +00001350uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1352 assert(Index < JT.size() && "Invalid jump table index!");
1353
1354 unsigned Offset = 0;
1355 unsigned EntrySize = JumpTable->getEntrySize();
1356
1357 for (unsigned i = 0; i < Index; ++i)
1358 Offset += JT[i].MBBs.size();
1359
1360 Offset *= EntrySize;
1361
Evan Cheng6e561c72008-12-10 02:32:19 +00001362 return (uintptr_t)((char *)JumpTableBase + Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363}
1364
1365//===----------------------------------------------------------------------===//
1366// Public interface to this file
1367//===----------------------------------------------------------------------===//
1368
Chris Lattnere44be002007-12-06 01:08:09 +00001369MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1370 return new JITEmitter(jit, JMM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371}
1372
1373// getPointerToNamedFunction - This function is used as a global wrapper to
1374// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1375// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1376// need to resolve function(s) that are being mis-codegenerated, so we need to
1377// resolve their addresses at runtime, and this is the way to do it.
1378extern "C" {
1379 void *getPointerToNamedFunction(const char *Name) {
1380 if (Function *F = TheJIT->FindFunctionNamed(Name))
1381 return TheJIT->getPointerToFunction(F);
1382 return TheJIT->getPointerToNamedFunction(Name);
1383 }
1384}
1385
1386// getPointerToFunctionOrStub - If the specified function has been
1387// code-gen'd, return a pointer to the function. If not, compile it, or use
1388// a stub to implement lazy compilation if available.
1389//
1390void *JIT::getPointerToFunctionOrStub(Function *F) {
1391 // If we have already code generated the function, just return the address.
1392 if (void *Addr = getPointerToGlobalIfAvailable(F))
1393 return Addr;
1394
1395 // Get a stub if the target supports it.
Evan Cheng89b29a12008-08-20 00:28:12 +00001396 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1397 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001398 return JE->getJITResolver().getFunctionStub(F);
1399}
1400
Nate Begeman7b1a8472009-02-18 08:31:02 +00001401void JIT::updateFunctionStub(Function *F) {
1402 // Get the empty stub we generated earlier.
1403 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1404 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1405 void *Stub = JE->getJITResolver().getFunctionStub(F);
1406
1407 // Tell the target jit info to rewrite the stub at the specified address,
1408 // rather than creating a new one.
1409 void *Addr = getPointerToGlobalIfAvailable(F);
1410 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1411}
1412
1413/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1414/// that were emitted during code generation.
1415///
1416void JIT::updateDlsymStubTable() {
1417 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1418 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1419
1420 SmallVector<GlobalValue*, 8> GVs;
1421 SmallVector<void*, 8> Ptrs;
1422
1423 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1424
1425 // If there are no relocatable stubs, return.
1426 if (GVs.empty())
1427 return;
1428
1429 // If there are no new relocatable stubs, return.
1430 void *CurTable = JE->getMemMgr()->getDlsymTable();
1431 if (CurTable && (*(unsigned *)CurTable == GVs.size()))
1432 return;
1433
1434 // Calculate the size of the stub info
Nate Begeman2fd66162009-03-02 23:10:14 +00001435 unsigned offset = 4 + 4 * GVs.size() + sizeof(intptr_t) * GVs.size();
Nate Begeman7b1a8472009-02-18 08:31:02 +00001436
1437 SmallVector<unsigned, 8> Offsets;
1438 for (unsigned i = 0; i != GVs.size(); ++i) {
1439 Offsets.push_back(offset);
1440 offset += GVs[i]->getName().length() + 1;
1441 }
1442
Nate Begemana5645962009-03-05 06:34:37 +00001443 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begeman7b1a8472009-02-18 08:31:02 +00001444 JE->startGVStub(0, offset, 4);
1445
1446 // Emit the number of records
1447 MCE->emitInt32(GVs.size());
1448
1449 // Emit the string offsets
1450 for (unsigned i = 0; i != GVs.size(); ++i)
1451 MCE->emitInt32(Offsets[i]);
1452
Nate Begemane1ba87f2009-03-04 19:10:38 +00001453 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1454 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1455 // relocation can write the relocated pointer at the appropriate place in
1456 // the stub.
1457 for (unsigned i = 0; i != GVs.size(); ++i) {
1458 intptr_t Ptr = (intptr_t)Ptrs[i];
1459 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1460
1461 if (isa<Function>(GVs[i]))
1462 Ptr |= (intptr_t)1;
1463
Nate Begeman7b1a8472009-02-18 08:31:02 +00001464 if (sizeof(void *) == 8)
Nate Begemane1ba87f2009-03-04 19:10:38 +00001465 MCE->emitInt64(Ptr);
Nate Begeman7b1a8472009-02-18 08:31:02 +00001466 else
Nate Begemane1ba87f2009-03-04 19:10:38 +00001467 MCE->emitInt32(Ptr);
1468 }
Nate Begeman7b1a8472009-02-18 08:31:02 +00001469
Nate Begemana5645962009-03-05 06:34:37 +00001470 // Emit the strings.
Nate Begeman7b1a8472009-02-18 08:31:02 +00001471 for (unsigned i = 0; i != GVs.size(); ++i)
1472 MCE->emitString(GVs[i]->getName());
1473
Nate Begemana5645962009-03-05 06:34:37 +00001474 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1475 // deallocate space for the old one, if one existed.
Nate Begeman7b1a8472009-02-18 08:31:02 +00001476 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1477}
1478
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001479/// freeMachineCodeForFunction - release machine code memory for given Function.
1480///
1481void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +00001482
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001483 // Delete translation for this from the ExecutionEngine, so it will get
1484 // retranslated next time it is used.
Chris Lattnerf50e3572008-04-04 05:51:42 +00001485 void *OldPtr = updateGlobalMapping(F, 0);
1486
1487 if (OldPtr)
1488 RemoveFunctionFromSymbolTable(OldPtr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001489
1490 // Free the actual memory for the function body and related stuff.
Evan Cheng89b29a12008-08-20 00:28:12 +00001491 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1492 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001493}
1494