blob: 63ac6f1c722f3897e6667bde8424a7e559bccdf6 [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");
54static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000055
Andrew Lenhartha00269b2005-07-29 23:40:16 +000056
Chris Lattner54266522004-11-20 23:57:07 +000057//===----------------------------------------------------------------------===//
58// JIT lazy compilation code.
59//
60namespace {
Reid Spenceree448632005-07-12 15:51:55 +000061 class JITResolverState {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000062 public:
63 typedef std::map<AssertingVH<Function>, void*> FunctionToStubMapTy;
64 typedef std::map<void*, Function*> StubToFunctionMapTy;
65 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
Reid Spenceree448632005-07-12 15:51:55 +000066 private:
67 /// FunctionToStubMap - Keep track of the stub created for a particular
68 /// function so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000069 FunctionToStubMapTy FunctionToStubMap;
Reid Spenceree448632005-07-12 15:51:55 +000070
71 /// StubToFunctionMap - Keep track of the function that each stub
72 /// corresponds to.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000073 StubToFunctionMapTy StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000074
Evan Cheng5594f122008-11-10 01:52:24 +000075 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +000076 /// particular GlobalVariable so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000077 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000078
Reid Spenceree448632005-07-12 15:51:55 +000079 public:
Nick Lewyckye2bcf132009-04-27 05:09:44 +000080 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000081 assert(locked.holds(TheJIT->lock));
82 return FunctionToStubMap;
83 }
Jeff Cohen00b168892005-07-27 06:12:32 +000084
Nick Lewyckye2bcf132009-04-27 05:09:44 +000085 StubToFunctionMapTy& getStubToFunctionMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000086 assert(locked.holds(TheJIT->lock));
87 return StubToFunctionMap;
88 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000089
Nick Lewyckye2bcf132009-04-27 05:09:44 +000090 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +000091 assert(locked.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +000092 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000093 }
Reid Spenceree448632005-07-12 15:51:55 +000094 };
Jeff Cohen00b168892005-07-27 06:12:32 +000095
Chris Lattner54266522004-11-20 23:57:07 +000096 /// JITResolver - Keep track of, and resolve, call sites for functions that
97 /// have not yet been compiled.
98 class JITResolver {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000099 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
100 typedef JITResolverState::StubToFunctionMapTy StubToFunctionMapTy;
101 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
102
Chris Lattner5e225582004-11-21 03:37:42 +0000103 /// LazyResolverFn - The target lazy resolver function that we actually
104 /// rewrite instructions to use.
105 TargetJITInfo::LazyResolverFn LazyResolverFn;
106
Reid Spenceree448632005-07-12 15:51:55 +0000107 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000108
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000109 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
110 /// external functions.
111 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000112
Evan Cheng1606e8e2009-03-13 07:51:59 +0000113 /// revGOTMap - map addresses to indexes in the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000114 std::map<void*, unsigned> revGOTMap;
115 unsigned nextGOTIndex;
116
Chris Lattnere7484012007-02-24 02:57:03 +0000117 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000118 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000119 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000120 TheJIT = &jit;
121
122 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
123 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
124 TheJITResolver = this;
125 }
126
127 ~JITResolver() {
128 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000129 }
Chris Lattner54266522004-11-20 23:57:07 +0000130
Evan Cheng704bff92008-11-13 21:50:50 +0000131 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
132 /// if it has already been created.
133 void *getFunctionStubIfAvailable(Function *F);
134
Chris Lattner54266522004-11-20 23:57:07 +0000135 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begemand6b7a242009-02-18 08:31:02 +0000136 /// one on demand as needed. If empty is true, create a function stub
137 /// pointing at address 0, to be filled in later.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000138 void *getFunctionStub(Function *F);
Chris Lattner54266522004-11-20 23:57:07 +0000139
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000140 /// getExternalFunctionStub - Return a stub for the function at the
141 /// specified address, created lazily on demand.
142 void *getExternalFunctionStub(void *FnAddr);
143
Evan Cheng5594f122008-11-10 01:52:24 +0000144 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000145 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000146 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000147
Chris Lattner5e225582004-11-21 03:37:42 +0000148 /// AddCallbackAtLocation - If the target is capable of rewriting an
149 /// instruction without the use of a stub, record the location of the use so
150 /// we know which function is being used at the location.
151 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000152 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000153 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000154 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000155 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000156 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000157
158 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000159 SmallVectorImpl<void*> &Ptrs);
160
161 GlobalValue *invalidateStub(void *Stub);
Chris Lattner5e225582004-11-21 03:37:42 +0000162
Andrew Lenharth6a974612005-07-28 12:44:13 +0000163 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000164 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000165 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000166 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000167
Chris Lattner54266522004-11-20 23:57:07 +0000168 /// JITCompilerFn - This function is called to resolve a stub to a compiled
169 /// address. If the LLVM Function corresponding to the stub has not yet
170 /// been compiled, this function compiles it first.
171 static void *JITCompilerFn(void *Stub);
172 };
173}
174
Chris Lattnere7484012007-02-24 02:57:03 +0000175JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000176
Evan Cheng704bff92008-11-13 21:50:50 +0000177/// getFunctionStubIfAvailable - This returns a pointer to a function stub
178/// if it has already been created.
179void *JITResolver::getFunctionStubIfAvailable(Function *F) {
180 MutexGuard locked(TheJIT->lock);
181
182 // If we already have a stub for this function, recycle it.
183 void *&Stub = state.getFunctionToStubMap(locked)[F];
184 return Stub;
185}
186
Chris Lattner54266522004-11-20 23:57:07 +0000187/// getFunctionStub - This returns a pointer to a function stub, creating
188/// one on demand as needed.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000189void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000190 MutexGuard locked(TheJIT->lock);
191
Chris Lattner54266522004-11-20 23:57:07 +0000192 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000193 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000194 if (Stub) return Stub;
195
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000196 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
197 // case we must resolve the symbol now.
198 void *Actual = TheJIT->isLazyCompilationDisabled()
199 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
200
201 // If this is an external declaration, attempt to resolve the address now
202 // to place in the stub.
Dan Gohman69f93782009-01-05 05:32:42 +0000203 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000204 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000205
Dan Gohman69f93782009-01-05 05:32:42 +0000206 // If we resolved the symbol to a null address (eg. a weak external)
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000207 // don't emit a stub. Return a null pointer to the application. If dlsym
208 // stubs are enabled, not being able to resolve the address is not
209 // meaningful.
210 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
Dan Gohman69f93782009-01-05 05:32:42 +0000211 }
212
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000213 // Codegen a new stub, calling the lazy resolver or the actual address of the
214 // external function, if it was resolved.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000215 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000216 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000217
Chris Lattner870286a2006-06-01 17:29:22 +0000218 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000219 // If we are getting the stub for an external function, we really want the
220 // address of the stub in the GlobalAddressMap for the JIT, not the address
221 // of the external function.
222 TheJIT->updateGlobalMapping(F, Stub);
223 }
Chris Lattner54266522004-11-20 23:57:07 +0000224
Chris Lattnerbe3ae8e2009-03-05 06:48:16 +0000225 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
Bill Wendling832171c2006-12-07 20:04:42 +0000226 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000227
Chris Lattner54266522004-11-20 23:57:07 +0000228 // Finally, keep track of the stub-to-Function mapping so that the
229 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000230 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begemand6b7a242009-02-18 08:31:02 +0000231
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000232 // If we are JIT'ing non-lazily but need to call a function that does not
233 // exist yet, add it to the JIT's work list so that we can fill in the stub
234 // address later.
235 if (!Actual && TheJIT->isLazyCompilationDisabled())
236 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
237 TheJIT->addPendingFunction(F);
Nate Begemand6b7a242009-02-18 08:31:02 +0000238
Chris Lattner54266522004-11-20 23:57:07 +0000239 return Stub;
240}
241
Evan Cheng5594f122008-11-10 01:52:24 +0000242/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000243/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000244void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000245 MutexGuard locked(TheJIT->lock);
246
247 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000248 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
249 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000250
Evan Chenge4d783d2008-11-10 23:26:16 +0000251 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000252 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000253 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000254
Evan Cheng5594f122008-11-10 01:52:24 +0000255 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
Evan Chengbe8c03f2008-01-04 10:46:51 +0000256 << GV->getName() << "'\n";
257
Evan Cheng5594f122008-11-10 01:52:24 +0000258 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000259}
260
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000261/// getExternalFunctionStub - Return a stub for the function at the
262/// specified address, created lazily on demand.
263void *JITResolver::getExternalFunctionStub(void *FnAddr) {
264 // If we already have a stub for this function, recycle it.
265 void *&Stub = ExternalFnToStubMap[FnAddr];
266 if (Stub) return Stub;
267
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000268 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000269 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000270
Bill Wendling832171c2006-12-07 20:04:42 +0000271 DOUT << "JIT: Stub emitted at [" << Stub
272 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000273 return Stub;
274}
275
Andrew Lenharth6a974612005-07-28 12:44:13 +0000276unsigned JITResolver::getGOTIndexForAddr(void* addr) {
277 unsigned idx = revGOTMap[addr];
278 if (!idx) {
279 idx = ++nextGOTIndex;
280 revGOTMap[addr] = idx;
Evan Cheng366cf292008-11-07 22:30:29 +0000281 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000282 }
283 return idx;
284}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000285
Nate Begemand6b7a242009-02-18 08:31:02 +0000286void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
287 SmallVectorImpl<void*> &Ptrs) {
288 MutexGuard locked(TheJIT->lock);
289
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000290 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
291 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begemand6b7a242009-02-18 08:31:02 +0000292
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000293 for (FunctionToStubMapTy::iterator i = FM.begin(), e = FM.end(); i != e; ++i){
Nate Begemand6b7a242009-02-18 08:31:02 +0000294 Function *F = i->first;
295 if (F->isDeclaration() && F->hasExternalLinkage()) {
296 GVs.push_back(i->first);
297 Ptrs.push_back(i->second);
298 }
299 }
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000300 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begemand6b7a242009-02-18 08:31:02 +0000301 i != e; ++i) {
302 GVs.push_back(i->first);
303 Ptrs.push_back(i->second);
304 }
305}
306
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000307GlobalValue *JITResolver::invalidateStub(void *Stub) {
308 MutexGuard locked(TheJIT->lock);
309
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000310 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
311 StubToFunctionMapTy &SM = state.getStubToFunctionMap(locked);
312 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000313
314 // Look up the cheap way first, to see if it's a function stub we are
315 // invalidating. If so, remove it from both the forward and reverse maps.
316 if (SM.find(Stub) != SM.end()) {
317 Function *F = SM[Stub];
318 SM.erase(Stub);
319 FM.erase(F);
320 return F;
321 }
322
Nate Begeman841c6a42009-03-11 07:03:43 +0000323 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000324 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000325 i != e; ++i) {
326 if (i->second != Stub)
327 continue;
328 GlobalValue *GV = i->first;
329 GM.erase(i);
330 return GV;
331 }
332
Nate Begeman841c6a42009-03-11 07:03:43 +0000333 // Lastly, check to see if it's in the ExternalFnToStubMap.
334 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
335 e = ExternalFnToStubMap.end(); i != e; ++i) {
336 if (i->second != Stub)
337 continue;
338 ExternalFnToStubMap.erase(i);
339 break;
340 }
341
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000342 return 0;
343}
344
Chris Lattner54266522004-11-20 23:57:07 +0000345/// JITCompilerFn - This function is called when a lazy compilation stub has
346/// been entered. It looks up which function this stub corresponds to, compiles
347/// it if necessary, then returns the resultant function pointer.
348void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000349 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000350
351 Function* F = 0;
352 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000353
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000354 {
355 // Only lock for getting the Function. The call getPointerToFunction made
356 // in this function might trigger function materializing, which requires
357 // JIT lock to be unlocked.
358 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000359
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000360 // The address given to us for the stub may not be exactly right, it might be
361 // a little bit after the stub. As such, use upper_bound to find it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000362 StubToFunctionMapTy::iterator I =
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000363 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
364 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
365 "This is not a known stub!");
366 F = (--I)->second;
367 ActualPtr = I->first;
368 }
Chris Lattner54266522004-11-20 23:57:07 +0000369
Evan Cheng9da60f92007-06-30 00:10:37 +0000370 // If we have already code generated the function, just return the address.
371 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000372
Evan Cheng9da60f92007-06-30 00:10:37 +0000373 if (!Result) {
374 // Otherwise we don't have it, do lazy compilation now.
375
376 // If lazy compilation is disabled, emit a useful error message and abort.
377 if (TheJIT->isLazyCompilationDisabled()) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000378 llvm_report_error("LLVM JIT requested to do lazy compilation of function '"
379 + F->getName() + "' when lazy compiles are disabled!");
Evan Cheng9da60f92007-06-30 00:10:37 +0000380 }
381
382 // We might like to remove the stub from the StubToFunction map.
383 // We can't do that! Multiple threads could be stuck, waiting to acquire the
384 // lock above. As soon as the 1st function finishes compiling the function,
385 // the next one will be released, and needs to be able to find the function
386 // it needs to call.
387 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000388
Evan Cheng9da60f92007-06-30 00:10:37 +0000389 DOUT << "JIT: Lazily resolving function '" << F->getName()
390 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000391 << ActualPtr << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000392
Evan Cheng9da60f92007-06-30 00:10:37 +0000393 Result = TheJIT->getPointerToFunction(F);
394 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000395
396 // Reacquire the lock to erase the stub in the map.
397 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000398
399 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000400 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000401
402 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000403
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000404 // What we will do is set the compiled function address to map to the
405 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000406 // if they see it still using the stub address.
407 // Note: this is done so the Resolver doesn't have to manage GOT memory
408 // Do this without allocating map space if the target isn't using a GOT
409 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
410 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
411
Chris Lattner54266522004-11-20 23:57:07 +0000412 return Result;
413}
Chris Lattner688506d2003-08-14 18:35:27 +0000414
Chris Lattner8ac66c12008-04-04 05:51:42 +0000415//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000416// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000417//
Chris Lattner688506d2003-08-14 18:35:27 +0000418namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000419 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
420 /// used to output functions to memory for execution.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +0000421 class JITEmitter : public JITCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000422 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000423
Chris Lattner6125fdd2003-05-09 03:30:07 +0000424 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000425 // save BufferBegin/BufferEnd/CurBufferPtr here.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000426 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000427
Chris Lattner5be478f2004-11-20 03:46:14 +0000428 /// Relocations - These are the relocations that the function needs, as
429 /// emitted.
430 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000431
432 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
433 /// It is filled in by the StartMachineBasicBlock callback and queried by
434 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000435 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000436
Chris Lattner239862c2006-02-09 04:49:59 +0000437 /// ConstantPool - The constant pool for the current function.
438 ///
439 MachineConstantPool *ConstantPool;
440
441 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
442 ///
443 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000444
Evan Cheng1606e8e2009-03-13 07:51:59 +0000445 /// ConstPoolAddresses - Addresses of individual constant pool entries.
446 ///
447 SmallVector<uintptr_t, 8> ConstPoolAddresses;
448
Nate Begeman019f8512006-09-10 23:03:44 +0000449 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000450 ///
451 MachineJumpTableInfo *JumpTable;
452
453 /// JumpTableBase - A pointer to the first entry in the jump table.
454 ///
455 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000456
Chris Lattnere7484012007-02-24 02:57:03 +0000457 /// Resolver - This contains info about the currently resolved functions.
458 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000459
460 /// DE - The dwarf emitter for the jit.
461 JITDwarfEmitter *DE;
462
463 /// LabelLocations - This vector is a mapping from Label ID's to their
464 /// address.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000465 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000466
467 /// MMI - Machine module info for exception informations
468 MachineModuleInfo* MMI;
469
Dale Johannesendd947ea2008-08-07 01:30:15 +0000470 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000471 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000472
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000473 // CurFn - The llvm function being emitted. Only valid during
474 // finishFunction().
475 const Function *CurFn;
476
477 // CurFnStubUses - For a given Function, a vector of stubs that it
478 // references. This facilitates the JIT detecting that a stub is no
479 // longer used, so that it may be deallocated.
480 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
481
482 // StubFnRefs - For a given pointer to a stub, a set of Functions which
483 // reference the stub. When the count of a stub's references drops to zero,
484 // the stub is unused.
485 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
486
Nate Begeman841c6a42009-03-11 07:03:43 +0000487 // ExtFnStubs - A map of external function names to stubs which have entries
488 // in the JITResolver's ExternalFnToStubMap.
489 StringMap<void *> ExtFnStubs;
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +0000490
Chris Lattnere7484012007-02-24 02:57:03 +0000491 public:
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000492 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0) {
Chris Lattner9f2f1422007-12-06 01:08:09 +0000493 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000494 if (jit.getJITInfo().needsGOT()) {
495 MemMgr->AllocateGOT();
496 DOUT << "JIT is managing a GOT\n";
497 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000498
499 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000500 }
501 ~JITEmitter() {
502 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000503 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000504 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000505
506 /// classof - Methods for support type inquiry through isa, cast, and
507 /// dyn_cast:
508 ///
509 static inline bool classof(const JITEmitter*) { return true; }
510 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000511
512 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000513
514 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000515 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000516
517 void emitConstantPool(MachineConstantPool *MCP);
518 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000519 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000520
Evan Chengce4a70b2008-11-08 08:02:53 +0000521 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000522 unsigned Alignment = 1);
Nate Begemand6b7a242009-02-18 08:31:02 +0000523 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
524 unsigned StubSize);
Evan Chengce4a70b2008-11-08 08:02:53 +0000525 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000526
Nuno Lopescef75272008-10-21 11:42:16 +0000527 /// allocateSpace - Reserves space in the current block if any, or
528 /// allocate a new one of the given size.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000529 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000530
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000531 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
532 /// this method does not allocate memory in the current output buffer,
533 /// because a global may live longer than the current function.
534 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
535
Chris Lattner5be478f2004-11-20 03:46:14 +0000536 virtual void addRelocation(const MachineRelocation &MR) {
537 Relocations.push_back(MR);
538 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000539
540 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
541 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
542 MBBLocations.resize((MBB->getNumber()+1)*2);
543 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Evan Cheng366cf292008-11-07 22:30:29 +0000544 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
545 << (void*) getCurrentPCValue() << "]\n";
Chris Lattnerb4432f32006-05-03 17:10:41 +0000546 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000547
Evan Cheng5788d1a2008-12-10 02:32:19 +0000548 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
549 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000550
Evan Cheng5788d1a2008-12-10 02:32:19 +0000551 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000552 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
553 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
554 return MBBLocations[MBB->getNumber()];
555 }
556
Chris Lattnere993cc22006-05-11 23:08:08 +0000557 /// deallocateMemForFunction - Deallocate all memory for the specified
558 /// function body.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000559 void deallocateMemForFunction(Function *F);
Nate Begeman841c6a42009-03-11 07:03:43 +0000560
561 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
562 /// using the stub at the specified address. Allows
563 /// deallocateMemForFunction to also remove stubs no longer referenced.
564 void AddStubToCurrentFunction(void *Stub);
565
566 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
567 /// MachineRelocations that reference external functions by name.
568 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000569
570 virtual void emitLabel(uint64_t LabelID) {
571 if (LabelLocations.size() <= LabelID)
572 LabelLocations.resize((LabelID+1)*2);
573 LabelLocations[LabelID] = getCurrentPCValue();
574 }
575
Evan Cheng5788d1a2008-12-10 02:32:19 +0000576 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000577 assert(LabelLocations.size() > (unsigned)LabelID &&
578 LabelLocations[LabelID] && "Label not emitted!");
579 return LabelLocations[LabelID];
580 }
581
582 virtual void setModuleInfo(MachineModuleInfo* Info) {
583 MMI = Info;
584 if (ExceptionHandling) DE->setModuleInfo(Info);
585 }
586
Jim Grosbachcce6c292008-10-03 16:17:20 +0000587 void setMemoryExecutable(void) {
588 MemMgr->setMemoryExecutable();
589 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000590
591 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000592
Chris Lattner54266522004-11-20 23:57:07 +0000593 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000594 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000595 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000596 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000597 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
598 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
599 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
600 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000601 };
602}
603
Chris Lattner166f2262004-11-22 22:00:25 +0000604void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
605 bool DoesntNeedStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000606 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000607 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000608
Chris Lattner18e04592008-06-25 20:21:35 +0000609 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000610 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000611
612 // If we have already compiled the function, return a pointer to its body.
613 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000614 void *ResultPtr;
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000615 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
Evan Cheng704bff92008-11-13 21:50:50 +0000616 // Return the function stub if it's already created.
617 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000618 if (ResultPtr)
619 AddStubToCurrentFunction(ResultPtr);
620 } else {
Evan Cheng704bff92008-11-13 21:50:50 +0000621 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000622 }
Chris Lattner54266522004-11-20 23:57:07 +0000623 if (ResultPtr) return ResultPtr;
624
Nate Begemand6b7a242009-02-18 08:31:02 +0000625 // If this is an external function pointer, we can force the JIT to
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000626 // 'compile' it, which really just adds it to the map. In dlsym mode,
627 // external functions are forced through a stub, regardless of reloc type.
628 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
629 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
Nate Begemand6b7a242009-02-18 08:31:02 +0000630 return TheJIT->getPointerToFunction(F);
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000631
Chris Lattner5e225582004-11-21 03:37:42 +0000632 // Okay, the function has not been compiled yet, if the target callback
633 // mechanism is capable of rewriting the instruction directly, prefer to do
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000634 // that instead of emitting a stub. This uses the lazy resolver, so is not
635 // legal if lazy compilation is disabled.
636 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Chris Lattnere7484012007-02-24 02:57:03 +0000637 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000638
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000639 // Otherwise, we have to emit a stub.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000640 void *StubAddr = Resolver.getFunctionStub(F);
641
642 // Add the stub to the current function's list of referenced stubs, so we can
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000643 // deallocate them if the current function is ever freed. It's possible to
644 // return null from getFunctionStub in the case of a weak extern that fails
645 // to resolve.
646 if (StubAddr)
647 AddStubToCurrentFunction(StubAddr);
648
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000649 return StubAddr;
Chris Lattner54266522004-11-20 23:57:07 +0000650}
651
Evan Cheng5594f122008-11-10 01:52:24 +0000652void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000653 bool NoNeedStub) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000654 // Make sure GV is emitted first, and create a stub containing the fully
655 // resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000656 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000657 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
658
659 // Add the stub to the current function's list of referenced stubs, so we can
660 // deallocate them if the current function is ever freed.
661 AddStubToCurrentFunction(StubAddr);
662
663 return StubAddr;
664}
665
666void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
667 if (!TheJIT->areDlsymStubsEnabled())
668 return;
669
670 assert(CurFn && "Stub added to current function, but current function is 0!");
671
672 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
673 StubsUsed.push_back(StubAddr);
674
675 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
676 FnRefs.insert(CurFn);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000677}
678
Evan Cheng1606e8e2009-03-13 07:51:59 +0000679static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
680 const TargetData *TD) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000681 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
682 if (Constants.empty()) return 0;
683
Evan Cheng1606e8e2009-03-13 07:51:59 +0000684 unsigned Size = 0;
685 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
686 MachineConstantPoolEntry CPE = Constants[i];
687 unsigned AlignMask = CPE.getAlignment() - 1;
688 Size = (Size + AlignMask) & ~AlignMask;
689 const Type *Ty = CPE.getType();
Duncan Sands777d2302009-05-09 07:06:46 +0000690 Size += TD->getTypeAllocSize(Ty);
Evan Cheng1606e8e2009-03-13 07:51:59 +0000691 }
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000692 return Size;
693}
694
695static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
696 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
697 if (JT.empty()) return 0;
698
699 unsigned NumEntries = 0;
700 for (unsigned i = 0, e = JT.size(); i != e; ++i)
701 NumEntries += JT[i].MBBs.size();
702
703 unsigned EntrySize = MJTI->getEntrySize();
704
705 return NumEntries * EntrySize;
706}
707
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000708static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000709 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000710 // Since we do not know where the buffer will be allocated, be pessimistic.
711 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000712}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000713
Dale Johannesendd947ea2008-08-07 01:30:15 +0000714/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
715/// into the running total Size.
716
717unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
718 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000719 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000720 size_t GVAlign =
721 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000722 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000723 DEBUG(GV->dump());
724 // Assume code section ends with worst possible alignment, so first
725 // variable needs maximal padding.
726 if (Size==0)
727 Size = 1;
728 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
729 Size += GVSize;
730 return Size;
731}
732
733/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
734/// but are referenced from the constant; put them in GVSet and add their
735/// size into the running total Size.
736
737unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
738 unsigned Size) {
739 // If its undefined, return the garbage.
740 if (isa<UndefValue>(C))
741 return Size;
742
743 // If the value is a ConstantExpr
744 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
745 Constant *Op0 = CE->getOperand(0);
746 switch (CE->getOpcode()) {
747 case Instruction::GetElementPtr:
748 case Instruction::Trunc:
749 case Instruction::ZExt:
750 case Instruction::SExt:
751 case Instruction::FPTrunc:
752 case Instruction::FPExt:
753 case Instruction::UIToFP:
754 case Instruction::SIToFP:
755 case Instruction::FPToUI:
756 case Instruction::FPToSI:
757 case Instruction::PtrToInt:
758 case Instruction::IntToPtr:
759 case Instruction::BitCast: {
760 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
761 break;
762 }
763 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000764 case Instruction::FAdd:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000765 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000766 case Instruction::FSub:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000767 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000768 case Instruction::FMul:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000769 case Instruction::UDiv:
770 case Instruction::SDiv:
771 case Instruction::URem:
772 case Instruction::SRem:
773 case Instruction::And:
774 case Instruction::Or:
775 case Instruction::Xor: {
776 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
777 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
778 break;
779 }
780 default: {
Torok Edwin7d696d82009-07-11 13:10:19 +0000781 std::string msg;
782 raw_string_ostream Msg(msg);
783 Msg << "ConstantExpr not handled: " << *CE;
784 llvm_report_error(Msg.str());
Dale Johannesendd947ea2008-08-07 01:30:15 +0000785 }
786 }
787 }
788
789 if (C->getType()->getTypeID() == Type::PointerTyID)
790 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000791 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000792 Size = addSizeOfGlobal(GV, Size);
793
794 return Size;
795}
796
797/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
798/// but are referenced from the given initializer.
799
800unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
801 unsigned Size) {
802 if (!isa<UndefValue>(Init) &&
803 !isa<ConstantVector>(Init) &&
804 !isa<ConstantAggregateZero>(Init) &&
805 !isa<ConstantArray>(Init) &&
806 !isa<ConstantStruct>(Init) &&
807 Init->getType()->isFirstClassType())
808 Size = addSizeOfGlobalsInConstantVal(Init, Size);
809 return Size;
810}
811
812/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
813/// globals; then walk the initializers of those globals looking for more.
814/// If their size has not been considered yet, add it into the running total
815/// Size.
816
817unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
818 unsigned Size = 0;
819 GVSet.clear();
820
821 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
822 MBB != E; ++MBB) {
823 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
824 I != E; ++I) {
825 const TargetInstrDesc &Desc = I->getDesc();
826 const MachineInstr &MI = *I;
827 unsigned NumOps = Desc.getNumOperands();
828 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
829 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000830 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000831 GlobalValue* V = MO.getGlobal();
832 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
833 if (!GV)
834 continue;
835 // If seen in previous function, it will have an entry here.
836 if (TheJIT->getPointerToGlobalIfAvailable(GV))
837 continue;
838 // If seen earlier in this function, it will have an entry here.
839 // FIXME: it should be possible to combine these tables, by
840 // assuming the addresses of the new globals in this module
841 // start at 0 (or something) and adjusting them after codegen
842 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000843 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000844 // A variable as yet unseen. Add in its size.
845 Size = addSizeOfGlobal(GV, Size);
846 }
847 }
848 }
849 }
Evan Chengeb5d95a2008-11-06 17:46:04 +0000850 DOUT << "JIT: About to look through initializers\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000851 // Look for more globals that are referenced only from initializers.
852 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +0000853 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000854 I != GVSet.end(); I++) {
855 const GlobalVariable* GV = *I;
856 if (GV->hasInitializer())
857 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
858 }
859
860 return Size;
861}
862
Chris Lattner166f2262004-11-22 22:00:25 +0000863void JITEmitter::startFunction(MachineFunction &F) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000864 DOUT << "JIT: Starting CodeGen of Function "
865 << F.getFunction()->getName() << "\n";
866
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000867 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000868 // Set the memory writable, if it's not already
869 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000870 if (MemMgr->NeedsExactSize()) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000871 DOUT << "JIT: ExactSize\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000872 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
873 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
874 MachineConstantPool *MCP = F.getConstantPool();
875
876 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000877 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000878
879 // Add the alignment of the constant pool
Evan Cheng1606e8e2009-03-13 07:51:59 +0000880 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000881
882 // Add the constant pool size
Evan Cheng1606e8e2009-03-13 07:51:59 +0000883 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000884
885 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000886 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000887
888 // Add the jump table size
889 ActualSize += GetJumpTableSizeInBytes(MJTI);
890
891 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000892 ActualSize = RoundUpToAlign(ActualSize,
893 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000894
895 // Add the function size
896 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000897
Evan Chengeb5d95a2008-11-06 17:46:04 +0000898 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000899 // Add the size of the globals that will be allocated after this function.
900 // These are all the ones referenced from this function that were not
901 // previously allocated.
902 ActualSize += GetSizeOfGlobalsInBytes(F);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000903 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000904 }
905
Chris Lattner8907b4b2007-12-05 23:39:57 +0000906 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
907 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +0000908 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000909
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000910 // Ensure the constant pool/jump table info is at least 4-byte aligned.
911 emitAlignment(16);
912
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000913 emitConstantPool(F.getConstantPool());
914 initJumpTableInfo(F.getJumpTableInfo());
915
916 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000917 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000918 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +0000919
Chris Lattnerb4432f32006-05-03 17:10:41 +0000920 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000921}
922
Chris Lattner43b429b2006-05-02 18:27:26 +0000923bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000924 if (CurBufferPtr == BufferEnd) {
925 // FIXME: Allocate more space, then try again.
Torok Edwin7d696d82009-07-11 13:10:19 +0000926 llvm_report_error("JIT: Ran out of space for generated machine code!");
Chris Lattnere993cc22006-05-11 23:08:08 +0000927 }
928
Jim Laskeyb92767a2006-12-14 22:53:42 +0000929 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +0000930
Chris Lattnera8279532006-06-16 18:09:26 +0000931 // FnStart is the start of the text, not the start of the constant pool and
932 // other per-function data.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000933 uint8_t *FnStart =
934 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000935
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +0000936 // FnEnd is the end of the function's machine code.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000937 uint8_t *FnEnd = CurBufferPtr;
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +0000938
Chris Lattner5be478f2004-11-20 03:46:14 +0000939 if (!Relocations.empty()) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000940 CurFn = F.getFunction();
Chris Lattnere884dc22005-07-20 16:29:20 +0000941 NumRelos += Relocations.size();
942
Chris Lattner5be478f2004-11-20 03:46:14 +0000943 // Resolve the relocations to concrete pointers.
944 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
945 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +0000946 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +0000947 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +0000948 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +0000949 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
950 false);
Evan Chengd7398c92008-11-08 07:37:34 +0000951 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Evan Chengca66b082008-11-08 07:22:53 +0000952 << ResultPtr << "]\n";
Misha Brukmanf976c852005-04-21 22:55:34 +0000953
Evan Chengef5784e2008-10-29 23:54:46 +0000954 // If the target REALLY wants a stub for this function, emit it now.
Nate Begeman841c6a42009-03-11 07:03:43 +0000955 if (!MR.doesntNeedStub()) {
956 if (!TheJIT->areDlsymStubsEnabled()) {
957 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
958 } else {
959 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
960 if (!Stub) {
961 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
962 AddStubToCurrentFunction(Stub);
963 }
964 ResultPtr = Stub;
965 }
966 }
Evan Chengef5784e2008-10-29 23:54:46 +0000967 } else if (MR.isGlobalValue()) {
968 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
969 BufferBegin+MR.getMachineCodeOffset(),
970 MR.doesntNeedStub());
Evan Cheng5594f122008-11-10 01:52:24 +0000971 } else if (MR.isIndirectSymbol()) {
972 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +0000973 BufferBegin+MR.getMachineCodeOffset(),
974 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +0000975 } else if (MR.isBasicBlock()) {
976 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
977 } else if (MR.isConstantPoolIndex()) {
978 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
979 } else {
980 assert(MR.isJumpTableIndex());
981 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
982 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000983
Evan Chengef5784e2008-10-29 23:54:46 +0000984 MR.setResultPointer(ResultPtr);
985 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000986
Andrew Lenharth6a974612005-07-28 12:44:13 +0000987 // if we are managing the GOT and the relocation wants an index,
988 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +0000989 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000990 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000991 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000992 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000993 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +0000994 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +0000995 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +0000996 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000997 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000998 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000999 }
1000
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001001 CurFn = 0;
Chris Lattner43b429b2006-05-02 18:27:26 +00001002 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +00001003 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +00001004 }
1005
Chris Lattnerd2d5c762006-05-03 18:55:56 +00001006 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +00001007 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001008 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001009 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001010 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +00001011 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1012 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001013 }
1014 }
1015
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001016 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1017 // global variables that were referenced in the relocations.
1018 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
Evan Cheng5788d1a2008-12-10 02:32:19 +00001019
1020 if (CurBufferPtr == BufferEnd) {
1021 // FIXME: Allocate more space, then try again.
Torok Edwin7d696d82009-07-11 13:10:19 +00001022 llvm_report_error("JIT: Ran out of space for generated machine code!");
Evan Cheng5788d1a2008-12-10 02:32:19 +00001023 }
1024
Nuno Lopescef75272008-10-21 11:42:16 +00001025 BufferBegin = CurBufferPtr = 0;
1026 NumBytes += FnEnd-FnStart;
1027
Evan Cheng55fc2802006-07-25 20:40:54 +00001028 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +00001029 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001030
1031 JITEvent_EmittedFunctionDetails Details;
1032 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
1033 Details);
Evan Cheng55fc2802006-07-25 20:40:54 +00001034
Bill Wendling832171c2006-12-07 20:04:42 +00001035 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1036 << "] Function: " << F.getFunction()->getName()
1037 << ": " << (FnEnd-FnStart) << " bytes of text, "
1038 << Relocations.size() << " relocations\n";
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +00001039
Chris Lattner5be478f2004-11-20 03:46:14 +00001040 Relocations.clear();
Evan Cheng1606e8e2009-03-13 07:51:59 +00001041 ConstPoolAddresses.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +00001042
Evan Chengbc4707a2008-09-18 07:54:21 +00001043 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +00001044 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +00001045
Chris Lattnerc5633c22007-01-20 20:51:43 +00001046#ifndef NDEBUG
Evan Chenga7916f52008-11-05 23:44:08 +00001047 {
Evan Chenge7c35512008-11-12 08:22:43 +00001048 if (sys::hasDisassembler()) {
1049 DOUT << "JIT: Disassembled code:\n";
Evan Chengeb5d95a2008-11-06 17:46:04 +00001050 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001051 } else {
1052 DOUT << "JIT: Binary code:\n";
Evan Chenga7916f52008-11-05 23:44:08 +00001053 DOUT << std::hex;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001054 uint8_t* q = FnStart;
Evan Chenge7c35512008-11-12 08:22:43 +00001055 for (int i = 0; q < FnEnd; q += 4, ++i) {
1056 if (i == 4)
1057 i = 0;
1058 if (i == 0)
1059 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1060 << (long)(q - FnStart) << ": ";
1061 bool Done = false;
1062 for (int j = 3; j >= 0; --j) {
1063 if (q + j >= FnEnd)
1064 Done = true;
1065 else
1066 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1067 }
1068 if (Done)
1069 break;
1070 DOUT << ' ';
1071 if (i == 3)
Evan Cheng6863fb02008-11-06 01:18:29 +00001072 DOUT << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001073 }
1074 DOUT << std::dec;
Evan Cheng6863fb02008-11-06 01:18:29 +00001075 DOUT<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001076 }
1077 }
Chris Lattnerc5633c22007-01-20 20:51:43 +00001078#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001079 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001080 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001081 SavedBufferBegin = BufferBegin;
1082 SavedBufferEnd = BufferEnd;
1083 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001084
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001085 if (MemMgr->NeedsExactSize()) {
1086 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001087 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001088
1089 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1090 ActualSize);
1091 BufferEnd = BufferBegin+ActualSize;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001092 uint8_t* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +00001093 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1094 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001095 BufferBegin = SavedBufferBegin;
1096 BufferEnd = SavedBufferEnd;
1097 CurBufferPtr = SavedCurBufferPtr;
1098
1099 TheJIT->RegisterTable(FrameRegister);
1100 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001101
1102 if (MMI)
1103 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001104
Chris Lattner43b429b2006-05-02 18:27:26 +00001105 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001106}
1107
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001108/// deallocateMemForFunction - Deallocate all memory for the specified
1109/// function body. Also drop any references the function has to stubs.
1110void JITEmitter::deallocateMemForFunction(Function *F) {
1111 MemMgr->deallocateMemForFunction(F);
1112
1113 // If the function did not reference any stubs, return.
1114 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1115 return;
1116
1117 // For each referenced stub, erase the reference to this function, and then
1118 // erase the list of referenced stubs.
1119 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1120 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1121 void *Stub = StubList[i];
Nate Begeman841c6a42009-03-11 07:03:43 +00001122
1123 // If we already invalidated this stub for this function, continue.
1124 if (StubFnRefs.count(Stub) == 0)
1125 continue;
1126
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001127 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1128 FnRefs.erase(F);
1129
1130 // If this function was the last reference to the stub, invalidate the stub
1131 // in the JITResolver. Were there a memory manager deallocateStub routine,
1132 // we could call that at this point too.
1133 if (FnRefs.empty()) {
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001134 DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
Nate Begeman841c6a42009-03-11 07:03:43 +00001135 StubFnRefs.erase(Stub);
1136
1137 // Invalidate the stub. If it is a GV stub, update the JIT's global
1138 // mapping for that GV to zero, otherwise, search the string map of
1139 // external function names to stubs and remove the entry for this stub.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001140 GlobalValue *GV = Resolver.invalidateStub(Stub);
Nate Begeman841c6a42009-03-11 07:03:43 +00001141 if (GV) {
1142 TheJIT->updateGlobalMapping(GV, 0);
1143 } else {
1144 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1145 e = ExtFnStubs.end(); i != e; ++i) {
1146 if (i->second == Stub) {
1147 ExtFnStubs.erase(i);
1148 break;
1149 }
1150 }
1151 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001152 }
1153 }
1154 CurFnStubUses.erase(F);
1155}
1156
1157
Evan Cheng5788d1a2008-12-10 02:32:19 +00001158void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +00001159 if (BufferBegin)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001160 return JITCodeEmitter::allocateSpace(Size, Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +00001161
1162 // create a new memory block if there is no active one.
1163 // care must be taken so that BufferBegin is invalidated when a
1164 // block is trimmed
1165 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1166 BufferEnd = BufferBegin+Size;
1167 return CurBufferPtr;
1168}
1169
Jeffrey Yasskin489393d2009-07-08 21:59:57 +00001170void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1171 // Delegate this call through the memory manager.
1172 return MemMgr->allocateGlobal(Size, Alignment);
1173}
1174
Chris Lattner166f2262004-11-22 22:00:25 +00001175void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001176 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001177 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001178
Chris Lattnerfa77d432006-02-09 04:22:52 +00001179 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001180 if (Constants.empty()) return;
1181
Evan Cheng1606e8e2009-03-13 07:51:59 +00001182 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1183 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng97b8c402008-04-12 00:22:01 +00001184 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001185 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001186
1187 if (ConstantPoolBase == 0) return; // Buffer overflow.
1188
Evan Cheng97b8c402008-04-12 00:22:01 +00001189 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1190 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1191
Chris Lattner239862c2006-02-09 04:49:59 +00001192 // Initialize the memory for all of the constant pool entries.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001193 unsigned Offset = 0;
Chris Lattner3029f922006-02-09 04:46:04 +00001194 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng1606e8e2009-03-13 07:51:59 +00001195 MachineConstantPoolEntry CPE = Constants[i];
1196 unsigned AlignMask = CPE.getAlignment() - 1;
1197 Offset = (Offset + AlignMask) & ~AlignMask;
1198
1199 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1200 ConstPoolAddresses.push_back(CAddr);
1201 if (CPE.isMachineConstantPoolEntry()) {
Evan Chengcd5731d2006-09-12 20:59:59 +00001202 // FIXME: add support to lower machine constant pool values into bytes!
Torok Edwin7d696d82009-07-11 13:10:19 +00001203 llvm_report_error("Initialize memory with machine specific constant pool"
1204 "entry has not been implemented!");
Evan Chengcd5731d2006-09-12 20:59:59 +00001205 }
Evan Cheng1606e8e2009-03-13 07:51:59 +00001206 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1207 DOUT << "JIT: CP" << i << " at [0x"
1208 << std::hex << CAddr << std::dec << "]\n";
1209
1210 const Type *Ty = CPE.Val.ConstVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00001211 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
Chris Lattner1cc08382003-01-13 01:00:12 +00001212 }
1213}
1214
Nate Begeman37efe672006-04-22 18:53:45 +00001215void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001216 if (TheJIT->getJITInfo().hasCustomJumpTables())
1217 return;
1218
Nate Begeman37efe672006-04-22 18:53:45 +00001219 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1220 if (JT.empty()) return;
1221
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001222 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001223 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001224 NumEntries += JT[i].MBBs.size();
1225
1226 unsigned EntrySize = MJTI->getEntrySize();
1227
Nate Begeman37efe672006-04-22 18:53:45 +00001228 // Just allocate space for all the jump tables now. We will fix up the actual
1229 // MBB entries in the tables after we emit the code for each block, since then
1230 // we will know the final locations of the MBBs in memory.
1231 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001232 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001233}
1234
Jim Laskeyb92767a2006-12-14 22:53:42 +00001235void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001236 if (TheJIT->getJITInfo().hasCustomJumpTables())
1237 return;
1238
Nate Begeman37efe672006-04-22 18:53:45 +00001239 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001240 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001241
Jim Laskeyb92767a2006-12-14 22:53:42 +00001242 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001243 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1244 // For each jump table, place the offset from the beginning of the table
1245 // to the target address.
1246 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001247
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001248 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1249 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1250 // Store the offset of the basic block for this jump table slot in the
1251 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001252 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001253 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001254 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001255 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1256 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001257 }
1258 } else {
1259 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1260
1261 // For each jump table, map each target in the jump table to the address of
1262 // an emitted MachineBasicBlock.
1263 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1264
1265 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1266 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1267 // Store the address of the basic block for this jump table slot in the
1268 // memory we allocated for the jump table in 'initJumpTableInfo'
1269 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1270 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1271 }
Nate Begeman37efe672006-04-22 18:53:45 +00001272 }
1273}
1274
Evan Chengce4a70b2008-11-08 08:02:53 +00001275void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1276 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001277 SavedBufferBegin = BufferBegin;
1278 SavedBufferEnd = BufferEnd;
1279 SavedCurBufferPtr = CurBufferPtr;
1280
Evan Chengce4a70b2008-11-08 08:02:53 +00001281 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001282 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001283}
1284
Nate Begemand6b7a242009-02-18 08:31:02 +00001285void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1286 unsigned StubSize) {
1287 SavedBufferBegin = BufferBegin;
1288 SavedBufferEnd = BufferEnd;
1289 SavedCurBufferPtr = CurBufferPtr;
1290
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001291 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
Nate Begemand6b7a242009-02-18 08:31:02 +00001292 BufferEnd = BufferBegin+StubSize+1;
1293}
1294
Evan Chengce4a70b2008-11-08 08:02:53 +00001295void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001296 NumBytes += getCurrentPCOffset();
1297 std::swap(SavedBufferBegin, BufferBegin);
1298 BufferEnd = SavedBufferEnd;
1299 CurBufferPtr = SavedCurBufferPtr;
1300 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001301}
1302
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001303// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1304// in the constant pool that was last emitted with the 'emitConstantPool'
1305// method.
1306//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001307uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001308 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001309 "Invalid ConstantPoolIndex!");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001310 return ConstPoolAddresses[ConstantNum];
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001311}
1312
Nate Begeman37efe672006-04-22 18:53:45 +00001313// getJumpTableEntryAddress - Return the address of the JumpTable with index
1314// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1315//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001316uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001317 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1318 assert(Index < JT.size() && "Invalid jump table index!");
1319
1320 unsigned Offset = 0;
1321 unsigned EntrySize = JumpTable->getEntrySize();
1322
1323 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001324 Offset += JT[i].MBBs.size();
1325
1326 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001327
Evan Cheng5788d1a2008-12-10 02:32:19 +00001328 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001329}
1330
Chris Lattnere993cc22006-05-11 23:08:08 +00001331//===----------------------------------------------------------------------===//
1332// Public interface to this file
1333//===----------------------------------------------------------------------===//
1334
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001335JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
Chris Lattner9f2f1422007-12-06 01:08:09 +00001336 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +00001337}
1338
Misha Brukmand69c1e62003-07-28 19:09:06 +00001339// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001340// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001341// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1342// need to resolve function(s) that are being mis-codegenerated, so we need to
1343// resolve their addresses at runtime, and this is the way to do it.
1344extern "C" {
1345 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001346 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001347 return TheJIT->getPointerToFunction(F);
1348 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001349 }
1350}
Chris Lattnere993cc22006-05-11 23:08:08 +00001351
1352// getPointerToFunctionOrStub - If the specified function has been
1353// code-gen'd, return a pointer to the function. If not, compile it, or use
1354// a stub to implement lazy compilation if available.
1355//
1356void *JIT::getPointerToFunctionOrStub(Function *F) {
1357 // If we have already code generated the function, just return the address.
1358 if (void *Addr = getPointerToGlobalIfAvailable(F))
1359 return Addr;
1360
Chris Lattnere7484012007-02-24 02:57:03 +00001361 // Get a stub if the target supports it.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001362 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Evan Chenga044dfc2008-08-20 00:28:12 +00001363 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001364 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001365}
1366
Nate Begemand6b7a242009-02-18 08:31:02 +00001367void JIT::updateFunctionStub(Function *F) {
1368 // Get the empty stub we generated earlier.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001369 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001370 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1371 void *Stub = JE->getJITResolver().getFunctionStub(F);
1372
1373 // Tell the target jit info to rewrite the stub at the specified address,
1374 // rather than creating a new one.
1375 void *Addr = getPointerToGlobalIfAvailable(F);
1376 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1377}
1378
1379/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1380/// that were emitted during code generation.
1381///
1382void JIT::updateDlsymStubTable() {
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001383 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001384 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1385
1386 SmallVector<GlobalValue*, 8> GVs;
1387 SmallVector<void*, 8> Ptrs;
Nate Begeman841c6a42009-03-11 07:03:43 +00001388 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
Nate Begemand6b7a242009-02-18 08:31:02 +00001389
1390 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1391
Nate Begeman841c6a42009-03-11 07:03:43 +00001392 unsigned nStubs = GVs.size() + ExtFns.size();
1393
Nate Begemand6b7a242009-02-18 08:31:02 +00001394 // If there are no relocatable stubs, return.
Nate Begeman841c6a42009-03-11 07:03:43 +00001395 if (nStubs == 0)
Nate Begemand6b7a242009-02-18 08:31:02 +00001396 return;
1397
1398 // If there are no new relocatable stubs, return.
1399 void *CurTable = JE->getMemMgr()->getDlsymTable();
Nate Begeman841c6a42009-03-11 07:03:43 +00001400 if (CurTable && (*(unsigned *)CurTable == nStubs))
Nate Begemand6b7a242009-02-18 08:31:02 +00001401 return;
1402
1403 // Calculate the size of the stub info
Nate Begeman841c6a42009-03-11 07:03:43 +00001404 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
Nate Begemand6b7a242009-02-18 08:31:02 +00001405
1406 SmallVector<unsigned, 8> Offsets;
1407 for (unsigned i = 0; i != GVs.size(); ++i) {
1408 Offsets.push_back(offset);
1409 offset += GVs[i]->getName().length() + 1;
1410 }
Nate Begeman841c6a42009-03-11 07:03:43 +00001411 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1412 i != e; ++i) {
1413 Offsets.push_back(offset);
1414 offset += strlen(i->first()) + 1;
1415 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001416
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001417 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begemand6b7a242009-02-18 08:31:02 +00001418 JE->startGVStub(0, offset, 4);
1419
1420 // Emit the number of records
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001421 JE->emitInt32(nStubs);
Nate Begemand6b7a242009-02-18 08:31:02 +00001422
1423 // Emit the string offsets
Nate Begeman841c6a42009-03-11 07:03:43 +00001424 for (unsigned i = 0; i != nStubs; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001425 JE->emitInt32(Offsets[i]);
Nate Begemand6b7a242009-02-18 08:31:02 +00001426
Nate Begeman66941982009-03-04 19:10:38 +00001427 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1428 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1429 // relocation can write the relocated pointer at the appropriate place in
1430 // the stub.
1431 for (unsigned i = 0; i != GVs.size(); ++i) {
1432 intptr_t Ptr = (intptr_t)Ptrs[i];
1433 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1434
1435 if (isa<Function>(GVs[i]))
1436 Ptr |= (intptr_t)1;
1437
Nate Begeman841c6a42009-03-11 07:03:43 +00001438 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001439 JE->emitInt64(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001440 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001441 JE->emitInt32(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001442 }
1443 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1444 i != e; ++i) {
1445 intptr_t Ptr = (intptr_t)i->second | 1;
1446
1447 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001448 JE->emitInt64(Ptr);
Nate Begemand6b7a242009-02-18 08:31:02 +00001449 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001450 JE->emitInt32(Ptr);
Nate Begeman66941982009-03-04 19:10:38 +00001451 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001452
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001453 // Emit the strings.
Nate Begemand6b7a242009-02-18 08:31:02 +00001454 for (unsigned i = 0; i != GVs.size(); ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001455 JE->emitString(GVs[i]->getName());
Nate Begeman841c6a42009-03-11 07:03:43 +00001456 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1457 i != e; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001458 JE->emitString(i->first());
Nate Begemand6b7a242009-02-18 08:31:02 +00001459
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001460 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1461 // deallocate space for the old one, if one existed.
Nate Begemand6b7a242009-02-18 08:31:02 +00001462 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1463}
1464
Chris Lattnere993cc22006-05-11 23:08:08 +00001465/// freeMachineCodeForFunction - release machine code memory for given Function.
1466///
1467void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001468
Chris Lattnere993cc22006-05-11 23:08:08 +00001469 // Delete translation for this from the ExecutionEngine, so it will get
1470 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001471 void *OldPtr = updateGlobalMapping(F, 0);
1472
1473 if (OldPtr)
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001474 TheJIT->NotifyFreeingMachineCode(*F, OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001475
1476 // Free the actual memory for the function body and related stuff.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001477 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1478 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001479}