blob: 15ea90d84bdbe5a7c6948098a5607f36b00faa2b [file] [log] [blame]
Chris Lattner166f2262004-11-22 22:00:25 +00001//===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbd199fb2002-12-24 00:01:05 +00009//
Chris Lattner5be478f2004-11-20 03:46:14 +000010// 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.
Chris Lattnerbd199fb2002-12-24 00:01:05 +000012//
13//===----------------------------------------------------------------------===//
14
Chris Lattner3785fad2003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Chris Lattner4d326fa2003-12-20 01:46:27 +000016#include "JIT.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000017#include "JITDwarfEmitter.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000018#include "llvm/Constants.h"
Chris Lattner2c0a6a12003-11-30 04:23:21 +000019#include "llvm/Module.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000020#include "llvm/DerivedTypes.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000021#include "llvm/CodeGen/MachineCodeEmitter.h"
22#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000023#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman37efe672006-04-22 18:53:45 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000026#include "llvm/CodeGen/MachineRelocation.h"
Chris Lattner8907b4b2007-12-05 23:39:57 +000027#include "llvm/ExecutionEngine/JITMemoryManager.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000028#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000029#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000030#include "llvm/Target/TargetJITInfo.h"
Jim Laskeyacd80ac2006-12-14 19:17:33 +000031#include "llvm/Target/TargetMachine.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000032#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000034#include "llvm/Support/MutexGuard.h"
Anton Korobeynikovfd58e6e2007-01-23 10:26:08 +000035#include "llvm/System/Disassembler.h"
Chris Lattnerbc52cad2008-06-25 17:18:44 +000036#include "llvm/System/Memory.h"
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +000037#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng47c01a02008-11-07 09:02:17 +000038#include "llvm/ADT/SmallPtrSet.h"
Nate Begemand6b7a242009-02-18 08:31:02 +000039#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000040#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000041#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000042#ifndef NDEBUG
43#include <iomanip>
44#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Chris Lattner36343732006-12-19 22:43:32 +000047STATISTIC(NumBytes, "Number of bytes of machine code compiled");
48STATISTIC(NumRelos, "Number of relocations applied");
49static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000050
Andrew Lenhartha00269b2005-07-29 23:40:16 +000051
Chris Lattner54266522004-11-20 23:57:07 +000052//===----------------------------------------------------------------------===//
53// JIT lazy compilation code.
54//
55namespace {
Reid Spenceree448632005-07-12 15:51:55 +000056 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;
Jeff Cohen00b168892005-07-27 06:12:32 +000065
Evan Cheng5594f122008-11-10 01:52:24 +000066 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +000067 /// particular GlobalVariable so that we can reuse them if necessary.
Evan Cheng5594f122008-11-10 01:52:24 +000068 std::map<GlobalValue*, void*> GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000069
Reid Spenceree448632005-07-12 15:51:55 +000070 public:
71 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
72 assert(locked.holds(TheJIT->lock));
73 return FunctionToStubMap;
74 }
Jeff Cohen00b168892005-07-27 06:12:32 +000075
Reid Spenceree448632005-07-12 15:51:55 +000076 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
77 assert(locked.holds(TheJIT->lock));
78 return StubToFunctionMap;
79 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000080
81 std::map<GlobalValue*, void*>&
Evan Cheng5594f122008-11-10 01:52:24 +000082 getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +000083 assert(locked.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +000084 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000085 }
Reid Spenceree448632005-07-12 15:51:55 +000086 };
Jeff Cohen00b168892005-07-27 06:12:32 +000087
Chris Lattner54266522004-11-20 23:57:07 +000088 /// JITResolver - Keep track of, and resolve, call sites for functions that
89 /// have not yet been compiled.
90 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +000091 /// LazyResolverFn - The target lazy resolver function that we actually
92 /// rewrite instructions to use.
93 TargetJITInfo::LazyResolverFn LazyResolverFn;
94
Reid Spenceree448632005-07-12 15:51:55 +000095 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +000096
Chris Lattnerd91ff7c2005-04-18 01:44:27 +000097 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
98 /// external functions.
99 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000100
101 //map addresses to indexes in the GOT
102 std::map<void*, unsigned> revGOTMap;
103 unsigned nextGOTIndex;
104
Chris Lattnere7484012007-02-24 02:57:03 +0000105 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000106 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000107 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +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;
Chris Lattner5e225582004-11-21 03:37:42 +0000117 }
Chris Lattner54266522004-11-20 23:57:07 +0000118
Evan Cheng704bff92008-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
Chris Lattner54266522004-11-20 23:57:07 +0000123 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begemand6b7a242009-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);
Chris Lattner54266522004-11-20 23:57:07 +0000127
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000128 /// getExternalFunctionStub - Return a stub for the function at the
129 /// specified address, created lazily on demand.
130 void *getExternalFunctionStub(void *FnAddr);
131
Evan Cheng5594f122008-11-10 01:52:24 +0000132 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000133 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000134 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000135
Chris Lattner5e225582004-11-21 03:37:42 +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) {
Reid Spenceree448632005-07-12 15:51:55 +0000140 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000141 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000142 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000143 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000144 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000145
146 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000147 SmallVectorImpl<void*> &Ptrs);
148
149 GlobalValue *invalidateStub(void *Stub);
Chris Lattner5e225582004-11-21 03:37:42 +0000150
Andrew Lenharth6a974612005-07-28 12:44:13 +0000151 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000152 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000153 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000154 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000155
Chris Lattner54266522004-11-20 23:57:07 +0000156 /// 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
Chris Lattnere7484012007-02-24 02:57:03 +0000163JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000164
Evan Cheng704bff92008-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
Chris Lattner54266522004-11-20 23:57:07 +0000175/// getFunctionStub - This returns a pointer to a function stub, creating
176/// one on demand as needed.
Nate Begemand6b7a242009-02-18 08:31:02 +0000177void *JITResolver::getFunctionStub(Function *F, bool empty) {
Reid Spenceree448632005-07-12 15:51:55 +0000178 MutexGuard locked(TheJIT->lock);
179
Chris Lattner54266522004-11-20 23:57:07 +0000180 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000181 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000182 if (Stub) return Stub;
183
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000184 // 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 Begemand6b7a242009-02-18 08:31:02 +0000186 void *Actual = empty ? (void*)0 : (void*)(intptr_t)LazyResolverFn;
Dan Gohman69f93782009-01-05 05:32:42 +0000187 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000188 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000189
Dan Gohman69f93782009-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
Chris Lattner54266522004-11-20 23:57:07 +0000195 // Otherwise, codegen a new stub. For now, the stub will call the lazy
196 // resolver function.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000197 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000198 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000199
Chris Lattner870286a2006-06-01 17:29:22 +0000200 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000201 // 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 }
Chris Lattner54266522004-11-20 23:57:07 +0000206
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000207 cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
Bill Wendling832171c2006-12-07 20:04:42 +0000208 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000209
Chris Lattner54266522004-11-20 23:57:07 +0000210 // Finally, keep track of the stub-to-Function mapping so that the
211 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000212 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begemand6b7a242009-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
Chris Lattner54266522004-11-20 23:57:07 +0000219 return Stub;
220}
221
Evan Cheng5594f122008-11-10 01:52:24 +0000222/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000223/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000224void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-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 Cheng5594f122008-11-10 01:52:24 +0000228 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
229 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000230
Evan Chenge4d783d2008-11-10 23:26:16 +0000231 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000232 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000233 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000234
Evan Cheng5594f122008-11-10 01:52:24 +0000235 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
Evan Chengbe8c03f2008-01-04 10:46:51 +0000236 << GV->getName() << "'\n";
237
Evan Cheng5594f122008-11-10 01:52:24 +0000238 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000239}
240
Chris Lattnerd91ff7c2005-04-18 01:44:27 +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 Geoffray51cc3c12008-04-16 20:46:05 +0000248 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000249 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000250
Bill Wendling832171c2006-12-07 20:04:42 +0000251 DOUT << "JIT: Stub emitted at [" << Stub
252 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000253 return Stub;
254}
255
Andrew Lenharth6a974612005-07-28 12:44:13 +0000256unsigned JITResolver::getGOTIndexForAddr(void* addr) {
257 unsigned idx = revGOTMap[addr];
258 if (!idx) {
259 idx = ++nextGOTIndex;
260 revGOTMap[addr] = idx;
Evan Cheng366cf292008-11-07 22:30:29 +0000261 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000262 }
263 return idx;
264}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000265
Nate Begemand6b7a242009-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 Begeman50cd6fd2009-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
Chris Lattner54266522004-11-20 23:57:07 +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) {
Chris Lattnere7484012007-02-24 02:57:03 +0000321 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000322
323 Function* F = 0;
324 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000325
Nicolas Geoffraydcb31e12008-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);
Reid Spenceree448632005-07-12 15:51:55 +0000331
Nicolas Geoffraydcb31e12008-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 }
Chris Lattner54266522004-11-20 23:57:07 +0000341
Evan Cheng9da60f92007-06-30 00:10:37 +0000342 // If we have already code generated the function, just return the address.
343 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000344
Evan Cheng9da60f92007-06-30 00:10:37 +0000345 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);
Chris Lattner54266522004-11-20 23:57:07 +0000361
Evan Cheng9da60f92007-06-30 00:10:37 +0000362 DOUT << "JIT: Lazily resolving function '" << F->getName()
363 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000364 << ActualPtr << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000365
Evan Cheng9da60f92007-06-30 00:10:37 +0000366 Result = TheJIT->getPointerToFunction(F);
367 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000368
369 // Reacquire the lock to erase the stub in the map.
370 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000371
372 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000373 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000374
375 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000376
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000377 // 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
Andrew Lenharth6a974612005-07-28 12:44:13 +0000379 // 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
Chris Lattner54266522004-11-20 23:57:07 +0000385 return Result;
386}
Chris Lattner688506d2003-08-14 18:35:27 +0000387
Chris Lattner8ac66c12008-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 Chengbdb6ca12008-05-15 17:31:35 +0000398#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattner8ac66c12008-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 Lattner3b374482008-04-13 07:04:56 +0000461 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000462 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
463 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
464
465 // Copy the old entries over.
Nate Begemand6b7a242009-02-18 08:31:02 +0000466 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattner8ac66c12008-04-04 05:51:42 +0000467
468 // Swap the new symbols in, delete the old ones.
469 SymTabPtr->Symbols = NewSymbols;
Chris Lattner3b374482008-04-13 07:04:56 +0000470 SymTabPtr->NumAllocated = NewSize;
Chris Lattner8ac66c12008-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 Begemanf44085a2008-05-18 19:09:10 +0000510 if (SymTabPtr->NumSymbols != 0)
Chris Lattner8ac66c12008-04-04 05:51:42 +0000511 return;
512
513 *SymTabPtrPtr = 0;
514 delete [] Symbols;
515 delete SymTabPtr;
516}
Chris Lattner688506d2003-08-14 18:35:27 +0000517
Chris Lattner54266522004-11-20 23:57:07 +0000518//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000519// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000520//
Chris Lattner688506d2003-08-14 18:35:27 +0000521namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000522 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
523 /// used to output functions to memory for execution.
524 class JITEmitter : public MachineCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000525 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000526
Chris Lattner6125fdd2003-05-09 03:30:07 +0000527 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000528 // save BufferBegin/BufferEnd/CurBufferPtr here.
529 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000530
Chris Lattner5be478f2004-11-20 03:46:14 +0000531 /// Relocations - These are the relocations that the function needs, as
532 /// emitted.
533 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000534
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 Cheng5788d1a2008-12-10 02:32:19 +0000538 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000539
Chris Lattner239862c2006-02-09 04:49:59 +0000540 /// 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;
Nate Begeman37efe672006-04-22 18:53:45 +0000547
Nate Begeman019f8512006-09-10 23:03:44 +0000548 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000549 ///
550 MachineJumpTableInfo *JumpTable;
551
552 /// JumpTableBase - A pointer to the first entry in the jump table.
553 ///
554 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000555
Chris Lattnere7484012007-02-24 02:57:03 +0000556 /// Resolver - This contains info about the currently resolved functions.
557 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-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 Cheng5788d1a2008-12-10 02:32:19 +0000564 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000565
566 /// MMI - Machine module info for exception informations
567 MachineModuleInfo* MMI;
568
Dale Johannesendd947ea2008-08-07 01:30:15 +0000569 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000570 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000571
Nate Begeman50cd6fd2009-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
Chris Lattnere7484012007-02-24 02:57:03 +0000586 public:
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000587 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0) {
Chris Lattner9f2f1422007-12-06 01:08:09 +0000588 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000589 if (jit.getJITInfo().needsGOT()) {
590 MemMgr->AllocateGOT();
591 DOUT << "JIT is managing a GOT\n";
592 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000593
594 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000595 }
596 ~JITEmitter() {
597 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000598 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000599 }
Evan Chenga044dfc2008-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; }
Chris Lattnere7484012007-02-24 02:57:03 +0000606
607 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000608
609 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000610 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000611
612 void emitConstantPool(MachineConstantPool *MCP);
613 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000614 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000615
Evan Chengce4a70b2008-11-08 08:02:53 +0000616 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000617 unsigned Alignment = 1);
Nate Begemand6b7a242009-02-18 08:31:02 +0000618 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
619 unsigned StubSize);
Evan Chengce4a70b2008-11-08 08:02:53 +0000620 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000621
Nuno Lopescef75272008-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 Cheng5788d1a2008-12-10 02:32:19 +0000624 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000625
Chris Lattner5be478f2004-11-20 03:46:14 +0000626 virtual void addRelocation(const MachineRelocation &MR) {
627 Relocations.push_back(MR);
628 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000629
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 Cheng366cf292008-11-07 22:30:29 +0000634 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
635 << (void*) getCurrentPCValue() << "]\n";
Chris Lattnerb4432f32006-05-03 17:10:41 +0000636 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000637
Evan Cheng5788d1a2008-12-10 02:32:19 +0000638 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
639 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000640
Evan Cheng5788d1a2008-12-10 02:32:19 +0000641 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000642 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
643 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
644 return MBBLocations[MBB->getNumber()];
645 }
646
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000647 void AddStubToCurrentFunction(void *Stub);
648
Chris Lattnere993cc22006-05-11 23:08:08 +0000649 /// deallocateMemForFunction - Deallocate all memory for the specified
650 /// function body.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000651 void deallocateMemForFunction(Function *F);
Nicolas Geoffrayafe6c2b2008-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 Cheng5788d1a2008-12-10 02:32:19 +0000659 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-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 Grosbachcce6c292008-10-03 16:17:20 +0000670 void setMemoryExecutable(void) {
671 MemMgr->setMemoryExecutable();
672 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000673
674 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000675
Chris Lattner54266522004-11-20 23:57:07 +0000676 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000677 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000678 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000679 bool NoNeedStub);
Dale Johannesendd947ea2008-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);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000684 };
685}
686
Chris Lattner166f2262004-11-22 22:00:25 +0000687void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
688 bool DoesntNeedStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000689 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000690 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000691
Chris Lattner18e04592008-06-25 20:21:35 +0000692 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000693 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000694
695 // If we have already compiled the function, return a pointer to its body.
696 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000697 void *ResultPtr;
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000698 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
Evan Cheng704bff92008-11-13 21:50:50 +0000699 // Return the function stub if it's already created.
700 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000701 if (ResultPtr)
702 AddStubToCurrentFunction(ResultPtr);
703 } else {
Evan Cheng704bff92008-11-13 21:50:50 +0000704 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000705 }
Chris Lattner54266522004-11-20 23:57:07 +0000706 if (ResultPtr) return ResultPtr;
707
Nate Begemand6b7a242009-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);
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000712
Nate Begemand6b7a242009-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
Chris Lattner5e225582004-11-21 03:37:42 +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)
Chris Lattnere7484012007-02-24 02:57:03 +0000724 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000725
Chris Lattner54266522004-11-20 23:57:07 +0000726 // Otherwise, we have to emit a lazy resolving stub.
Nate Begeman50cd6fd2009-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;
Chris Lattner54266522004-11-20 23:57:07 +0000734}
735
Evan Cheng5594f122008-11-10 01:52:24 +0000736void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000737 bool NoNeedStub) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000738 // Make sure GV is emitted first, and create a stub containing the fully
739 // resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000740 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begeman50cd6fd2009-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 Chengbe8c03f2008-01-04 10:46:51 +0000761}
762
Nicolas Geoffraydc17ab22008-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 Sandsceb4d1a2009-01-12 20:38:59 +0000771 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
Nicolas Geoffraydc17ab22008-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 Geoffray580631a2008-04-20 23:39:44 +0000788static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000789 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000790 // Since we do not know where the buffer will be allocated, be pessimistic.
791 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000792}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000793
Dale Johannesendd947ea2008-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 Sandsceb4d1a2009-01-12 20:38:59 +0000799 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypePaddedSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000800 size_t GVAlign =
801 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000802 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesendd947ea2008-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 Cheng47c01a02008-11-07 09:02:17 +0000866 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-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 Gohmand735b802008-10-03 15:45:36 +0000905 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-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 Cheng47c01a02008-11-07 09:02:17 +0000918 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-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 Chengeb5d95a2008-11-06 17:46:04 +0000925 DOUT << "JIT: About to look through initializers\n";
Dale Johannesendd947ea2008-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 Cheng47c01a02008-11-07 09:02:17 +0000928 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-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
Chris Lattner166f2262004-11-22 22:00:25 +0000938void JITEmitter::startFunction(MachineFunction &F) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000939 DOUT << "JIT: Starting CodeGen of Function "
940 << F.getFunction()->getName() << "\n";
941
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000942 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000943 // Set the memory writable, if it's not already
944 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000945 if (MemMgr->NeedsExactSize()) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000946 DOUT << "JIT: ExactSize\n";
Nicolas Geoffraydc17ab22008-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 Geoffray580631a2008-04-20 23:39:44 +0000952 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000953
954 // Add the alignment of the constant pool
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000955 ActualSize = RoundUpToAlign(ActualSize,
956 1 << MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-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 Geoffray580631a2008-04-20 23:39:44 +0000962 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-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 Geoffray580631a2008-04-20 23:39:44 +0000968 ActualSize = RoundUpToAlign(ActualSize,
969 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000970
971 // Add the function size
972 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000973
Evan Chengeb5d95a2008-11-06 17:46:04 +0000974 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesendd947ea2008-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 Chengeb5d95a2008-11-06 17:46:04 +0000979 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000980 }
981
Chris Lattner8907b4b2007-12-05 23:39:57 +0000982 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
983 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +0000984 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000985
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000986 // Ensure the constant pool/jump table info is at least 4-byte aligned.
987 emitAlignment(16);
988
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000989 emitConstantPool(F.getConstantPool());
990 initJumpTableInfo(F.getJumpTableInfo());
991
992 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000993 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000994 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +0000995
Chris Lattnerb4432f32006-05-03 17:10:41 +0000996 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000997}
998
Chris Lattner43b429b2006-05-02 18:27:26 +0000999bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +00001000 if (CurBufferPtr == BufferEnd) {
1001 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +00001002 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +00001003 abort();
1004 }
1005
Jim Laskeyb92767a2006-12-14 22:53:42 +00001006 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +00001007
Chris Lattnera8279532006-06-16 18:09:26 +00001008 // 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());
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001012
Chris Lattner5be478f2004-11-20 03:46:14 +00001013 if (!Relocations.empty()) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001014 CurFn = F.getFunction();
Chris Lattnere884dc22005-07-20 16:29:20 +00001015 NumRelos += Relocations.size();
1016
Chris Lattner5be478f2004-11-20 03:46:14 +00001017 // Resolve the relocations to concrete pointers.
1018 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1019 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +00001020 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +00001021 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +00001022 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +00001023 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1024 false);
Evan Chengd7398c92008-11-08 07:37:34 +00001025 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Evan Chengca66b082008-11-08 07:22:53 +00001026 << ResultPtr << "]\n";
Misha Brukmanf976c852005-04-21 22:55:34 +00001027
Evan Chengef5784e2008-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 Cheng5594f122008-11-10 01:52:24 +00001035 } else if (MR.isIndirectSymbol()) {
1036 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +00001037 BufferBegin+MR.getMachineCodeOffset(),
1038 MR.doesntNeedStub());
Evan Chengef5784e2008-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 }
Jeff Cohen00b168892005-07-27 06:12:32 +00001047
Evan Chengef5784e2008-10-29 23:54:46 +00001048 MR.setResultPointer(ResultPtr);
1049 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001050
Andrew Lenharth6a974612005-07-28 12:44:13 +00001051 // if we are managing the GOT and the relocation wants an index,
1052 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +00001053 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001054 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +00001055 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001056 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001057 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +00001058 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +00001059 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +00001060 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001061 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001062 }
Chris Lattner5be478f2004-11-20 03:46:14 +00001063 }
1064
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001065 CurFn = 0;
Chris Lattner43b429b2006-05-02 18:27:26 +00001066 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +00001067 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +00001068 }
1069
Chris Lattnerd2d5c762006-05-03 18:55:56 +00001070 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +00001071 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001072 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001073 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001074 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +00001075 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1076 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001077 }
1078 }
1079
Nuno Lopescef75272008-10-21 11:42:16 +00001080 unsigned char *FnEnd = CurBufferPtr;
1081
1082 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
Evan Cheng5788d1a2008-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 Lopescef75272008-10-21 11:42:16 +00001090 BufferBegin = CurBufferPtr = 0;
1091 NumBytes += FnEnd-FnStart;
1092
Evan Cheng55fc2802006-07-25 20:40:54 +00001093 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +00001094 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattner8ac66c12008-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);
Evan Cheng55fc2802006-07-25 20:40:54 +00001099
Bill Wendling832171c2006-12-07 20:04:42 +00001100 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1101 << "] Function: " << F.getFunction()->getName()
1102 << ": " << (FnEnd-FnStart) << " bytes of text, "
1103 << Relocations.size() << " relocations\n";
Chris Lattner5be478f2004-11-20 03:46:14 +00001104 Relocations.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +00001105
Evan Chengbc4707a2008-09-18 07:54:21 +00001106 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +00001107 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +00001108
Chris Lattnerc5633c22007-01-20 20:51:43 +00001109#ifndef NDEBUG
Evan Chenga7916f52008-11-05 23:44:08 +00001110 {
Evan Chenge7c35512008-11-12 08:22:43 +00001111 if (sys::hasDisassembler()) {
1112 DOUT << "JIT: Disassembled code:\n";
Evan Chengeb5d95a2008-11-06 17:46:04 +00001113 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001114 } else {
1115 DOUT << "JIT: Binary code:\n";
Evan Chenga7916f52008-11-05 23:44:08 +00001116 DOUT << std::hex;
Evan Chenga7916f52008-11-05 23:44:08 +00001117 unsigned char* q = FnStart;
Evan Chenge7c35512008-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 Cheng6863fb02008-11-06 01:18:29 +00001135 DOUT << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001136 }
1137 DOUT << std::dec;
Evan Cheng6863fb02008-11-06 01:18:29 +00001138 DOUT<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001139 }
1140 }
Chris Lattnerc5633c22007-01-20 20:51:43 +00001141#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001142 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001143 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001144 SavedBufferBegin = BufferBegin;
1145 SavedBufferEnd = BufferEnd;
1146 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001147
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001148 if (MemMgr->NeedsExactSize()) {
1149 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001150 }
Nicolas Geoffrayafe6c2b2008-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 Lattner0fdaa0b2008-03-07 20:05:43 +00001156 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1157 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001158 BufferBegin = SavedBufferBegin;
1159 BufferEnd = SavedBufferEnd;
1160 CurBufferPtr = SavedCurBufferPtr;
1161
1162 TheJIT->RegisterTable(FrameRegister);
1163 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001164
1165 if (MMI)
1166 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001167
Chris Lattner43b429b2006-05-02 18:27:26 +00001168 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001169}
1170
Nate Begeman50cd6fd2009-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 Cheng5788d1a2008-12-10 02:32:19 +00001200void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-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
Chris Lattner166f2262004-11-22 22:00:25 +00001212void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001213 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001214 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001215
Chris Lattnerfa77d432006-02-09 04:22:52 +00001216 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001217 if (Constants.empty()) return;
1218
Evan Chengcd5731d2006-09-12 20:59:59 +00001219 MachineConstantPoolEntry CPE = Constants.back();
1220 unsigned Size = CPE.Offset;
1221 const Type *Ty = CPE.isMachineConstantPoolEntry()
Chris Lattner8a650092006-09-13 16:21:10 +00001222 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001223 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001224
Evan Cheng97b8c402008-04-12 00:22:01 +00001225 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1226 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001227 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001228
1229 if (ConstantPoolBase == 0) return; // Buffer overflow.
1230
Evan Cheng97b8c402008-04-12 00:22:01 +00001231 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1232 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1233
Chris Lattner239862c2006-02-09 04:49:59 +00001234 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +00001235 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +00001236 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Evan Chengcd5731d2006-09-12 20:59:59 +00001237 if (Constants[i].isMachineConstantPoolEntry()) {
1238 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +00001239 cerr << "Initialize memory with machine specific constant pool entry"
1240 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +00001241 abort();
1242 }
1243 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
Evan Cheng97b8c402008-04-12 00:22:01 +00001244 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
Chris Lattner1cc08382003-01-13 01:00:12 +00001245 }
1246}
1247
Nate Begeman37efe672006-04-22 18:53:45 +00001248void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001249 if (TheJIT->getJITInfo().hasCustomJumpTables())
1250 return;
1251
Nate Begeman37efe672006-04-22 18:53:45 +00001252 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1253 if (JT.empty()) return;
1254
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001255 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001256 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001257 NumEntries += JT[i].MBBs.size();
1258
1259 unsigned EntrySize = MJTI->getEntrySize();
1260
Nate Begeman37efe672006-04-22 18:53:45 +00001261 // 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;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001265 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001266}
1267
Jim Laskeyb92767a2006-12-14 22:53:42 +00001268void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001269 if (TheJIT->getJITInfo().hasCustomJumpTables())
1270 return;
1271
Nate Begeman37efe672006-04-22 18:53:45 +00001272 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001273 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001274
Jim Laskeyb92767a2006-12-14 22:53:42 +00001275 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001276 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;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001280
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001281 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 Cheng5788d1a2008-12-10 02:32:19 +00001285 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001286 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001287 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001288 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1289 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +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 }
Nate Begeman37efe672006-04-22 18:53:45 +00001305 }
1306}
1307
Evan Chengce4a70b2008-11-08 08:02:53 +00001308void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1309 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001310 SavedBufferBegin = BufferBegin;
1311 SavedBufferEnd = BufferEnd;
1312 SavedCurBufferPtr = CurBufferPtr;
1313
Evan Chengce4a70b2008-11-08 08:02:53 +00001314 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001315 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001316}
1317
Nate Begemand6b7a242009-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 Chengce4a70b2008-11-08 08:02:53 +00001328void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001329 NumBytes += getCurrentPCOffset();
1330 std::swap(SavedBufferBegin, BufferBegin);
1331 BufferEnd = SavedBufferEnd;
1332 CurBufferPtr = SavedCurBufferPtr;
1333 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001334}
1335
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001336// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1337// in the constant pool that was last emitted with the 'emitConstantPool'
1338// method.
1339//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001340uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001341 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001342 "Invalid ConstantPoolIndex!");
Evan Cheng5788d1a2008-12-10 02:32:19 +00001343 return (uintptr_t)ConstantPoolBase +
Chris Lattner239862c2006-02-09 04:49:59 +00001344 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001345}
1346
Nate Begeman37efe672006-04-22 18:53:45 +00001347// getJumpTableEntryAddress - Return the address of the JumpTable with index
1348// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1349//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001350uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +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)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001358 Offset += JT[i].MBBs.size();
1359
1360 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001361
Evan Cheng5788d1a2008-12-10 02:32:19 +00001362 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001363}
1364
Chris Lattnere993cc22006-05-11 23:08:08 +00001365//===----------------------------------------------------------------------===//
1366// Public interface to this file
1367//===----------------------------------------------------------------------===//
1368
Chris Lattner9f2f1422007-12-06 01:08:09 +00001369MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1370 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +00001371}
1372
Misha Brukmand69c1e62003-07-28 19:09:06 +00001373// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001374// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001375// 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) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001380 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001381 return TheJIT->getPointerToFunction(F);
1382 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001383 }
1384}
Chris Lattnere993cc22006-05-11 23:08:08 +00001385
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
Chris Lattnere7484012007-02-24 02:57:03 +00001395 // Get a stub if the target supports it.
Evan Chenga044dfc2008-08-20 00:28:12 +00001396 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1397 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001398 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001399}
1400
Nate Begemand6b7a242009-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 Begeman0b82f772009-03-02 23:10:14 +00001435 unsigned offset = 4 + 4 * GVs.size() + sizeof(intptr_t) * GVs.size();
Nate Begemand6b7a242009-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 Begeman50cd6fd2009-03-05 06:34:37 +00001443 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begemand6b7a242009-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 Begeman66941982009-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 Begemand6b7a242009-02-18 08:31:02 +00001464 if (sizeof(void *) == 8)
Nate Begeman66941982009-03-04 19:10:38 +00001465 MCE->emitInt64(Ptr);
Nate Begemand6b7a242009-02-18 08:31:02 +00001466 else
Nate Begeman66941982009-03-04 19:10:38 +00001467 MCE->emitInt32(Ptr);
1468 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001469
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001470 // Emit the strings.
Nate Begemand6b7a242009-02-18 08:31:02 +00001471 for (unsigned i = 0; i != GVs.size(); ++i)
1472 MCE->emitString(GVs[i]->getName());
1473
Nate Begeman50cd6fd2009-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 Begemand6b7a242009-02-18 08:31:02 +00001476 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1477}
1478
Chris Lattnere993cc22006-05-11 23:08:08 +00001479/// freeMachineCodeForFunction - release machine code memory for given Function.
1480///
1481void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001482
Chris Lattnere993cc22006-05-11 23:08:08 +00001483 // Delete translation for this from the ExecutionEngine, so it will get
1484 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001485 void *OldPtr = updateGlobalMapping(F, 0);
1486
1487 if (OldPtr)
1488 RemoveFunctionFromSymbolTable(OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001489
1490 // Free the actual memory for the function body and related stuff.
Evan Chenga044dfc2008-08-20 00:28:12 +00001491 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1492 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001493}
1494