blob: 252b86d5e351050582179740b36f3a532811fa20 [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"
Nick Lewycky848b3142009-04-19 18:32:03 +000035#include "llvm/Support/ValueHandle.h"
Anton Korobeynikovfd58e6e2007-01-23 10:26:08 +000036#include "llvm/System/Disassembler.h"
Chris Lattnerbc52cad2008-06-25 17:18:44 +000037#include "llvm/System/Memory.h"
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +000038#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng47c01a02008-11-07 09:02:17 +000039#include "llvm/ADT/SmallPtrSet.h"
Nate Begemand6b7a242009-02-18 08:31:02 +000040#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000041#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000042#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000043#ifndef NDEBUG
44#include <iomanip>
45#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000046using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000047
Chris Lattner36343732006-12-19 22:43:32 +000048STATISTIC(NumBytes, "Number of bytes of machine code compiled");
49STATISTIC(NumRelos, "Number of relocations applied");
50static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000051
Andrew Lenhartha00269b2005-07-29 23:40:16 +000052
Chris Lattner54266522004-11-20 23:57:07 +000053//===----------------------------------------------------------------------===//
54// JIT lazy compilation code.
55//
56namespace {
Reid Spenceree448632005-07-12 15:51:55 +000057 class JITResolverState {
58 private:
59 /// FunctionToStubMap - Keep track of the stub created for a particular
60 /// function so that we can reuse them if necessary.
Nick Lewycky848b3142009-04-19 18:32:03 +000061 std::map<AssertingVH<Function>, void*> FunctionToStubMap;
Reid Spenceree448632005-07-12 15:51:55 +000062
63 /// StubToFunctionMap - Keep track of the function that each stub
64 /// corresponds to.
Nick Lewycky848b3142009-04-19 18:32:03 +000065 std::map<void*, AssertingVH<Function> > StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000066
Evan Cheng5594f122008-11-10 01:52:24 +000067 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +000068 /// particular GlobalVariable so that we can reuse them if necessary.
Evan Cheng5594f122008-11-10 01:52:24 +000069 std::map<GlobalValue*, void*> GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000070
Reid Spenceree448632005-07-12 15:51:55 +000071 public:
Nick Lewycky848b3142009-04-19 18:32:03 +000072 std::map<AssertingVH<Function>, void*>& getFunctionToStubMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000073 assert(locked.holds(TheJIT->lock));
74 return FunctionToStubMap;
75 }
Jeff Cohen00b168892005-07-27 06:12:32 +000076
Nick Lewycky848b3142009-04-19 18:32:03 +000077 std::map<void*, AssertingVH<Function> >& getStubToFunctionMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000078 assert(locked.holds(TheJIT->lock));
79 return StubToFunctionMap;
80 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000081
82 std::map<GlobalValue*, void*>&
Evan Cheng5594f122008-11-10 01:52:24 +000083 getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +000084 assert(locked.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +000085 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000086 }
Reid Spenceree448632005-07-12 15:51:55 +000087 };
Jeff Cohen00b168892005-07-27 06:12:32 +000088
Chris Lattner54266522004-11-20 23:57:07 +000089 /// JITResolver - Keep track of, and resolve, call sites for functions that
90 /// have not yet been compiled.
91 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +000092 /// LazyResolverFn - The target lazy resolver function that we actually
93 /// rewrite instructions to use.
94 TargetJITInfo::LazyResolverFn LazyResolverFn;
95
Reid Spenceree448632005-07-12 15:51:55 +000096 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +000097
Chris Lattnerd91ff7c2005-04-18 01:44:27 +000098 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
99 /// external functions.
100 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000101
Evan Cheng1606e8e2009-03-13 07:51:59 +0000102 /// revGOTMap - map addresses to indexes in the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000103 std::map<void*, unsigned> revGOTMap;
104 unsigned nextGOTIndex;
105
Chris Lattnere7484012007-02-24 02:57:03 +0000106 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000107 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000108 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000109 TheJIT = &jit;
110
111 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
112 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
113 TheJITResolver = this;
114 }
115
116 ~JITResolver() {
117 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000118 }
Chris Lattner54266522004-11-20 23:57:07 +0000119
Evan Cheng704bff92008-11-13 21:50:50 +0000120 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
121 /// if it has already been created.
122 void *getFunctionStubIfAvailable(Function *F);
123
Chris Lattner54266522004-11-20 23:57:07 +0000124 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begemand6b7a242009-02-18 08:31:02 +0000125 /// one on demand as needed. If empty is true, create a function stub
126 /// pointing at address 0, to be filled in later.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000127 void *getFunctionStub(Function *F);
Chris Lattner54266522004-11-20 23:57:07 +0000128
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000129 /// getExternalFunctionStub - Return a stub for the function at the
130 /// specified address, created lazily on demand.
131 void *getExternalFunctionStub(void *FnAddr);
132
Evan Cheng5594f122008-11-10 01:52:24 +0000133 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000134 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000135 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000136
Chris Lattner5e225582004-11-21 03:37:42 +0000137 /// AddCallbackAtLocation - If the target is capable of rewriting an
138 /// instruction without the use of a stub, record the location of the use so
139 /// we know which function is being used at the location.
140 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000141 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000142 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000143 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000144 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000145 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000146
147 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000148 SmallVectorImpl<void*> &Ptrs);
149
150 GlobalValue *invalidateStub(void *Stub);
Chris Lattner5e225582004-11-21 03:37:42 +0000151
Andrew Lenharth6a974612005-07-28 12:44:13 +0000152 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000153 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000154 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000155 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000156
Chris Lattner54266522004-11-20 23:57:07 +0000157 /// JITCompilerFn - This function is called to resolve a stub to a compiled
158 /// address. If the LLVM Function corresponding to the stub has not yet
159 /// been compiled, this function compiles it first.
160 static void *JITCompilerFn(void *Stub);
161 };
162}
163
Chris Lattnere7484012007-02-24 02:57:03 +0000164JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000165
Evan Cheng704bff92008-11-13 21:50:50 +0000166/// getFunctionStubIfAvailable - This returns a pointer to a function stub
167/// if it has already been created.
168void *JITResolver::getFunctionStubIfAvailable(Function *F) {
169 MutexGuard locked(TheJIT->lock);
170
171 // If we already have a stub for this function, recycle it.
172 void *&Stub = state.getFunctionToStubMap(locked)[F];
173 return Stub;
174}
175
Chris Lattner54266522004-11-20 23:57:07 +0000176/// getFunctionStub - This returns a pointer to a function stub, creating
177/// one on demand as needed.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000178void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000179 MutexGuard locked(TheJIT->lock);
180
Chris Lattner54266522004-11-20 23:57:07 +0000181 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000182 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000183 if (Stub) return Stub;
184
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000185 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
186 // case we must resolve the symbol now.
187 void *Actual = TheJIT->isLazyCompilationDisabled()
188 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
189
190 // If this is an external declaration, attempt to resolve the address now
191 // to place in the stub.
Dan Gohman69f93782009-01-05 05:32:42 +0000192 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000193 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000194
Dan Gohman69f93782009-01-05 05:32:42 +0000195 // If we resolved the symbol to a null address (eg. a weak external)
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000196 // don't emit a stub. Return a null pointer to the application. If dlsym
197 // stubs are enabled, not being able to resolve the address is not
198 // meaningful.
199 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
Dan Gohman69f93782009-01-05 05:32:42 +0000200 }
201
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000202 // Codegen a new stub, calling the lazy resolver or the actual address of the
203 // external function, if it was resolved.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000204 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000205 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000206
Chris Lattner870286a2006-06-01 17:29:22 +0000207 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000208 // If we are getting the stub for an external function, we really want the
209 // address of the stub in the GlobalAddressMap for the JIT, not the address
210 // of the external function.
211 TheJIT->updateGlobalMapping(F, Stub);
212 }
Chris Lattner54266522004-11-20 23:57:07 +0000213
Chris Lattnerbe3ae8e2009-03-05 06:48:16 +0000214 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
Bill Wendling832171c2006-12-07 20:04:42 +0000215 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000216
Chris Lattner54266522004-11-20 23:57:07 +0000217 // Finally, keep track of the stub-to-Function mapping so that the
218 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000219 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begemand6b7a242009-02-18 08:31:02 +0000220
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000221 // If we are JIT'ing non-lazily but need to call a function that does not
222 // exist yet, add it to the JIT's work list so that we can fill in the stub
223 // address later.
224 if (!Actual && TheJIT->isLazyCompilationDisabled())
225 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
226 TheJIT->addPendingFunction(F);
Nate Begemand6b7a242009-02-18 08:31:02 +0000227
Chris Lattner54266522004-11-20 23:57:07 +0000228 return Stub;
229}
230
Evan Cheng5594f122008-11-10 01:52:24 +0000231/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000232/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000233void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000234 MutexGuard locked(TheJIT->lock);
235
236 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000237 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
238 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000239
Evan Chenge4d783d2008-11-10 23:26:16 +0000240 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000241 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000242 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000243
Evan Cheng5594f122008-11-10 01:52:24 +0000244 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
Evan Chengbe8c03f2008-01-04 10:46:51 +0000245 << GV->getName() << "'\n";
246
Evan Cheng5594f122008-11-10 01:52:24 +0000247 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000248}
249
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000250/// getExternalFunctionStub - Return a stub for the function at the
251/// specified address, created lazily on demand.
252void *JITResolver::getExternalFunctionStub(void *FnAddr) {
253 // If we already have a stub for this function, recycle it.
254 void *&Stub = ExternalFnToStubMap[FnAddr];
255 if (Stub) return Stub;
256
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000257 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000258 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000259
Bill Wendling832171c2006-12-07 20:04:42 +0000260 DOUT << "JIT: Stub emitted at [" << Stub
261 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000262 return Stub;
263}
264
Andrew Lenharth6a974612005-07-28 12:44:13 +0000265unsigned JITResolver::getGOTIndexForAddr(void* addr) {
266 unsigned idx = revGOTMap[addr];
267 if (!idx) {
268 idx = ++nextGOTIndex;
269 revGOTMap[addr] = idx;
Evan Cheng366cf292008-11-07 22:30:29 +0000270 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000271 }
272 return idx;
273}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000274
Nate Begemand6b7a242009-02-18 08:31:02 +0000275void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
276 SmallVectorImpl<void*> &Ptrs) {
277 MutexGuard locked(TheJIT->lock);
278
Nick Lewycky848b3142009-04-19 18:32:03 +0000279 std::map<AssertingVH<Function>,void*> &FM =state.getFunctionToStubMap(locked);
Nate Begemand6b7a242009-02-18 08:31:02 +0000280 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
281
Nick Lewycky848b3142009-04-19 18:32:03 +0000282 for (std::map<AssertingVH<Function>,void*>::iterator i = FM.begin(),
283 e = FM.end(); i != e; ++i) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000284 Function *F = i->first;
285 if (F->isDeclaration() && F->hasExternalLinkage()) {
286 GVs.push_back(i->first);
287 Ptrs.push_back(i->second);
288 }
289 }
290 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
291 i != e; ++i) {
292 GVs.push_back(i->first);
293 Ptrs.push_back(i->second);
294 }
295}
296
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000297GlobalValue *JITResolver::invalidateStub(void *Stub) {
298 MutexGuard locked(TheJIT->lock);
299
Nick Lewycky848b3142009-04-19 18:32:03 +0000300 std::map<AssertingVH<Function>,void*> &FM =state.getFunctionToStubMap(locked);
301 std::map<void*,AssertingVH<Function> > &SM=state.getStubToFunctionMap(locked);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000302 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
303
304 // Look up the cheap way first, to see if it's a function stub we are
305 // invalidating. If so, remove it from both the forward and reverse maps.
306 if (SM.find(Stub) != SM.end()) {
307 Function *F = SM[Stub];
308 SM.erase(Stub);
309 FM.erase(F);
310 return F;
311 }
312
Nate Begeman841c6a42009-03-11 07:03:43 +0000313 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000314 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
315 i != e; ++i) {
316 if (i->second != Stub)
317 continue;
318 GlobalValue *GV = i->first;
319 GM.erase(i);
320 return GV;
321 }
322
Nate Begeman841c6a42009-03-11 07:03:43 +0000323 // Lastly, check to see if it's in the ExternalFnToStubMap.
324 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
325 e = ExternalFnToStubMap.end(); i != e; ++i) {
326 if (i->second != Stub)
327 continue;
328 ExternalFnToStubMap.erase(i);
329 break;
330 }
331
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000332 return 0;
333}
334
Chris Lattner54266522004-11-20 23:57:07 +0000335/// JITCompilerFn - This function is called when a lazy compilation stub has
336/// been entered. It looks up which function this stub corresponds to, compiles
337/// it if necessary, then returns the resultant function pointer.
338void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000339 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000340
341 Function* F = 0;
342 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000343
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000344 {
345 // Only lock for getting the Function. The call getPointerToFunction made
346 // in this function might trigger function materializing, which requires
347 // JIT lock to be unlocked.
348 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000349
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000350 // The address given to us for the stub may not be exactly right, it might be
351 // a little bit after the stub. As such, use upper_bound to find it.
Nick Lewycky848b3142009-04-19 18:32:03 +0000352 std::map<void*, AssertingVH<Function> >::iterator I =
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000353 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
354 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
355 "This is not a known stub!");
356 F = (--I)->second;
357 ActualPtr = I->first;
358 }
Chris Lattner54266522004-11-20 23:57:07 +0000359
Evan Cheng9da60f92007-06-30 00:10:37 +0000360 // If we have already code generated the function, just return the address.
361 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000362
Evan Cheng9da60f92007-06-30 00:10:37 +0000363 if (!Result) {
364 // Otherwise we don't have it, do lazy compilation now.
365
366 // If lazy compilation is disabled, emit a useful error message and abort.
367 if (TheJIT->isLazyCompilationDisabled()) {
368 cerr << "LLVM JIT requested to do lazy compilation of function '"
369 << F->getName() << "' when lazy compiles are disabled!\n";
370 abort();
371 }
372
373 // We might like to remove the stub from the StubToFunction map.
374 // We can't do that! Multiple threads could be stuck, waiting to acquire the
375 // lock above. As soon as the 1st function finishes compiling the function,
376 // the next one will be released, and needs to be able to find the function
377 // it needs to call.
378 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000379
Evan Cheng9da60f92007-06-30 00:10:37 +0000380 DOUT << "JIT: Lazily resolving function '" << F->getName()
381 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000382 << ActualPtr << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000383
Evan Cheng9da60f92007-06-30 00:10:37 +0000384 Result = TheJIT->getPointerToFunction(F);
385 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000386
387 // Reacquire the lock to erase the stub in the map.
388 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000389
390 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000391 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000392
393 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000394
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000395 // What we will do is set the compiled function address to map to the
396 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000397 // if they see it still using the stub address.
398 // Note: this is done so the Resolver doesn't have to manage GOT memory
399 // Do this without allocating map space if the target isn't using a GOT
400 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
401 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
402
Chris Lattner54266522004-11-20 23:57:07 +0000403 return Result;
404}
Chris Lattner688506d2003-08-14 18:35:27 +0000405
Chris Lattner8ac66c12008-04-04 05:51:42 +0000406//===----------------------------------------------------------------------===//
407// Function Index Support
408
409// On MacOS we generate an index of currently JIT'd functions so that
410// performance tools can determine a symbol name and accurate code range for a
411// PC value. Because performance tools are generally asynchronous, the code
412// below is written with the hope that it could be interrupted at any time and
413// have useful answers. However, we don't go crazy with atomic operations, we
414// just do a "reasonable effort".
415#ifdef __APPLE__
Evan Chengbdb6ca12008-05-15 17:31:35 +0000416#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattner8ac66c12008-04-04 05:51:42 +0000417#endif
418
419/// JitSymbolEntry - Each function that is JIT compiled results in one of these
420/// being added to an array of symbols. This indicates the name of the function
421/// as well as the address range it occupies. This allows the client to map
422/// from a PC value to the name of the function.
423struct JitSymbolEntry {
424 const char *FnName; // FnName - a strdup'd string.
425 void *FnStart;
426 intptr_t FnSize;
427};
428
429
430struct JitSymbolTable {
431 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
432 /// pointer is not used right now, but might be used in the future. Consider
433 /// it reserved for future use.
434 JitSymbolTable *NextPtr;
435
436 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
437 /// 'NumSymbols' symbols are valid.
438 JitSymbolEntry *Symbols;
439
440 /// NumSymbols - This indicates the number entries in the Symbols array that
441 /// are valid.
442 unsigned NumSymbols;
443
444 /// NumAllocated - This indicates the amount of space we have in the Symbols
445 /// array. This is a private field that should not be read by external tools.
446 unsigned NumAllocated;
447};
448
449#if ENABLE_JIT_SYMBOL_TABLE
450JitSymbolTable *__jitSymbolTable;
451#endif
452
453static void AddFunctionToSymbolTable(const char *FnName,
454 void *FnStart, intptr_t FnSize) {
455 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
456 JitSymbolTable **SymTabPtrPtr = 0;
457#if !ENABLE_JIT_SYMBOL_TABLE
458 return;
459#else
460 SymTabPtrPtr = &__jitSymbolTable;
461#endif
462
463 // If this is the first entry in the symbol table, add the JitSymbolTable
464 // index.
465 if (*SymTabPtrPtr == 0) {
466 JitSymbolTable *New = new JitSymbolTable();
467 New->NextPtr = 0;
468 New->Symbols = 0;
469 New->NumSymbols = 0;
470 New->NumAllocated = 0;
471 *SymTabPtrPtr = New;
472 }
473
474 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
475
476 // If we have space in the table, reallocate the table.
477 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
478 // If we don't have space, reallocate the table.
Chris Lattner3b374482008-04-13 07:04:56 +0000479 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000480 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
481 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
482
483 // Copy the old entries over.
Nate Begemand6b7a242009-02-18 08:31:02 +0000484 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattner8ac66c12008-04-04 05:51:42 +0000485
486 // Swap the new symbols in, delete the old ones.
487 SymTabPtr->Symbols = NewSymbols;
Chris Lattner3b374482008-04-13 07:04:56 +0000488 SymTabPtr->NumAllocated = NewSize;
Chris Lattner8ac66c12008-04-04 05:51:42 +0000489 delete [] OldSymbols;
490 }
491
492 // Otherwise, we have enough space, just tack it onto the end of the array.
493 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
494 Entry.FnName = strdup(FnName);
495 Entry.FnStart = FnStart;
496 Entry.FnSize = FnSize;
497 ++SymTabPtr->NumSymbols;
498}
499
500static void RemoveFunctionFromSymbolTable(void *FnStart) {
501 assert(FnStart && "Invalid function pointer");
502 JitSymbolTable **SymTabPtrPtr = 0;
503#if !ENABLE_JIT_SYMBOL_TABLE
504 return;
505#else
506 SymTabPtrPtr = &__jitSymbolTable;
507#endif
508
509 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
510 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
511
512 // Scan the table to find its index. The table is not sorted, so do a linear
513 // scan.
514 unsigned Index;
515 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
516 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
517
518 // Once we have an index, we know to nuke this entry, overwrite it with the
519 // entry at the end of the array, making the last entry redundant.
520 const char *OldName = Symbols[Index].FnName;
521 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
522 free((void*)OldName);
523
524 // Drop the number of symbols in the table.
525 --SymTabPtr->NumSymbols;
526
527 // Finally, if we deleted the final symbol, deallocate the table itself.
Nate Begemanf44085a2008-05-18 19:09:10 +0000528 if (SymTabPtr->NumSymbols != 0)
Chris Lattner8ac66c12008-04-04 05:51:42 +0000529 return;
530
531 *SymTabPtrPtr = 0;
532 delete [] Symbols;
533 delete SymTabPtr;
534}
Chris Lattner688506d2003-08-14 18:35:27 +0000535
Chris Lattner54266522004-11-20 23:57:07 +0000536//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000537// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000538//
Chris Lattner688506d2003-08-14 18:35:27 +0000539namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000540 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
541 /// used to output functions to memory for execution.
542 class JITEmitter : public MachineCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000543 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000544
Chris Lattner6125fdd2003-05-09 03:30:07 +0000545 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000546 // save BufferBegin/BufferEnd/CurBufferPtr here.
547 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000548
Chris Lattner5be478f2004-11-20 03:46:14 +0000549 /// Relocations - These are the relocations that the function needs, as
550 /// emitted.
551 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000552
553 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
554 /// It is filled in by the StartMachineBasicBlock callback and queried by
555 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000556 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000557
Chris Lattner239862c2006-02-09 04:49:59 +0000558 /// ConstantPool - The constant pool for the current function.
559 ///
560 MachineConstantPool *ConstantPool;
561
562 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
563 ///
564 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000565
Evan Cheng1606e8e2009-03-13 07:51:59 +0000566 /// ConstPoolAddresses - Addresses of individual constant pool entries.
567 ///
568 SmallVector<uintptr_t, 8> ConstPoolAddresses;
569
Nate Begeman019f8512006-09-10 23:03:44 +0000570 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000571 ///
572 MachineJumpTableInfo *JumpTable;
573
574 /// JumpTableBase - A pointer to the first entry in the jump table.
575 ///
576 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000577
Chris Lattnere7484012007-02-24 02:57:03 +0000578 /// Resolver - This contains info about the currently resolved functions.
579 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000580
581 /// DE - The dwarf emitter for the jit.
582 JITDwarfEmitter *DE;
583
584 /// LabelLocations - This vector is a mapping from Label ID's to their
585 /// address.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000586 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000587
588 /// MMI - Machine module info for exception informations
589 MachineModuleInfo* MMI;
590
Dale Johannesendd947ea2008-08-07 01:30:15 +0000591 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000592 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000593
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000594 // CurFn - The llvm function being emitted. Only valid during
595 // finishFunction().
596 const Function *CurFn;
597
598 // CurFnStubUses - For a given Function, a vector of stubs that it
599 // references. This facilitates the JIT detecting that a stub is no
600 // longer used, so that it may be deallocated.
601 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
602
603 // StubFnRefs - For a given pointer to a stub, a set of Functions which
604 // reference the stub. When the count of a stub's references drops to zero,
605 // the stub is unused.
606 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
607
Nate Begeman841c6a42009-03-11 07:03:43 +0000608 // ExtFnStubs - A map of external function names to stubs which have entries
609 // in the JITResolver's ExternalFnToStubMap.
610 StringMap<void *> ExtFnStubs;
611
Chris Lattnere7484012007-02-24 02:57:03 +0000612 public:
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000613 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0) {
Chris Lattner9f2f1422007-12-06 01:08:09 +0000614 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000615 if (jit.getJITInfo().needsGOT()) {
616 MemMgr->AllocateGOT();
617 DOUT << "JIT is managing a GOT\n";
618 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000619
620 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000621 }
622 ~JITEmitter() {
623 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000624 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000625 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000626
627 /// classof - Methods for support type inquiry through isa, cast, and
628 /// dyn_cast:
629 ///
630 static inline bool classof(const JITEmitter*) { return true; }
631 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000632
633 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000634
635 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000636 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000637
638 void emitConstantPool(MachineConstantPool *MCP);
639 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000640 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000641
Evan Chengce4a70b2008-11-08 08:02:53 +0000642 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000643 unsigned Alignment = 1);
Nate Begemand6b7a242009-02-18 08:31:02 +0000644 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
645 unsigned StubSize);
Evan Chengce4a70b2008-11-08 08:02:53 +0000646 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000647
Nuno Lopescef75272008-10-21 11:42:16 +0000648 /// allocateSpace - Reserves space in the current block if any, or
649 /// allocate a new one of the given size.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000650 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000651
Chris Lattner5be478f2004-11-20 03:46:14 +0000652 virtual void addRelocation(const MachineRelocation &MR) {
653 Relocations.push_back(MR);
654 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000655
656 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
657 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
658 MBBLocations.resize((MBB->getNumber()+1)*2);
659 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Evan Cheng366cf292008-11-07 22:30:29 +0000660 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
661 << (void*) getCurrentPCValue() << "]\n";
Chris Lattnerb4432f32006-05-03 17:10:41 +0000662 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000663
Evan Cheng5788d1a2008-12-10 02:32:19 +0000664 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
665 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000666
Evan Cheng5788d1a2008-12-10 02:32:19 +0000667 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000668 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
669 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
670 return MBBLocations[MBB->getNumber()];
671 }
672
Chris Lattnere993cc22006-05-11 23:08:08 +0000673 /// deallocateMemForFunction - Deallocate all memory for the specified
674 /// function body.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000675 void deallocateMemForFunction(Function *F);
Nate Begeman841c6a42009-03-11 07:03:43 +0000676
677 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
678 /// using the stub at the specified address. Allows
679 /// deallocateMemForFunction to also remove stubs no longer referenced.
680 void AddStubToCurrentFunction(void *Stub);
681
682 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
683 /// MachineRelocations that reference external functions by name.
684 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000685
686 virtual void emitLabel(uint64_t LabelID) {
687 if (LabelLocations.size() <= LabelID)
688 LabelLocations.resize((LabelID+1)*2);
689 LabelLocations[LabelID] = getCurrentPCValue();
690 }
691
Evan Cheng5788d1a2008-12-10 02:32:19 +0000692 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000693 assert(LabelLocations.size() > (unsigned)LabelID &&
694 LabelLocations[LabelID] && "Label not emitted!");
695 return LabelLocations[LabelID];
696 }
697
698 virtual void setModuleInfo(MachineModuleInfo* Info) {
699 MMI = Info;
700 if (ExceptionHandling) DE->setModuleInfo(Info);
701 }
702
Jim Grosbachcce6c292008-10-03 16:17:20 +0000703 void setMemoryExecutable(void) {
704 MemMgr->setMemoryExecutable();
705 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000706
707 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000708
Chris Lattner54266522004-11-20 23:57:07 +0000709 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000710 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000711 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000712 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000713 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
714 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
715 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
716 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000717 };
718}
719
Chris Lattner166f2262004-11-22 22:00:25 +0000720void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
721 bool DoesntNeedStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000722 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000723 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000724
Chris Lattner18e04592008-06-25 20:21:35 +0000725 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000726 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000727
728 // If we have already compiled the function, return a pointer to its body.
729 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000730 void *ResultPtr;
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000731 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
Evan Cheng704bff92008-11-13 21:50:50 +0000732 // Return the function stub if it's already created.
733 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000734 if (ResultPtr)
735 AddStubToCurrentFunction(ResultPtr);
736 } else {
Evan Cheng704bff92008-11-13 21:50:50 +0000737 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000738 }
Chris Lattner54266522004-11-20 23:57:07 +0000739 if (ResultPtr) return ResultPtr;
740
Nate Begemand6b7a242009-02-18 08:31:02 +0000741 // If this is an external function pointer, we can force the JIT to
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000742 // 'compile' it, which really just adds it to the map. In dlsym mode,
743 // external functions are forced through a stub, regardless of reloc type.
744 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
745 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
Nate Begemand6b7a242009-02-18 08:31:02 +0000746 return TheJIT->getPointerToFunction(F);
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000747
Chris Lattner5e225582004-11-21 03:37:42 +0000748 // Okay, the function has not been compiled yet, if the target callback
749 // mechanism is capable of rewriting the instruction directly, prefer to do
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000750 // that instead of emitting a stub. This uses the lazy resolver, so is not
751 // legal if lazy compilation is disabled.
752 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Chris Lattnere7484012007-02-24 02:57:03 +0000753 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000754
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000755 // Otherwise, we have to emit a stub.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000756 void *StubAddr = Resolver.getFunctionStub(F);
757
758 // Add the stub to the current function's list of referenced stubs, so we can
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000759 // deallocate them if the current function is ever freed. It's possible to
760 // return null from getFunctionStub in the case of a weak extern that fails
761 // to resolve.
762 if (StubAddr)
763 AddStubToCurrentFunction(StubAddr);
764
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000765 return StubAddr;
Chris Lattner54266522004-11-20 23:57:07 +0000766}
767
Evan Cheng5594f122008-11-10 01:52:24 +0000768void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000769 bool NoNeedStub) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000770 // Make sure GV is emitted first, and create a stub containing the fully
771 // resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000772 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000773 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
774
775 // Add the stub to the current function's list of referenced stubs, so we can
776 // deallocate them if the current function is ever freed.
777 AddStubToCurrentFunction(StubAddr);
778
779 return StubAddr;
780}
781
782void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
783 if (!TheJIT->areDlsymStubsEnabled())
784 return;
785
786 assert(CurFn && "Stub added to current function, but current function is 0!");
787
788 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
789 StubsUsed.push_back(StubAddr);
790
791 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
792 FnRefs.insert(CurFn);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000793}
794
Evan Cheng1606e8e2009-03-13 07:51:59 +0000795static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
796 const TargetData *TD) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000797 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
798 if (Constants.empty()) return 0;
799
Evan Cheng1606e8e2009-03-13 07:51:59 +0000800 unsigned Size = 0;
801 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
802 MachineConstantPoolEntry CPE = Constants[i];
803 unsigned AlignMask = CPE.getAlignment() - 1;
804 Size = (Size + AlignMask) & ~AlignMask;
805 const Type *Ty = CPE.getType();
806 Size += TD->getTypePaddedSize(Ty);
807 }
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000808 return Size;
809}
810
811static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
812 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
813 if (JT.empty()) return 0;
814
815 unsigned NumEntries = 0;
816 for (unsigned i = 0, e = JT.size(); i != e; ++i)
817 NumEntries += JT[i].MBBs.size();
818
819 unsigned EntrySize = MJTI->getEntrySize();
820
821 return NumEntries * EntrySize;
822}
823
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000824static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000825 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000826 // Since we do not know where the buffer will be allocated, be pessimistic.
827 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000828}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000829
Dale Johannesendd947ea2008-08-07 01:30:15 +0000830/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
831/// into the running total Size.
832
833unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
834 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000835 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypePaddedSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000836 size_t GVAlign =
837 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000838 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000839 DEBUG(GV->dump());
840 // Assume code section ends with worst possible alignment, so first
841 // variable needs maximal padding.
842 if (Size==0)
843 Size = 1;
844 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
845 Size += GVSize;
846 return Size;
847}
848
849/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
850/// but are referenced from the constant; put them in GVSet and add their
851/// size into the running total Size.
852
853unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
854 unsigned Size) {
855 // If its undefined, return the garbage.
856 if (isa<UndefValue>(C))
857 return Size;
858
859 // If the value is a ConstantExpr
860 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
861 Constant *Op0 = CE->getOperand(0);
862 switch (CE->getOpcode()) {
863 case Instruction::GetElementPtr:
864 case Instruction::Trunc:
865 case Instruction::ZExt:
866 case Instruction::SExt:
867 case Instruction::FPTrunc:
868 case Instruction::FPExt:
869 case Instruction::UIToFP:
870 case Instruction::SIToFP:
871 case Instruction::FPToUI:
872 case Instruction::FPToSI:
873 case Instruction::PtrToInt:
874 case Instruction::IntToPtr:
875 case Instruction::BitCast: {
876 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
877 break;
878 }
879 case Instruction::Add:
880 case Instruction::Sub:
881 case Instruction::Mul:
882 case Instruction::UDiv:
883 case Instruction::SDiv:
884 case Instruction::URem:
885 case Instruction::SRem:
886 case Instruction::And:
887 case Instruction::Or:
888 case Instruction::Xor: {
889 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
890 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
891 break;
892 }
893 default: {
894 cerr << "ConstantExpr not handled: " << *CE << "\n";
895 abort();
896 }
897 }
898 }
899
900 if (C->getType()->getTypeID() == Type::PointerTyID)
901 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000902 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000903 Size = addSizeOfGlobal(GV, Size);
904
905 return Size;
906}
907
908/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
909/// but are referenced from the given initializer.
910
911unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
912 unsigned Size) {
913 if (!isa<UndefValue>(Init) &&
914 !isa<ConstantVector>(Init) &&
915 !isa<ConstantAggregateZero>(Init) &&
916 !isa<ConstantArray>(Init) &&
917 !isa<ConstantStruct>(Init) &&
918 Init->getType()->isFirstClassType())
919 Size = addSizeOfGlobalsInConstantVal(Init, Size);
920 return Size;
921}
922
923/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
924/// globals; then walk the initializers of those globals looking for more.
925/// If their size has not been considered yet, add it into the running total
926/// Size.
927
928unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
929 unsigned Size = 0;
930 GVSet.clear();
931
932 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
933 MBB != E; ++MBB) {
934 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
935 I != E; ++I) {
936 const TargetInstrDesc &Desc = I->getDesc();
937 const MachineInstr &MI = *I;
938 unsigned NumOps = Desc.getNumOperands();
939 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
940 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000941 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000942 GlobalValue* V = MO.getGlobal();
943 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
944 if (!GV)
945 continue;
946 // If seen in previous function, it will have an entry here.
947 if (TheJIT->getPointerToGlobalIfAvailable(GV))
948 continue;
949 // If seen earlier in this function, it will have an entry here.
950 // FIXME: it should be possible to combine these tables, by
951 // assuming the addresses of the new globals in this module
952 // start at 0 (or something) and adjusting them after codegen
953 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000954 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000955 // A variable as yet unseen. Add in its size.
956 Size = addSizeOfGlobal(GV, Size);
957 }
958 }
959 }
960 }
Evan Chengeb5d95a2008-11-06 17:46:04 +0000961 DOUT << "JIT: About to look through initializers\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000962 // Look for more globals that are referenced only from initializers.
963 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +0000964 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000965 I != GVSet.end(); I++) {
966 const GlobalVariable* GV = *I;
967 if (GV->hasInitializer())
968 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
969 }
970
971 return Size;
972}
973
Chris Lattner166f2262004-11-22 22:00:25 +0000974void JITEmitter::startFunction(MachineFunction &F) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000975 DOUT << "JIT: Starting CodeGen of Function "
976 << F.getFunction()->getName() << "\n";
977
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000978 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000979 // Set the memory writable, if it's not already
980 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000981 if (MemMgr->NeedsExactSize()) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000982 DOUT << "JIT: ExactSize\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000983 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
984 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
985 MachineConstantPool *MCP = F.getConstantPool();
986
987 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000988 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000989
990 // Add the alignment of the constant pool
Evan Cheng1606e8e2009-03-13 07:51:59 +0000991 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000992
993 // Add the constant pool size
Evan Cheng1606e8e2009-03-13 07:51:59 +0000994 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000995
996 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000997 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000998
999 // Add the jump table size
1000 ActualSize += GetJumpTableSizeInBytes(MJTI);
1001
1002 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +00001003 ActualSize = RoundUpToAlign(ActualSize,
1004 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001005
1006 // Add the function size
1007 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +00001008
Evan Chengeb5d95a2008-11-06 17:46:04 +00001009 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +00001010 // Add the size of the globals that will be allocated after this function.
1011 // These are all the ones referenced from this function that were not
1012 // previously allocated.
1013 ActualSize += GetSizeOfGlobalsInBytes(F);
Evan Chengeb5d95a2008-11-06 17:46:04 +00001014 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001015 }
1016
Chris Lattner8907b4b2007-12-05 23:39:57 +00001017 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1018 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +00001019 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001020
Evan Cheng9a1e9b92006-11-16 20:04:54 +00001021 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1022 emitAlignment(16);
1023
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001024 emitConstantPool(F.getConstantPool());
1025 initJumpTableInfo(F.getJumpTableInfo());
1026
1027 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +00001028 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001029 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +00001030
Chris Lattnerb4432f32006-05-03 17:10:41 +00001031 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001032}
1033
Chris Lattner43b429b2006-05-02 18:27:26 +00001034bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +00001035 if (CurBufferPtr == BufferEnd) {
1036 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +00001037 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +00001038 abort();
1039 }
1040
Jim Laskeyb92767a2006-12-14 22:53:42 +00001041 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +00001042
Chris Lattnera8279532006-06-16 18:09:26 +00001043 // FnStart is the start of the text, not the start of the constant pool and
1044 // other per-function data.
1045 unsigned char *FnStart =
1046 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001047
Chris Lattner5be478f2004-11-20 03:46:14 +00001048 if (!Relocations.empty()) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001049 CurFn = F.getFunction();
Chris Lattnere884dc22005-07-20 16:29:20 +00001050 NumRelos += Relocations.size();
1051
Chris Lattner5be478f2004-11-20 03:46:14 +00001052 // Resolve the relocations to concrete pointers.
1053 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1054 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +00001055 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +00001056 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +00001057 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +00001058 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1059 false);
Evan Chengd7398c92008-11-08 07:37:34 +00001060 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Evan Chengca66b082008-11-08 07:22:53 +00001061 << ResultPtr << "]\n";
Misha Brukmanf976c852005-04-21 22:55:34 +00001062
Evan Chengef5784e2008-10-29 23:54:46 +00001063 // If the target REALLY wants a stub for this function, emit it now.
Nate Begeman841c6a42009-03-11 07:03:43 +00001064 if (!MR.doesntNeedStub()) {
1065 if (!TheJIT->areDlsymStubsEnabled()) {
1066 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1067 } else {
1068 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1069 if (!Stub) {
1070 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1071 AddStubToCurrentFunction(Stub);
1072 }
1073 ResultPtr = Stub;
1074 }
1075 }
Evan Chengef5784e2008-10-29 23:54:46 +00001076 } else if (MR.isGlobalValue()) {
1077 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1078 BufferBegin+MR.getMachineCodeOffset(),
1079 MR.doesntNeedStub());
Evan Cheng5594f122008-11-10 01:52:24 +00001080 } else if (MR.isIndirectSymbol()) {
1081 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +00001082 BufferBegin+MR.getMachineCodeOffset(),
1083 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +00001084 } else if (MR.isBasicBlock()) {
1085 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1086 } else if (MR.isConstantPoolIndex()) {
1087 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1088 } else {
1089 assert(MR.isJumpTableIndex());
1090 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1091 }
Jeff Cohen00b168892005-07-27 06:12:32 +00001092
Evan Chengef5784e2008-10-29 23:54:46 +00001093 MR.setResultPointer(ResultPtr);
1094 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001095
Andrew Lenharth6a974612005-07-28 12:44:13 +00001096 // if we are managing the GOT and the relocation wants an index,
1097 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +00001098 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001099 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +00001100 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001101 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001102 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +00001103 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +00001104 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +00001105 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001106 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001107 }
Chris Lattner5be478f2004-11-20 03:46:14 +00001108 }
1109
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001110 CurFn = 0;
Chris Lattner43b429b2006-05-02 18:27:26 +00001111 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +00001112 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +00001113 }
1114
Chris Lattnerd2d5c762006-05-03 18:55:56 +00001115 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +00001116 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001117 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001118 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001119 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +00001120 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1121 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001122 }
1123 }
1124
Nuno Lopescef75272008-10-21 11:42:16 +00001125 unsigned char *FnEnd = CurBufferPtr;
1126
1127 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
Evan Cheng5788d1a2008-12-10 02:32:19 +00001128
1129 if (CurBufferPtr == BufferEnd) {
1130 // FIXME: Allocate more space, then try again.
1131 cerr << "JIT: Ran out of space for generated machine code!\n";
1132 abort();
1133 }
1134
Nuno Lopescef75272008-10-21 11:42:16 +00001135 BufferBegin = CurBufferPtr = 0;
1136 NumBytes += FnEnd-FnStart;
1137
Evan Cheng55fc2802006-07-25 20:40:54 +00001138 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +00001139 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattner8ac66c12008-04-04 05:51:42 +00001140
1141 // Add it to the JIT symbol table if the host wants it.
1142 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1143 FnStart, FnEnd-FnStart);
Evan Cheng55fc2802006-07-25 20:40:54 +00001144
Bill Wendling832171c2006-12-07 20:04:42 +00001145 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1146 << "] Function: " << F.getFunction()->getName()
1147 << ": " << (FnEnd-FnStart) << " bytes of text, "
1148 << Relocations.size() << " relocations\n";
Chris Lattner5be478f2004-11-20 03:46:14 +00001149 Relocations.clear();
Evan Cheng1606e8e2009-03-13 07:51:59 +00001150 ConstPoolAddresses.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +00001151
Evan Chengbc4707a2008-09-18 07:54:21 +00001152 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +00001153 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +00001154
Chris Lattnerc5633c22007-01-20 20:51:43 +00001155#ifndef NDEBUG
Evan Chenga7916f52008-11-05 23:44:08 +00001156 {
Evan Chenge7c35512008-11-12 08:22:43 +00001157 if (sys::hasDisassembler()) {
1158 DOUT << "JIT: Disassembled code:\n";
Evan Chengeb5d95a2008-11-06 17:46:04 +00001159 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001160 } else {
1161 DOUT << "JIT: Binary code:\n";
Evan Chenga7916f52008-11-05 23:44:08 +00001162 DOUT << std::hex;
Evan Chenga7916f52008-11-05 23:44:08 +00001163 unsigned char* q = FnStart;
Evan Chenge7c35512008-11-12 08:22:43 +00001164 for (int i = 0; q < FnEnd; q += 4, ++i) {
1165 if (i == 4)
1166 i = 0;
1167 if (i == 0)
1168 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1169 << (long)(q - FnStart) << ": ";
1170 bool Done = false;
1171 for (int j = 3; j >= 0; --j) {
1172 if (q + j >= FnEnd)
1173 Done = true;
1174 else
1175 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1176 }
1177 if (Done)
1178 break;
1179 DOUT << ' ';
1180 if (i == 3)
Evan Cheng6863fb02008-11-06 01:18:29 +00001181 DOUT << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001182 }
1183 DOUT << std::dec;
Evan Cheng6863fb02008-11-06 01:18:29 +00001184 DOUT<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001185 }
1186 }
Chris Lattnerc5633c22007-01-20 20:51:43 +00001187#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001188 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001189 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001190 SavedBufferBegin = BufferBegin;
1191 SavedBufferEnd = BufferEnd;
1192 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001193
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001194 if (MemMgr->NeedsExactSize()) {
1195 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001196 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001197
1198 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1199 ActualSize);
1200 BufferEnd = BufferBegin+ActualSize;
1201 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +00001202 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1203 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001204 BufferBegin = SavedBufferBegin;
1205 BufferEnd = SavedBufferEnd;
1206 CurBufferPtr = SavedCurBufferPtr;
1207
1208 TheJIT->RegisterTable(FrameRegister);
1209 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001210
1211 if (MMI)
1212 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001213
Chris Lattner43b429b2006-05-02 18:27:26 +00001214 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001215}
1216
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001217/// deallocateMemForFunction - Deallocate all memory for the specified
1218/// function body. Also drop any references the function has to stubs.
1219void JITEmitter::deallocateMemForFunction(Function *F) {
1220 MemMgr->deallocateMemForFunction(F);
1221
1222 // If the function did not reference any stubs, return.
1223 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1224 return;
1225
1226 // For each referenced stub, erase the reference to this function, and then
1227 // erase the list of referenced stubs.
1228 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1229 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1230 void *Stub = StubList[i];
Nate Begeman841c6a42009-03-11 07:03:43 +00001231
1232 // If we already invalidated this stub for this function, continue.
1233 if (StubFnRefs.count(Stub) == 0)
1234 continue;
1235
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001236 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1237 FnRefs.erase(F);
1238
1239 // If this function was the last reference to the stub, invalidate the stub
1240 // in the JITResolver. Were there a memory manager deallocateStub routine,
1241 // we could call that at this point too.
1242 if (FnRefs.empty()) {
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001243 DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
Nate Begeman841c6a42009-03-11 07:03:43 +00001244 StubFnRefs.erase(Stub);
1245
1246 // Invalidate the stub. If it is a GV stub, update the JIT's global
1247 // mapping for that GV to zero, otherwise, search the string map of
1248 // external function names to stubs and remove the entry for this stub.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001249 GlobalValue *GV = Resolver.invalidateStub(Stub);
Nate Begeman841c6a42009-03-11 07:03:43 +00001250 if (GV) {
1251 TheJIT->updateGlobalMapping(GV, 0);
1252 } else {
1253 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1254 e = ExtFnStubs.end(); i != e; ++i) {
1255 if (i->second == Stub) {
1256 ExtFnStubs.erase(i);
1257 break;
1258 }
1259 }
1260 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001261 }
1262 }
1263 CurFnStubUses.erase(F);
1264}
1265
1266
Evan Cheng5788d1a2008-12-10 02:32:19 +00001267void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +00001268 if (BufferBegin)
1269 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1270
1271 // create a new memory block if there is no active one.
1272 // care must be taken so that BufferBegin is invalidated when a
1273 // block is trimmed
1274 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1275 BufferEnd = BufferBegin+Size;
1276 return CurBufferPtr;
1277}
1278
Chris Lattner166f2262004-11-22 22:00:25 +00001279void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001280 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001281 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001282
Chris Lattnerfa77d432006-02-09 04:22:52 +00001283 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001284 if (Constants.empty()) return;
1285
Evan Cheng1606e8e2009-03-13 07:51:59 +00001286 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1287 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng97b8c402008-04-12 00:22:01 +00001288 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001289 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001290
1291 if (ConstantPoolBase == 0) return; // Buffer overflow.
1292
Evan Cheng97b8c402008-04-12 00:22:01 +00001293 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1294 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1295
Chris Lattner239862c2006-02-09 04:49:59 +00001296 // Initialize the memory for all of the constant pool entries.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001297 unsigned Offset = 0;
Chris Lattner3029f922006-02-09 04:46:04 +00001298 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng1606e8e2009-03-13 07:51:59 +00001299 MachineConstantPoolEntry CPE = Constants[i];
1300 unsigned AlignMask = CPE.getAlignment() - 1;
1301 Offset = (Offset + AlignMask) & ~AlignMask;
1302
1303 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1304 ConstPoolAddresses.push_back(CAddr);
1305 if (CPE.isMachineConstantPoolEntry()) {
Evan Chengcd5731d2006-09-12 20:59:59 +00001306 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +00001307 cerr << "Initialize memory with machine specific constant pool entry"
1308 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +00001309 abort();
1310 }
Evan Cheng1606e8e2009-03-13 07:51:59 +00001311 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1312 DOUT << "JIT: CP" << i << " at [0x"
1313 << std::hex << CAddr << std::dec << "]\n";
1314
1315 const Type *Ty = CPE.Val.ConstVal->getType();
1316 Offset += TheJIT->getTargetData()->getTypePaddedSize(Ty);
Chris Lattner1cc08382003-01-13 01:00:12 +00001317 }
1318}
1319
Nate Begeman37efe672006-04-22 18:53:45 +00001320void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001321 if (TheJIT->getJITInfo().hasCustomJumpTables())
1322 return;
1323
Nate Begeman37efe672006-04-22 18:53:45 +00001324 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1325 if (JT.empty()) return;
1326
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001327 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001328 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001329 NumEntries += JT[i].MBBs.size();
1330
1331 unsigned EntrySize = MJTI->getEntrySize();
1332
Nate Begeman37efe672006-04-22 18:53:45 +00001333 // Just allocate space for all the jump tables now. We will fix up the actual
1334 // MBB entries in the tables after we emit the code for each block, since then
1335 // we will know the final locations of the MBBs in memory.
1336 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001337 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001338}
1339
Jim Laskeyb92767a2006-12-14 22:53:42 +00001340void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001341 if (TheJIT->getJITInfo().hasCustomJumpTables())
1342 return;
1343
Nate Begeman37efe672006-04-22 18:53:45 +00001344 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001345 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001346
Jim Laskeyb92767a2006-12-14 22:53:42 +00001347 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001348 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1349 // For each jump table, place the offset from the beginning of the table
1350 // to the target address.
1351 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001352
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001353 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1354 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1355 // Store the offset of the basic block for this jump table slot in the
1356 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001357 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001358 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001359 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001360 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1361 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001362 }
1363 } else {
1364 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1365
1366 // For each jump table, map each target in the jump table to the address of
1367 // an emitted MachineBasicBlock.
1368 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1369
1370 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1371 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1372 // Store the address of the basic block for this jump table slot in the
1373 // memory we allocated for the jump table in 'initJumpTableInfo'
1374 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1375 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1376 }
Nate Begeman37efe672006-04-22 18:53:45 +00001377 }
1378}
1379
Evan Chengce4a70b2008-11-08 08:02:53 +00001380void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1381 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001382 SavedBufferBegin = BufferBegin;
1383 SavedBufferEnd = BufferEnd;
1384 SavedCurBufferPtr = CurBufferPtr;
1385
Evan Chengce4a70b2008-11-08 08:02:53 +00001386 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001387 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001388}
1389
Nate Begemand6b7a242009-02-18 08:31:02 +00001390void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1391 unsigned StubSize) {
1392 SavedBufferBegin = BufferBegin;
1393 SavedBufferEnd = BufferEnd;
1394 SavedCurBufferPtr = CurBufferPtr;
1395
1396 BufferBegin = CurBufferPtr = (unsigned char *)Buffer;
1397 BufferEnd = BufferBegin+StubSize+1;
1398}
1399
Evan Chengce4a70b2008-11-08 08:02:53 +00001400void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001401 NumBytes += getCurrentPCOffset();
1402 std::swap(SavedBufferBegin, BufferBegin);
1403 BufferEnd = SavedBufferEnd;
1404 CurBufferPtr = SavedCurBufferPtr;
1405 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001406}
1407
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001408// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1409// in the constant pool that was last emitted with the 'emitConstantPool'
1410// method.
1411//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001412uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001413 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001414 "Invalid ConstantPoolIndex!");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001415 return ConstPoolAddresses[ConstantNum];
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001416}
1417
Nate Begeman37efe672006-04-22 18:53:45 +00001418// getJumpTableEntryAddress - Return the address of the JumpTable with index
1419// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1420//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001421uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001422 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1423 assert(Index < JT.size() && "Invalid jump table index!");
1424
1425 unsigned Offset = 0;
1426 unsigned EntrySize = JumpTable->getEntrySize();
1427
1428 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001429 Offset += JT[i].MBBs.size();
1430
1431 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001432
Evan Cheng5788d1a2008-12-10 02:32:19 +00001433 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001434}
1435
Chris Lattnere993cc22006-05-11 23:08:08 +00001436//===----------------------------------------------------------------------===//
1437// Public interface to this file
1438//===----------------------------------------------------------------------===//
1439
Chris Lattner9f2f1422007-12-06 01:08:09 +00001440MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1441 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +00001442}
1443
Misha Brukmand69c1e62003-07-28 19:09:06 +00001444// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001445// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001446// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1447// need to resolve function(s) that are being mis-codegenerated, so we need to
1448// resolve their addresses at runtime, and this is the way to do it.
1449extern "C" {
1450 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001451 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001452 return TheJIT->getPointerToFunction(F);
1453 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001454 }
1455}
Chris Lattnere993cc22006-05-11 23:08:08 +00001456
1457// getPointerToFunctionOrStub - If the specified function has been
1458// code-gen'd, return a pointer to the function. If not, compile it, or use
1459// a stub to implement lazy compilation if available.
1460//
1461void *JIT::getPointerToFunctionOrStub(Function *F) {
1462 // If we have already code generated the function, just return the address.
1463 if (void *Addr = getPointerToGlobalIfAvailable(F))
1464 return Addr;
1465
Chris Lattnere7484012007-02-24 02:57:03 +00001466 // Get a stub if the target supports it.
Evan Chenga044dfc2008-08-20 00:28:12 +00001467 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1468 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001469 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001470}
1471
Nate Begemand6b7a242009-02-18 08:31:02 +00001472void JIT::updateFunctionStub(Function *F) {
1473 // Get the empty stub we generated earlier.
1474 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1475 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1476 void *Stub = JE->getJITResolver().getFunctionStub(F);
1477
1478 // Tell the target jit info to rewrite the stub at the specified address,
1479 // rather than creating a new one.
1480 void *Addr = getPointerToGlobalIfAvailable(F);
1481 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1482}
1483
1484/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1485/// that were emitted during code generation.
1486///
1487void JIT::updateDlsymStubTable() {
1488 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1489 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1490
1491 SmallVector<GlobalValue*, 8> GVs;
1492 SmallVector<void*, 8> Ptrs;
Nate Begeman841c6a42009-03-11 07:03:43 +00001493 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
Nate Begemand6b7a242009-02-18 08:31:02 +00001494
1495 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1496
Nate Begeman841c6a42009-03-11 07:03:43 +00001497 unsigned nStubs = GVs.size() + ExtFns.size();
1498
Nate Begemand6b7a242009-02-18 08:31:02 +00001499 // If there are no relocatable stubs, return.
Nate Begeman841c6a42009-03-11 07:03:43 +00001500 if (nStubs == 0)
Nate Begemand6b7a242009-02-18 08:31:02 +00001501 return;
1502
1503 // If there are no new relocatable stubs, return.
1504 void *CurTable = JE->getMemMgr()->getDlsymTable();
Nate Begeman841c6a42009-03-11 07:03:43 +00001505 if (CurTable && (*(unsigned *)CurTable == nStubs))
Nate Begemand6b7a242009-02-18 08:31:02 +00001506 return;
1507
1508 // Calculate the size of the stub info
Nate Begeman841c6a42009-03-11 07:03:43 +00001509 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
Nate Begemand6b7a242009-02-18 08:31:02 +00001510
1511 SmallVector<unsigned, 8> Offsets;
1512 for (unsigned i = 0; i != GVs.size(); ++i) {
1513 Offsets.push_back(offset);
1514 offset += GVs[i]->getName().length() + 1;
1515 }
Nate Begeman841c6a42009-03-11 07:03:43 +00001516 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1517 i != e; ++i) {
1518 Offsets.push_back(offset);
1519 offset += strlen(i->first()) + 1;
1520 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001521
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001522 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begemand6b7a242009-02-18 08:31:02 +00001523 JE->startGVStub(0, offset, 4);
1524
1525 // Emit the number of records
Nate Begeman841c6a42009-03-11 07:03:43 +00001526 MCE->emitInt32(nStubs);
Nate Begemand6b7a242009-02-18 08:31:02 +00001527
1528 // Emit the string offsets
Nate Begeman841c6a42009-03-11 07:03:43 +00001529 for (unsigned i = 0; i != nStubs; ++i)
Nate Begemand6b7a242009-02-18 08:31:02 +00001530 MCE->emitInt32(Offsets[i]);
1531
Nate Begeman66941982009-03-04 19:10:38 +00001532 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1533 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1534 // relocation can write the relocated pointer at the appropriate place in
1535 // the stub.
1536 for (unsigned i = 0; i != GVs.size(); ++i) {
1537 intptr_t Ptr = (intptr_t)Ptrs[i];
1538 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1539
1540 if (isa<Function>(GVs[i]))
1541 Ptr |= (intptr_t)1;
1542
Nate Begeman841c6a42009-03-11 07:03:43 +00001543 if (sizeof(Ptr) == 8)
1544 MCE->emitInt64(Ptr);
1545 else
1546 MCE->emitInt32(Ptr);
1547 }
1548 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1549 i != e; ++i) {
1550 intptr_t Ptr = (intptr_t)i->second | 1;
1551
1552 if (sizeof(Ptr) == 8)
Nate Begeman66941982009-03-04 19:10:38 +00001553 MCE->emitInt64(Ptr);
Nate Begemand6b7a242009-02-18 08:31:02 +00001554 else
Nate Begeman66941982009-03-04 19:10:38 +00001555 MCE->emitInt32(Ptr);
1556 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001557
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001558 // Emit the strings.
Nate Begemand6b7a242009-02-18 08:31:02 +00001559 for (unsigned i = 0; i != GVs.size(); ++i)
1560 MCE->emitString(GVs[i]->getName());
Nate Begeman841c6a42009-03-11 07:03:43 +00001561 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1562 i != e; ++i)
1563 MCE->emitString(i->first());
Nate Begemand6b7a242009-02-18 08:31:02 +00001564
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001565 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1566 // deallocate space for the old one, if one existed.
Nate Begemand6b7a242009-02-18 08:31:02 +00001567 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1568}
1569
Chris Lattnere993cc22006-05-11 23:08:08 +00001570/// freeMachineCodeForFunction - release machine code memory for given Function.
1571///
1572void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001573
Chris Lattnere993cc22006-05-11 23:08:08 +00001574 // Delete translation for this from the ExecutionEngine, so it will get
1575 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001576 void *OldPtr = updateGlobalMapping(F, 0);
1577
1578 if (OldPtr)
1579 RemoveFunctionFromSymbolTable(OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001580
1581 // Free the actual memory for the function body and related stuff.
Evan Chenga044dfc2008-08-20 00:28:12 +00001582 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1583 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001584}
1585