blob: 8fe7ab848b7361cf7f48bfa0bc8e55516f1e8c52 [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"
Chris Lattnere7fd5532006-05-08 22:00:52 +000036#include "llvm/Support/MutexGuard.h"
Nick Lewycky848b3142009-04-19 18:32:03 +000037#include "llvm/Support/ValueHandle.h"
Anton Korobeynikovfd58e6e2007-01-23 10:26:08 +000038#include "llvm/System/Disassembler.h"
Chris Lattnerbc52cad2008-06-25 17:18:44 +000039#include "llvm/System/Memory.h"
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +000040#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng47c01a02008-11-07 09:02:17 +000041#include "llvm/ADT/SmallPtrSet.h"
Nate Begemand6b7a242009-02-18 08:31:02 +000042#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000043#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000044#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000045#ifndef NDEBUG
46#include <iomanip>
47#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000048using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000049
Chris Lattner36343732006-12-19 22:43:32 +000050STATISTIC(NumBytes, "Number of bytes of machine code compiled");
51STATISTIC(NumRelos, "Number of relocations applied");
52static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000053
Andrew Lenhartha00269b2005-07-29 23:40:16 +000054
Chris Lattner54266522004-11-20 23:57:07 +000055//===----------------------------------------------------------------------===//
56// JIT lazy compilation code.
57//
58namespace {
Reid Spenceree448632005-07-12 15:51:55 +000059 class JITResolverState {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000060 public:
61 typedef std::map<AssertingVH<Function>, void*> FunctionToStubMapTy;
62 typedef std::map<void*, Function*> StubToFunctionMapTy;
63 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
Reid Spenceree448632005-07-12 15:51:55 +000064 private:
65 /// FunctionToStubMap - Keep track of the stub created for a particular
66 /// function so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000067 FunctionToStubMapTy FunctionToStubMap;
Reid Spenceree448632005-07-12 15:51:55 +000068
69 /// StubToFunctionMap - Keep track of the function that each stub
70 /// corresponds to.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000071 StubToFunctionMapTy StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000072
Evan Cheng5594f122008-11-10 01:52:24 +000073 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +000074 /// particular GlobalVariable so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000075 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000076
Reid Spenceree448632005-07-12 15:51:55 +000077 public:
Nick Lewyckye2bcf132009-04-27 05:09:44 +000078 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000079 assert(locked.holds(TheJIT->lock));
80 return FunctionToStubMap;
81 }
Jeff Cohen00b168892005-07-27 06:12:32 +000082
Nick Lewyckye2bcf132009-04-27 05:09:44 +000083 StubToFunctionMapTy& getStubToFunctionMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000084 assert(locked.holds(TheJIT->lock));
85 return StubToFunctionMap;
86 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000087
Nick Lewyckye2bcf132009-04-27 05:09:44 +000088 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +000089 assert(locked.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +000090 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000091 }
Reid Spenceree448632005-07-12 15:51:55 +000092 };
Jeff Cohen00b168892005-07-27 06:12:32 +000093
Chris Lattner54266522004-11-20 23:57:07 +000094 /// JITResolver - Keep track of, and resolve, call sites for functions that
95 /// have not yet been compiled.
96 class JITResolver {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000097 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
98 typedef JITResolverState::StubToFunctionMapTy StubToFunctionMapTy;
99 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
100
Chris Lattner5e225582004-11-21 03:37:42 +0000101 /// LazyResolverFn - The target lazy resolver function that we actually
102 /// rewrite instructions to use.
103 TargetJITInfo::LazyResolverFn LazyResolverFn;
104
Reid Spenceree448632005-07-12 15:51:55 +0000105 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000106
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000107 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
108 /// external functions.
109 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000110
Evan Cheng1606e8e2009-03-13 07:51:59 +0000111 /// revGOTMap - map addresses to indexes in the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000112 std::map<void*, unsigned> revGOTMap;
113 unsigned nextGOTIndex;
114
Chris Lattnere7484012007-02-24 02:57:03 +0000115 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000116 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000117 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000118 TheJIT = &jit;
119
120 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
121 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
122 TheJITResolver = this;
123 }
124
125 ~JITResolver() {
126 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000127 }
Chris Lattner54266522004-11-20 23:57:07 +0000128
Evan Cheng704bff92008-11-13 21:50:50 +0000129 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
130 /// if it has already been created.
131 void *getFunctionStubIfAvailable(Function *F);
132
Chris Lattner54266522004-11-20 23:57:07 +0000133 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begemand6b7a242009-02-18 08:31:02 +0000134 /// one on demand as needed. If empty is true, create a function stub
135 /// pointing at address 0, to be filled in later.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000136 void *getFunctionStub(Function *F);
Chris Lattner54266522004-11-20 23:57:07 +0000137
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000138 /// getExternalFunctionStub - Return a stub for the function at the
139 /// specified address, created lazily on demand.
140 void *getExternalFunctionStub(void *FnAddr);
141
Evan Cheng5594f122008-11-10 01:52:24 +0000142 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000143 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000144 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000145
Chris Lattner5e225582004-11-21 03:37:42 +0000146 /// AddCallbackAtLocation - If the target is capable of rewriting an
147 /// instruction without the use of a stub, record the location of the use so
148 /// we know which function is being used at the location.
149 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000150 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000151 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000152 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000153 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000154 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000155
156 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000157 SmallVectorImpl<void*> &Ptrs);
158
159 GlobalValue *invalidateStub(void *Stub);
Chris Lattner5e225582004-11-21 03:37:42 +0000160
Andrew Lenharth6a974612005-07-28 12:44:13 +0000161 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000162 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000163 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000164 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000165
Chris Lattner54266522004-11-20 23:57:07 +0000166 /// JITCompilerFn - This function is called to resolve a stub to a compiled
167 /// address. If the LLVM Function corresponding to the stub has not yet
168 /// been compiled, this function compiles it first.
169 static void *JITCompilerFn(void *Stub);
170 };
171}
172
Chris Lattnere7484012007-02-24 02:57:03 +0000173JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000174
Evan Cheng704bff92008-11-13 21:50:50 +0000175/// getFunctionStubIfAvailable - This returns a pointer to a function stub
176/// if it has already been created.
177void *JITResolver::getFunctionStubIfAvailable(Function *F) {
178 MutexGuard locked(TheJIT->lock);
179
180 // If we already have a stub for this function, recycle it.
181 void *&Stub = state.getFunctionToStubMap(locked)[F];
182 return Stub;
183}
184
Chris Lattner54266522004-11-20 23:57:07 +0000185/// getFunctionStub - This returns a pointer to a function stub, creating
186/// one on demand as needed.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000187void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000188 MutexGuard locked(TheJIT->lock);
189
Chris Lattner54266522004-11-20 23:57:07 +0000190 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000191 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000192 if (Stub) return Stub;
193
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000194 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
195 // case we must resolve the symbol now.
196 void *Actual = TheJIT->isLazyCompilationDisabled()
197 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
198
199 // If this is an external declaration, attempt to resolve the address now
200 // to place in the stub.
Dan Gohman69f93782009-01-05 05:32:42 +0000201 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000202 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000203
Dan Gohman69f93782009-01-05 05:32:42 +0000204 // If we resolved the symbol to a null address (eg. a weak external)
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000205 // don't emit a stub. Return a null pointer to the application. If dlsym
206 // stubs are enabled, not being able to resolve the address is not
207 // meaningful.
208 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
Dan Gohman69f93782009-01-05 05:32:42 +0000209 }
210
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000211 // Codegen a new stub, calling the lazy resolver or the actual address of the
212 // external function, if it was resolved.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000213 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000214 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000215
Chris Lattner870286a2006-06-01 17:29:22 +0000216 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000217 // If we are getting the stub for an external function, we really want the
218 // address of the stub in the GlobalAddressMap for the JIT, not the address
219 // of the external function.
220 TheJIT->updateGlobalMapping(F, Stub);
221 }
Chris Lattner54266522004-11-20 23:57:07 +0000222
Chris Lattnerbe3ae8e2009-03-05 06:48:16 +0000223 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
Bill Wendling832171c2006-12-07 20:04:42 +0000224 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000225
Chris Lattner54266522004-11-20 23:57:07 +0000226 // Finally, keep track of the stub-to-Function mapping so that the
227 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000228 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begemand6b7a242009-02-18 08:31:02 +0000229
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000230 // If we are JIT'ing non-lazily but need to call a function that does not
231 // exist yet, add it to the JIT's work list so that we can fill in the stub
232 // address later.
233 if (!Actual && TheJIT->isLazyCompilationDisabled())
234 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
235 TheJIT->addPendingFunction(F);
Nate Begemand6b7a242009-02-18 08:31:02 +0000236
Chris Lattner54266522004-11-20 23:57:07 +0000237 return Stub;
238}
239
Evan Cheng5594f122008-11-10 01:52:24 +0000240/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000241/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000242void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000243 MutexGuard locked(TheJIT->lock);
244
245 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000246 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
247 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000248
Evan Chenge4d783d2008-11-10 23:26:16 +0000249 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000250 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000251 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000252
Evan Cheng5594f122008-11-10 01:52:24 +0000253 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
Evan Chengbe8c03f2008-01-04 10:46:51 +0000254 << GV->getName() << "'\n";
255
Evan Cheng5594f122008-11-10 01:52:24 +0000256 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000257}
258
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000259/// getExternalFunctionStub - Return a stub for the function at the
260/// specified address, created lazily on demand.
261void *JITResolver::getExternalFunctionStub(void *FnAddr) {
262 // If we already have a stub for this function, recycle it.
263 void *&Stub = ExternalFnToStubMap[FnAddr];
264 if (Stub) return Stub;
265
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000266 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000267 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000268
Bill Wendling832171c2006-12-07 20:04:42 +0000269 DOUT << "JIT: Stub emitted at [" << Stub
270 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000271 return Stub;
272}
273
Andrew Lenharth6a974612005-07-28 12:44:13 +0000274unsigned JITResolver::getGOTIndexForAddr(void* addr) {
275 unsigned idx = revGOTMap[addr];
276 if (!idx) {
277 idx = ++nextGOTIndex;
278 revGOTMap[addr] = idx;
Evan Cheng366cf292008-11-07 22:30:29 +0000279 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000280 }
281 return idx;
282}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000283
Nate Begemand6b7a242009-02-18 08:31:02 +0000284void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
285 SmallVectorImpl<void*> &Ptrs) {
286 MutexGuard locked(TheJIT->lock);
287
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000288 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
289 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begemand6b7a242009-02-18 08:31:02 +0000290
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000291 for (FunctionToStubMapTy::iterator i = FM.begin(), e = FM.end(); i != e; ++i){
Nate Begemand6b7a242009-02-18 08:31:02 +0000292 Function *F = i->first;
293 if (F->isDeclaration() && F->hasExternalLinkage()) {
294 GVs.push_back(i->first);
295 Ptrs.push_back(i->second);
296 }
297 }
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000298 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begemand6b7a242009-02-18 08:31:02 +0000299 i != e; ++i) {
300 GVs.push_back(i->first);
301 Ptrs.push_back(i->second);
302 }
303}
304
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000305GlobalValue *JITResolver::invalidateStub(void *Stub) {
306 MutexGuard locked(TheJIT->lock);
307
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000308 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
309 StubToFunctionMapTy &SM = state.getStubToFunctionMap(locked);
310 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000311
312 // Look up the cheap way first, to see if it's a function stub we are
313 // invalidating. If so, remove it from both the forward and reverse maps.
314 if (SM.find(Stub) != SM.end()) {
315 Function *F = SM[Stub];
316 SM.erase(Stub);
317 FM.erase(F);
318 return F;
319 }
320
Nate Begeman841c6a42009-03-11 07:03:43 +0000321 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000322 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000323 i != e; ++i) {
324 if (i->second != Stub)
325 continue;
326 GlobalValue *GV = i->first;
327 GM.erase(i);
328 return GV;
329 }
330
Nate Begeman841c6a42009-03-11 07:03:43 +0000331 // Lastly, check to see if it's in the ExternalFnToStubMap.
332 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
333 e = ExternalFnToStubMap.end(); i != e; ++i) {
334 if (i->second != Stub)
335 continue;
336 ExternalFnToStubMap.erase(i);
337 break;
338 }
339
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000340 return 0;
341}
342
Chris Lattner54266522004-11-20 23:57:07 +0000343/// JITCompilerFn - This function is called when a lazy compilation stub has
344/// been entered. It looks up which function this stub corresponds to, compiles
345/// it if necessary, then returns the resultant function pointer.
346void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000347 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000348
349 Function* F = 0;
350 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000351
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000352 {
353 // Only lock for getting the Function. The call getPointerToFunction made
354 // in this function might trigger function materializing, which requires
355 // JIT lock to be unlocked.
356 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000357
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000358 // The address given to us for the stub may not be exactly right, it might be
359 // a little bit after the stub. As such, use upper_bound to find it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000360 StubToFunctionMapTy::iterator I =
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000361 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
362 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
363 "This is not a known stub!");
364 F = (--I)->second;
365 ActualPtr = I->first;
366 }
Chris Lattner54266522004-11-20 23:57:07 +0000367
Evan Cheng9da60f92007-06-30 00:10:37 +0000368 // If we have already code generated the function, just return the address.
369 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000370
Evan Cheng9da60f92007-06-30 00:10:37 +0000371 if (!Result) {
372 // Otherwise we don't have it, do lazy compilation now.
373
374 // If lazy compilation is disabled, emit a useful error message and abort.
375 if (TheJIT->isLazyCompilationDisabled()) {
376 cerr << "LLVM JIT requested to do lazy compilation of function '"
377 << F->getName() << "' when lazy compiles are disabled!\n";
378 abort();
379 }
380
381 // We might like to remove the stub from the StubToFunction map.
382 // We can't do that! Multiple threads could be stuck, waiting to acquire the
383 // lock above. As soon as the 1st function finishes compiling the function,
384 // the next one will be released, and needs to be able to find the function
385 // it needs to call.
386 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000387
Evan Cheng9da60f92007-06-30 00:10:37 +0000388 DOUT << "JIT: Lazily resolving function '" << F->getName()
389 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000390 << ActualPtr << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000391
Evan Cheng9da60f92007-06-30 00:10:37 +0000392 Result = TheJIT->getPointerToFunction(F);
393 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000394
395 // Reacquire the lock to erase the stub in the map.
396 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000397
398 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000399 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000400
401 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000402
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000403 // What we will do is set the compiled function address to map to the
404 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000405 // if they see it still using the stub address.
406 // Note: this is done so the Resolver doesn't have to manage GOT memory
407 // Do this without allocating map space if the target isn't using a GOT
408 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
409 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
410
Chris Lattner54266522004-11-20 23:57:07 +0000411 return Result;
412}
Chris Lattner688506d2003-08-14 18:35:27 +0000413
Chris Lattner8ac66c12008-04-04 05:51:42 +0000414//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000415// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000416//
Chris Lattner688506d2003-08-14 18:35:27 +0000417namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000418 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
419 /// used to output functions to memory for execution.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +0000420 class JITEmitter : public JITCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000421 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000422
Chris Lattner6125fdd2003-05-09 03:30:07 +0000423 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000424 // save BufferBegin/BufferEnd/CurBufferPtr here.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000425 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000426
Chris Lattner5be478f2004-11-20 03:46:14 +0000427 /// Relocations - These are the relocations that the function needs, as
428 /// emitted.
429 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000430
431 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
432 /// It is filled in by the StartMachineBasicBlock callback and queried by
433 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000434 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000435
Chris Lattner239862c2006-02-09 04:49:59 +0000436 /// ConstantPool - The constant pool for the current function.
437 ///
438 MachineConstantPool *ConstantPool;
439
440 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
441 ///
442 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000443
Evan Cheng1606e8e2009-03-13 07:51:59 +0000444 /// ConstPoolAddresses - Addresses of individual constant pool entries.
445 ///
446 SmallVector<uintptr_t, 8> ConstPoolAddresses;
447
Nate Begeman019f8512006-09-10 23:03:44 +0000448 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000449 ///
450 MachineJumpTableInfo *JumpTable;
451
452 /// JumpTableBase - A pointer to the first entry in the jump table.
453 ///
454 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000455
Chris Lattnere7484012007-02-24 02:57:03 +0000456 /// Resolver - This contains info about the currently resolved functions.
457 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000458
459 /// DE - The dwarf emitter for the jit.
460 JITDwarfEmitter *DE;
461
462 /// LabelLocations - This vector is a mapping from Label ID's to their
463 /// address.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000464 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000465
466 /// MMI - Machine module info for exception informations
467 MachineModuleInfo* MMI;
468
Dale Johannesendd947ea2008-08-07 01:30:15 +0000469 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000470 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000471
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000472 // CurFn - The llvm function being emitted. Only valid during
473 // finishFunction().
474 const Function *CurFn;
475
476 // CurFnStubUses - For a given Function, a vector of stubs that it
477 // references. This facilitates the JIT detecting that a stub is no
478 // longer used, so that it may be deallocated.
479 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
480
481 // StubFnRefs - For a given pointer to a stub, a set of Functions which
482 // reference the stub. When the count of a stub's references drops to zero,
483 // the stub is unused.
484 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
485
Nate Begeman841c6a42009-03-11 07:03:43 +0000486 // ExtFnStubs - A map of external function names to stubs which have entries
487 // in the JITResolver's ExternalFnToStubMap.
488 StringMap<void *> ExtFnStubs;
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +0000489
Chris Lattnere7484012007-02-24 02:57:03 +0000490 public:
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000491 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0) {
Chris Lattner9f2f1422007-12-06 01:08:09 +0000492 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000493 if (jit.getJITInfo().needsGOT()) {
494 MemMgr->AllocateGOT();
495 DOUT << "JIT is managing a GOT\n";
496 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000497
498 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000499 }
500 ~JITEmitter() {
501 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000502 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000503 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000504
505 /// classof - Methods for support type inquiry through isa, cast, and
506 /// dyn_cast:
507 ///
508 static inline bool classof(const JITEmitter*) { return true; }
509 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000510
511 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000512
513 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000514 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000515
516 void emitConstantPool(MachineConstantPool *MCP);
517 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000518 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000519
Evan Chengce4a70b2008-11-08 08:02:53 +0000520 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000521 unsigned Alignment = 1);
Nate Begemand6b7a242009-02-18 08:31:02 +0000522 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
523 unsigned StubSize);
Evan Chengce4a70b2008-11-08 08:02:53 +0000524 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000525
Nuno Lopescef75272008-10-21 11:42:16 +0000526 /// allocateSpace - Reserves space in the current block if any, or
527 /// allocate a new one of the given size.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000528 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000529
Chris Lattner5be478f2004-11-20 03:46:14 +0000530 virtual void addRelocation(const MachineRelocation &MR) {
531 Relocations.push_back(MR);
532 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000533
534 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
535 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
536 MBBLocations.resize((MBB->getNumber()+1)*2);
537 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Evan Cheng366cf292008-11-07 22:30:29 +0000538 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
539 << (void*) getCurrentPCValue() << "]\n";
Chris Lattnerb4432f32006-05-03 17:10:41 +0000540 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000541
Evan Cheng5788d1a2008-12-10 02:32:19 +0000542 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
543 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000544
Evan Cheng5788d1a2008-12-10 02:32:19 +0000545 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000546 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
547 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
548 return MBBLocations[MBB->getNumber()];
549 }
550
Chris Lattnere993cc22006-05-11 23:08:08 +0000551 /// deallocateMemForFunction - Deallocate all memory for the specified
552 /// function body.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000553 void deallocateMemForFunction(Function *F);
Nate Begeman841c6a42009-03-11 07:03:43 +0000554
555 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
556 /// using the stub at the specified address. Allows
557 /// deallocateMemForFunction to also remove stubs no longer referenced.
558 void AddStubToCurrentFunction(void *Stub);
559
560 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
561 /// MachineRelocations that reference external functions by name.
562 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000563
564 virtual void emitLabel(uint64_t LabelID) {
565 if (LabelLocations.size() <= LabelID)
566 LabelLocations.resize((LabelID+1)*2);
567 LabelLocations[LabelID] = getCurrentPCValue();
568 }
569
Evan Cheng5788d1a2008-12-10 02:32:19 +0000570 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000571 assert(LabelLocations.size() > (unsigned)LabelID &&
572 LabelLocations[LabelID] && "Label not emitted!");
573 return LabelLocations[LabelID];
574 }
575
576 virtual void setModuleInfo(MachineModuleInfo* Info) {
577 MMI = Info;
578 if (ExceptionHandling) DE->setModuleInfo(Info);
579 }
580
Jim Grosbachcce6c292008-10-03 16:17:20 +0000581 void setMemoryExecutable(void) {
582 MemMgr->setMemoryExecutable();
583 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000584
585 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000586
Chris Lattner54266522004-11-20 23:57:07 +0000587 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000588 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000589 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000590 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000591 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
592 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
593 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
594 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000595 };
596}
597
Chris Lattner166f2262004-11-22 22:00:25 +0000598void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
599 bool DoesntNeedStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000600 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000601 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000602
Chris Lattner18e04592008-06-25 20:21:35 +0000603 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000604 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000605
606 // If we have already compiled the function, return a pointer to its body.
607 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000608 void *ResultPtr;
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000609 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
Evan Cheng704bff92008-11-13 21:50:50 +0000610 // Return the function stub if it's already created.
611 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000612 if (ResultPtr)
613 AddStubToCurrentFunction(ResultPtr);
614 } else {
Evan Cheng704bff92008-11-13 21:50:50 +0000615 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000616 }
Chris Lattner54266522004-11-20 23:57:07 +0000617 if (ResultPtr) return ResultPtr;
618
Nate Begemand6b7a242009-02-18 08:31:02 +0000619 // If this is an external function pointer, we can force the JIT to
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000620 // 'compile' it, which really just adds it to the map. In dlsym mode,
621 // external functions are forced through a stub, regardless of reloc type.
622 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
623 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
Nate Begemand6b7a242009-02-18 08:31:02 +0000624 return TheJIT->getPointerToFunction(F);
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000625
Chris Lattner5e225582004-11-21 03:37:42 +0000626 // Okay, the function has not been compiled yet, if the target callback
627 // mechanism is capable of rewriting the instruction directly, prefer to do
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000628 // that instead of emitting a stub. This uses the lazy resolver, so is not
629 // legal if lazy compilation is disabled.
630 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Chris Lattnere7484012007-02-24 02:57:03 +0000631 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000632
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000633 // Otherwise, we have to emit a stub.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000634 void *StubAddr = Resolver.getFunctionStub(F);
635
636 // Add the stub to the current function's list of referenced stubs, so we can
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000637 // deallocate them if the current function is ever freed. It's possible to
638 // return null from getFunctionStub in the case of a weak extern that fails
639 // to resolve.
640 if (StubAddr)
641 AddStubToCurrentFunction(StubAddr);
642
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000643 return StubAddr;
Chris Lattner54266522004-11-20 23:57:07 +0000644}
645
Evan Cheng5594f122008-11-10 01:52:24 +0000646void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000647 bool NoNeedStub) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000648 // Make sure GV is emitted first, and create a stub containing the fully
649 // resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000650 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000651 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
652
653 // Add the stub to the current function's list of referenced stubs, so we can
654 // deallocate them if the current function is ever freed.
655 AddStubToCurrentFunction(StubAddr);
656
657 return StubAddr;
658}
659
660void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
661 if (!TheJIT->areDlsymStubsEnabled())
662 return;
663
664 assert(CurFn && "Stub added to current function, but current function is 0!");
665
666 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
667 StubsUsed.push_back(StubAddr);
668
669 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
670 FnRefs.insert(CurFn);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000671}
672
Evan Cheng1606e8e2009-03-13 07:51:59 +0000673static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
674 const TargetData *TD) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000675 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
676 if (Constants.empty()) return 0;
677
Evan Cheng1606e8e2009-03-13 07:51:59 +0000678 unsigned Size = 0;
679 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
680 MachineConstantPoolEntry CPE = Constants[i];
681 unsigned AlignMask = CPE.getAlignment() - 1;
682 Size = (Size + AlignMask) & ~AlignMask;
683 const Type *Ty = CPE.getType();
Duncan Sands777d2302009-05-09 07:06:46 +0000684 Size += TD->getTypeAllocSize(Ty);
Evan Cheng1606e8e2009-03-13 07:51:59 +0000685 }
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000686 return Size;
687}
688
689static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
690 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
691 if (JT.empty()) return 0;
692
693 unsigned NumEntries = 0;
694 for (unsigned i = 0, e = JT.size(); i != e; ++i)
695 NumEntries += JT[i].MBBs.size();
696
697 unsigned EntrySize = MJTI->getEntrySize();
698
699 return NumEntries * EntrySize;
700}
701
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000702static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000703 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000704 // Since we do not know where the buffer will be allocated, be pessimistic.
705 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000706}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000707
Dale Johannesendd947ea2008-08-07 01:30:15 +0000708/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
709/// into the running total Size.
710
711unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
712 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000713 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000714 size_t GVAlign =
715 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000716 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000717 DEBUG(GV->dump());
718 // Assume code section ends with worst possible alignment, so first
719 // variable needs maximal padding.
720 if (Size==0)
721 Size = 1;
722 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
723 Size += GVSize;
724 return Size;
725}
726
727/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
728/// but are referenced from the constant; put them in GVSet and add their
729/// size into the running total Size.
730
731unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
732 unsigned Size) {
733 // If its undefined, return the garbage.
734 if (isa<UndefValue>(C))
735 return Size;
736
737 // If the value is a ConstantExpr
738 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
739 Constant *Op0 = CE->getOperand(0);
740 switch (CE->getOpcode()) {
741 case Instruction::GetElementPtr:
742 case Instruction::Trunc:
743 case Instruction::ZExt:
744 case Instruction::SExt:
745 case Instruction::FPTrunc:
746 case Instruction::FPExt:
747 case Instruction::UIToFP:
748 case Instruction::SIToFP:
749 case Instruction::FPToUI:
750 case Instruction::FPToSI:
751 case Instruction::PtrToInt:
752 case Instruction::IntToPtr:
753 case Instruction::BitCast: {
754 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
755 break;
756 }
757 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000758 case Instruction::FAdd:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000759 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000760 case Instruction::FSub:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000761 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000762 case Instruction::FMul:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000763 case Instruction::UDiv:
764 case Instruction::SDiv:
765 case Instruction::URem:
766 case Instruction::SRem:
767 case Instruction::And:
768 case Instruction::Or:
769 case Instruction::Xor: {
770 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
771 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
772 break;
773 }
774 default: {
775 cerr << "ConstantExpr not handled: " << *CE << "\n";
776 abort();
777 }
778 }
779 }
780
781 if (C->getType()->getTypeID() == Type::PointerTyID)
782 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000783 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000784 Size = addSizeOfGlobal(GV, Size);
785
786 return Size;
787}
788
789/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
790/// but are referenced from the given initializer.
791
792unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
793 unsigned Size) {
794 if (!isa<UndefValue>(Init) &&
795 !isa<ConstantVector>(Init) &&
796 !isa<ConstantAggregateZero>(Init) &&
797 !isa<ConstantArray>(Init) &&
798 !isa<ConstantStruct>(Init) &&
799 Init->getType()->isFirstClassType())
800 Size = addSizeOfGlobalsInConstantVal(Init, Size);
801 return Size;
802}
803
804/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
805/// globals; then walk the initializers of those globals looking for more.
806/// If their size has not been considered yet, add it into the running total
807/// Size.
808
809unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
810 unsigned Size = 0;
811 GVSet.clear();
812
813 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
814 MBB != E; ++MBB) {
815 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
816 I != E; ++I) {
817 const TargetInstrDesc &Desc = I->getDesc();
818 const MachineInstr &MI = *I;
819 unsigned NumOps = Desc.getNumOperands();
820 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
821 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000822 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000823 GlobalValue* V = MO.getGlobal();
824 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
825 if (!GV)
826 continue;
827 // If seen in previous function, it will have an entry here.
828 if (TheJIT->getPointerToGlobalIfAvailable(GV))
829 continue;
830 // If seen earlier in this function, it will have an entry here.
831 // FIXME: it should be possible to combine these tables, by
832 // assuming the addresses of the new globals in this module
833 // start at 0 (or something) and adjusting them after codegen
834 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000835 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000836 // A variable as yet unseen. Add in its size.
837 Size = addSizeOfGlobal(GV, Size);
838 }
839 }
840 }
841 }
Evan Chengeb5d95a2008-11-06 17:46:04 +0000842 DOUT << "JIT: About to look through initializers\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000843 // Look for more globals that are referenced only from initializers.
844 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +0000845 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000846 I != GVSet.end(); I++) {
847 const GlobalVariable* GV = *I;
848 if (GV->hasInitializer())
849 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
850 }
851
852 return Size;
853}
854
Chris Lattner166f2262004-11-22 22:00:25 +0000855void JITEmitter::startFunction(MachineFunction &F) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000856 DOUT << "JIT: Starting CodeGen of Function "
857 << F.getFunction()->getName() << "\n";
858
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000859 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000860 // Set the memory writable, if it's not already
861 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000862 if (MemMgr->NeedsExactSize()) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000863 DOUT << "JIT: ExactSize\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000864 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
865 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
866 MachineConstantPool *MCP = F.getConstantPool();
867
868 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000869 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000870
871 // Add the alignment of the constant pool
Evan Cheng1606e8e2009-03-13 07:51:59 +0000872 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000873
874 // Add the constant pool size
Evan Cheng1606e8e2009-03-13 07:51:59 +0000875 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000876
877 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000878 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000879
880 // Add the jump table size
881 ActualSize += GetJumpTableSizeInBytes(MJTI);
882
883 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000884 ActualSize = RoundUpToAlign(ActualSize,
885 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000886
887 // Add the function size
888 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000889
Evan Chengeb5d95a2008-11-06 17:46:04 +0000890 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000891 // Add the size of the globals that will be allocated after this function.
892 // These are all the ones referenced from this function that were not
893 // previously allocated.
894 ActualSize += GetSizeOfGlobalsInBytes(F);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000895 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000896 }
897
Chris Lattner8907b4b2007-12-05 23:39:57 +0000898 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
899 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +0000900 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000901
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000902 // Ensure the constant pool/jump table info is at least 4-byte aligned.
903 emitAlignment(16);
904
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000905 emitConstantPool(F.getConstantPool());
906 initJumpTableInfo(F.getJumpTableInfo());
907
908 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000909 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000910 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +0000911
Chris Lattnerb4432f32006-05-03 17:10:41 +0000912 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000913}
914
Chris Lattner43b429b2006-05-02 18:27:26 +0000915bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000916 if (CurBufferPtr == BufferEnd) {
917 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +0000918 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +0000919 abort();
920 }
921
Jim Laskeyb92767a2006-12-14 22:53:42 +0000922 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +0000923
Chris Lattnera8279532006-06-16 18:09:26 +0000924 // FnStart is the start of the text, not the start of the constant pool and
925 // other per-function data.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000926 uint8_t *FnStart =
927 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000928
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +0000929 // FnEnd is the end of the function's machine code.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000930 uint8_t *FnEnd = CurBufferPtr;
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +0000931
Chris Lattner5be478f2004-11-20 03:46:14 +0000932 if (!Relocations.empty()) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000933 CurFn = F.getFunction();
Chris Lattnere884dc22005-07-20 16:29:20 +0000934 NumRelos += Relocations.size();
935
Chris Lattner5be478f2004-11-20 03:46:14 +0000936 // Resolve the relocations to concrete pointers.
937 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
938 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +0000939 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +0000940 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +0000941 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +0000942 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
943 false);
Evan Chengd7398c92008-11-08 07:37:34 +0000944 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Evan Chengca66b082008-11-08 07:22:53 +0000945 << ResultPtr << "]\n";
Misha Brukmanf976c852005-04-21 22:55:34 +0000946
Evan Chengef5784e2008-10-29 23:54:46 +0000947 // If the target REALLY wants a stub for this function, emit it now.
Nate Begeman841c6a42009-03-11 07:03:43 +0000948 if (!MR.doesntNeedStub()) {
949 if (!TheJIT->areDlsymStubsEnabled()) {
950 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
951 } else {
952 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
953 if (!Stub) {
954 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
955 AddStubToCurrentFunction(Stub);
956 }
957 ResultPtr = Stub;
958 }
959 }
Evan Chengef5784e2008-10-29 23:54:46 +0000960 } else if (MR.isGlobalValue()) {
961 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
962 BufferBegin+MR.getMachineCodeOffset(),
963 MR.doesntNeedStub());
Evan Cheng5594f122008-11-10 01:52:24 +0000964 } else if (MR.isIndirectSymbol()) {
965 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +0000966 BufferBegin+MR.getMachineCodeOffset(),
967 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +0000968 } else if (MR.isBasicBlock()) {
969 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
970 } else if (MR.isConstantPoolIndex()) {
971 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
972 } else {
973 assert(MR.isJumpTableIndex());
974 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
975 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000976
Evan Chengef5784e2008-10-29 23:54:46 +0000977 MR.setResultPointer(ResultPtr);
978 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000979
Andrew Lenharth6a974612005-07-28 12:44:13 +0000980 // if we are managing the GOT and the relocation wants an index,
981 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +0000982 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000983 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000984 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000985 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000986 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +0000987 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +0000988 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +0000989 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000990 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000991 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000992 }
993
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000994 CurFn = 0;
Chris Lattner43b429b2006-05-02 18:27:26 +0000995 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +0000996 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000997 }
998
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000999 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +00001000 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001001 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001002 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001003 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +00001004 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1005 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001006 }
1007 }
1008
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001009 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1010 // global variables that were referenced in the relocations.
1011 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
Evan Cheng5788d1a2008-12-10 02:32:19 +00001012
1013 if (CurBufferPtr == BufferEnd) {
1014 // FIXME: Allocate more space, then try again.
1015 cerr << "JIT: Ran out of space for generated machine code!\n";
1016 abort();
1017 }
1018
Nuno Lopescef75272008-10-21 11:42:16 +00001019 BufferBegin = CurBufferPtr = 0;
1020 NumBytes += FnEnd-FnStart;
1021
Evan Cheng55fc2802006-07-25 20:40:54 +00001022 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +00001023 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001024
1025 JITEvent_EmittedFunctionDetails Details;
1026 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
1027 Details);
Evan Cheng55fc2802006-07-25 20:40:54 +00001028
Bill Wendling832171c2006-12-07 20:04:42 +00001029 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1030 << "] Function: " << F.getFunction()->getName()
1031 << ": " << (FnEnd-FnStart) << " bytes of text, "
1032 << Relocations.size() << " relocations\n";
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +00001033
Chris Lattner5be478f2004-11-20 03:46:14 +00001034 Relocations.clear();
Evan Cheng1606e8e2009-03-13 07:51:59 +00001035 ConstPoolAddresses.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +00001036
Evan Chengbc4707a2008-09-18 07:54:21 +00001037 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +00001038 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +00001039
Chris Lattnerc5633c22007-01-20 20:51:43 +00001040#ifndef NDEBUG
Evan Chenga7916f52008-11-05 23:44:08 +00001041 {
Evan Chenge7c35512008-11-12 08:22:43 +00001042 if (sys::hasDisassembler()) {
1043 DOUT << "JIT: Disassembled code:\n";
Evan Chengeb5d95a2008-11-06 17:46:04 +00001044 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001045 } else {
1046 DOUT << "JIT: Binary code:\n";
Evan Chenga7916f52008-11-05 23:44:08 +00001047 DOUT << std::hex;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001048 uint8_t* q = FnStart;
Evan Chenge7c35512008-11-12 08:22:43 +00001049 for (int i = 0; q < FnEnd; q += 4, ++i) {
1050 if (i == 4)
1051 i = 0;
1052 if (i == 0)
1053 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1054 << (long)(q - FnStart) << ": ";
1055 bool Done = false;
1056 for (int j = 3; j >= 0; --j) {
1057 if (q + j >= FnEnd)
1058 Done = true;
1059 else
1060 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1061 }
1062 if (Done)
1063 break;
1064 DOUT << ' ';
1065 if (i == 3)
Evan Cheng6863fb02008-11-06 01:18:29 +00001066 DOUT << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001067 }
1068 DOUT << std::dec;
Evan Cheng6863fb02008-11-06 01:18:29 +00001069 DOUT<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001070 }
1071 }
Chris Lattnerc5633c22007-01-20 20:51:43 +00001072#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001073 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001074 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001075 SavedBufferBegin = BufferBegin;
1076 SavedBufferEnd = BufferEnd;
1077 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001078
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001079 if (MemMgr->NeedsExactSize()) {
1080 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001081 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001082
1083 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1084 ActualSize);
1085 BufferEnd = BufferBegin+ActualSize;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001086 uint8_t* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +00001087 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1088 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001089 BufferBegin = SavedBufferBegin;
1090 BufferEnd = SavedBufferEnd;
1091 CurBufferPtr = SavedCurBufferPtr;
1092
1093 TheJIT->RegisterTable(FrameRegister);
1094 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001095
1096 if (MMI)
1097 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001098
Chris Lattner43b429b2006-05-02 18:27:26 +00001099 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001100}
1101
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001102/// deallocateMemForFunction - Deallocate all memory for the specified
1103/// function body. Also drop any references the function has to stubs.
1104void JITEmitter::deallocateMemForFunction(Function *F) {
1105 MemMgr->deallocateMemForFunction(F);
1106
1107 // If the function did not reference any stubs, return.
1108 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1109 return;
1110
1111 // For each referenced stub, erase the reference to this function, and then
1112 // erase the list of referenced stubs.
1113 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1114 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1115 void *Stub = StubList[i];
Nate Begeman841c6a42009-03-11 07:03:43 +00001116
1117 // If we already invalidated this stub for this function, continue.
1118 if (StubFnRefs.count(Stub) == 0)
1119 continue;
1120
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001121 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1122 FnRefs.erase(F);
1123
1124 // If this function was the last reference to the stub, invalidate the stub
1125 // in the JITResolver. Were there a memory manager deallocateStub routine,
1126 // we could call that at this point too.
1127 if (FnRefs.empty()) {
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001128 DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
Nate Begeman841c6a42009-03-11 07:03:43 +00001129 StubFnRefs.erase(Stub);
1130
1131 // Invalidate the stub. If it is a GV stub, update the JIT's global
1132 // mapping for that GV to zero, otherwise, search the string map of
1133 // external function names to stubs and remove the entry for this stub.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001134 GlobalValue *GV = Resolver.invalidateStub(Stub);
Nate Begeman841c6a42009-03-11 07:03:43 +00001135 if (GV) {
1136 TheJIT->updateGlobalMapping(GV, 0);
1137 } else {
1138 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1139 e = ExtFnStubs.end(); i != e; ++i) {
1140 if (i->second == Stub) {
1141 ExtFnStubs.erase(i);
1142 break;
1143 }
1144 }
1145 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001146 }
1147 }
1148 CurFnStubUses.erase(F);
1149}
1150
1151
Evan Cheng5788d1a2008-12-10 02:32:19 +00001152void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +00001153 if (BufferBegin)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001154 return JITCodeEmitter::allocateSpace(Size, Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +00001155
1156 // create a new memory block if there is no active one.
1157 // care must be taken so that BufferBegin is invalidated when a
1158 // block is trimmed
1159 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1160 BufferEnd = BufferBegin+Size;
1161 return CurBufferPtr;
1162}
1163
Chris Lattner166f2262004-11-22 22:00:25 +00001164void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001165 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001166 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001167
Chris Lattnerfa77d432006-02-09 04:22:52 +00001168 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001169 if (Constants.empty()) return;
1170
Evan Cheng1606e8e2009-03-13 07:51:59 +00001171 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1172 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng97b8c402008-04-12 00:22:01 +00001173 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001174 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001175
1176 if (ConstantPoolBase == 0) return; // Buffer overflow.
1177
Evan Cheng97b8c402008-04-12 00:22:01 +00001178 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1179 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1180
Chris Lattner239862c2006-02-09 04:49:59 +00001181 // Initialize the memory for all of the constant pool entries.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001182 unsigned Offset = 0;
Chris Lattner3029f922006-02-09 04:46:04 +00001183 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng1606e8e2009-03-13 07:51:59 +00001184 MachineConstantPoolEntry CPE = Constants[i];
1185 unsigned AlignMask = CPE.getAlignment() - 1;
1186 Offset = (Offset + AlignMask) & ~AlignMask;
1187
1188 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1189 ConstPoolAddresses.push_back(CAddr);
1190 if (CPE.isMachineConstantPoolEntry()) {
Evan Chengcd5731d2006-09-12 20:59:59 +00001191 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +00001192 cerr << "Initialize memory with machine specific constant pool entry"
1193 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +00001194 abort();
1195 }
Evan Cheng1606e8e2009-03-13 07:51:59 +00001196 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1197 DOUT << "JIT: CP" << i << " at [0x"
1198 << std::hex << CAddr << std::dec << "]\n";
1199
1200 const Type *Ty = CPE.Val.ConstVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00001201 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
Chris Lattner1cc08382003-01-13 01:00:12 +00001202 }
1203}
1204
Nate Begeman37efe672006-04-22 18:53:45 +00001205void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001206 if (TheJIT->getJITInfo().hasCustomJumpTables())
1207 return;
1208
Nate Begeman37efe672006-04-22 18:53:45 +00001209 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1210 if (JT.empty()) return;
1211
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001212 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001213 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001214 NumEntries += JT[i].MBBs.size();
1215
1216 unsigned EntrySize = MJTI->getEntrySize();
1217
Nate Begeman37efe672006-04-22 18:53:45 +00001218 // Just allocate space for all the jump tables now. We will fix up the actual
1219 // MBB entries in the tables after we emit the code for each block, since then
1220 // we will know the final locations of the MBBs in memory.
1221 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001222 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001223}
1224
Jim Laskeyb92767a2006-12-14 22:53:42 +00001225void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001226 if (TheJIT->getJITInfo().hasCustomJumpTables())
1227 return;
1228
Nate Begeman37efe672006-04-22 18:53:45 +00001229 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001230 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001231
Jim Laskeyb92767a2006-12-14 22:53:42 +00001232 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001233 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1234 // For each jump table, place the offset from the beginning of the table
1235 // to the target address.
1236 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001237
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001238 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1239 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1240 // Store the offset of the basic block for this jump table slot in the
1241 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001242 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001243 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001244 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001245 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1246 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001247 }
1248 } else {
1249 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1250
1251 // For each jump table, map each target in the jump table to the address of
1252 // an emitted MachineBasicBlock.
1253 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1254
1255 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1256 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1257 // Store the address of the basic block for this jump table slot in the
1258 // memory we allocated for the jump table in 'initJumpTableInfo'
1259 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1260 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1261 }
Nate Begeman37efe672006-04-22 18:53:45 +00001262 }
1263}
1264
Evan Chengce4a70b2008-11-08 08:02:53 +00001265void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1266 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001267 SavedBufferBegin = BufferBegin;
1268 SavedBufferEnd = BufferEnd;
1269 SavedCurBufferPtr = CurBufferPtr;
1270
Evan Chengce4a70b2008-11-08 08:02:53 +00001271 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001272 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001273}
1274
Nate Begemand6b7a242009-02-18 08:31:02 +00001275void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1276 unsigned StubSize) {
1277 SavedBufferBegin = BufferBegin;
1278 SavedBufferEnd = BufferEnd;
1279 SavedCurBufferPtr = CurBufferPtr;
1280
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001281 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
Nate Begemand6b7a242009-02-18 08:31:02 +00001282 BufferEnd = BufferBegin+StubSize+1;
1283}
1284
Evan Chengce4a70b2008-11-08 08:02:53 +00001285void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001286 NumBytes += getCurrentPCOffset();
1287 std::swap(SavedBufferBegin, BufferBegin);
1288 BufferEnd = SavedBufferEnd;
1289 CurBufferPtr = SavedCurBufferPtr;
1290 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001291}
1292
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001293// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1294// in the constant pool that was last emitted with the 'emitConstantPool'
1295// method.
1296//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001297uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001298 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001299 "Invalid ConstantPoolIndex!");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001300 return ConstPoolAddresses[ConstantNum];
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001301}
1302
Nate Begeman37efe672006-04-22 18:53:45 +00001303// getJumpTableEntryAddress - Return the address of the JumpTable with index
1304// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1305//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001306uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001307 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1308 assert(Index < JT.size() && "Invalid jump table index!");
1309
1310 unsigned Offset = 0;
1311 unsigned EntrySize = JumpTable->getEntrySize();
1312
1313 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001314 Offset += JT[i].MBBs.size();
1315
1316 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001317
Evan Cheng5788d1a2008-12-10 02:32:19 +00001318 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001319}
1320
Chris Lattnere993cc22006-05-11 23:08:08 +00001321//===----------------------------------------------------------------------===//
1322// Public interface to this file
1323//===----------------------------------------------------------------------===//
1324
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001325JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
Chris Lattner9f2f1422007-12-06 01:08:09 +00001326 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +00001327}
1328
Misha Brukmand69c1e62003-07-28 19:09:06 +00001329// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001330// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001331// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1332// need to resolve function(s) that are being mis-codegenerated, so we need to
1333// resolve their addresses at runtime, and this is the way to do it.
1334extern "C" {
1335 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001336 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001337 return TheJIT->getPointerToFunction(F);
1338 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001339 }
1340}
Chris Lattnere993cc22006-05-11 23:08:08 +00001341
1342// getPointerToFunctionOrStub - If the specified function has been
1343// code-gen'd, return a pointer to the function. If not, compile it, or use
1344// a stub to implement lazy compilation if available.
1345//
1346void *JIT::getPointerToFunctionOrStub(Function *F) {
1347 // If we have already code generated the function, just return the address.
1348 if (void *Addr = getPointerToGlobalIfAvailable(F))
1349 return Addr;
1350
Chris Lattnere7484012007-02-24 02:57:03 +00001351 // Get a stub if the target supports it.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001352 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Evan Chenga044dfc2008-08-20 00:28:12 +00001353 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001354 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001355}
1356
Nate Begemand6b7a242009-02-18 08:31:02 +00001357void JIT::updateFunctionStub(Function *F) {
1358 // Get the empty stub we generated earlier.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001359 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001360 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1361 void *Stub = JE->getJITResolver().getFunctionStub(F);
1362
1363 // Tell the target jit info to rewrite the stub at the specified address,
1364 // rather than creating a new one.
1365 void *Addr = getPointerToGlobalIfAvailable(F);
1366 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1367}
1368
1369/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1370/// that were emitted during code generation.
1371///
1372void JIT::updateDlsymStubTable() {
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001373 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001374 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1375
1376 SmallVector<GlobalValue*, 8> GVs;
1377 SmallVector<void*, 8> Ptrs;
Nate Begeman841c6a42009-03-11 07:03:43 +00001378 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
Nate Begemand6b7a242009-02-18 08:31:02 +00001379
1380 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1381
Nate Begeman841c6a42009-03-11 07:03:43 +00001382 unsigned nStubs = GVs.size() + ExtFns.size();
1383
Nate Begemand6b7a242009-02-18 08:31:02 +00001384 // If there are no relocatable stubs, return.
Nate Begeman841c6a42009-03-11 07:03:43 +00001385 if (nStubs == 0)
Nate Begemand6b7a242009-02-18 08:31:02 +00001386 return;
1387
1388 // If there are no new relocatable stubs, return.
1389 void *CurTable = JE->getMemMgr()->getDlsymTable();
Nate Begeman841c6a42009-03-11 07:03:43 +00001390 if (CurTable && (*(unsigned *)CurTable == nStubs))
Nate Begemand6b7a242009-02-18 08:31:02 +00001391 return;
1392
1393 // Calculate the size of the stub info
Nate Begeman841c6a42009-03-11 07:03:43 +00001394 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
Nate Begemand6b7a242009-02-18 08:31:02 +00001395
1396 SmallVector<unsigned, 8> Offsets;
1397 for (unsigned i = 0; i != GVs.size(); ++i) {
1398 Offsets.push_back(offset);
1399 offset += GVs[i]->getName().length() + 1;
1400 }
Nate Begeman841c6a42009-03-11 07:03:43 +00001401 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1402 i != e; ++i) {
1403 Offsets.push_back(offset);
1404 offset += strlen(i->first()) + 1;
1405 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001406
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001407 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begemand6b7a242009-02-18 08:31:02 +00001408 JE->startGVStub(0, offset, 4);
1409
1410 // Emit the number of records
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001411 JE->emitInt32(nStubs);
Nate Begemand6b7a242009-02-18 08:31:02 +00001412
1413 // Emit the string offsets
Nate Begeman841c6a42009-03-11 07:03:43 +00001414 for (unsigned i = 0; i != nStubs; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001415 JE->emitInt32(Offsets[i]);
Nate Begemand6b7a242009-02-18 08:31:02 +00001416
Nate Begeman66941982009-03-04 19:10:38 +00001417 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1418 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1419 // relocation can write the relocated pointer at the appropriate place in
1420 // the stub.
1421 for (unsigned i = 0; i != GVs.size(); ++i) {
1422 intptr_t Ptr = (intptr_t)Ptrs[i];
1423 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1424
1425 if (isa<Function>(GVs[i]))
1426 Ptr |= (intptr_t)1;
1427
Nate Begeman841c6a42009-03-11 07:03:43 +00001428 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001429 JE->emitInt64(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001430 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001431 JE->emitInt32(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001432 }
1433 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1434 i != e; ++i) {
1435 intptr_t Ptr = (intptr_t)i->second | 1;
1436
1437 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001438 JE->emitInt64(Ptr);
Nate Begemand6b7a242009-02-18 08:31:02 +00001439 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001440 JE->emitInt32(Ptr);
Nate Begeman66941982009-03-04 19:10:38 +00001441 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001442
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001443 // Emit the strings.
Nate Begemand6b7a242009-02-18 08:31:02 +00001444 for (unsigned i = 0; i != GVs.size(); ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001445 JE->emitString(GVs[i]->getName());
Nate Begeman841c6a42009-03-11 07:03:43 +00001446 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1447 i != e; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001448 JE->emitString(i->first());
Nate Begemand6b7a242009-02-18 08:31:02 +00001449
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001450 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1451 // deallocate space for the old one, if one existed.
Nate Begemand6b7a242009-02-18 08:31:02 +00001452 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1453}
1454
Chris Lattnere993cc22006-05-11 23:08:08 +00001455/// freeMachineCodeForFunction - release machine code memory for given Function.
1456///
1457void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001458
Chris Lattnere993cc22006-05-11 23:08:08 +00001459 // Delete translation for this from the ExecutionEngine, so it will get
1460 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001461 void *OldPtr = updateGlobalMapping(F, 0);
1462
1463 if (OldPtr)
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001464 TheJIT->NotifyFreeingMachineCode(*F, OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001465
1466 // Free the actual memory for the function body and related stuff.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001467 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1468 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001469}