blob: 54c54518b8f766e1ae129919afb4ac7ca60a4550 [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
Evan Cheng1606e8e2009-03-13 07:51:59 +0000101 /// revGOTMap - map addresses to indexes in the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000102 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.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000126 void *getFunctionStub(Function *F);
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 Begemanb9c6c9b2009-03-07 06:41:19 +0000177void *JITResolver::getFunctionStub(Function *F) {
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
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000184 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
185 // case we must resolve the symbol now.
186 void *Actual = TheJIT->isLazyCompilationDisabled()
187 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
188
189 // If this is an external declaration, attempt to resolve the address now
190 // to place in the stub.
Dan Gohman69f93782009-01-05 05:32:42 +0000191 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000192 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000193
Dan Gohman69f93782009-01-05 05:32:42 +0000194 // If we resolved the symbol to a null address (eg. a weak external)
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000195 // don't emit a stub. Return a null pointer to the application. If dlsym
196 // stubs are enabled, not being able to resolve the address is not
197 // meaningful.
198 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
Dan Gohman69f93782009-01-05 05:32:42 +0000199 }
200
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000201 // Codegen a new stub, calling the lazy resolver or the actual address of the
202 // external function, if it was resolved.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000203 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000204 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000205
Chris Lattner870286a2006-06-01 17:29:22 +0000206 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000207 // If we are getting the stub for an external function, we really want the
208 // address of the stub in the GlobalAddressMap for the JIT, not the address
209 // of the external function.
210 TheJIT->updateGlobalMapping(F, Stub);
211 }
Chris Lattner54266522004-11-20 23:57:07 +0000212
Chris Lattnerbe3ae8e2009-03-05 06:48:16 +0000213 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
Bill Wendling832171c2006-12-07 20:04:42 +0000214 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000215
Chris Lattner54266522004-11-20 23:57:07 +0000216 // Finally, keep track of the stub-to-Function mapping so that the
217 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000218 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begemand6b7a242009-02-18 08:31:02 +0000219
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000220 // If we are JIT'ing non-lazily but need to call a function that does not
221 // exist yet, add it to the JIT's work list so that we can fill in the stub
222 // address later.
223 if (!Actual && TheJIT->isLazyCompilationDisabled())
224 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
225 TheJIT->addPendingFunction(F);
Nate Begemand6b7a242009-02-18 08:31:02 +0000226
Chris Lattner54266522004-11-20 23:57:07 +0000227 return Stub;
228}
229
Evan Cheng5594f122008-11-10 01:52:24 +0000230/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000231/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000232void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000233 MutexGuard locked(TheJIT->lock);
234
235 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000236 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
237 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000238
Evan Chenge4d783d2008-11-10 23:26:16 +0000239 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000240 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000241 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000242
Evan Cheng5594f122008-11-10 01:52:24 +0000243 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
Evan Chengbe8c03f2008-01-04 10:46:51 +0000244 << GV->getName() << "'\n";
245
Evan Cheng5594f122008-11-10 01:52:24 +0000246 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000247}
248
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000249/// getExternalFunctionStub - Return a stub for the function at the
250/// specified address, created lazily on demand.
251void *JITResolver::getExternalFunctionStub(void *FnAddr) {
252 // If we already have a stub for this function, recycle it.
253 void *&Stub = ExternalFnToStubMap[FnAddr];
254 if (Stub) return Stub;
255
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000256 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000257 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000258
Bill Wendling832171c2006-12-07 20:04:42 +0000259 DOUT << "JIT: Stub emitted at [" << Stub
260 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000261 return Stub;
262}
263
Andrew Lenharth6a974612005-07-28 12:44:13 +0000264unsigned JITResolver::getGOTIndexForAddr(void* addr) {
265 unsigned idx = revGOTMap[addr];
266 if (!idx) {
267 idx = ++nextGOTIndex;
268 revGOTMap[addr] = idx;
Evan Cheng366cf292008-11-07 22:30:29 +0000269 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000270 }
271 return idx;
272}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000273
Nate Begemand6b7a242009-02-18 08:31:02 +0000274void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
275 SmallVectorImpl<void*> &Ptrs) {
276 MutexGuard locked(TheJIT->lock);
277
278 std::map<Function*,void*> &FM = state.getFunctionToStubMap(locked);
279 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
280
281 for (std::map<Function*,void*>::iterator i = FM.begin(), e = FM.end();
282 i != e; ++i) {
283 Function *F = i->first;
284 if (F->isDeclaration() && F->hasExternalLinkage()) {
285 GVs.push_back(i->first);
286 Ptrs.push_back(i->second);
287 }
288 }
289 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
290 i != e; ++i) {
291 GVs.push_back(i->first);
292 Ptrs.push_back(i->second);
293 }
294}
295
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000296GlobalValue *JITResolver::invalidateStub(void *Stub) {
297 MutexGuard locked(TheJIT->lock);
298
299 std::map<Function*,void*> &FM = state.getFunctionToStubMap(locked);
300 std::map<void*,Function*> &SM = state.getStubToFunctionMap(locked);
301 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
302
303 // Look up the cheap way first, to see if it's a function stub we are
304 // invalidating. If so, remove it from both the forward and reverse maps.
305 if (SM.find(Stub) != SM.end()) {
306 Function *F = SM[Stub];
307 SM.erase(Stub);
308 FM.erase(F);
309 return F;
310 }
311
Nate Begeman841c6a42009-03-11 07:03:43 +0000312 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000313 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
314 i != e; ++i) {
315 if (i->second != Stub)
316 continue;
317 GlobalValue *GV = i->first;
318 GM.erase(i);
319 return GV;
320 }
321
Nate Begeman841c6a42009-03-11 07:03:43 +0000322 // Lastly, check to see if it's in the ExternalFnToStubMap.
323 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
324 e = ExternalFnToStubMap.end(); i != e; ++i) {
325 if (i->second != Stub)
326 continue;
327 ExternalFnToStubMap.erase(i);
328 break;
329 }
330
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000331 return 0;
332}
333
Chris Lattner54266522004-11-20 23:57:07 +0000334/// JITCompilerFn - This function is called when a lazy compilation stub has
335/// been entered. It looks up which function this stub corresponds to, compiles
336/// it if necessary, then returns the resultant function pointer.
337void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000338 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000339
340 Function* F = 0;
341 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000342
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000343 {
344 // Only lock for getting the Function. The call getPointerToFunction made
345 // in this function might trigger function materializing, which requires
346 // JIT lock to be unlocked.
347 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000348
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000349 // The address given to us for the stub may not be exactly right, it might be
350 // a little bit after the stub. As such, use upper_bound to find it.
351 std::map<void*, Function*>::iterator I =
352 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
353 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
354 "This is not a known stub!");
355 F = (--I)->second;
356 ActualPtr = I->first;
357 }
Chris Lattner54266522004-11-20 23:57:07 +0000358
Evan Cheng9da60f92007-06-30 00:10:37 +0000359 // If we have already code generated the function, just return the address.
360 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000361
Evan Cheng9da60f92007-06-30 00:10:37 +0000362 if (!Result) {
363 // Otherwise we don't have it, do lazy compilation now.
364
365 // If lazy compilation is disabled, emit a useful error message and abort.
366 if (TheJIT->isLazyCompilationDisabled()) {
367 cerr << "LLVM JIT requested to do lazy compilation of function '"
368 << F->getName() << "' when lazy compiles are disabled!\n";
369 abort();
370 }
371
372 // We might like to remove the stub from the StubToFunction map.
373 // We can't do that! Multiple threads could be stuck, waiting to acquire the
374 // lock above. As soon as the 1st function finishes compiling the function,
375 // the next one will be released, and needs to be able to find the function
376 // it needs to call.
377 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000378
Evan Cheng9da60f92007-06-30 00:10:37 +0000379 DOUT << "JIT: Lazily resolving function '" << F->getName()
380 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000381 << ActualPtr << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000382
Evan Cheng9da60f92007-06-30 00:10:37 +0000383 Result = TheJIT->getPointerToFunction(F);
384 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000385
386 // Reacquire the lock to erase the stub in the map.
387 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000388
389 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000390 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000391
392 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000393
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000394 // What we will do is set the compiled function address to map to the
395 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000396 // if they see it still using the stub address.
397 // Note: this is done so the Resolver doesn't have to manage GOT memory
398 // Do this without allocating map space if the target isn't using a GOT
399 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
400 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
401
Chris Lattner54266522004-11-20 23:57:07 +0000402 return Result;
403}
Chris Lattner688506d2003-08-14 18:35:27 +0000404
Chris Lattner8ac66c12008-04-04 05:51:42 +0000405//===----------------------------------------------------------------------===//
406// Function Index Support
407
408// On MacOS we generate an index of currently JIT'd functions so that
409// performance tools can determine a symbol name and accurate code range for a
410// PC value. Because performance tools are generally asynchronous, the code
411// below is written with the hope that it could be interrupted at any time and
412// have useful answers. However, we don't go crazy with atomic operations, we
413// just do a "reasonable effort".
414#ifdef __APPLE__
Evan Chengbdb6ca12008-05-15 17:31:35 +0000415#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattner8ac66c12008-04-04 05:51:42 +0000416#endif
417
418/// JitSymbolEntry - Each function that is JIT compiled results in one of these
419/// being added to an array of symbols. This indicates the name of the function
420/// as well as the address range it occupies. This allows the client to map
421/// from a PC value to the name of the function.
422struct JitSymbolEntry {
423 const char *FnName; // FnName - a strdup'd string.
424 void *FnStart;
425 intptr_t FnSize;
426};
427
428
429struct JitSymbolTable {
430 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
431 /// pointer is not used right now, but might be used in the future. Consider
432 /// it reserved for future use.
433 JitSymbolTable *NextPtr;
434
435 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
436 /// 'NumSymbols' symbols are valid.
437 JitSymbolEntry *Symbols;
438
439 /// NumSymbols - This indicates the number entries in the Symbols array that
440 /// are valid.
441 unsigned NumSymbols;
442
443 /// NumAllocated - This indicates the amount of space we have in the Symbols
444 /// array. This is a private field that should not be read by external tools.
445 unsigned NumAllocated;
446};
447
448#if ENABLE_JIT_SYMBOL_TABLE
449JitSymbolTable *__jitSymbolTable;
450#endif
451
452static void AddFunctionToSymbolTable(const char *FnName,
453 void *FnStart, intptr_t FnSize) {
454 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
455 JitSymbolTable **SymTabPtrPtr = 0;
456#if !ENABLE_JIT_SYMBOL_TABLE
457 return;
458#else
459 SymTabPtrPtr = &__jitSymbolTable;
460#endif
461
462 // If this is the first entry in the symbol table, add the JitSymbolTable
463 // index.
464 if (*SymTabPtrPtr == 0) {
465 JitSymbolTable *New = new JitSymbolTable();
466 New->NextPtr = 0;
467 New->Symbols = 0;
468 New->NumSymbols = 0;
469 New->NumAllocated = 0;
470 *SymTabPtrPtr = New;
471 }
472
473 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
474
475 // If we have space in the table, reallocate the table.
476 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
477 // If we don't have space, reallocate the table.
Chris Lattner3b374482008-04-13 07:04:56 +0000478 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000479 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
480 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
481
482 // Copy the old entries over.
Nate Begemand6b7a242009-02-18 08:31:02 +0000483 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattner8ac66c12008-04-04 05:51:42 +0000484
485 // Swap the new symbols in, delete the old ones.
486 SymTabPtr->Symbols = NewSymbols;
Chris Lattner3b374482008-04-13 07:04:56 +0000487 SymTabPtr->NumAllocated = NewSize;
Chris Lattner8ac66c12008-04-04 05:51:42 +0000488 delete [] OldSymbols;
489 }
490
491 // Otherwise, we have enough space, just tack it onto the end of the array.
492 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
493 Entry.FnName = strdup(FnName);
494 Entry.FnStart = FnStart;
495 Entry.FnSize = FnSize;
496 ++SymTabPtr->NumSymbols;
497}
498
499static void RemoveFunctionFromSymbolTable(void *FnStart) {
500 assert(FnStart && "Invalid function pointer");
501 JitSymbolTable **SymTabPtrPtr = 0;
502#if !ENABLE_JIT_SYMBOL_TABLE
503 return;
504#else
505 SymTabPtrPtr = &__jitSymbolTable;
506#endif
507
508 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
509 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
510
511 // Scan the table to find its index. The table is not sorted, so do a linear
512 // scan.
513 unsigned Index;
514 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
515 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
516
517 // Once we have an index, we know to nuke this entry, overwrite it with the
518 // entry at the end of the array, making the last entry redundant.
519 const char *OldName = Symbols[Index].FnName;
520 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
521 free((void*)OldName);
522
523 // Drop the number of symbols in the table.
524 --SymTabPtr->NumSymbols;
525
526 // Finally, if we deleted the final symbol, deallocate the table itself.
Nate Begemanf44085a2008-05-18 19:09:10 +0000527 if (SymTabPtr->NumSymbols != 0)
Chris Lattner8ac66c12008-04-04 05:51:42 +0000528 return;
529
530 *SymTabPtrPtr = 0;
531 delete [] Symbols;
532 delete SymTabPtr;
533}
Chris Lattner688506d2003-08-14 18:35:27 +0000534
Chris Lattner54266522004-11-20 23:57:07 +0000535//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000536// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000537//
Chris Lattner688506d2003-08-14 18:35:27 +0000538namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000539 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
540 /// used to output functions to memory for execution.
541 class JITEmitter : public MachineCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000542 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000543
Chris Lattner6125fdd2003-05-09 03:30:07 +0000544 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000545 // save BufferBegin/BufferEnd/CurBufferPtr here.
546 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000547
Chris Lattner5be478f2004-11-20 03:46:14 +0000548 /// Relocations - These are the relocations that the function needs, as
549 /// emitted.
550 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000551
552 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
553 /// It is filled in by the StartMachineBasicBlock callback and queried by
554 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000555 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000556
Chris Lattner239862c2006-02-09 04:49:59 +0000557 /// ConstantPool - The constant pool for the current function.
558 ///
559 MachineConstantPool *ConstantPool;
560
561 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
562 ///
563 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000564
Evan Cheng1606e8e2009-03-13 07:51:59 +0000565 /// ConstPoolAddresses - Addresses of individual constant pool entries.
566 ///
567 SmallVector<uintptr_t, 8> ConstPoolAddresses;
568
Nate Begeman019f8512006-09-10 23:03:44 +0000569 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000570 ///
571 MachineJumpTableInfo *JumpTable;
572
573 /// JumpTableBase - A pointer to the first entry in the jump table.
574 ///
575 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000576
Chris Lattnere7484012007-02-24 02:57:03 +0000577 /// Resolver - This contains info about the currently resolved functions.
578 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000579
580 /// DE - The dwarf emitter for the jit.
581 JITDwarfEmitter *DE;
582
583 /// LabelLocations - This vector is a mapping from Label ID's to their
584 /// address.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000585 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000586
587 /// MMI - Machine module info for exception informations
588 MachineModuleInfo* MMI;
589
Dale Johannesendd947ea2008-08-07 01:30:15 +0000590 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000591 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000592
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000593 // CurFn - The llvm function being emitted. Only valid during
594 // finishFunction().
595 const Function *CurFn;
596
597 // CurFnStubUses - For a given Function, a vector of stubs that it
598 // references. This facilitates the JIT detecting that a stub is no
599 // longer used, so that it may be deallocated.
600 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
601
602 // StubFnRefs - For a given pointer to a stub, a set of Functions which
603 // reference the stub. When the count of a stub's references drops to zero,
604 // the stub is unused.
605 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
606
Nate Begeman841c6a42009-03-11 07:03:43 +0000607 // ExtFnStubs - A map of external function names to stubs which have entries
608 // in the JITResolver's ExternalFnToStubMap.
609 StringMap<void *> ExtFnStubs;
610
Chris Lattnere7484012007-02-24 02:57:03 +0000611 public:
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000612 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0) {
Chris Lattner9f2f1422007-12-06 01:08:09 +0000613 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000614 if (jit.getJITInfo().needsGOT()) {
615 MemMgr->AllocateGOT();
616 DOUT << "JIT is managing a GOT\n";
617 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000618
619 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000620 }
621 ~JITEmitter() {
622 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000623 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000624 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000625
626 /// classof - Methods for support type inquiry through isa, cast, and
627 /// dyn_cast:
628 ///
629 static inline bool classof(const JITEmitter*) { return true; }
630 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000631
632 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000633
634 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000635 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000636
637 void emitConstantPool(MachineConstantPool *MCP);
638 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000639 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000640
Evan Chengce4a70b2008-11-08 08:02:53 +0000641 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000642 unsigned Alignment = 1);
Nate Begemand6b7a242009-02-18 08:31:02 +0000643 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
644 unsigned StubSize);
Evan Chengce4a70b2008-11-08 08:02:53 +0000645 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000646
Nuno Lopescef75272008-10-21 11:42:16 +0000647 /// allocateSpace - Reserves space in the current block if any, or
648 /// allocate a new one of the given size.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000649 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000650
Chris Lattner5be478f2004-11-20 03:46:14 +0000651 virtual void addRelocation(const MachineRelocation &MR) {
652 Relocations.push_back(MR);
653 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000654
655 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
656 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
657 MBBLocations.resize((MBB->getNumber()+1)*2);
658 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Evan Cheng366cf292008-11-07 22:30:29 +0000659 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
660 << (void*) getCurrentPCValue() << "]\n";
Chris Lattnerb4432f32006-05-03 17:10:41 +0000661 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000662
Evan Cheng5788d1a2008-12-10 02:32:19 +0000663 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
664 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000665
Evan Cheng5788d1a2008-12-10 02:32:19 +0000666 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000667 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
668 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
669 return MBBLocations[MBB->getNumber()];
670 }
671
Chris Lattnere993cc22006-05-11 23:08:08 +0000672 /// deallocateMemForFunction - Deallocate all memory for the specified
673 /// function body.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000674 void deallocateMemForFunction(Function *F);
Nate Begeman841c6a42009-03-11 07:03:43 +0000675
676 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
677 /// using the stub at the specified address. Allows
678 /// deallocateMemForFunction to also remove stubs no longer referenced.
679 void AddStubToCurrentFunction(void *Stub);
680
681 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
682 /// MachineRelocations that reference external functions by name.
683 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000684
685 virtual void emitLabel(uint64_t LabelID) {
686 if (LabelLocations.size() <= LabelID)
687 LabelLocations.resize((LabelID+1)*2);
688 LabelLocations[LabelID] = getCurrentPCValue();
689 }
690
Evan Cheng5788d1a2008-12-10 02:32:19 +0000691 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000692 assert(LabelLocations.size() > (unsigned)LabelID &&
693 LabelLocations[LabelID] && "Label not emitted!");
694 return LabelLocations[LabelID];
695 }
696
697 virtual void setModuleInfo(MachineModuleInfo* Info) {
698 MMI = Info;
699 if (ExceptionHandling) DE->setModuleInfo(Info);
700 }
701
Jim Grosbachcce6c292008-10-03 16:17:20 +0000702 void setMemoryExecutable(void) {
703 MemMgr->setMemoryExecutable();
704 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000705
706 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000707
Chris Lattner54266522004-11-20 23:57:07 +0000708 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000709 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000710 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000711 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000712 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
713 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
714 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
715 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000716 };
717}
718
Chris Lattner166f2262004-11-22 22:00:25 +0000719void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
720 bool DoesntNeedStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000721 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000722 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000723
Chris Lattner18e04592008-06-25 20:21:35 +0000724 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000725 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000726
727 // If we have already compiled the function, return a pointer to its body.
728 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000729 void *ResultPtr;
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000730 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
Evan Cheng704bff92008-11-13 21:50:50 +0000731 // Return the function stub if it's already created.
732 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000733 if (ResultPtr)
734 AddStubToCurrentFunction(ResultPtr);
735 } else {
Evan Cheng704bff92008-11-13 21:50:50 +0000736 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000737 }
Chris Lattner54266522004-11-20 23:57:07 +0000738 if (ResultPtr) return ResultPtr;
739
Nate Begemand6b7a242009-02-18 08:31:02 +0000740 // If this is an external function pointer, we can force the JIT to
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000741 // 'compile' it, which really just adds it to the map. In dlsym mode,
742 // external functions are forced through a stub, regardless of reloc type.
743 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
744 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
Nate Begemand6b7a242009-02-18 08:31:02 +0000745 return TheJIT->getPointerToFunction(F);
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000746
Chris Lattner5e225582004-11-21 03:37:42 +0000747 // Okay, the function has not been compiled yet, if the target callback
748 // mechanism is capable of rewriting the instruction directly, prefer to do
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000749 // that instead of emitting a stub. This uses the lazy resolver, so is not
750 // legal if lazy compilation is disabled.
751 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Chris Lattnere7484012007-02-24 02:57:03 +0000752 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000753
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000754 // Otherwise, we have to emit a stub.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000755 void *StubAddr = Resolver.getFunctionStub(F);
756
757 // Add the stub to the current function's list of referenced stubs, so we can
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000758 // deallocate them if the current function is ever freed. It's possible to
759 // return null from getFunctionStub in the case of a weak extern that fails
760 // to resolve.
761 if (StubAddr)
762 AddStubToCurrentFunction(StubAddr);
763
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000764 return StubAddr;
Chris Lattner54266522004-11-20 23:57:07 +0000765}
766
Evan Cheng5594f122008-11-10 01:52:24 +0000767void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000768 bool NoNeedStub) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000769 // Make sure GV is emitted first, and create a stub containing the fully
770 // resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000771 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000772 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
773
774 // Add the stub to the current function's list of referenced stubs, so we can
775 // deallocate them if the current function is ever freed.
776 AddStubToCurrentFunction(StubAddr);
777
778 return StubAddr;
779}
780
781void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
782 if (!TheJIT->areDlsymStubsEnabled())
783 return;
784
785 assert(CurFn && "Stub added to current function, but current function is 0!");
786
787 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
788 StubsUsed.push_back(StubAddr);
789
790 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
791 FnRefs.insert(CurFn);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000792}
793
Evan Cheng1606e8e2009-03-13 07:51:59 +0000794static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
795 const TargetData *TD) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000796 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
797 if (Constants.empty()) return 0;
798
Evan Cheng1606e8e2009-03-13 07:51:59 +0000799 unsigned Size = 0;
800 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
801 MachineConstantPoolEntry CPE = Constants[i];
802 unsigned AlignMask = CPE.getAlignment() - 1;
803 Size = (Size + AlignMask) & ~AlignMask;
804 const Type *Ty = CPE.getType();
805 Size += TD->getTypePaddedSize(Ty);
806 }
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000807 return Size;
808}
809
810static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
811 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
812 if (JT.empty()) return 0;
813
814 unsigned NumEntries = 0;
815 for (unsigned i = 0, e = JT.size(); i != e; ++i)
816 NumEntries += JT[i].MBBs.size();
817
818 unsigned EntrySize = MJTI->getEntrySize();
819
820 return NumEntries * EntrySize;
821}
822
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000823static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000824 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000825 // Since we do not know where the buffer will be allocated, be pessimistic.
826 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000827}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000828
Dale Johannesendd947ea2008-08-07 01:30:15 +0000829/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
830/// into the running total Size.
831
832unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
833 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000834 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypePaddedSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000835 size_t GVAlign =
836 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000837 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000838 DEBUG(GV->dump());
839 // Assume code section ends with worst possible alignment, so first
840 // variable needs maximal padding.
841 if (Size==0)
842 Size = 1;
843 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
844 Size += GVSize;
845 return Size;
846}
847
848/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
849/// but are referenced from the constant; put them in GVSet and add their
850/// size into the running total Size.
851
852unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
853 unsigned Size) {
854 // If its undefined, return the garbage.
855 if (isa<UndefValue>(C))
856 return Size;
857
858 // If the value is a ConstantExpr
859 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
860 Constant *Op0 = CE->getOperand(0);
861 switch (CE->getOpcode()) {
862 case Instruction::GetElementPtr:
863 case Instruction::Trunc:
864 case Instruction::ZExt:
865 case Instruction::SExt:
866 case Instruction::FPTrunc:
867 case Instruction::FPExt:
868 case Instruction::UIToFP:
869 case Instruction::SIToFP:
870 case Instruction::FPToUI:
871 case Instruction::FPToSI:
872 case Instruction::PtrToInt:
873 case Instruction::IntToPtr:
874 case Instruction::BitCast: {
875 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
876 break;
877 }
878 case Instruction::Add:
879 case Instruction::Sub:
880 case Instruction::Mul:
881 case Instruction::UDiv:
882 case Instruction::SDiv:
883 case Instruction::URem:
884 case Instruction::SRem:
885 case Instruction::And:
886 case Instruction::Or:
887 case Instruction::Xor: {
888 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
889 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
890 break;
891 }
892 default: {
893 cerr << "ConstantExpr not handled: " << *CE << "\n";
894 abort();
895 }
896 }
897 }
898
899 if (C->getType()->getTypeID() == Type::PointerTyID)
900 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000901 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000902 Size = addSizeOfGlobal(GV, Size);
903
904 return Size;
905}
906
907/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
908/// but are referenced from the given initializer.
909
910unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
911 unsigned Size) {
912 if (!isa<UndefValue>(Init) &&
913 !isa<ConstantVector>(Init) &&
914 !isa<ConstantAggregateZero>(Init) &&
915 !isa<ConstantArray>(Init) &&
916 !isa<ConstantStruct>(Init) &&
917 Init->getType()->isFirstClassType())
918 Size = addSizeOfGlobalsInConstantVal(Init, Size);
919 return Size;
920}
921
922/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
923/// globals; then walk the initializers of those globals looking for more.
924/// If their size has not been considered yet, add it into the running total
925/// Size.
926
927unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
928 unsigned Size = 0;
929 GVSet.clear();
930
931 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
932 MBB != E; ++MBB) {
933 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
934 I != E; ++I) {
935 const TargetInstrDesc &Desc = I->getDesc();
936 const MachineInstr &MI = *I;
937 unsigned NumOps = Desc.getNumOperands();
938 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
939 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000940 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000941 GlobalValue* V = MO.getGlobal();
942 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
943 if (!GV)
944 continue;
945 // If seen in previous function, it will have an entry here.
946 if (TheJIT->getPointerToGlobalIfAvailable(GV))
947 continue;
948 // If seen earlier in this function, it will have an entry here.
949 // FIXME: it should be possible to combine these tables, by
950 // assuming the addresses of the new globals in this module
951 // start at 0 (or something) and adjusting them after codegen
952 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000953 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000954 // A variable as yet unseen. Add in its size.
955 Size = addSizeOfGlobal(GV, Size);
956 }
957 }
958 }
959 }
Evan Chengeb5d95a2008-11-06 17:46:04 +0000960 DOUT << "JIT: About to look through initializers\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000961 // Look for more globals that are referenced only from initializers.
962 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +0000963 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000964 I != GVSet.end(); I++) {
965 const GlobalVariable* GV = *I;
966 if (GV->hasInitializer())
967 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
968 }
969
970 return Size;
971}
972
Chris Lattner166f2262004-11-22 22:00:25 +0000973void JITEmitter::startFunction(MachineFunction &F) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000974 DOUT << "JIT: Starting CodeGen of Function "
975 << F.getFunction()->getName() << "\n";
976
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000977 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000978 // Set the memory writable, if it's not already
979 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000980 if (MemMgr->NeedsExactSize()) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000981 DOUT << "JIT: ExactSize\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000982 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
983 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
984 MachineConstantPool *MCP = F.getConstantPool();
985
986 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000987 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000988
989 // Add the alignment of the constant pool
Evan Cheng1606e8e2009-03-13 07:51:59 +0000990 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000991
992 // Add the constant pool size
Evan Cheng1606e8e2009-03-13 07:51:59 +0000993 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000994
995 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000996 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000997
998 // Add the jump table size
999 ActualSize += GetJumpTableSizeInBytes(MJTI);
1000
1001 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +00001002 ActualSize = RoundUpToAlign(ActualSize,
1003 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001004
1005 // Add the function size
1006 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +00001007
Evan Chengeb5d95a2008-11-06 17:46:04 +00001008 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +00001009 // Add the size of the globals that will be allocated after this function.
1010 // These are all the ones referenced from this function that were not
1011 // previously allocated.
1012 ActualSize += GetSizeOfGlobalsInBytes(F);
Evan Chengeb5d95a2008-11-06 17:46:04 +00001013 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001014 }
1015
Chris Lattner8907b4b2007-12-05 23:39:57 +00001016 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1017 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +00001018 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001019
Evan Cheng9a1e9b92006-11-16 20:04:54 +00001020 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1021 emitAlignment(16);
1022
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001023 emitConstantPool(F.getConstantPool());
1024 initJumpTableInfo(F.getJumpTableInfo());
1025
1026 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +00001027 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001028 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +00001029
Chris Lattnerb4432f32006-05-03 17:10:41 +00001030 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001031}
1032
Chris Lattner43b429b2006-05-02 18:27:26 +00001033bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +00001034 if (CurBufferPtr == BufferEnd) {
1035 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +00001036 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +00001037 abort();
1038 }
1039
Jim Laskeyb92767a2006-12-14 22:53:42 +00001040 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +00001041
Chris Lattnera8279532006-06-16 18:09:26 +00001042 // FnStart is the start of the text, not the start of the constant pool and
1043 // other per-function data.
1044 unsigned char *FnStart =
1045 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001046
Chris Lattner5be478f2004-11-20 03:46:14 +00001047 if (!Relocations.empty()) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001048 CurFn = F.getFunction();
Chris Lattnere884dc22005-07-20 16:29:20 +00001049 NumRelos += Relocations.size();
1050
Chris Lattner5be478f2004-11-20 03:46:14 +00001051 // Resolve the relocations to concrete pointers.
1052 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1053 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +00001054 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +00001055 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +00001056 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +00001057 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1058 false);
Evan Chengd7398c92008-11-08 07:37:34 +00001059 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Evan Chengca66b082008-11-08 07:22:53 +00001060 << ResultPtr << "]\n";
Misha Brukmanf976c852005-04-21 22:55:34 +00001061
Evan Chengef5784e2008-10-29 23:54:46 +00001062 // If the target REALLY wants a stub for this function, emit it now.
Nate Begeman841c6a42009-03-11 07:03:43 +00001063 if (!MR.doesntNeedStub()) {
1064 if (!TheJIT->areDlsymStubsEnabled()) {
1065 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1066 } else {
1067 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1068 if (!Stub) {
1069 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1070 AddStubToCurrentFunction(Stub);
1071 }
1072 ResultPtr = Stub;
1073 }
1074 }
Evan Chengef5784e2008-10-29 23:54:46 +00001075 } else if (MR.isGlobalValue()) {
1076 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1077 BufferBegin+MR.getMachineCodeOffset(),
1078 MR.doesntNeedStub());
Evan Cheng5594f122008-11-10 01:52:24 +00001079 } else if (MR.isIndirectSymbol()) {
1080 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +00001081 BufferBegin+MR.getMachineCodeOffset(),
1082 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +00001083 } else if (MR.isBasicBlock()) {
1084 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1085 } else if (MR.isConstantPoolIndex()) {
1086 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1087 } else {
1088 assert(MR.isJumpTableIndex());
1089 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1090 }
Jeff Cohen00b168892005-07-27 06:12:32 +00001091
Evan Chengef5784e2008-10-29 23:54:46 +00001092 MR.setResultPointer(ResultPtr);
1093 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001094
Andrew Lenharth6a974612005-07-28 12:44:13 +00001095 // if we are managing the GOT and the relocation wants an index,
1096 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +00001097 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001098 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +00001099 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001100 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001101 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +00001102 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +00001103 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +00001104 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001105 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001106 }
Chris Lattner5be478f2004-11-20 03:46:14 +00001107 }
1108
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001109 CurFn = 0;
Chris Lattner43b429b2006-05-02 18:27:26 +00001110 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +00001111 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +00001112 }
1113
Chris Lattnerd2d5c762006-05-03 18:55:56 +00001114 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +00001115 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001116 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001117 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001118 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +00001119 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1120 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001121 }
1122 }
1123
Nuno Lopescef75272008-10-21 11:42:16 +00001124 unsigned char *FnEnd = CurBufferPtr;
1125
1126 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
Evan Cheng5788d1a2008-12-10 02:32:19 +00001127
1128 if (CurBufferPtr == BufferEnd) {
1129 // FIXME: Allocate more space, then try again.
1130 cerr << "JIT: Ran out of space for generated machine code!\n";
1131 abort();
1132 }
1133
Nuno Lopescef75272008-10-21 11:42:16 +00001134 BufferBegin = CurBufferPtr = 0;
1135 NumBytes += FnEnd-FnStart;
1136
Evan Cheng55fc2802006-07-25 20:40:54 +00001137 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +00001138 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattner8ac66c12008-04-04 05:51:42 +00001139
1140 // Add it to the JIT symbol table if the host wants it.
1141 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1142 FnStart, FnEnd-FnStart);
Evan Cheng55fc2802006-07-25 20:40:54 +00001143
Bill Wendling832171c2006-12-07 20:04:42 +00001144 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1145 << "] Function: " << F.getFunction()->getName()
1146 << ": " << (FnEnd-FnStart) << " bytes of text, "
1147 << Relocations.size() << " relocations\n";
Chris Lattner5be478f2004-11-20 03:46:14 +00001148 Relocations.clear();
Evan Cheng1606e8e2009-03-13 07:51:59 +00001149 ConstPoolAddresses.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +00001150
Evan Chengbc4707a2008-09-18 07:54:21 +00001151 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +00001152 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +00001153
Chris Lattnerc5633c22007-01-20 20:51:43 +00001154#ifndef NDEBUG
Evan Chenga7916f52008-11-05 23:44:08 +00001155 {
Evan Chenge7c35512008-11-12 08:22:43 +00001156 if (sys::hasDisassembler()) {
1157 DOUT << "JIT: Disassembled code:\n";
Evan Chengeb5d95a2008-11-06 17:46:04 +00001158 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001159 } else {
1160 DOUT << "JIT: Binary code:\n";
Evan Chenga7916f52008-11-05 23:44:08 +00001161 DOUT << std::hex;
Evan Chenga7916f52008-11-05 23:44:08 +00001162 unsigned char* q = FnStart;
Evan Chenge7c35512008-11-12 08:22:43 +00001163 for (int i = 0; q < FnEnd; q += 4, ++i) {
1164 if (i == 4)
1165 i = 0;
1166 if (i == 0)
1167 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1168 << (long)(q - FnStart) << ": ";
1169 bool Done = false;
1170 for (int j = 3; j >= 0; --j) {
1171 if (q + j >= FnEnd)
1172 Done = true;
1173 else
1174 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1175 }
1176 if (Done)
1177 break;
1178 DOUT << ' ';
1179 if (i == 3)
Evan Cheng6863fb02008-11-06 01:18:29 +00001180 DOUT << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001181 }
1182 DOUT << std::dec;
Evan Cheng6863fb02008-11-06 01:18:29 +00001183 DOUT<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001184 }
1185 }
Chris Lattnerc5633c22007-01-20 20:51:43 +00001186#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001187 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001188 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001189 SavedBufferBegin = BufferBegin;
1190 SavedBufferEnd = BufferEnd;
1191 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001192
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001193 if (MemMgr->NeedsExactSize()) {
1194 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001195 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001196
1197 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1198 ActualSize);
1199 BufferEnd = BufferBegin+ActualSize;
1200 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +00001201 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1202 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001203 BufferBegin = SavedBufferBegin;
1204 BufferEnd = SavedBufferEnd;
1205 CurBufferPtr = SavedCurBufferPtr;
1206
1207 TheJIT->RegisterTable(FrameRegister);
1208 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001209
1210 if (MMI)
1211 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001212
Chris Lattner43b429b2006-05-02 18:27:26 +00001213 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001214}
1215
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001216/// deallocateMemForFunction - Deallocate all memory for the specified
1217/// function body. Also drop any references the function has to stubs.
1218void JITEmitter::deallocateMemForFunction(Function *F) {
1219 MemMgr->deallocateMemForFunction(F);
1220
1221 // If the function did not reference any stubs, return.
1222 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1223 return;
1224
1225 // For each referenced stub, erase the reference to this function, and then
1226 // erase the list of referenced stubs.
1227 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1228 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1229 void *Stub = StubList[i];
Nate Begeman841c6a42009-03-11 07:03:43 +00001230
1231 // If we already invalidated this stub for this function, continue.
1232 if (StubFnRefs.count(Stub) == 0)
1233 continue;
1234
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001235 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1236 FnRefs.erase(F);
1237
1238 // If this function was the last reference to the stub, invalidate the stub
1239 // in the JITResolver. Were there a memory manager deallocateStub routine,
1240 // we could call that at this point too.
1241 if (FnRefs.empty()) {
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001242 DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
Nate Begeman841c6a42009-03-11 07:03:43 +00001243 StubFnRefs.erase(Stub);
1244
1245 // Invalidate the stub. If it is a GV stub, update the JIT's global
1246 // mapping for that GV to zero, otherwise, search the string map of
1247 // external function names to stubs and remove the entry for this stub.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001248 GlobalValue *GV = Resolver.invalidateStub(Stub);
Nate Begeman841c6a42009-03-11 07:03:43 +00001249 if (GV) {
1250 TheJIT->updateGlobalMapping(GV, 0);
1251 } else {
1252 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1253 e = ExtFnStubs.end(); i != e; ++i) {
1254 if (i->second == Stub) {
1255 ExtFnStubs.erase(i);
1256 break;
1257 }
1258 }
1259 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001260 }
1261 }
1262 CurFnStubUses.erase(F);
1263}
1264
1265
Evan Cheng5788d1a2008-12-10 02:32:19 +00001266void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +00001267 if (BufferBegin)
1268 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1269
1270 // create a new memory block if there is no active one.
1271 // care must be taken so that BufferBegin is invalidated when a
1272 // block is trimmed
1273 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1274 BufferEnd = BufferBegin+Size;
1275 return CurBufferPtr;
1276}
1277
Chris Lattner166f2262004-11-22 22:00:25 +00001278void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001279 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001280 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001281
Chris Lattnerfa77d432006-02-09 04:22:52 +00001282 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001283 if (Constants.empty()) return;
1284
Evan Cheng1606e8e2009-03-13 07:51:59 +00001285 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1286 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng97b8c402008-04-12 00:22:01 +00001287 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001288 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001289
1290 if (ConstantPoolBase == 0) return; // Buffer overflow.
1291
Evan Cheng97b8c402008-04-12 00:22:01 +00001292 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1293 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1294
Chris Lattner239862c2006-02-09 04:49:59 +00001295 // Initialize the memory for all of the constant pool entries.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001296 unsigned Offset = 0;
Chris Lattner3029f922006-02-09 04:46:04 +00001297 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng1606e8e2009-03-13 07:51:59 +00001298 MachineConstantPoolEntry CPE = Constants[i];
1299 unsigned AlignMask = CPE.getAlignment() - 1;
1300 Offset = (Offset + AlignMask) & ~AlignMask;
1301
1302 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1303 ConstPoolAddresses.push_back(CAddr);
1304 if (CPE.isMachineConstantPoolEntry()) {
Evan Chengcd5731d2006-09-12 20:59:59 +00001305 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +00001306 cerr << "Initialize memory with machine specific constant pool entry"
1307 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +00001308 abort();
1309 }
Evan Cheng1606e8e2009-03-13 07:51:59 +00001310 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1311 DOUT << "JIT: CP" << i << " at [0x"
1312 << std::hex << CAddr << std::dec << "]\n";
1313
1314 const Type *Ty = CPE.Val.ConstVal->getType();
1315 Offset += TheJIT->getTargetData()->getTypePaddedSize(Ty);
Chris Lattner1cc08382003-01-13 01:00:12 +00001316 }
1317}
1318
Nate Begeman37efe672006-04-22 18:53:45 +00001319void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001320 if (TheJIT->getJITInfo().hasCustomJumpTables())
1321 return;
1322
Nate Begeman37efe672006-04-22 18:53:45 +00001323 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1324 if (JT.empty()) return;
1325
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001326 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001327 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001328 NumEntries += JT[i].MBBs.size();
1329
1330 unsigned EntrySize = MJTI->getEntrySize();
1331
Nate Begeman37efe672006-04-22 18:53:45 +00001332 // Just allocate space for all the jump tables now. We will fix up the actual
1333 // MBB entries in the tables after we emit the code for each block, since then
1334 // we will know the final locations of the MBBs in memory.
1335 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001336 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001337}
1338
Jim Laskeyb92767a2006-12-14 22:53:42 +00001339void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001340 if (TheJIT->getJITInfo().hasCustomJumpTables())
1341 return;
1342
Nate Begeman37efe672006-04-22 18:53:45 +00001343 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001344 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001345
Jim Laskeyb92767a2006-12-14 22:53:42 +00001346 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001347 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1348 // For each jump table, place the offset from the beginning of the table
1349 // to the target address.
1350 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001351
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001352 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1353 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1354 // Store the offset of the basic block for this jump table slot in the
1355 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001356 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001357 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001358 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001359 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1360 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001361 }
1362 } else {
1363 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1364
1365 // For each jump table, map each target in the jump table to the address of
1366 // an emitted MachineBasicBlock.
1367 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1368
1369 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1370 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1371 // Store the address of the basic block for this jump table slot in the
1372 // memory we allocated for the jump table in 'initJumpTableInfo'
1373 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1374 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1375 }
Nate Begeman37efe672006-04-22 18:53:45 +00001376 }
1377}
1378
Evan Chengce4a70b2008-11-08 08:02:53 +00001379void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1380 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001381 SavedBufferBegin = BufferBegin;
1382 SavedBufferEnd = BufferEnd;
1383 SavedCurBufferPtr = CurBufferPtr;
1384
Evan Chengce4a70b2008-11-08 08:02:53 +00001385 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001386 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001387}
1388
Nate Begemand6b7a242009-02-18 08:31:02 +00001389void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1390 unsigned StubSize) {
1391 SavedBufferBegin = BufferBegin;
1392 SavedBufferEnd = BufferEnd;
1393 SavedCurBufferPtr = CurBufferPtr;
1394
1395 BufferBegin = CurBufferPtr = (unsigned char *)Buffer;
1396 BufferEnd = BufferBegin+StubSize+1;
1397}
1398
Evan Chengce4a70b2008-11-08 08:02:53 +00001399void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001400 NumBytes += getCurrentPCOffset();
1401 std::swap(SavedBufferBegin, BufferBegin);
1402 BufferEnd = SavedBufferEnd;
1403 CurBufferPtr = SavedCurBufferPtr;
1404 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001405}
1406
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001407// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1408// in the constant pool that was last emitted with the 'emitConstantPool'
1409// method.
1410//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001411uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001412 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001413 "Invalid ConstantPoolIndex!");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001414 return ConstPoolAddresses[ConstantNum];
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001415}
1416
Nate Begeman37efe672006-04-22 18:53:45 +00001417// getJumpTableEntryAddress - Return the address of the JumpTable with index
1418// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1419//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001420uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001421 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1422 assert(Index < JT.size() && "Invalid jump table index!");
1423
1424 unsigned Offset = 0;
1425 unsigned EntrySize = JumpTable->getEntrySize();
1426
1427 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001428 Offset += JT[i].MBBs.size();
1429
1430 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001431
Evan Cheng5788d1a2008-12-10 02:32:19 +00001432 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001433}
1434
Chris Lattnere993cc22006-05-11 23:08:08 +00001435//===----------------------------------------------------------------------===//
1436// Public interface to this file
1437//===----------------------------------------------------------------------===//
1438
Chris Lattner9f2f1422007-12-06 01:08:09 +00001439MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1440 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +00001441}
1442
Misha Brukmand69c1e62003-07-28 19:09:06 +00001443// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001444// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001445// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1446// need to resolve function(s) that are being mis-codegenerated, so we need to
1447// resolve their addresses at runtime, and this is the way to do it.
1448extern "C" {
1449 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001450 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001451 return TheJIT->getPointerToFunction(F);
1452 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001453 }
1454}
Chris Lattnere993cc22006-05-11 23:08:08 +00001455
1456// getPointerToFunctionOrStub - If the specified function has been
1457// code-gen'd, return a pointer to the function. If not, compile it, or use
1458// a stub to implement lazy compilation if available.
1459//
1460void *JIT::getPointerToFunctionOrStub(Function *F) {
1461 // If we have already code generated the function, just return the address.
1462 if (void *Addr = getPointerToGlobalIfAvailable(F))
1463 return Addr;
1464
Chris Lattnere7484012007-02-24 02:57:03 +00001465 // Get a stub if the target supports it.
Evan Chenga044dfc2008-08-20 00:28:12 +00001466 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1467 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001468 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001469}
1470
Nate Begemand6b7a242009-02-18 08:31:02 +00001471void JIT::updateFunctionStub(Function *F) {
1472 // Get the empty stub we generated earlier.
1473 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1474 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1475 void *Stub = JE->getJITResolver().getFunctionStub(F);
1476
1477 // Tell the target jit info to rewrite the stub at the specified address,
1478 // rather than creating a new one.
1479 void *Addr = getPointerToGlobalIfAvailable(F);
1480 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1481}
1482
1483/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1484/// that were emitted during code generation.
1485///
1486void JIT::updateDlsymStubTable() {
1487 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1488 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1489
1490 SmallVector<GlobalValue*, 8> GVs;
1491 SmallVector<void*, 8> Ptrs;
Nate Begeman841c6a42009-03-11 07:03:43 +00001492 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
Nate Begemand6b7a242009-02-18 08:31:02 +00001493
1494 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1495
Nate Begeman841c6a42009-03-11 07:03:43 +00001496 unsigned nStubs = GVs.size() + ExtFns.size();
1497
Nate Begemand6b7a242009-02-18 08:31:02 +00001498 // If there are no relocatable stubs, return.
Nate Begeman841c6a42009-03-11 07:03:43 +00001499 if (nStubs == 0)
Nate Begemand6b7a242009-02-18 08:31:02 +00001500 return;
1501
1502 // If there are no new relocatable stubs, return.
1503 void *CurTable = JE->getMemMgr()->getDlsymTable();
Nate Begeman841c6a42009-03-11 07:03:43 +00001504 if (CurTable && (*(unsigned *)CurTable == nStubs))
Nate Begemand6b7a242009-02-18 08:31:02 +00001505 return;
1506
1507 // Calculate the size of the stub info
Nate Begeman841c6a42009-03-11 07:03:43 +00001508 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
Nate Begemand6b7a242009-02-18 08:31:02 +00001509
1510 SmallVector<unsigned, 8> Offsets;
1511 for (unsigned i = 0; i != GVs.size(); ++i) {
1512 Offsets.push_back(offset);
1513 offset += GVs[i]->getName().length() + 1;
1514 }
Nate Begeman841c6a42009-03-11 07:03:43 +00001515 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1516 i != e; ++i) {
1517 Offsets.push_back(offset);
1518 offset += strlen(i->first()) + 1;
1519 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001520
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001521 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begemand6b7a242009-02-18 08:31:02 +00001522 JE->startGVStub(0, offset, 4);
1523
1524 // Emit the number of records
Nate Begeman841c6a42009-03-11 07:03:43 +00001525 MCE->emitInt32(nStubs);
Nate Begemand6b7a242009-02-18 08:31:02 +00001526
1527 // Emit the string offsets
Nate Begeman841c6a42009-03-11 07:03:43 +00001528 for (unsigned i = 0; i != nStubs; ++i)
Nate Begemand6b7a242009-02-18 08:31:02 +00001529 MCE->emitInt32(Offsets[i]);
1530
Nate Begeman66941982009-03-04 19:10:38 +00001531 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1532 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1533 // relocation can write the relocated pointer at the appropriate place in
1534 // the stub.
1535 for (unsigned i = 0; i != GVs.size(); ++i) {
1536 intptr_t Ptr = (intptr_t)Ptrs[i];
1537 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1538
1539 if (isa<Function>(GVs[i]))
1540 Ptr |= (intptr_t)1;
1541
Nate Begeman841c6a42009-03-11 07:03:43 +00001542 if (sizeof(Ptr) == 8)
1543 MCE->emitInt64(Ptr);
1544 else
1545 MCE->emitInt32(Ptr);
1546 }
1547 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1548 i != e; ++i) {
1549 intptr_t Ptr = (intptr_t)i->second | 1;
1550
1551 if (sizeof(Ptr) == 8)
Nate Begeman66941982009-03-04 19:10:38 +00001552 MCE->emitInt64(Ptr);
Nate Begemand6b7a242009-02-18 08:31:02 +00001553 else
Nate Begeman66941982009-03-04 19:10:38 +00001554 MCE->emitInt32(Ptr);
1555 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001556
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001557 // Emit the strings.
Nate Begemand6b7a242009-02-18 08:31:02 +00001558 for (unsigned i = 0; i != GVs.size(); ++i)
1559 MCE->emitString(GVs[i]->getName());
Nate Begeman841c6a42009-03-11 07:03:43 +00001560 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1561 i != e; ++i)
1562 MCE->emitString(i->first());
Nate Begemand6b7a242009-02-18 08:31:02 +00001563
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001564 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1565 // deallocate space for the old one, if one existed.
Nate Begemand6b7a242009-02-18 08:31:02 +00001566 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1567}
1568
Chris Lattnere993cc22006-05-11 23:08:08 +00001569/// freeMachineCodeForFunction - release machine code memory for given Function.
1570///
1571void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001572
Chris Lattnere993cc22006-05-11 23:08:08 +00001573 // Delete translation for this from the ExecutionEngine, so it will get
1574 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001575 void *OldPtr = updateGlobalMapping(F, 0);
1576
1577 if (OldPtr)
1578 RemoveFunctionFromSymbolTable(OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001579
1580 // Free the actual memory for the function body and related stuff.
Evan Chenga044dfc2008-08-20 00:28:12 +00001581 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1582 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001583}
1584