blob: c3e16510b46073d0da8d66af77447771cf835a42 [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"
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +000021#include "llvm/CodeGen/JITCodeEmitter.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000022#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"
Dale Johannesendd947ea2008-08-07 01:30:15 +000027#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +000028#include "llvm/ExecutionEngine/JITEventListener.h"
29#include "llvm/ExecutionEngine/JITMemoryManager.h"
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +000030#include "llvm/CodeGen/MachineCodeInfo.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000031#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000032#include "llvm/Target/TargetJITInfo.h"
Jim Laskeyacd80ac2006-12-14 19:17:33 +000033#include "llvm/Target/TargetMachine.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000034#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000036#include "llvm/Support/ErrorHandling.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000037#include "llvm/Support/MutexGuard.h"
Nick Lewycky848b3142009-04-19 18:32:03 +000038#include "llvm/Support/ValueHandle.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000039#include "llvm/Support/raw_ostream.h"
Anton Korobeynikovfd58e6e2007-01-23 10:26:08 +000040#include "llvm/System/Disassembler.h"
Chris Lattnerbc52cad2008-06-25 17:18:44 +000041#include "llvm/System/Memory.h"
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +000042#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng47c01a02008-11-07 09:02:17 +000043#include "llvm/ADT/SmallPtrSet.h"
Nate Begemand6b7a242009-02-18 08:31:02 +000044#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000045#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000046#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000047#ifndef NDEBUG
48#include <iomanip>
49#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000050using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000051
Chris Lattner36343732006-12-19 22:43:32 +000052STATISTIC(NumBytes, "Number of bytes of machine code compiled");
53STATISTIC(NumRelos, "Number of relocations applied");
Reid Kleckner10b4fc52009-07-23 21:46:56 +000054STATISTIC(NumRetries, "Number of retries with more memory");
Chris Lattner36343732006-12-19 22:43:32 +000055static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000056
Andrew Lenhartha00269b2005-07-29 23:40:16 +000057
Chris Lattner54266522004-11-20 23:57:07 +000058//===----------------------------------------------------------------------===//
59// JIT lazy compilation code.
60//
61namespace {
Reid Spenceree448632005-07-12 15:51:55 +000062 class JITResolverState {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000063 public:
64 typedef std::map<AssertingVH<Function>, void*> FunctionToStubMapTy;
65 typedef std::map<void*, Function*> StubToFunctionMapTy;
66 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
Reid Spenceree448632005-07-12 15:51:55 +000067 private:
68 /// FunctionToStubMap - Keep track of the stub created for a particular
69 /// function so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000070 FunctionToStubMapTy FunctionToStubMap;
Reid Spenceree448632005-07-12 15:51:55 +000071
72 /// StubToFunctionMap - Keep track of the function that each stub
73 /// corresponds to.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000074 StubToFunctionMapTy StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000075
Evan Cheng5594f122008-11-10 01:52:24 +000076 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +000077 /// particular GlobalVariable so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000078 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000079
Reid Spenceree448632005-07-12 15:51:55 +000080 public:
Nick Lewyckye2bcf132009-04-27 05:09:44 +000081 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000082 assert(locked.holds(TheJIT->lock));
83 return FunctionToStubMap;
84 }
Jeff Cohen00b168892005-07-27 06:12:32 +000085
Nick Lewyckye2bcf132009-04-27 05:09:44 +000086 StubToFunctionMapTy& getStubToFunctionMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000087 assert(locked.holds(TheJIT->lock));
88 return StubToFunctionMap;
89 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000090
Nick Lewyckye2bcf132009-04-27 05:09:44 +000091 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +000092 assert(locked.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +000093 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000094 }
Reid Spenceree448632005-07-12 15:51:55 +000095 };
Jeff Cohen00b168892005-07-27 06:12:32 +000096
Chris Lattner54266522004-11-20 23:57:07 +000097 /// JITResolver - Keep track of, and resolve, call sites for functions that
98 /// have not yet been compiled.
99 class JITResolver {
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000100 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
101 typedef JITResolverState::StubToFunctionMapTy StubToFunctionMapTy;
102 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
103
Chris Lattner5e225582004-11-21 03:37:42 +0000104 /// LazyResolverFn - The target lazy resolver function that we actually
105 /// rewrite instructions to use.
106 TargetJITInfo::LazyResolverFn LazyResolverFn;
107
Reid Spenceree448632005-07-12 15:51:55 +0000108 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000109
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000110 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
111 /// external functions.
112 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000113
Evan Cheng1606e8e2009-03-13 07:51:59 +0000114 /// revGOTMap - map addresses to indexes in the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000115 std::map<void*, unsigned> revGOTMap;
116 unsigned nextGOTIndex;
117
Chris Lattnere7484012007-02-24 02:57:03 +0000118 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000119 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000120 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000121 TheJIT = &jit;
122
123 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
124 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
125 TheJITResolver = this;
126 }
127
128 ~JITResolver() {
129 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000130 }
Chris Lattner54266522004-11-20 23:57:07 +0000131
Evan Cheng704bff92008-11-13 21:50:50 +0000132 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
133 /// if it has already been created.
134 void *getFunctionStubIfAvailable(Function *F);
135
Chris Lattner54266522004-11-20 23:57:07 +0000136 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begemand6b7a242009-02-18 08:31:02 +0000137 /// one on demand as needed. If empty is true, create a function stub
138 /// pointing at address 0, to be filled in later.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000139 void *getFunctionStub(Function *F);
Chris Lattner54266522004-11-20 23:57:07 +0000140
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000141 /// getExternalFunctionStub - Return a stub for the function at the
142 /// specified address, created lazily on demand.
143 void *getExternalFunctionStub(void *FnAddr);
144
Evan Cheng5594f122008-11-10 01:52:24 +0000145 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000146 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000147 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000148
Chris Lattner5e225582004-11-21 03:37:42 +0000149 /// AddCallbackAtLocation - If the target is capable of rewriting an
150 /// instruction without the use of a stub, record the location of the use so
151 /// we know which function is being used at the location.
152 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000153 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000154 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000155 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000156 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000157 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000158
159 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000160 SmallVectorImpl<void*> &Ptrs);
161
162 GlobalValue *invalidateStub(void *Stub);
Chris Lattner5e225582004-11-21 03:37:42 +0000163
Andrew Lenharth6a974612005-07-28 12:44:13 +0000164 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000165 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000166 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000167 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000168
Chris Lattner54266522004-11-20 23:57:07 +0000169 /// JITCompilerFn - This function is called to resolve a stub to a compiled
170 /// address. If the LLVM Function corresponding to the stub has not yet
171 /// been compiled, this function compiles it first.
172 static void *JITCompilerFn(void *Stub);
173 };
174}
175
Chris Lattnere7484012007-02-24 02:57:03 +0000176JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000177
Evan Cheng704bff92008-11-13 21:50:50 +0000178/// getFunctionStubIfAvailable - This returns a pointer to a function stub
179/// if it has already been created.
180void *JITResolver::getFunctionStubIfAvailable(Function *F) {
181 MutexGuard locked(TheJIT->lock);
182
183 // If we already have a stub for this function, recycle it.
184 void *&Stub = state.getFunctionToStubMap(locked)[F];
185 return Stub;
186}
187
Chris Lattner54266522004-11-20 23:57:07 +0000188/// getFunctionStub - This returns a pointer to a function stub, creating
189/// one on demand as needed.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000190void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000191 MutexGuard locked(TheJIT->lock);
192
Chris Lattner54266522004-11-20 23:57:07 +0000193 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000194 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000195 if (Stub) return Stub;
196
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000197 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
198 // case we must resolve the symbol now.
199 void *Actual = TheJIT->isLazyCompilationDisabled()
200 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
201
202 // If this is an external declaration, attempt to resolve the address now
203 // to place in the stub.
Dan Gohman69f93782009-01-05 05:32:42 +0000204 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000205 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000206
Dan Gohman69f93782009-01-05 05:32:42 +0000207 // If we resolved the symbol to a null address (eg. a weak external)
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000208 // don't emit a stub. Return a null pointer to the application. If dlsym
209 // stubs are enabled, not being able to resolve the address is not
210 // meaningful.
211 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
Dan Gohman69f93782009-01-05 05:32:42 +0000212 }
213
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000214 // Codegen a new stub, calling the lazy resolver or the actual address of the
215 // external function, if it was resolved.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000216 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000217 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000218
Chris Lattner870286a2006-06-01 17:29:22 +0000219 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000220 // If we are getting the stub for an external function, we really want the
221 // address of the stub in the GlobalAddressMap for the JIT, not the address
222 // of the external function.
223 TheJIT->updateGlobalMapping(F, Stub);
224 }
Chris Lattner54266522004-11-20 23:57:07 +0000225
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000226 DEBUG(errs() << "JIT: Stub emitted at [" << Stub << "] for function '"
227 << F->getName() << "'\n");
Chris Lattnercb479412004-11-21 03:44:32 +0000228
Chris Lattner54266522004-11-20 23:57:07 +0000229 // Finally, keep track of the stub-to-Function mapping so that the
230 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000231 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begemand6b7a242009-02-18 08:31:02 +0000232
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000233 // If we are JIT'ing non-lazily but need to call a function that does not
234 // exist yet, add it to the JIT's work list so that we can fill in the stub
235 // address later.
236 if (!Actual && TheJIT->isLazyCompilationDisabled())
237 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
238 TheJIT->addPendingFunction(F);
Nate Begemand6b7a242009-02-18 08:31:02 +0000239
Chris Lattner54266522004-11-20 23:57:07 +0000240 return Stub;
241}
242
Evan Cheng5594f122008-11-10 01:52:24 +0000243/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000244/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000245void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000246 MutexGuard locked(TheJIT->lock);
247
248 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000249 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
250 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000251
Evan Chenge4d783d2008-11-10 23:26:16 +0000252 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000253 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000254 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000255
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000256 DEBUG(errs() << "JIT: Indirect symbol emitted at [" << IndirectSym
257 << "] for GV '" << GV->getName() << "'\n");
Evan Chengbe8c03f2008-01-04 10:46:51 +0000258
Evan Cheng5594f122008-11-10 01:52:24 +0000259 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000260}
261
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000262/// getExternalFunctionStub - Return a stub for the function at the
263/// specified address, created lazily on demand.
264void *JITResolver::getExternalFunctionStub(void *FnAddr) {
265 // If we already have a stub for this function, recycle it.
266 void *&Stub = ExternalFnToStubMap[FnAddr];
267 if (Stub) return Stub;
268
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000269 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000270 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000271
Bill Wendling832171c2006-12-07 20:04:42 +0000272 DOUT << "JIT: Stub emitted at [" << Stub
273 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000274 return Stub;
275}
276
Andrew Lenharth6a974612005-07-28 12:44:13 +0000277unsigned JITResolver::getGOTIndexForAddr(void* addr) {
278 unsigned idx = revGOTMap[addr];
279 if (!idx) {
280 idx = ++nextGOTIndex;
281 revGOTMap[addr] = idx;
Evan Cheng366cf292008-11-07 22:30:29 +0000282 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000283 }
284 return idx;
285}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000286
Nate Begemand6b7a242009-02-18 08:31:02 +0000287void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
288 SmallVectorImpl<void*> &Ptrs) {
289 MutexGuard locked(TheJIT->lock);
290
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000291 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
292 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begemand6b7a242009-02-18 08:31:02 +0000293
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000294 for (FunctionToStubMapTy::iterator i = FM.begin(), e = FM.end(); i != e; ++i){
Nate Begemand6b7a242009-02-18 08:31:02 +0000295 Function *F = i->first;
296 if (F->isDeclaration() && F->hasExternalLinkage()) {
297 GVs.push_back(i->first);
298 Ptrs.push_back(i->second);
299 }
300 }
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000301 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begemand6b7a242009-02-18 08:31:02 +0000302 i != e; ++i) {
303 GVs.push_back(i->first);
304 Ptrs.push_back(i->second);
305 }
306}
307
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000308GlobalValue *JITResolver::invalidateStub(void *Stub) {
309 MutexGuard locked(TheJIT->lock);
310
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000311 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
312 StubToFunctionMapTy &SM = state.getStubToFunctionMap(locked);
313 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000314
315 // Look up the cheap way first, to see if it's a function stub we are
316 // invalidating. If so, remove it from both the forward and reverse maps.
317 if (SM.find(Stub) != SM.end()) {
318 Function *F = SM[Stub];
319 SM.erase(Stub);
320 FM.erase(F);
321 return F;
322 }
323
Nate Begeman841c6a42009-03-11 07:03:43 +0000324 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000325 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000326 i != e; ++i) {
327 if (i->second != Stub)
328 continue;
329 GlobalValue *GV = i->first;
330 GM.erase(i);
331 return GV;
332 }
333
Nate Begeman841c6a42009-03-11 07:03:43 +0000334 // Lastly, check to see if it's in the ExternalFnToStubMap.
335 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
336 e = ExternalFnToStubMap.end(); i != e; ++i) {
337 if (i->second != Stub)
338 continue;
339 ExternalFnToStubMap.erase(i);
340 break;
341 }
342
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000343 return 0;
344}
345
Chris Lattner54266522004-11-20 23:57:07 +0000346/// JITCompilerFn - This function is called when a lazy compilation stub has
347/// been entered. It looks up which function this stub corresponds to, compiles
348/// it if necessary, then returns the resultant function pointer.
349void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000350 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000351
352 Function* F = 0;
353 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000354
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000355 {
356 // Only lock for getting the Function. The call getPointerToFunction made
357 // in this function might trigger function materializing, which requires
358 // JIT lock to be unlocked.
359 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000360
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000361 // The address given to us for the stub may not be exactly right, it might be
362 // a little bit after the stub. As such, use upper_bound to find it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000363 StubToFunctionMapTy::iterator I =
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000364 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
365 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
366 "This is not a known stub!");
367 F = (--I)->second;
368 ActualPtr = I->first;
369 }
Chris Lattner54266522004-11-20 23:57:07 +0000370
Evan Cheng9da60f92007-06-30 00:10:37 +0000371 // If we have already code generated the function, just return the address.
372 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000373
Evan Cheng9da60f92007-06-30 00:10:37 +0000374 if (!Result) {
375 // Otherwise we don't have it, do lazy compilation now.
376
377 // If lazy compilation is disabled, emit a useful error message and abort.
378 if (TheJIT->isLazyCompilationDisabled()) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000379 llvm_report_error("LLVM JIT requested to do lazy compilation of function '"
380 + F->getName() + "' when lazy compiles are disabled!");
Evan Cheng9da60f92007-06-30 00:10:37 +0000381 }
382
383 // We might like to remove the stub from the StubToFunction map.
384 // We can't do that! Multiple threads could be stuck, waiting to acquire the
385 // lock above. As soon as the 1st function finishes compiling the function,
386 // the next one will be released, and needs to be able to find the function
387 // it needs to call.
388 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000389
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000390 DEBUG(errs() << "JIT: Lazily resolving function '" << F->getName()
391 << "' In stub ptr = " << Stub << " actual ptr = "
392 << ActualPtr << "\n");
Chris Lattner54266522004-11-20 23:57:07 +0000393
Evan Cheng9da60f92007-06-30 00:10:37 +0000394 Result = TheJIT->getPointerToFunction(F);
395 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000396
397 // Reacquire the lock to erase the stub in the map.
398 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000399
400 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000401 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000402
403 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000404
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000405 // What we will do is set the compiled function address to map to the
406 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000407 // if they see it still using the stub address.
408 // Note: this is done so the Resolver doesn't have to manage GOT memory
409 // Do this without allocating map space if the target isn't using a GOT
410 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
411 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
412
Chris Lattner54266522004-11-20 23:57:07 +0000413 return Result;
414}
Chris Lattner688506d2003-08-14 18:35:27 +0000415
Chris Lattner8ac66c12008-04-04 05:51:42 +0000416//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000417// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000418//
Chris Lattner688506d2003-08-14 18:35:27 +0000419namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000420 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
421 /// used to output functions to memory for execution.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +0000422 class JITEmitter : public JITCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000423 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000424
Chris Lattner6125fdd2003-05-09 03:30:07 +0000425 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000426 // save BufferBegin/BufferEnd/CurBufferPtr here.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000427 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000428
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000429 // When reattempting to JIT a function after running out of space, we store
430 // the estimated size of the function we're trying to JIT here, so we can
431 // ask the memory manager for at least this much space. When we
432 // successfully emit the function, we reset this back to zero.
433 uintptr_t SizeEstimate;
434
Chris Lattner5be478f2004-11-20 03:46:14 +0000435 /// Relocations - These are the relocations that the function needs, as
436 /// emitted.
437 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000438
439 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
440 /// It is filled in by the StartMachineBasicBlock callback and queried by
441 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000442 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000443
Chris Lattner239862c2006-02-09 04:49:59 +0000444 /// ConstantPool - The constant pool for the current function.
445 ///
446 MachineConstantPool *ConstantPool;
447
448 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
449 ///
450 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000451
Evan Cheng1606e8e2009-03-13 07:51:59 +0000452 /// ConstPoolAddresses - Addresses of individual constant pool entries.
453 ///
454 SmallVector<uintptr_t, 8> ConstPoolAddresses;
455
Nate Begeman019f8512006-09-10 23:03:44 +0000456 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000457 ///
458 MachineJumpTableInfo *JumpTable;
459
460 /// JumpTableBase - A pointer to the first entry in the jump table.
461 ///
462 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000463
Chris Lattnere7484012007-02-24 02:57:03 +0000464 /// Resolver - This contains info about the currently resolved functions.
465 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000466
467 /// DE - The dwarf emitter for the jit.
468 JITDwarfEmitter *DE;
469
470 /// LabelLocations - This vector is a mapping from Label ID's to their
471 /// address.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000472 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000473
474 /// MMI - Machine module info for exception informations
475 MachineModuleInfo* MMI;
476
Dale Johannesendd947ea2008-08-07 01:30:15 +0000477 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000478 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000479
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000480 // CurFn - The llvm function being emitted. Only valid during
481 // finishFunction().
482 const Function *CurFn;
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000483
484 /// Information about emitted code, which is passed to the
485 /// JITEventListeners. This is reset in startFunction and used in
486 /// finishFunction.
487 JITEvent_EmittedFunctionDetails EmissionDetails;
488
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000489 // CurFnStubUses - For a given Function, a vector of stubs that it
490 // references. This facilitates the JIT detecting that a stub is no
491 // longer used, so that it may be deallocated.
492 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
493
494 // StubFnRefs - For a given pointer to a stub, a set of Functions which
495 // reference the stub. When the count of a stub's references drops to zero,
496 // the stub is unused.
497 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
498
Nate Begeman841c6a42009-03-11 07:03:43 +0000499 // ExtFnStubs - A map of external function names to stubs which have entries
500 // in the JITResolver's ExternalFnToStubMap.
501 StringMap<void *> ExtFnStubs;
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +0000502
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000503 DebugLocTuple PrevDLT;
504
Chris Lattnere7484012007-02-24 02:57:03 +0000505 public:
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000506 JITEmitter(JIT &jit, JITMemoryManager *JMM)
507 : SizeEstimate(0), Resolver(jit), CurFn(0) {
Chris Lattner9f2f1422007-12-06 01:08:09 +0000508 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000509 if (jit.getJITInfo().needsGOT()) {
510 MemMgr->AllocateGOT();
511 DOUT << "JIT is managing a GOT\n";
512 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000513
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000514 if (DwarfExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000515 }
516 ~JITEmitter() {
517 delete MemMgr;
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000518 if (DwarfExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000519 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000520
521 /// classof - Methods for support type inquiry through isa, cast, and
522 /// dyn_cast:
523 ///
524 static inline bool classof(const JITEmitter*) { return true; }
525 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000526
527 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000528
529 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000530 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000531
532 void emitConstantPool(MachineConstantPool *MCP);
533 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000534 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000535
Evan Chengce4a70b2008-11-08 08:02:53 +0000536 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000537 unsigned Alignment = 1);
Nate Begemand6b7a242009-02-18 08:31:02 +0000538 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
539 unsigned StubSize);
Evan Chengce4a70b2008-11-08 08:02:53 +0000540 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000541
Nuno Lopescef75272008-10-21 11:42:16 +0000542 /// allocateSpace - Reserves space in the current block if any, or
543 /// allocate a new one of the given size.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000544 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000545
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000546 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
547 /// this method does not allocate memory in the current output buffer,
548 /// because a global may live longer than the current function.
549 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
550
Chris Lattner5be478f2004-11-20 03:46:14 +0000551 virtual void addRelocation(const MachineRelocation &MR) {
552 Relocations.push_back(MR);
553 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000554
555 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
556 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
557 MBBLocations.resize((MBB->getNumber()+1)*2);
558 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Evan Cheng366cf292008-11-07 22:30:29 +0000559 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
560 << (void*) getCurrentPCValue() << "]\n";
Chris Lattnerb4432f32006-05-03 17:10:41 +0000561 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000562
Evan Cheng5788d1a2008-12-10 02:32:19 +0000563 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
564 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000565
Evan Cheng5788d1a2008-12-10 02:32:19 +0000566 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000567 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
568 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
569 return MBBLocations[MBB->getNumber()];
570 }
571
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000572 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
573 /// given function. Increase the minimum allocation size so that we get
574 /// more memory next time.
575 void retryWithMoreMemory(MachineFunction &F);
576
Chris Lattnere993cc22006-05-11 23:08:08 +0000577 /// deallocateMemForFunction - Deallocate all memory for the specified
578 /// function body.
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000579 void deallocateMemForFunction(const Function *F);
Nate Begeman841c6a42009-03-11 07:03:43 +0000580
581 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
582 /// using the stub at the specified address. Allows
583 /// deallocateMemForFunction to also remove stubs no longer referenced.
584 void AddStubToCurrentFunction(void *Stub);
585
586 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
587 /// MachineRelocations that reference external functions by name.
588 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000589
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000590 virtual void processDebugLoc(DebugLoc DL);
591
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000592 virtual void emitLabel(uint64_t LabelID) {
593 if (LabelLocations.size() <= LabelID)
594 LabelLocations.resize((LabelID+1)*2);
595 LabelLocations[LabelID] = getCurrentPCValue();
596 }
597
Evan Cheng5788d1a2008-12-10 02:32:19 +0000598 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000599 assert(LabelLocations.size() > (unsigned)LabelID &&
600 LabelLocations[LabelID] && "Label not emitted!");
601 return LabelLocations[LabelID];
602 }
603
604 virtual void setModuleInfo(MachineModuleInfo* Info) {
605 MMI = Info;
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000606 if (DwarfExceptionHandling) DE->setModuleInfo(Info);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000607 }
608
Jim Grosbachcce6c292008-10-03 16:17:20 +0000609 void setMemoryExecutable(void) {
610 MemMgr->setMemoryExecutable();
611 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000612
613 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000614
Chris Lattner54266522004-11-20 23:57:07 +0000615 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000616 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000617 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000618 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000619 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
620 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
621 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
622 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000623 };
624}
625
Chris Lattner166f2262004-11-22 22:00:25 +0000626void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
627 bool DoesntNeedStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000628 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000629 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000630
Chris Lattner18e04592008-06-25 20:21:35 +0000631 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000632 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000633
634 // If we have already compiled the function, return a pointer to its body.
635 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000636 void *ResultPtr;
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000637 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
Evan Cheng704bff92008-11-13 21:50:50 +0000638 // Return the function stub if it's already created.
639 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000640 if (ResultPtr)
641 AddStubToCurrentFunction(ResultPtr);
642 } else {
Evan Cheng704bff92008-11-13 21:50:50 +0000643 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000644 }
Chris Lattner54266522004-11-20 23:57:07 +0000645 if (ResultPtr) return ResultPtr;
646
Nate Begemand6b7a242009-02-18 08:31:02 +0000647 // If this is an external function pointer, we can force the JIT to
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000648 // 'compile' it, which really just adds it to the map. In dlsym mode,
649 // external functions are forced through a stub, regardless of reloc type.
650 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
651 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
Nate Begemand6b7a242009-02-18 08:31:02 +0000652 return TheJIT->getPointerToFunction(F);
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000653
Chris Lattner5e225582004-11-21 03:37:42 +0000654 // Okay, the function has not been compiled yet, if the target callback
655 // mechanism is capable of rewriting the instruction directly, prefer to do
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000656 // that instead of emitting a stub. This uses the lazy resolver, so is not
657 // legal if lazy compilation is disabled.
658 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Chris Lattnere7484012007-02-24 02:57:03 +0000659 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000660
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000661 // Otherwise, we have to emit a stub.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000662 void *StubAddr = Resolver.getFunctionStub(F);
663
664 // Add the stub to the current function's list of referenced stubs, so we can
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000665 // deallocate them if the current function is ever freed. It's possible to
666 // return null from getFunctionStub in the case of a weak extern that fails
667 // to resolve.
668 if (StubAddr)
669 AddStubToCurrentFunction(StubAddr);
670
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000671 return StubAddr;
Chris Lattner54266522004-11-20 23:57:07 +0000672}
673
Evan Cheng5594f122008-11-10 01:52:24 +0000674void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000675 bool NoNeedStub) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000676 // Make sure GV is emitted first, and create a stub containing the fully
677 // resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000678 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000679 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
680
681 // Add the stub to the current function's list of referenced stubs, so we can
682 // deallocate them if the current function is ever freed.
683 AddStubToCurrentFunction(StubAddr);
684
685 return StubAddr;
686}
687
688void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
689 if (!TheJIT->areDlsymStubsEnabled())
690 return;
691
692 assert(CurFn && "Stub added to current function, but current function is 0!");
693
694 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
695 StubsUsed.push_back(StubAddr);
696
697 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
698 FnRefs.insert(CurFn);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000699}
700
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000701void JITEmitter::processDebugLoc(DebugLoc DL) {
702 if (!DL.isUnknown()) {
703 DebugLocTuple CurDLT = EmissionDetails.MF->getDebugLocTuple(DL);
704
705 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT) {
706 JITEvent_EmittedFunctionDetails::LineStart NextLine;
707 NextLine.Address = getCurrentPCValue();
708 NextLine.Loc = DL;
709 EmissionDetails.LineStarts.push_back(NextLine);
710 }
711
712 PrevDLT = CurDLT;
713 }
714}
715
Evan Cheng1606e8e2009-03-13 07:51:59 +0000716static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
717 const TargetData *TD) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000718 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
719 if (Constants.empty()) return 0;
720
Evan Cheng1606e8e2009-03-13 07:51:59 +0000721 unsigned Size = 0;
722 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
723 MachineConstantPoolEntry CPE = Constants[i];
724 unsigned AlignMask = CPE.getAlignment() - 1;
725 Size = (Size + AlignMask) & ~AlignMask;
726 const Type *Ty = CPE.getType();
Duncan Sands777d2302009-05-09 07:06:46 +0000727 Size += TD->getTypeAllocSize(Ty);
Evan Cheng1606e8e2009-03-13 07:51:59 +0000728 }
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000729 return Size;
730}
731
732static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
733 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
734 if (JT.empty()) return 0;
735
736 unsigned NumEntries = 0;
737 for (unsigned i = 0, e = JT.size(); i != e; ++i)
738 NumEntries += JT[i].MBBs.size();
739
740 unsigned EntrySize = MJTI->getEntrySize();
741
742 return NumEntries * EntrySize;
743}
744
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000745static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000746 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000747 // Since we do not know where the buffer will be allocated, be pessimistic.
748 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000749}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000750
Dale Johannesendd947ea2008-08-07 01:30:15 +0000751/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
752/// into the running total Size.
753
754unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
755 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000756 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000757 size_t GVAlign =
758 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000759 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000760 DEBUG(GV->dump());
761 // Assume code section ends with worst possible alignment, so first
762 // variable needs maximal padding.
763 if (Size==0)
764 Size = 1;
765 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
766 Size += GVSize;
767 return Size;
768}
769
770/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
771/// but are referenced from the constant; put them in GVSet and add their
772/// size into the running total Size.
773
774unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
775 unsigned Size) {
776 // If its undefined, return the garbage.
777 if (isa<UndefValue>(C))
778 return Size;
779
780 // If the value is a ConstantExpr
781 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
782 Constant *Op0 = CE->getOperand(0);
783 switch (CE->getOpcode()) {
784 case Instruction::GetElementPtr:
785 case Instruction::Trunc:
786 case Instruction::ZExt:
787 case Instruction::SExt:
788 case Instruction::FPTrunc:
789 case Instruction::FPExt:
790 case Instruction::UIToFP:
791 case Instruction::SIToFP:
792 case Instruction::FPToUI:
793 case Instruction::FPToSI:
794 case Instruction::PtrToInt:
795 case Instruction::IntToPtr:
796 case Instruction::BitCast: {
797 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
798 break;
799 }
800 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000801 case Instruction::FAdd:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000802 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000803 case Instruction::FSub:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000804 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000805 case Instruction::FMul:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000806 case Instruction::UDiv:
807 case Instruction::SDiv:
808 case Instruction::URem:
809 case Instruction::SRem:
810 case Instruction::And:
811 case Instruction::Or:
812 case Instruction::Xor: {
813 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
814 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
815 break;
816 }
817 default: {
Torok Edwin7d696d82009-07-11 13:10:19 +0000818 std::string msg;
819 raw_string_ostream Msg(msg);
820 Msg << "ConstantExpr not handled: " << *CE;
821 llvm_report_error(Msg.str());
Dale Johannesendd947ea2008-08-07 01:30:15 +0000822 }
823 }
824 }
825
826 if (C->getType()->getTypeID() == Type::PointerTyID)
827 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000828 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000829 Size = addSizeOfGlobal(GV, Size);
830
831 return Size;
832}
833
834/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
835/// but are referenced from the given initializer.
836
837unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
838 unsigned Size) {
839 if (!isa<UndefValue>(Init) &&
840 !isa<ConstantVector>(Init) &&
841 !isa<ConstantAggregateZero>(Init) &&
842 !isa<ConstantArray>(Init) &&
843 !isa<ConstantStruct>(Init) &&
844 Init->getType()->isFirstClassType())
845 Size = addSizeOfGlobalsInConstantVal(Init, Size);
846 return Size;
847}
848
849/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
850/// globals; then walk the initializers of those globals looking for more.
851/// If their size has not been considered yet, add it into the running total
852/// Size.
853
854unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
855 unsigned Size = 0;
856 GVSet.clear();
857
858 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
859 MBB != E; ++MBB) {
860 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
861 I != E; ++I) {
862 const TargetInstrDesc &Desc = I->getDesc();
863 const MachineInstr &MI = *I;
864 unsigned NumOps = Desc.getNumOperands();
865 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
866 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000867 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000868 GlobalValue* V = MO.getGlobal();
869 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
870 if (!GV)
871 continue;
872 // If seen in previous function, it will have an entry here.
873 if (TheJIT->getPointerToGlobalIfAvailable(GV))
874 continue;
875 // If seen earlier in this function, it will have an entry here.
876 // FIXME: it should be possible to combine these tables, by
877 // assuming the addresses of the new globals in this module
878 // start at 0 (or something) and adjusting them after codegen
879 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000880 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000881 // A variable as yet unseen. Add in its size.
882 Size = addSizeOfGlobal(GV, Size);
883 }
884 }
885 }
886 }
Evan Chengeb5d95a2008-11-06 17:46:04 +0000887 DOUT << "JIT: About to look through initializers\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000888 // Look for more globals that are referenced only from initializers.
889 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +0000890 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000891 I != GVSet.end(); I++) {
892 const GlobalVariable* GV = *I;
893 if (GV->hasInitializer())
894 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
895 }
896
897 return Size;
898}
899
Chris Lattner166f2262004-11-22 22:00:25 +0000900void JITEmitter::startFunction(MachineFunction &F) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000901 DEBUG(errs() << "JIT: Starting CodeGen of Function "
902 << F.getFunction()->getName() << "\n");
Evan Chengeb5d95a2008-11-06 17:46:04 +0000903
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000904 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000905 // Set the memory writable, if it's not already
906 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000907 if (MemMgr->NeedsExactSize()) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000908 DOUT << "JIT: ExactSize\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000909 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
910 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
911 MachineConstantPool *MCP = F.getConstantPool();
912
913 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000914 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000915
916 // Add the alignment of the constant pool
Evan Cheng1606e8e2009-03-13 07:51:59 +0000917 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000918
919 // Add the constant pool size
Evan Cheng1606e8e2009-03-13 07:51:59 +0000920 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000921
922 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000923 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000924
925 // Add the jump table size
926 ActualSize += GetJumpTableSizeInBytes(MJTI);
927
928 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000929 ActualSize = RoundUpToAlign(ActualSize,
930 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000931
932 // Add the function size
933 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000934
Evan Chengeb5d95a2008-11-06 17:46:04 +0000935 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000936 // Add the size of the globals that will be allocated after this function.
937 // These are all the ones referenced from this function that were not
938 // previously allocated.
939 ActualSize += GetSizeOfGlobalsInBytes(F);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000940 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000941 } else if (SizeEstimate > 0) {
942 // SizeEstimate will be non-zero on reallocation attempts.
943 ActualSize = SizeEstimate;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000944 }
945
Chris Lattner8907b4b2007-12-05 23:39:57 +0000946 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
947 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +0000948 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000949
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000950 // Ensure the constant pool/jump table info is at least 4-byte aligned.
951 emitAlignment(16);
952
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000953 emitConstantPool(F.getConstantPool());
954 initJumpTableInfo(F.getJumpTableInfo());
955
956 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000957 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000958 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +0000959
Chris Lattnerb4432f32006-05-03 17:10:41 +0000960 MBBLocations.clear();
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000961
962 EmissionDetails.MF = &F;
963 EmissionDetails.LineStarts.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000964}
965
Chris Lattner43b429b2006-05-02 18:27:26 +0000966bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000967 if (CurBufferPtr == BufferEnd) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000968 // We must call endFunctionBody before retrying, because
969 // deallocateMemForFunction requires it.
970 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
971 retryWithMoreMemory(F);
972 return true;
Chris Lattnere993cc22006-05-11 23:08:08 +0000973 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000974
Jim Laskeyb92767a2006-12-14 22:53:42 +0000975 emitJumpTableInfo(F.getJumpTableInfo());
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000976
Chris Lattnera8279532006-06-16 18:09:26 +0000977 // FnStart is the start of the text, not the start of the constant pool and
978 // other per-function data.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000979 uint8_t *FnStart =
980 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000981
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +0000982 // FnEnd is the end of the function's machine code.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000983 uint8_t *FnEnd = CurBufferPtr;
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +0000984
Chris Lattner5be478f2004-11-20 03:46:14 +0000985 if (!Relocations.empty()) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000986 CurFn = F.getFunction();
Chris Lattnere884dc22005-07-20 16:29:20 +0000987 NumRelos += Relocations.size();
988
Chris Lattner5be478f2004-11-20 03:46:14 +0000989 // Resolve the relocations to concrete pointers.
990 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
991 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +0000992 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +0000993 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +0000994 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +0000995 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
996 false);
Evan Chengd7398c92008-11-08 07:37:34 +0000997 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Evan Chengca66b082008-11-08 07:22:53 +0000998 << ResultPtr << "]\n";
Misha Brukmanf976c852005-04-21 22:55:34 +0000999
Evan Chengef5784e2008-10-29 23:54:46 +00001000 // If the target REALLY wants a stub for this function, emit it now.
Nate Begeman841c6a42009-03-11 07:03:43 +00001001 if (!MR.doesntNeedStub()) {
1002 if (!TheJIT->areDlsymStubsEnabled()) {
1003 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1004 } else {
1005 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1006 if (!Stub) {
1007 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1008 AddStubToCurrentFunction(Stub);
1009 }
1010 ResultPtr = Stub;
1011 }
1012 }
Evan Chengef5784e2008-10-29 23:54:46 +00001013 } else if (MR.isGlobalValue()) {
1014 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1015 BufferBegin+MR.getMachineCodeOffset(),
1016 MR.doesntNeedStub());
Evan Cheng5594f122008-11-10 01:52:24 +00001017 } else if (MR.isIndirectSymbol()) {
1018 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +00001019 BufferBegin+MR.getMachineCodeOffset(),
1020 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +00001021 } else if (MR.isBasicBlock()) {
1022 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1023 } else if (MR.isConstantPoolIndex()) {
1024 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1025 } else {
1026 assert(MR.isJumpTableIndex());
1027 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1028 }
Jeff Cohen00b168892005-07-27 06:12:32 +00001029
Evan Chengef5784e2008-10-29 23:54:46 +00001030 MR.setResultPointer(ResultPtr);
1031 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001032
Andrew Lenharth6a974612005-07-28 12:44:13 +00001033 // if we are managing the GOT and the relocation wants an index,
1034 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +00001035 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001036 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +00001037 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001038 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001039 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +00001040 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +00001041 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +00001042 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001043 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001044 }
Chris Lattner5be478f2004-11-20 03:46:14 +00001045 }
1046
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001047 CurFn = 0;
Chris Lattner43b429b2006-05-02 18:27:26 +00001048 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +00001049 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +00001050 }
1051
Chris Lattnerd2d5c762006-05-03 18:55:56 +00001052 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +00001053 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001054 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001055 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001056 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +00001057 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1058 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001059 }
1060 }
1061
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001062 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1063 // global variables that were referenced in the relocations.
1064 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
Evan Cheng5788d1a2008-12-10 02:32:19 +00001065
1066 if (CurBufferPtr == BufferEnd) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001067 retryWithMoreMemory(F);
1068 return true;
1069 } else {
1070 // Now that we've succeeded in emitting the function, reset the
1071 // SizeEstimate back down to zero.
1072 SizeEstimate = 0;
Evan Cheng5788d1a2008-12-10 02:32:19 +00001073 }
1074
Nuno Lopescef75272008-10-21 11:42:16 +00001075 BufferBegin = CurBufferPtr = 0;
1076 NumBytes += FnEnd-FnStart;
1077
Evan Cheng55fc2802006-07-25 20:40:54 +00001078 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +00001079 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001080
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001081 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
Jeffrey Yasskin32360a72009-07-16 21:07:26 +00001082 EmissionDetails);
Evan Cheng55fc2802006-07-25 20:40:54 +00001083
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001084 DEBUG(errs() << "JIT: Finished CodeGen of [" << (void*)FnStart
1085 << "] Function: " << F.getFunction()->getName()
1086 << ": " << (FnEnd-FnStart) << " bytes of text, "
1087 << Relocations.size() << " relocations\n");
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +00001088
Chris Lattner5be478f2004-11-20 03:46:14 +00001089 Relocations.clear();
Evan Cheng1606e8e2009-03-13 07:51:59 +00001090 ConstPoolAddresses.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +00001091
Evan Chengbc4707a2008-09-18 07:54:21 +00001092 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +00001093 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +00001094
Chris Lattnerc5633c22007-01-20 20:51:43 +00001095#ifndef NDEBUG
Evan Chenga7916f52008-11-05 23:44:08 +00001096 {
Evan Chenge7c35512008-11-12 08:22:43 +00001097 if (sys::hasDisassembler()) {
1098 DOUT << "JIT: Disassembled code:\n";
Evan Chengeb5d95a2008-11-06 17:46:04 +00001099 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001100 } else {
1101 DOUT << "JIT: Binary code:\n";
Evan Chenga7916f52008-11-05 23:44:08 +00001102 DOUT << std::hex;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001103 uint8_t* q = FnStart;
Evan Chenge7c35512008-11-12 08:22:43 +00001104 for (int i = 0; q < FnEnd; q += 4, ++i) {
1105 if (i == 4)
1106 i = 0;
1107 if (i == 0)
1108 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1109 << (long)(q - FnStart) << ": ";
1110 bool Done = false;
1111 for (int j = 3; j >= 0; --j) {
1112 if (q + j >= FnEnd)
1113 Done = true;
1114 else
1115 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1116 }
1117 if (Done)
1118 break;
1119 DOUT << ' ';
1120 if (i == 3)
Evan Cheng6863fb02008-11-06 01:18:29 +00001121 DOUT << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001122 }
1123 DOUT << std::dec;
Evan Cheng6863fb02008-11-06 01:18:29 +00001124 DOUT<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001125 }
1126 }
Chris Lattnerc5633c22007-01-20 20:51:43 +00001127#endif
Jim Grosbach1b747ad2009-08-11 00:09:57 +00001128 if (DwarfExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001129 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001130 SavedBufferBegin = BufferBegin;
1131 SavedBufferEnd = BufferEnd;
1132 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001133
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001134 if (MemMgr->NeedsExactSize()) {
1135 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001136 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001137
1138 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1139 ActualSize);
1140 BufferEnd = BufferBegin+ActualSize;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001141 uint8_t* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +00001142 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1143 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001144 BufferBegin = SavedBufferBegin;
1145 BufferEnd = SavedBufferEnd;
1146 CurBufferPtr = SavedCurBufferPtr;
1147
1148 TheJIT->RegisterTable(FrameRegister);
1149 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001150
1151 if (MMI)
1152 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001153
Chris Lattner43b429b2006-05-02 18:27:26 +00001154 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001155}
1156
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001157void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
1158 DOUT << "JIT: Ran out of space for native code. Reattempting.\n";
1159 Relocations.clear(); // Clear the old relocations or we'll reapply them.
1160 ConstPoolAddresses.clear();
1161 ++NumRetries;
1162 deallocateMemForFunction(F.getFunction());
1163 // Try again with at least twice as much free space.
1164 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
1165}
1166
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001167/// deallocateMemForFunction - Deallocate all memory for the specified
1168/// function body. Also drop any references the function has to stubs.
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001169void JITEmitter::deallocateMemForFunction(const Function *F) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001170 MemMgr->deallocateMemForFunction(F);
1171
1172 // If the function did not reference any stubs, return.
1173 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1174 return;
1175
1176 // For each referenced stub, erase the reference to this function, and then
1177 // erase the list of referenced stubs.
1178 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1179 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1180 void *Stub = StubList[i];
Nate Begeman841c6a42009-03-11 07:03:43 +00001181
1182 // If we already invalidated this stub for this function, continue.
1183 if (StubFnRefs.count(Stub) == 0)
1184 continue;
1185
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001186 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1187 FnRefs.erase(F);
1188
1189 // If this function was the last reference to the stub, invalidate the stub
1190 // in the JITResolver. Were there a memory manager deallocateStub routine,
1191 // we could call that at this point too.
1192 if (FnRefs.empty()) {
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001193 DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
Nate Begeman841c6a42009-03-11 07:03:43 +00001194 StubFnRefs.erase(Stub);
1195
1196 // Invalidate the stub. If it is a GV stub, update the JIT's global
1197 // mapping for that GV to zero, otherwise, search the string map of
1198 // external function names to stubs and remove the entry for this stub.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001199 GlobalValue *GV = Resolver.invalidateStub(Stub);
Nate Begeman841c6a42009-03-11 07:03:43 +00001200 if (GV) {
1201 TheJIT->updateGlobalMapping(GV, 0);
1202 } else {
1203 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1204 e = ExtFnStubs.end(); i != e; ++i) {
1205 if (i->second == Stub) {
1206 ExtFnStubs.erase(i);
1207 break;
1208 }
1209 }
1210 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001211 }
1212 }
1213 CurFnStubUses.erase(F);
1214}
1215
1216
Evan Cheng5788d1a2008-12-10 02:32:19 +00001217void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +00001218 if (BufferBegin)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001219 return JITCodeEmitter::allocateSpace(Size, Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +00001220
1221 // create a new memory block if there is no active one.
1222 // care must be taken so that BufferBegin is invalidated when a
1223 // block is trimmed
1224 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1225 BufferEnd = BufferBegin+Size;
1226 return CurBufferPtr;
1227}
1228
Jeffrey Yasskin489393d2009-07-08 21:59:57 +00001229void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1230 // Delegate this call through the memory manager.
1231 return MemMgr->allocateGlobal(Size, Alignment);
1232}
1233
Chris Lattner166f2262004-11-22 22:00:25 +00001234void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001235 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001236 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001237
Chris Lattnerfa77d432006-02-09 04:22:52 +00001238 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001239 if (Constants.empty()) return;
1240
Evan Cheng1606e8e2009-03-13 07:51:59 +00001241 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1242 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng97b8c402008-04-12 00:22:01 +00001243 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001244 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001245
1246 if (ConstantPoolBase == 0) return; // Buffer overflow.
1247
Evan Cheng97b8c402008-04-12 00:22:01 +00001248 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1249 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1250
Chris Lattner239862c2006-02-09 04:49:59 +00001251 // Initialize the memory for all of the constant pool entries.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001252 unsigned Offset = 0;
Chris Lattner3029f922006-02-09 04:46:04 +00001253 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng1606e8e2009-03-13 07:51:59 +00001254 MachineConstantPoolEntry CPE = Constants[i];
1255 unsigned AlignMask = CPE.getAlignment() - 1;
1256 Offset = (Offset + AlignMask) & ~AlignMask;
1257
1258 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1259 ConstPoolAddresses.push_back(CAddr);
1260 if (CPE.isMachineConstantPoolEntry()) {
Evan Chengcd5731d2006-09-12 20:59:59 +00001261 // FIXME: add support to lower machine constant pool values into bytes!
Torok Edwin7d696d82009-07-11 13:10:19 +00001262 llvm_report_error("Initialize memory with machine specific constant pool"
1263 "entry has not been implemented!");
Evan Chengcd5731d2006-09-12 20:59:59 +00001264 }
Evan Cheng1606e8e2009-03-13 07:51:59 +00001265 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1266 DOUT << "JIT: CP" << i << " at [0x"
1267 << std::hex << CAddr << std::dec << "]\n";
1268
1269 const Type *Ty = CPE.Val.ConstVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00001270 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
Chris Lattner1cc08382003-01-13 01:00:12 +00001271 }
1272}
1273
Nate Begeman37efe672006-04-22 18:53:45 +00001274void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001275 if (TheJIT->getJITInfo().hasCustomJumpTables())
1276 return;
1277
Nate Begeman37efe672006-04-22 18:53:45 +00001278 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1279 if (JT.empty()) return;
1280
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001281 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001282 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001283 NumEntries += JT[i].MBBs.size();
1284
1285 unsigned EntrySize = MJTI->getEntrySize();
1286
Nate Begeman37efe672006-04-22 18:53:45 +00001287 // Just allocate space for all the jump tables now. We will fix up the actual
1288 // MBB entries in the tables after we emit the code for each block, since then
1289 // we will know the final locations of the MBBs in memory.
1290 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001291 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001292}
1293
Jim Laskeyb92767a2006-12-14 22:53:42 +00001294void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001295 if (TheJIT->getJITInfo().hasCustomJumpTables())
1296 return;
1297
Nate Begeman37efe672006-04-22 18:53:45 +00001298 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001299 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001300
Jim Laskeyb92767a2006-12-14 22:53:42 +00001301 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001302 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1303 // For each jump table, place the offset from the beginning of the table
1304 // to the target address.
1305 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001306
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001307 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1308 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1309 // Store the offset of the basic block for this jump table slot in the
1310 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001311 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001312 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001313 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001314 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1315 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001316 }
1317 } else {
1318 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1319
1320 // For each jump table, map each target in the jump table to the address of
1321 // an emitted MachineBasicBlock.
1322 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1323
1324 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1325 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1326 // Store the address of the basic block for this jump table slot in the
1327 // memory we allocated for the jump table in 'initJumpTableInfo'
1328 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1329 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1330 }
Nate Begeman37efe672006-04-22 18:53:45 +00001331 }
1332}
1333
Evan Chengce4a70b2008-11-08 08:02:53 +00001334void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1335 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001336 SavedBufferBegin = BufferBegin;
1337 SavedBufferEnd = BufferEnd;
1338 SavedCurBufferPtr = CurBufferPtr;
1339
Evan Chengce4a70b2008-11-08 08:02:53 +00001340 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001341 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001342}
1343
Nate Begemand6b7a242009-02-18 08:31:02 +00001344void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1345 unsigned StubSize) {
1346 SavedBufferBegin = BufferBegin;
1347 SavedBufferEnd = BufferEnd;
1348 SavedCurBufferPtr = CurBufferPtr;
1349
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001350 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
Nate Begemand6b7a242009-02-18 08:31:02 +00001351 BufferEnd = BufferBegin+StubSize+1;
1352}
1353
Evan Chengce4a70b2008-11-08 08:02:53 +00001354void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001355 NumBytes += getCurrentPCOffset();
1356 std::swap(SavedBufferBegin, BufferBegin);
1357 BufferEnd = SavedBufferEnd;
1358 CurBufferPtr = SavedCurBufferPtr;
1359 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001360}
1361
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001362// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1363// in the constant pool that was last emitted with the 'emitConstantPool'
1364// method.
1365//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001366uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001367 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001368 "Invalid ConstantPoolIndex!");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001369 return ConstPoolAddresses[ConstantNum];
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001370}
1371
Nate Begeman37efe672006-04-22 18:53:45 +00001372// getJumpTableEntryAddress - Return the address of the JumpTable with index
1373// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1374//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001375uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001376 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1377 assert(Index < JT.size() && "Invalid jump table index!");
1378
1379 unsigned Offset = 0;
1380 unsigned EntrySize = JumpTable->getEntrySize();
1381
1382 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001383 Offset += JT[i].MBBs.size();
1384
1385 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001386
Evan Cheng5788d1a2008-12-10 02:32:19 +00001387 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001388}
1389
Chris Lattnere993cc22006-05-11 23:08:08 +00001390//===----------------------------------------------------------------------===//
1391// Public interface to this file
1392//===----------------------------------------------------------------------===//
1393
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001394JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
Chris Lattner9f2f1422007-12-06 01:08:09 +00001395 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +00001396}
1397
Misha Brukmand69c1e62003-07-28 19:09:06 +00001398// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001399// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001400// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1401// need to resolve function(s) that are being mis-codegenerated, so we need to
1402// resolve their addresses at runtime, and this is the way to do it.
1403extern "C" {
1404 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001405 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001406 return TheJIT->getPointerToFunction(F);
1407 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001408 }
1409}
Chris Lattnere993cc22006-05-11 23:08:08 +00001410
1411// getPointerToFunctionOrStub - If the specified function has been
1412// code-gen'd, return a pointer to the function. If not, compile it, or use
1413// a stub to implement lazy compilation if available.
1414//
1415void *JIT::getPointerToFunctionOrStub(Function *F) {
1416 // If we have already code generated the function, just return the address.
1417 if (void *Addr = getPointerToGlobalIfAvailable(F))
1418 return Addr;
1419
Chris Lattnere7484012007-02-24 02:57:03 +00001420 // Get a stub if the target supports it.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001421 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Evan Chenga044dfc2008-08-20 00:28:12 +00001422 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001423 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001424}
1425
Nate Begemand6b7a242009-02-18 08:31:02 +00001426void JIT::updateFunctionStub(Function *F) {
1427 // Get the empty stub we generated earlier.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001428 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001429 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1430 void *Stub = JE->getJITResolver().getFunctionStub(F);
1431
1432 // Tell the target jit info to rewrite the stub at the specified address,
1433 // rather than creating a new one.
1434 void *Addr = getPointerToGlobalIfAvailable(F);
1435 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1436}
1437
1438/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1439/// that were emitted during code generation.
1440///
1441void JIT::updateDlsymStubTable() {
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001442 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001443 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1444
1445 SmallVector<GlobalValue*, 8> GVs;
1446 SmallVector<void*, 8> Ptrs;
Nate Begeman841c6a42009-03-11 07:03:43 +00001447 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
Nate Begemand6b7a242009-02-18 08:31:02 +00001448
1449 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1450
Nate Begeman841c6a42009-03-11 07:03:43 +00001451 unsigned nStubs = GVs.size() + ExtFns.size();
1452
Nate Begemand6b7a242009-02-18 08:31:02 +00001453 // If there are no relocatable stubs, return.
Nate Begeman841c6a42009-03-11 07:03:43 +00001454 if (nStubs == 0)
Nate Begemand6b7a242009-02-18 08:31:02 +00001455 return;
1456
1457 // If there are no new relocatable stubs, return.
1458 void *CurTable = JE->getMemMgr()->getDlsymTable();
Nate Begeman841c6a42009-03-11 07:03:43 +00001459 if (CurTable && (*(unsigned *)CurTable == nStubs))
Nate Begemand6b7a242009-02-18 08:31:02 +00001460 return;
1461
1462 // Calculate the size of the stub info
Nate Begeman841c6a42009-03-11 07:03:43 +00001463 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
Nate Begemand6b7a242009-02-18 08:31:02 +00001464
1465 SmallVector<unsigned, 8> Offsets;
1466 for (unsigned i = 0; i != GVs.size(); ++i) {
1467 Offsets.push_back(offset);
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001468 offset += GVs[i]->getName().size() + 1;
Nate Begemand6b7a242009-02-18 08:31:02 +00001469 }
Nate Begeman841c6a42009-03-11 07:03:43 +00001470 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1471 i != e; ++i) {
1472 Offsets.push_back(offset);
1473 offset += strlen(i->first()) + 1;
1474 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001475
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001476 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begemand6b7a242009-02-18 08:31:02 +00001477 JE->startGVStub(0, offset, 4);
1478
1479 // Emit the number of records
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001480 JE->emitInt32(nStubs);
Nate Begemand6b7a242009-02-18 08:31:02 +00001481
1482 // Emit the string offsets
Nate Begeman841c6a42009-03-11 07:03:43 +00001483 for (unsigned i = 0; i != nStubs; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001484 JE->emitInt32(Offsets[i]);
Nate Begemand6b7a242009-02-18 08:31:02 +00001485
Nate Begeman66941982009-03-04 19:10:38 +00001486 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1487 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1488 // relocation can write the relocated pointer at the appropriate place in
1489 // the stub.
1490 for (unsigned i = 0; i != GVs.size(); ++i) {
1491 intptr_t Ptr = (intptr_t)Ptrs[i];
1492 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1493
1494 if (isa<Function>(GVs[i]))
1495 Ptr |= (intptr_t)1;
1496
Nate Begeman841c6a42009-03-11 07:03:43 +00001497 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001498 JE->emitInt64(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001499 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001500 JE->emitInt32(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001501 }
1502 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1503 i != e; ++i) {
1504 intptr_t Ptr = (intptr_t)i->second | 1;
1505
1506 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001507 JE->emitInt64(Ptr);
Nate Begemand6b7a242009-02-18 08:31:02 +00001508 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001509 JE->emitInt32(Ptr);
Nate Begeman66941982009-03-04 19:10:38 +00001510 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001511
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001512 // Emit the strings.
Nate Begemand6b7a242009-02-18 08:31:02 +00001513 for (unsigned i = 0; i != GVs.size(); ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001514 JE->emitString(GVs[i]->getName());
Nate Begeman841c6a42009-03-11 07:03:43 +00001515 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1516 i != e; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001517 JE->emitString(i->first());
Nate Begemand6b7a242009-02-18 08:31:02 +00001518
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001519 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1520 // deallocate space for the old one, if one existed.
Nate Begemand6b7a242009-02-18 08:31:02 +00001521 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1522}
1523
Chris Lattnere993cc22006-05-11 23:08:08 +00001524/// freeMachineCodeForFunction - release machine code memory for given Function.
1525///
1526void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001527
Chris Lattnere993cc22006-05-11 23:08:08 +00001528 // Delete translation for this from the ExecutionEngine, so it will get
1529 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001530 void *OldPtr = updateGlobalMapping(F, 0);
1531
1532 if (OldPtr)
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001533 TheJIT->NotifyFreeingMachineCode(*F, OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001534
1535 // Free the actual memory for the function body and related stuff.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001536 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1537 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001538}