blob: 43f23e443426a5fa491144721d08260cc51b5fcc [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"
Chris Lattner8907b4b2007-12-05 23:39:57 +000027#include "llvm/ExecutionEngine/JITMemoryManager.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000028#include "llvm/ExecutionEngine/GenericValue.h"
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +000029#include "llvm/CodeGen/MachineCodeInfo.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000030#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000031#include "llvm/Target/TargetJITInfo.h"
Jim Laskeyacd80ac2006-12-14 19:17:33 +000032#include "llvm/Target/TargetMachine.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000033#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000034#include "llvm/Support/Debug.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000035#include "llvm/Support/MutexGuard.h"
Nick Lewycky848b3142009-04-19 18:32:03 +000036#include "llvm/Support/ValueHandle.h"
Anton Korobeynikovfd58e6e2007-01-23 10:26:08 +000037#include "llvm/System/Disassembler.h"
Chris Lattnerbc52cad2008-06-25 17:18:44 +000038#include "llvm/System/Memory.h"
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +000039#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng47c01a02008-11-07 09:02:17 +000040#include "llvm/ADT/SmallPtrSet.h"
Nate Begemand6b7a242009-02-18 08:31:02 +000041#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000042#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000043#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000044#ifndef NDEBUG
45#include <iomanip>
46#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000047using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000048
Chris Lattner36343732006-12-19 22:43:32 +000049STATISTIC(NumBytes, "Number of bytes of machine code compiled");
50STATISTIC(NumRelos, "Number of relocations applied");
51static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000052
Andrew Lenhartha00269b2005-07-29 23:40:16 +000053
Chris Lattner54266522004-11-20 23:57:07 +000054//===----------------------------------------------------------------------===//
55// JIT lazy compilation code.
56//
57namespace {
Reid Spenceree448632005-07-12 15:51:55 +000058 class JITResolverState {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000059 public:
60 typedef std::map<AssertingVH<Function>, void*> FunctionToStubMapTy;
61 typedef std::map<void*, Function*> StubToFunctionMapTy;
62 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
Reid Spenceree448632005-07-12 15:51:55 +000063 private:
64 /// FunctionToStubMap - Keep track of the stub created for a particular
65 /// function so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000066 FunctionToStubMapTy FunctionToStubMap;
Reid Spenceree448632005-07-12 15:51:55 +000067
68 /// StubToFunctionMap - Keep track of the function that each stub
69 /// corresponds to.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000070 StubToFunctionMapTy StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000071
Evan Cheng5594f122008-11-10 01:52:24 +000072 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +000073 /// particular GlobalVariable so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000074 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000075
Reid Spenceree448632005-07-12 15:51:55 +000076 public:
Nick Lewyckye2bcf132009-04-27 05:09:44 +000077 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000078 assert(locked.holds(TheJIT->lock));
79 return FunctionToStubMap;
80 }
Jeff Cohen00b168892005-07-27 06:12:32 +000081
Nick Lewyckye2bcf132009-04-27 05:09:44 +000082 StubToFunctionMapTy& getStubToFunctionMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000083 assert(locked.holds(TheJIT->lock));
84 return StubToFunctionMap;
85 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000086
Nick Lewyckye2bcf132009-04-27 05:09:44 +000087 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +000088 assert(locked.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +000089 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000090 }
Reid Spenceree448632005-07-12 15:51:55 +000091 };
Jeff Cohen00b168892005-07-27 06:12:32 +000092
Chris Lattner54266522004-11-20 23:57:07 +000093 /// JITResolver - Keep track of, and resolve, call sites for functions that
94 /// have not yet been compiled.
95 class JITResolver {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000096 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
97 typedef JITResolverState::StubToFunctionMapTy StubToFunctionMapTy;
98 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
99
Chris Lattner5e225582004-11-21 03:37:42 +0000100 /// LazyResolverFn - The target lazy resolver function that we actually
101 /// rewrite instructions to use.
102 TargetJITInfo::LazyResolverFn LazyResolverFn;
103
Reid Spenceree448632005-07-12 15:51:55 +0000104 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000105
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000106 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
107 /// external functions.
108 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000109
Evan Cheng1606e8e2009-03-13 07:51:59 +0000110 /// revGOTMap - map addresses to indexes in the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000111 std::map<void*, unsigned> revGOTMap;
112 unsigned nextGOTIndex;
113
Chris Lattnere7484012007-02-24 02:57:03 +0000114 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000115 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000116 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000117 TheJIT = &jit;
118
119 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
120 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
121 TheJITResolver = this;
122 }
123
124 ~JITResolver() {
125 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000126 }
Chris Lattner54266522004-11-20 23:57:07 +0000127
Evan Cheng704bff92008-11-13 21:50:50 +0000128 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
129 /// if it has already been created.
130 void *getFunctionStubIfAvailable(Function *F);
131
Chris Lattner54266522004-11-20 23:57:07 +0000132 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begemand6b7a242009-02-18 08:31:02 +0000133 /// one on demand as needed. If empty is true, create a function stub
134 /// pointing at address 0, to be filled in later.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000135 void *getFunctionStub(Function *F);
Chris Lattner54266522004-11-20 23:57:07 +0000136
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000137 /// getExternalFunctionStub - Return a stub for the function at the
138 /// specified address, created lazily on demand.
139 void *getExternalFunctionStub(void *FnAddr);
140
Evan Cheng5594f122008-11-10 01:52:24 +0000141 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000142 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000143 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000144
Chris Lattner5e225582004-11-21 03:37:42 +0000145 /// AddCallbackAtLocation - If the target is capable of rewriting an
146 /// instruction without the use of a stub, record the location of the use so
147 /// we know which function is being used at the location.
148 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000149 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000150 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000151 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000152 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000153 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000154
155 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000156 SmallVectorImpl<void*> &Ptrs);
157
158 GlobalValue *invalidateStub(void *Stub);
Chris Lattner5e225582004-11-21 03:37:42 +0000159
Andrew Lenharth6a974612005-07-28 12:44:13 +0000160 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000161 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000162 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000163 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000164
Chris Lattner54266522004-11-20 23:57:07 +0000165 /// JITCompilerFn - This function is called to resolve a stub to a compiled
166 /// address. If the LLVM Function corresponding to the stub has not yet
167 /// been compiled, this function compiles it first.
168 static void *JITCompilerFn(void *Stub);
169 };
170}
171
Chris Lattnere7484012007-02-24 02:57:03 +0000172JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000173
Evan Cheng704bff92008-11-13 21:50:50 +0000174/// getFunctionStubIfAvailable - This returns a pointer to a function stub
175/// if it has already been created.
176void *JITResolver::getFunctionStubIfAvailable(Function *F) {
177 MutexGuard locked(TheJIT->lock);
178
179 // If we already have a stub for this function, recycle it.
180 void *&Stub = state.getFunctionToStubMap(locked)[F];
181 return Stub;
182}
183
Chris Lattner54266522004-11-20 23:57:07 +0000184/// getFunctionStub - This returns a pointer to a function stub, creating
185/// one on demand as needed.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000186void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000187 MutexGuard locked(TheJIT->lock);
188
Chris Lattner54266522004-11-20 23:57:07 +0000189 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000190 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000191 if (Stub) return Stub;
192
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000193 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
194 // case we must resolve the symbol now.
195 void *Actual = TheJIT->isLazyCompilationDisabled()
196 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
197
198 // If this is an external declaration, attempt to resolve the address now
199 // to place in the stub.
Dan Gohman69f93782009-01-05 05:32:42 +0000200 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000201 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000202
Dan Gohman69f93782009-01-05 05:32:42 +0000203 // If we resolved the symbol to a null address (eg. a weak external)
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000204 // don't emit a stub. Return a null pointer to the application. If dlsym
205 // stubs are enabled, not being able to resolve the address is not
206 // meaningful.
207 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
Dan Gohman69f93782009-01-05 05:32:42 +0000208 }
209
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000210 // Codegen a new stub, calling the lazy resolver or the actual address of the
211 // external function, if it was resolved.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000212 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000213 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000214
Chris Lattner870286a2006-06-01 17:29:22 +0000215 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000216 // If we are getting the stub for an external function, we really want the
217 // address of the stub in the GlobalAddressMap for the JIT, not the address
218 // of the external function.
219 TheJIT->updateGlobalMapping(F, Stub);
220 }
Chris Lattner54266522004-11-20 23:57:07 +0000221
Chris Lattnerbe3ae8e2009-03-05 06:48:16 +0000222 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
Bill Wendling832171c2006-12-07 20:04:42 +0000223 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000224
Chris Lattner54266522004-11-20 23:57:07 +0000225 // Finally, keep track of the stub-to-Function mapping so that the
226 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000227 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begemand6b7a242009-02-18 08:31:02 +0000228
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000229 // If we are JIT'ing non-lazily but need to call a function that does not
230 // exist yet, add it to the JIT's work list so that we can fill in the stub
231 // address later.
232 if (!Actual && TheJIT->isLazyCompilationDisabled())
233 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
234 TheJIT->addPendingFunction(F);
Nate Begemand6b7a242009-02-18 08:31:02 +0000235
Chris Lattner54266522004-11-20 23:57:07 +0000236 return Stub;
237}
238
Evan Cheng5594f122008-11-10 01:52:24 +0000239/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000240/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000241void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000242 MutexGuard locked(TheJIT->lock);
243
244 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000245 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
246 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000247
Evan Chenge4d783d2008-11-10 23:26:16 +0000248 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000249 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000250 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000251
Evan Cheng5594f122008-11-10 01:52:24 +0000252 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
Evan Chengbe8c03f2008-01-04 10:46:51 +0000253 << GV->getName() << "'\n";
254
Evan Cheng5594f122008-11-10 01:52:24 +0000255 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000256}
257
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000258/// getExternalFunctionStub - Return a stub for the function at the
259/// specified address, created lazily on demand.
260void *JITResolver::getExternalFunctionStub(void *FnAddr) {
261 // If we already have a stub for this function, recycle it.
262 void *&Stub = ExternalFnToStubMap[FnAddr];
263 if (Stub) return Stub;
264
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000265 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000266 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000267
Bill Wendling832171c2006-12-07 20:04:42 +0000268 DOUT << "JIT: Stub emitted at [" << Stub
269 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000270 return Stub;
271}
272
Andrew Lenharth6a974612005-07-28 12:44:13 +0000273unsigned JITResolver::getGOTIndexForAddr(void* addr) {
274 unsigned idx = revGOTMap[addr];
275 if (!idx) {
276 idx = ++nextGOTIndex;
277 revGOTMap[addr] = idx;
Evan Cheng366cf292008-11-07 22:30:29 +0000278 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000279 }
280 return idx;
281}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000282
Nate Begemand6b7a242009-02-18 08:31:02 +0000283void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
284 SmallVectorImpl<void*> &Ptrs) {
285 MutexGuard locked(TheJIT->lock);
286
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000287 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
288 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begemand6b7a242009-02-18 08:31:02 +0000289
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000290 for (FunctionToStubMapTy::iterator i = FM.begin(), e = FM.end(); i != e; ++i){
Nate Begemand6b7a242009-02-18 08:31:02 +0000291 Function *F = i->first;
292 if (F->isDeclaration() && F->hasExternalLinkage()) {
293 GVs.push_back(i->first);
294 Ptrs.push_back(i->second);
295 }
296 }
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000297 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begemand6b7a242009-02-18 08:31:02 +0000298 i != e; ++i) {
299 GVs.push_back(i->first);
300 Ptrs.push_back(i->second);
301 }
302}
303
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000304GlobalValue *JITResolver::invalidateStub(void *Stub) {
305 MutexGuard locked(TheJIT->lock);
306
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000307 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
308 StubToFunctionMapTy &SM = state.getStubToFunctionMap(locked);
309 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000310
311 // Look up the cheap way first, to see if it's a function stub we are
312 // invalidating. If so, remove it from both the forward and reverse maps.
313 if (SM.find(Stub) != SM.end()) {
314 Function *F = SM[Stub];
315 SM.erase(Stub);
316 FM.erase(F);
317 return F;
318 }
319
Nate Begeman841c6a42009-03-11 07:03:43 +0000320 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000321 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000322 i != e; ++i) {
323 if (i->second != Stub)
324 continue;
325 GlobalValue *GV = i->first;
326 GM.erase(i);
327 return GV;
328 }
329
Nate Begeman841c6a42009-03-11 07:03:43 +0000330 // Lastly, check to see if it's in the ExternalFnToStubMap.
331 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
332 e = ExternalFnToStubMap.end(); i != e; ++i) {
333 if (i->second != Stub)
334 continue;
335 ExternalFnToStubMap.erase(i);
336 break;
337 }
338
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000339 return 0;
340}
341
Chris Lattner54266522004-11-20 23:57:07 +0000342/// JITCompilerFn - This function is called when a lazy compilation stub has
343/// been entered. It looks up which function this stub corresponds to, compiles
344/// it if necessary, then returns the resultant function pointer.
345void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000346 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000347
348 Function* F = 0;
349 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000350
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000351 {
352 // Only lock for getting the Function. The call getPointerToFunction made
353 // in this function might trigger function materializing, which requires
354 // JIT lock to be unlocked.
355 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000356
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000357 // The address given to us for the stub may not be exactly right, it might be
358 // a little bit after the stub. As such, use upper_bound to find it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000359 StubToFunctionMapTy::iterator I =
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000360 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
361 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
362 "This is not a known stub!");
363 F = (--I)->second;
364 ActualPtr = I->first;
365 }
Chris Lattner54266522004-11-20 23:57:07 +0000366
Evan Cheng9da60f92007-06-30 00:10:37 +0000367 // If we have already code generated the function, just return the address.
368 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000369
Evan Cheng9da60f92007-06-30 00:10:37 +0000370 if (!Result) {
371 // Otherwise we don't have it, do lazy compilation now.
372
373 // If lazy compilation is disabled, emit a useful error message and abort.
374 if (TheJIT->isLazyCompilationDisabled()) {
375 cerr << "LLVM JIT requested to do lazy compilation of function '"
376 << F->getName() << "' when lazy compiles are disabled!\n";
377 abort();
378 }
379
380 // We might like to remove the stub from the StubToFunction map.
381 // We can't do that! Multiple threads could be stuck, waiting to acquire the
382 // lock above. As soon as the 1st function finishes compiling the function,
383 // the next one will be released, and needs to be able to find the function
384 // it needs to call.
385 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000386
Evan Cheng9da60f92007-06-30 00:10:37 +0000387 DOUT << "JIT: Lazily resolving function '" << F->getName()
388 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000389 << ActualPtr << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000390
Evan Cheng9da60f92007-06-30 00:10:37 +0000391 Result = TheJIT->getPointerToFunction(F);
392 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000393
394 // Reacquire the lock to erase the stub in the map.
395 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000396
397 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000398 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000399
400 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000401
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000402 // What we will do is set the compiled function address to map to the
403 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000404 // if they see it still using the stub address.
405 // Note: this is done so the Resolver doesn't have to manage GOT memory
406 // Do this without allocating map space if the target isn't using a GOT
407 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
408 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
409
Chris Lattner54266522004-11-20 23:57:07 +0000410 return Result;
411}
Chris Lattner688506d2003-08-14 18:35:27 +0000412
Chris Lattner8ac66c12008-04-04 05:51:42 +0000413//===----------------------------------------------------------------------===//
414// Function Index Support
415
416// On MacOS we generate an index of currently JIT'd functions so that
417// performance tools can determine a symbol name and accurate code range for a
418// PC value. Because performance tools are generally asynchronous, the code
419// below is written with the hope that it could be interrupted at any time and
420// have useful answers. However, we don't go crazy with atomic operations, we
421// just do a "reasonable effort".
422#ifdef __APPLE__
Evan Chengbdb6ca12008-05-15 17:31:35 +0000423#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattner8ac66c12008-04-04 05:51:42 +0000424#endif
425
426/// JitSymbolEntry - Each function that is JIT compiled results in one of these
427/// being added to an array of symbols. This indicates the name of the function
428/// as well as the address range it occupies. This allows the client to map
429/// from a PC value to the name of the function.
430struct JitSymbolEntry {
431 const char *FnName; // FnName - a strdup'd string.
432 void *FnStart;
433 intptr_t FnSize;
434};
435
436
437struct JitSymbolTable {
438 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
439 /// pointer is not used right now, but might be used in the future. Consider
440 /// it reserved for future use.
441 JitSymbolTable *NextPtr;
442
443 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
444 /// 'NumSymbols' symbols are valid.
445 JitSymbolEntry *Symbols;
446
447 /// NumSymbols - This indicates the number entries in the Symbols array that
448 /// are valid.
449 unsigned NumSymbols;
450
451 /// NumAllocated - This indicates the amount of space we have in the Symbols
452 /// array. This is a private field that should not be read by external tools.
453 unsigned NumAllocated;
454};
455
456#if ENABLE_JIT_SYMBOL_TABLE
457JitSymbolTable *__jitSymbolTable;
458#endif
459
460static void AddFunctionToSymbolTable(const char *FnName,
461 void *FnStart, intptr_t FnSize) {
462 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
463 JitSymbolTable **SymTabPtrPtr = 0;
464#if !ENABLE_JIT_SYMBOL_TABLE
465 return;
466#else
467 SymTabPtrPtr = &__jitSymbolTable;
468#endif
469
470 // If this is the first entry in the symbol table, add the JitSymbolTable
471 // index.
472 if (*SymTabPtrPtr == 0) {
473 JitSymbolTable *New = new JitSymbolTable();
474 New->NextPtr = 0;
475 New->Symbols = 0;
476 New->NumSymbols = 0;
477 New->NumAllocated = 0;
478 *SymTabPtrPtr = New;
479 }
480
481 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
482
483 // If we have space in the table, reallocate the table.
484 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
485 // If we don't have space, reallocate the table.
Chris Lattner3b374482008-04-13 07:04:56 +0000486 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000487 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
488 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
489
490 // Copy the old entries over.
Nate Begemand6b7a242009-02-18 08:31:02 +0000491 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattner8ac66c12008-04-04 05:51:42 +0000492
493 // Swap the new symbols in, delete the old ones.
494 SymTabPtr->Symbols = NewSymbols;
Chris Lattner3b374482008-04-13 07:04:56 +0000495 SymTabPtr->NumAllocated = NewSize;
Chris Lattner8ac66c12008-04-04 05:51:42 +0000496 delete [] OldSymbols;
497 }
498
499 // Otherwise, we have enough space, just tack it onto the end of the array.
500 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
501 Entry.FnName = strdup(FnName);
502 Entry.FnStart = FnStart;
503 Entry.FnSize = FnSize;
504 ++SymTabPtr->NumSymbols;
505}
506
507static void RemoveFunctionFromSymbolTable(void *FnStart) {
508 assert(FnStart && "Invalid function pointer");
509 JitSymbolTable **SymTabPtrPtr = 0;
510#if !ENABLE_JIT_SYMBOL_TABLE
511 return;
512#else
513 SymTabPtrPtr = &__jitSymbolTable;
514#endif
515
516 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
517 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
518
519 // Scan the table to find its index. The table is not sorted, so do a linear
520 // scan.
521 unsigned Index;
522 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
523 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
524
525 // Once we have an index, we know to nuke this entry, overwrite it with the
526 // entry at the end of the array, making the last entry redundant.
527 const char *OldName = Symbols[Index].FnName;
528 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
529 free((void*)OldName);
530
531 // Drop the number of symbols in the table.
532 --SymTabPtr->NumSymbols;
533
534 // Finally, if we deleted the final symbol, deallocate the table itself.
Nate Begemanf44085a2008-05-18 19:09:10 +0000535 if (SymTabPtr->NumSymbols != 0)
Chris Lattner8ac66c12008-04-04 05:51:42 +0000536 return;
537
538 *SymTabPtrPtr = 0;
539 delete [] Symbols;
540 delete SymTabPtr;
541}
Chris Lattner688506d2003-08-14 18:35:27 +0000542
Chris Lattner54266522004-11-20 23:57:07 +0000543//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000544// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000545//
Chris Lattner688506d2003-08-14 18:35:27 +0000546namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000547 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
548 /// used to output functions to memory for execution.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +0000549 class JITEmitter : public JITCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000550 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000551
Chris Lattner6125fdd2003-05-09 03:30:07 +0000552 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000553 // save BufferBegin/BufferEnd/CurBufferPtr here.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000554 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000555
Chris Lattner5be478f2004-11-20 03:46:14 +0000556 /// Relocations - These are the relocations that the function needs, as
557 /// emitted.
558 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000559
560 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
561 /// It is filled in by the StartMachineBasicBlock callback and queried by
562 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000563 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000564
Chris Lattner239862c2006-02-09 04:49:59 +0000565 /// ConstantPool - The constant pool for the current function.
566 ///
567 MachineConstantPool *ConstantPool;
568
569 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
570 ///
571 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000572
Evan Cheng1606e8e2009-03-13 07:51:59 +0000573 /// ConstPoolAddresses - Addresses of individual constant pool entries.
574 ///
575 SmallVector<uintptr_t, 8> ConstPoolAddresses;
576
Nate Begeman019f8512006-09-10 23:03:44 +0000577 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000578 ///
579 MachineJumpTableInfo *JumpTable;
580
581 /// JumpTableBase - A pointer to the first entry in the jump table.
582 ///
583 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000584
Chris Lattnere7484012007-02-24 02:57:03 +0000585 /// Resolver - This contains info about the currently resolved functions.
586 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000587
588 /// DE - The dwarf emitter for the jit.
589 JITDwarfEmitter *DE;
590
591 /// LabelLocations - This vector is a mapping from Label ID's to their
592 /// address.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000593 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000594
595 /// MMI - Machine module info for exception informations
596 MachineModuleInfo* MMI;
597
Dale Johannesendd947ea2008-08-07 01:30:15 +0000598 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000599 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000600
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000601 // CurFn - The llvm function being emitted. Only valid during
602 // finishFunction().
603 const Function *CurFn;
604
605 // CurFnStubUses - For a given Function, a vector of stubs that it
606 // references. This facilitates the JIT detecting that a stub is no
607 // longer used, so that it may be deallocated.
608 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
609
610 // StubFnRefs - For a given pointer to a stub, a set of Functions which
611 // reference the stub. When the count of a stub's references drops to zero,
612 // the stub is unused.
613 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
614
Nate Begeman841c6a42009-03-11 07:03:43 +0000615 // ExtFnStubs - A map of external function names to stubs which have entries
616 // in the JITResolver's ExternalFnToStubMap.
617 StringMap<void *> ExtFnStubs;
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +0000618
619 // MCI - A pointer to a MachineCodeInfo object to update with information.
620 MachineCodeInfo *MCI;
621
Chris Lattnere7484012007-02-24 02:57:03 +0000622 public:
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +0000623 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0), MCI(0) {
Chris Lattner9f2f1422007-12-06 01:08:09 +0000624 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000625 if (jit.getJITInfo().needsGOT()) {
626 MemMgr->AllocateGOT();
627 DOUT << "JIT is managing a GOT\n";
628 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000629
630 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000631 }
632 ~JITEmitter() {
633 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000634 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000635 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000636
637 /// classof - Methods for support type inquiry through isa, cast, and
638 /// dyn_cast:
639 ///
640 static inline bool classof(const JITEmitter*) { return true; }
641 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000642
643 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000644
645 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000646 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000647
648 void emitConstantPool(MachineConstantPool *MCP);
649 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000650 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000651
Evan Chengce4a70b2008-11-08 08:02:53 +0000652 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000653 unsigned Alignment = 1);
Nate Begemand6b7a242009-02-18 08:31:02 +0000654 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
655 unsigned StubSize);
Evan Chengce4a70b2008-11-08 08:02:53 +0000656 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000657
Nuno Lopescef75272008-10-21 11:42:16 +0000658 /// allocateSpace - Reserves space in the current block if any, or
659 /// allocate a new one of the given size.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000660 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000661
Chris Lattner5be478f2004-11-20 03:46:14 +0000662 virtual void addRelocation(const MachineRelocation &MR) {
663 Relocations.push_back(MR);
664 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000665
666 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
667 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
668 MBBLocations.resize((MBB->getNumber()+1)*2);
669 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Evan Cheng366cf292008-11-07 22:30:29 +0000670 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
671 << (void*) getCurrentPCValue() << "]\n";
Chris Lattnerb4432f32006-05-03 17:10:41 +0000672 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000673
Evan Cheng5788d1a2008-12-10 02:32:19 +0000674 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
675 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000676
Evan Cheng5788d1a2008-12-10 02:32:19 +0000677 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000678 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
679 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
680 return MBBLocations[MBB->getNumber()];
681 }
682
Chris Lattnere993cc22006-05-11 23:08:08 +0000683 /// deallocateMemForFunction - Deallocate all memory for the specified
684 /// function body.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000685 void deallocateMemForFunction(Function *F);
Nate Begeman841c6a42009-03-11 07:03:43 +0000686
687 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
688 /// using the stub at the specified address. Allows
689 /// deallocateMemForFunction to also remove stubs no longer referenced.
690 void AddStubToCurrentFunction(void *Stub);
691
692 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
693 /// MachineRelocations that reference external functions by name.
694 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000695
696 virtual void emitLabel(uint64_t LabelID) {
697 if (LabelLocations.size() <= LabelID)
698 LabelLocations.resize((LabelID+1)*2);
699 LabelLocations[LabelID] = getCurrentPCValue();
700 }
701
Evan Cheng5788d1a2008-12-10 02:32:19 +0000702 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000703 assert(LabelLocations.size() > (unsigned)LabelID &&
704 LabelLocations[LabelID] && "Label not emitted!");
705 return LabelLocations[LabelID];
706 }
707
708 virtual void setModuleInfo(MachineModuleInfo* Info) {
709 MMI = Info;
710 if (ExceptionHandling) DE->setModuleInfo(Info);
711 }
712
Jim Grosbachcce6c292008-10-03 16:17:20 +0000713 void setMemoryExecutable(void) {
714 MemMgr->setMemoryExecutable();
715 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000716
717 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000718
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +0000719 void setMachineCodeInfo(MachineCodeInfo *mci) {
720 MCI = mci;
721 }
722
Chris Lattner54266522004-11-20 23:57:07 +0000723 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000724 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000725 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000726 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000727 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
728 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
729 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
730 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000731 };
732}
733
Chris Lattner166f2262004-11-22 22:00:25 +0000734void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
735 bool DoesntNeedStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000736 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000737 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000738
Chris Lattner18e04592008-06-25 20:21:35 +0000739 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000740 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000741
742 // If we have already compiled the function, return a pointer to its body.
743 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000744 void *ResultPtr;
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000745 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
Evan Cheng704bff92008-11-13 21:50:50 +0000746 // Return the function stub if it's already created.
747 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000748 if (ResultPtr)
749 AddStubToCurrentFunction(ResultPtr);
750 } else {
Evan Cheng704bff92008-11-13 21:50:50 +0000751 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000752 }
Chris Lattner54266522004-11-20 23:57:07 +0000753 if (ResultPtr) return ResultPtr;
754
Nate Begemand6b7a242009-02-18 08:31:02 +0000755 // If this is an external function pointer, we can force the JIT to
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000756 // 'compile' it, which really just adds it to the map. In dlsym mode,
757 // external functions are forced through a stub, regardless of reloc type.
758 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
759 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
Nate Begemand6b7a242009-02-18 08:31:02 +0000760 return TheJIT->getPointerToFunction(F);
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000761
Chris Lattner5e225582004-11-21 03:37:42 +0000762 // Okay, the function has not been compiled yet, if the target callback
763 // mechanism is capable of rewriting the instruction directly, prefer to do
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000764 // that instead of emitting a stub. This uses the lazy resolver, so is not
765 // legal if lazy compilation is disabled.
766 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Chris Lattnere7484012007-02-24 02:57:03 +0000767 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000768
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000769 // Otherwise, we have to emit a stub.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000770 void *StubAddr = Resolver.getFunctionStub(F);
771
772 // Add the stub to the current function's list of referenced stubs, so we can
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000773 // deallocate them if the current function is ever freed. It's possible to
774 // return null from getFunctionStub in the case of a weak extern that fails
775 // to resolve.
776 if (StubAddr)
777 AddStubToCurrentFunction(StubAddr);
778
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000779 return StubAddr;
Chris Lattner54266522004-11-20 23:57:07 +0000780}
781
Evan Cheng5594f122008-11-10 01:52:24 +0000782void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000783 bool NoNeedStub) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000784 // Make sure GV is emitted first, and create a stub containing the fully
785 // resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000786 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000787 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
788
789 // Add the stub to the current function's list of referenced stubs, so we can
790 // deallocate them if the current function is ever freed.
791 AddStubToCurrentFunction(StubAddr);
792
793 return StubAddr;
794}
795
796void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
797 if (!TheJIT->areDlsymStubsEnabled())
798 return;
799
800 assert(CurFn && "Stub added to current function, but current function is 0!");
801
802 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
803 StubsUsed.push_back(StubAddr);
804
805 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
806 FnRefs.insert(CurFn);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000807}
808
Evan Cheng1606e8e2009-03-13 07:51:59 +0000809static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
810 const TargetData *TD) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000811 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
812 if (Constants.empty()) return 0;
813
Evan Cheng1606e8e2009-03-13 07:51:59 +0000814 unsigned Size = 0;
815 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
816 MachineConstantPoolEntry CPE = Constants[i];
817 unsigned AlignMask = CPE.getAlignment() - 1;
818 Size = (Size + AlignMask) & ~AlignMask;
819 const Type *Ty = CPE.getType();
Duncan Sands777d2302009-05-09 07:06:46 +0000820 Size += TD->getTypeAllocSize(Ty);
Evan Cheng1606e8e2009-03-13 07:51:59 +0000821 }
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000822 return Size;
823}
824
825static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
826 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
827 if (JT.empty()) return 0;
828
829 unsigned NumEntries = 0;
830 for (unsigned i = 0, e = JT.size(); i != e; ++i)
831 NumEntries += JT[i].MBBs.size();
832
833 unsigned EntrySize = MJTI->getEntrySize();
834
835 return NumEntries * EntrySize;
836}
837
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000838static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000839 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000840 // Since we do not know where the buffer will be allocated, be pessimistic.
841 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000842}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000843
Dale Johannesendd947ea2008-08-07 01:30:15 +0000844/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
845/// into the running total Size.
846
847unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
848 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000849 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000850 size_t GVAlign =
851 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000852 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000853 DEBUG(GV->dump());
854 // Assume code section ends with worst possible alignment, so first
855 // variable needs maximal padding.
856 if (Size==0)
857 Size = 1;
858 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
859 Size += GVSize;
860 return Size;
861}
862
863/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
864/// but are referenced from the constant; put them in GVSet and add their
865/// size into the running total Size.
866
867unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
868 unsigned Size) {
869 // If its undefined, return the garbage.
870 if (isa<UndefValue>(C))
871 return Size;
872
873 // If the value is a ConstantExpr
874 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
875 Constant *Op0 = CE->getOperand(0);
876 switch (CE->getOpcode()) {
877 case Instruction::GetElementPtr:
878 case Instruction::Trunc:
879 case Instruction::ZExt:
880 case Instruction::SExt:
881 case Instruction::FPTrunc:
882 case Instruction::FPExt:
883 case Instruction::UIToFP:
884 case Instruction::SIToFP:
885 case Instruction::FPToUI:
886 case Instruction::FPToSI:
887 case Instruction::PtrToInt:
888 case Instruction::IntToPtr:
889 case Instruction::BitCast: {
890 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
891 break;
892 }
893 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000894 case Instruction::FAdd:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000895 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000896 case Instruction::FSub:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000897 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000898 case Instruction::FMul:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000899 case Instruction::UDiv:
900 case Instruction::SDiv:
901 case Instruction::URem:
902 case Instruction::SRem:
903 case Instruction::And:
904 case Instruction::Or:
905 case Instruction::Xor: {
906 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
907 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
908 break;
909 }
910 default: {
911 cerr << "ConstantExpr not handled: " << *CE << "\n";
912 abort();
913 }
914 }
915 }
916
917 if (C->getType()->getTypeID() == Type::PointerTyID)
918 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000919 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000920 Size = addSizeOfGlobal(GV, Size);
921
922 return Size;
923}
924
925/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
926/// but are referenced from the given initializer.
927
928unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
929 unsigned Size) {
930 if (!isa<UndefValue>(Init) &&
931 !isa<ConstantVector>(Init) &&
932 !isa<ConstantAggregateZero>(Init) &&
933 !isa<ConstantArray>(Init) &&
934 !isa<ConstantStruct>(Init) &&
935 Init->getType()->isFirstClassType())
936 Size = addSizeOfGlobalsInConstantVal(Init, Size);
937 return Size;
938}
939
940/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
941/// globals; then walk the initializers of those globals looking for more.
942/// If their size has not been considered yet, add it into the running total
943/// Size.
944
945unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
946 unsigned Size = 0;
947 GVSet.clear();
948
949 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
950 MBB != E; ++MBB) {
951 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
952 I != E; ++I) {
953 const TargetInstrDesc &Desc = I->getDesc();
954 const MachineInstr &MI = *I;
955 unsigned NumOps = Desc.getNumOperands();
956 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
957 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000958 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000959 GlobalValue* V = MO.getGlobal();
960 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
961 if (!GV)
962 continue;
963 // If seen in previous function, it will have an entry here.
964 if (TheJIT->getPointerToGlobalIfAvailable(GV))
965 continue;
966 // If seen earlier in this function, it will have an entry here.
967 // FIXME: it should be possible to combine these tables, by
968 // assuming the addresses of the new globals in this module
969 // start at 0 (or something) and adjusting them after codegen
970 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000971 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000972 // A variable as yet unseen. Add in its size.
973 Size = addSizeOfGlobal(GV, Size);
974 }
975 }
976 }
977 }
Evan Chengeb5d95a2008-11-06 17:46:04 +0000978 DOUT << "JIT: About to look through initializers\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000979 // Look for more globals that are referenced only from initializers.
980 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +0000981 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000982 I != GVSet.end(); I++) {
983 const GlobalVariable* GV = *I;
984 if (GV->hasInitializer())
985 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
986 }
987
988 return Size;
989}
990
Chris Lattner166f2262004-11-22 22:00:25 +0000991void JITEmitter::startFunction(MachineFunction &F) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000992 DOUT << "JIT: Starting CodeGen of Function "
993 << F.getFunction()->getName() << "\n";
994
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000995 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000996 // Set the memory writable, if it's not already
997 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000998 if (MemMgr->NeedsExactSize()) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000999 DOUT << "JIT: ExactSize\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001000 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
1001 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
1002 MachineConstantPool *MCP = F.getConstantPool();
1003
1004 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +00001005 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001006
1007 // Add the alignment of the constant pool
Evan Cheng1606e8e2009-03-13 07:51:59 +00001008 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001009
1010 // Add the constant pool size
Evan Cheng1606e8e2009-03-13 07:51:59 +00001011 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001012
1013 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +00001014 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001015
1016 // Add the jump table size
1017 ActualSize += GetJumpTableSizeInBytes(MJTI);
1018
1019 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +00001020 ActualSize = RoundUpToAlign(ActualSize,
1021 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001022
1023 // Add the function size
1024 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +00001025
Evan Chengeb5d95a2008-11-06 17:46:04 +00001026 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +00001027 // Add the size of the globals that will be allocated after this function.
1028 // These are all the ones referenced from this function that were not
1029 // previously allocated.
1030 ActualSize += GetSizeOfGlobalsInBytes(F);
Evan Chengeb5d95a2008-11-06 17:46:04 +00001031 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001032 }
1033
Chris Lattner8907b4b2007-12-05 23:39:57 +00001034 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1035 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +00001036 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001037
Evan Cheng9a1e9b92006-11-16 20:04:54 +00001038 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1039 emitAlignment(16);
1040
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001041 emitConstantPool(F.getConstantPool());
1042 initJumpTableInfo(F.getJumpTableInfo());
1043
1044 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +00001045 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001046 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +00001047
Chris Lattnerb4432f32006-05-03 17:10:41 +00001048 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001049}
1050
Chris Lattner43b429b2006-05-02 18:27:26 +00001051bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +00001052 if (CurBufferPtr == BufferEnd) {
1053 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +00001054 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +00001055 abort();
1056 }
1057
Jim Laskeyb92767a2006-12-14 22:53:42 +00001058 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +00001059
Chris Lattnera8279532006-06-16 18:09:26 +00001060 // FnStart is the start of the text, not the start of the constant pool and
1061 // other per-function data.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001062 uint8_t *FnStart =
1063 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001064
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001065 // FnEnd is the end of the function's machine code.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001066 uint8_t *FnEnd = CurBufferPtr;
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001067
Chris Lattner5be478f2004-11-20 03:46:14 +00001068 if (!Relocations.empty()) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001069 CurFn = F.getFunction();
Chris Lattnere884dc22005-07-20 16:29:20 +00001070 NumRelos += Relocations.size();
1071
Chris Lattner5be478f2004-11-20 03:46:14 +00001072 // Resolve the relocations to concrete pointers.
1073 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1074 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +00001075 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +00001076 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +00001077 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +00001078 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1079 false);
Evan Chengd7398c92008-11-08 07:37:34 +00001080 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Evan Chengca66b082008-11-08 07:22:53 +00001081 << ResultPtr << "]\n";
Misha Brukmanf976c852005-04-21 22:55:34 +00001082
Evan Chengef5784e2008-10-29 23:54:46 +00001083 // If the target REALLY wants a stub for this function, emit it now.
Nate Begeman841c6a42009-03-11 07:03:43 +00001084 if (!MR.doesntNeedStub()) {
1085 if (!TheJIT->areDlsymStubsEnabled()) {
1086 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1087 } else {
1088 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1089 if (!Stub) {
1090 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1091 AddStubToCurrentFunction(Stub);
1092 }
1093 ResultPtr = Stub;
1094 }
1095 }
Evan Chengef5784e2008-10-29 23:54:46 +00001096 } else if (MR.isGlobalValue()) {
1097 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1098 BufferBegin+MR.getMachineCodeOffset(),
1099 MR.doesntNeedStub());
Evan Cheng5594f122008-11-10 01:52:24 +00001100 } else if (MR.isIndirectSymbol()) {
1101 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +00001102 BufferBegin+MR.getMachineCodeOffset(),
1103 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +00001104 } else if (MR.isBasicBlock()) {
1105 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1106 } else if (MR.isConstantPoolIndex()) {
1107 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1108 } else {
1109 assert(MR.isJumpTableIndex());
1110 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1111 }
Jeff Cohen00b168892005-07-27 06:12:32 +00001112
Evan Chengef5784e2008-10-29 23:54:46 +00001113 MR.setResultPointer(ResultPtr);
1114 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001115
Andrew Lenharth6a974612005-07-28 12:44:13 +00001116 // if we are managing the GOT and the relocation wants an index,
1117 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +00001118 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001119 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +00001120 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001121 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001122 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +00001123 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +00001124 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +00001125 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001126 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001127 }
Chris Lattner5be478f2004-11-20 03:46:14 +00001128 }
1129
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001130 CurFn = 0;
Chris Lattner43b429b2006-05-02 18:27:26 +00001131 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +00001132 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +00001133 }
1134
Chris Lattnerd2d5c762006-05-03 18:55:56 +00001135 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +00001136 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001137 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001138 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001139 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +00001140 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1141 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001142 }
1143 }
1144
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001145 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1146 // global variables that were referenced in the relocations.
1147 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
Evan Cheng5788d1a2008-12-10 02:32:19 +00001148
1149 if (CurBufferPtr == BufferEnd) {
1150 // FIXME: Allocate more space, then try again.
1151 cerr << "JIT: Ran out of space for generated machine code!\n";
1152 abort();
1153 }
1154
Nuno Lopescef75272008-10-21 11:42:16 +00001155 BufferBegin = CurBufferPtr = 0;
1156 NumBytes += FnEnd-FnStart;
1157
Evan Cheng55fc2802006-07-25 20:40:54 +00001158 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +00001159 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattner8ac66c12008-04-04 05:51:42 +00001160
1161 // Add it to the JIT symbol table if the host wants it.
1162 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1163 FnStart, FnEnd-FnStart);
Evan Cheng55fc2802006-07-25 20:40:54 +00001164
Bill Wendling832171c2006-12-07 20:04:42 +00001165 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1166 << "] Function: " << F.getFunction()->getName()
1167 << ": " << (FnEnd-FnStart) << " bytes of text, "
1168 << Relocations.size() << " relocations\n";
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +00001169
1170 if (MCI) {
1171 MCI->setAddress(FnStart);
1172 MCI->setSize(FnEnd-FnStart);
1173 }
1174
Chris Lattner5be478f2004-11-20 03:46:14 +00001175 Relocations.clear();
Evan Cheng1606e8e2009-03-13 07:51:59 +00001176 ConstPoolAddresses.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +00001177
Evan Chengbc4707a2008-09-18 07:54:21 +00001178 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +00001179 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +00001180
Chris Lattnerc5633c22007-01-20 20:51:43 +00001181#ifndef NDEBUG
Evan Chenga7916f52008-11-05 23:44:08 +00001182 {
Evan Chenge7c35512008-11-12 08:22:43 +00001183 if (sys::hasDisassembler()) {
1184 DOUT << "JIT: Disassembled code:\n";
Evan Chengeb5d95a2008-11-06 17:46:04 +00001185 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001186 } else {
1187 DOUT << "JIT: Binary code:\n";
Evan Chenga7916f52008-11-05 23:44:08 +00001188 DOUT << std::hex;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001189 uint8_t* q = FnStart;
Evan Chenge7c35512008-11-12 08:22:43 +00001190 for (int i = 0; q < FnEnd; q += 4, ++i) {
1191 if (i == 4)
1192 i = 0;
1193 if (i == 0)
1194 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1195 << (long)(q - FnStart) << ": ";
1196 bool Done = false;
1197 for (int j = 3; j >= 0; --j) {
1198 if (q + j >= FnEnd)
1199 Done = true;
1200 else
1201 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1202 }
1203 if (Done)
1204 break;
1205 DOUT << ' ';
1206 if (i == 3)
Evan Cheng6863fb02008-11-06 01:18:29 +00001207 DOUT << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001208 }
1209 DOUT << std::dec;
Evan Cheng6863fb02008-11-06 01:18:29 +00001210 DOUT<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001211 }
1212 }
Chris Lattnerc5633c22007-01-20 20:51:43 +00001213#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001214 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001215 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001216 SavedBufferBegin = BufferBegin;
1217 SavedBufferEnd = BufferEnd;
1218 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001219
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001220 if (MemMgr->NeedsExactSize()) {
1221 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001222 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001223
1224 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1225 ActualSize);
1226 BufferEnd = BufferBegin+ActualSize;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001227 uint8_t* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +00001228 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1229 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001230 BufferBegin = SavedBufferBegin;
1231 BufferEnd = SavedBufferEnd;
1232 CurBufferPtr = SavedCurBufferPtr;
1233
1234 TheJIT->RegisterTable(FrameRegister);
1235 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001236
1237 if (MMI)
1238 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001239
Chris Lattner43b429b2006-05-02 18:27:26 +00001240 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001241}
1242
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001243/// deallocateMemForFunction - Deallocate all memory for the specified
1244/// function body. Also drop any references the function has to stubs.
1245void JITEmitter::deallocateMemForFunction(Function *F) {
1246 MemMgr->deallocateMemForFunction(F);
1247
1248 // If the function did not reference any stubs, return.
1249 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1250 return;
1251
1252 // For each referenced stub, erase the reference to this function, and then
1253 // erase the list of referenced stubs.
1254 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1255 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1256 void *Stub = StubList[i];
Nate Begeman841c6a42009-03-11 07:03:43 +00001257
1258 // If we already invalidated this stub for this function, continue.
1259 if (StubFnRefs.count(Stub) == 0)
1260 continue;
1261
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001262 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1263 FnRefs.erase(F);
1264
1265 // If this function was the last reference to the stub, invalidate the stub
1266 // in the JITResolver. Were there a memory manager deallocateStub routine,
1267 // we could call that at this point too.
1268 if (FnRefs.empty()) {
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001269 DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
Nate Begeman841c6a42009-03-11 07:03:43 +00001270 StubFnRefs.erase(Stub);
1271
1272 // Invalidate the stub. If it is a GV stub, update the JIT's global
1273 // mapping for that GV to zero, otherwise, search the string map of
1274 // external function names to stubs and remove the entry for this stub.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001275 GlobalValue *GV = Resolver.invalidateStub(Stub);
Nate Begeman841c6a42009-03-11 07:03:43 +00001276 if (GV) {
1277 TheJIT->updateGlobalMapping(GV, 0);
1278 } else {
1279 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1280 e = ExtFnStubs.end(); i != e; ++i) {
1281 if (i->second == Stub) {
1282 ExtFnStubs.erase(i);
1283 break;
1284 }
1285 }
1286 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001287 }
1288 }
1289 CurFnStubUses.erase(F);
1290}
1291
1292
Evan Cheng5788d1a2008-12-10 02:32:19 +00001293void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +00001294 if (BufferBegin)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001295 return JITCodeEmitter::allocateSpace(Size, Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +00001296
1297 // create a new memory block if there is no active one.
1298 // care must be taken so that BufferBegin is invalidated when a
1299 // block is trimmed
1300 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1301 BufferEnd = BufferBegin+Size;
1302 return CurBufferPtr;
1303}
1304
Chris Lattner166f2262004-11-22 22:00:25 +00001305void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001306 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001307 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001308
Chris Lattnerfa77d432006-02-09 04:22:52 +00001309 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001310 if (Constants.empty()) return;
1311
Evan Cheng1606e8e2009-03-13 07:51:59 +00001312 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1313 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng97b8c402008-04-12 00:22:01 +00001314 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001315 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001316
1317 if (ConstantPoolBase == 0) return; // Buffer overflow.
1318
Evan Cheng97b8c402008-04-12 00:22:01 +00001319 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1320 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1321
Chris Lattner239862c2006-02-09 04:49:59 +00001322 // Initialize the memory for all of the constant pool entries.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001323 unsigned Offset = 0;
Chris Lattner3029f922006-02-09 04:46:04 +00001324 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng1606e8e2009-03-13 07:51:59 +00001325 MachineConstantPoolEntry CPE = Constants[i];
1326 unsigned AlignMask = CPE.getAlignment() - 1;
1327 Offset = (Offset + AlignMask) & ~AlignMask;
1328
1329 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1330 ConstPoolAddresses.push_back(CAddr);
1331 if (CPE.isMachineConstantPoolEntry()) {
Evan Chengcd5731d2006-09-12 20:59:59 +00001332 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +00001333 cerr << "Initialize memory with machine specific constant pool entry"
1334 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +00001335 abort();
1336 }
Evan Cheng1606e8e2009-03-13 07:51:59 +00001337 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1338 DOUT << "JIT: CP" << i << " at [0x"
1339 << std::hex << CAddr << std::dec << "]\n";
1340
1341 const Type *Ty = CPE.Val.ConstVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00001342 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
Chris Lattner1cc08382003-01-13 01:00:12 +00001343 }
1344}
1345
Nate Begeman37efe672006-04-22 18:53:45 +00001346void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001347 if (TheJIT->getJITInfo().hasCustomJumpTables())
1348 return;
1349
Nate Begeman37efe672006-04-22 18:53:45 +00001350 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1351 if (JT.empty()) return;
1352
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001353 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001354 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001355 NumEntries += JT[i].MBBs.size();
1356
1357 unsigned EntrySize = MJTI->getEntrySize();
1358
Nate Begeman37efe672006-04-22 18:53:45 +00001359 // Just allocate space for all the jump tables now. We will fix up the actual
1360 // MBB entries in the tables after we emit the code for each block, since then
1361 // we will know the final locations of the MBBs in memory.
1362 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001363 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001364}
1365
Jim Laskeyb92767a2006-12-14 22:53:42 +00001366void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001367 if (TheJIT->getJITInfo().hasCustomJumpTables())
1368 return;
1369
Nate Begeman37efe672006-04-22 18:53:45 +00001370 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001371 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001372
Jim Laskeyb92767a2006-12-14 22:53:42 +00001373 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001374 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1375 // For each jump table, place the offset from the beginning of the table
1376 // to the target address.
1377 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001378
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001379 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1380 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1381 // Store the offset of the basic block for this jump table slot in the
1382 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001383 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001384 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001385 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001386 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1387 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001388 }
1389 } else {
1390 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1391
1392 // For each jump table, map each target in the jump table to the address of
1393 // an emitted MachineBasicBlock.
1394 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1395
1396 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1397 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1398 // Store the address of the basic block for this jump table slot in the
1399 // memory we allocated for the jump table in 'initJumpTableInfo'
1400 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1401 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1402 }
Nate Begeman37efe672006-04-22 18:53:45 +00001403 }
1404}
1405
Evan Chengce4a70b2008-11-08 08:02:53 +00001406void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1407 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001408 SavedBufferBegin = BufferBegin;
1409 SavedBufferEnd = BufferEnd;
1410 SavedCurBufferPtr = CurBufferPtr;
1411
Evan Chengce4a70b2008-11-08 08:02:53 +00001412 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001413 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001414}
1415
Nate Begemand6b7a242009-02-18 08:31:02 +00001416void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1417 unsigned StubSize) {
1418 SavedBufferBegin = BufferBegin;
1419 SavedBufferEnd = BufferEnd;
1420 SavedCurBufferPtr = CurBufferPtr;
1421
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001422 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
Nate Begemand6b7a242009-02-18 08:31:02 +00001423 BufferEnd = BufferBegin+StubSize+1;
1424}
1425
Evan Chengce4a70b2008-11-08 08:02:53 +00001426void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001427 NumBytes += getCurrentPCOffset();
1428 std::swap(SavedBufferBegin, BufferBegin);
1429 BufferEnd = SavedBufferEnd;
1430 CurBufferPtr = SavedCurBufferPtr;
1431 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001432}
1433
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001434// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1435// in the constant pool that was last emitted with the 'emitConstantPool'
1436// method.
1437//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001438uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001439 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001440 "Invalid ConstantPoolIndex!");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001441 return ConstPoolAddresses[ConstantNum];
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001442}
1443
Nate Begeman37efe672006-04-22 18:53:45 +00001444// getJumpTableEntryAddress - Return the address of the JumpTable with index
1445// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1446//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001447uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001448 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1449 assert(Index < JT.size() && "Invalid jump table index!");
1450
1451 unsigned Offset = 0;
1452 unsigned EntrySize = JumpTable->getEntrySize();
1453
1454 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001455 Offset += JT[i].MBBs.size();
1456
1457 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001458
Evan Cheng5788d1a2008-12-10 02:32:19 +00001459 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001460}
1461
Chris Lattnere993cc22006-05-11 23:08:08 +00001462//===----------------------------------------------------------------------===//
1463// Public interface to this file
1464//===----------------------------------------------------------------------===//
1465
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001466JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
Chris Lattner9f2f1422007-12-06 01:08:09 +00001467 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +00001468}
1469
Misha Brukmand69c1e62003-07-28 19:09:06 +00001470// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001471// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001472// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1473// need to resolve function(s) that are being mis-codegenerated, so we need to
1474// resolve their addresses at runtime, and this is the way to do it.
1475extern "C" {
1476 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001477 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001478 return TheJIT->getPointerToFunction(F);
1479 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001480 }
1481}
Chris Lattnere993cc22006-05-11 23:08:08 +00001482
1483// getPointerToFunctionOrStub - If the specified function has been
1484// code-gen'd, return a pointer to the function. If not, compile it, or use
1485// a stub to implement lazy compilation if available.
1486//
1487void *JIT::getPointerToFunctionOrStub(Function *F) {
1488 // If we have already code generated the function, just return the address.
1489 if (void *Addr = getPointerToGlobalIfAvailable(F))
1490 return Addr;
1491
Chris Lattnere7484012007-02-24 02:57:03 +00001492 // Get a stub if the target supports it.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001493 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Evan Chenga044dfc2008-08-20 00:28:12 +00001494 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001495 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001496}
1497
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +00001498void JIT::registerMachineCodeInfo(MachineCodeInfo *mc) {
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001499 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +00001500 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1501
1502 JE->setMachineCodeInfo(mc);
1503}
1504
Nate Begemand6b7a242009-02-18 08:31:02 +00001505void JIT::updateFunctionStub(Function *F) {
1506 // Get the empty stub we generated earlier.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001507 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001508 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1509 void *Stub = JE->getJITResolver().getFunctionStub(F);
1510
1511 // Tell the target jit info to rewrite the stub at the specified address,
1512 // rather than creating a new one.
1513 void *Addr = getPointerToGlobalIfAvailable(F);
1514 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1515}
1516
1517/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1518/// that were emitted during code generation.
1519///
1520void JIT::updateDlsymStubTable() {
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001521 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001522 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1523
1524 SmallVector<GlobalValue*, 8> GVs;
1525 SmallVector<void*, 8> Ptrs;
Nate Begeman841c6a42009-03-11 07:03:43 +00001526 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
Nate Begemand6b7a242009-02-18 08:31:02 +00001527
1528 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1529
Nate Begeman841c6a42009-03-11 07:03:43 +00001530 unsigned nStubs = GVs.size() + ExtFns.size();
1531
Nate Begemand6b7a242009-02-18 08:31:02 +00001532 // If there are no relocatable stubs, return.
Nate Begeman841c6a42009-03-11 07:03:43 +00001533 if (nStubs == 0)
Nate Begemand6b7a242009-02-18 08:31:02 +00001534 return;
1535
1536 // If there are no new relocatable stubs, return.
1537 void *CurTable = JE->getMemMgr()->getDlsymTable();
Nate Begeman841c6a42009-03-11 07:03:43 +00001538 if (CurTable && (*(unsigned *)CurTable == nStubs))
Nate Begemand6b7a242009-02-18 08:31:02 +00001539 return;
1540
1541 // Calculate the size of the stub info
Nate Begeman841c6a42009-03-11 07:03:43 +00001542 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
Nate Begemand6b7a242009-02-18 08:31:02 +00001543
1544 SmallVector<unsigned, 8> Offsets;
1545 for (unsigned i = 0; i != GVs.size(); ++i) {
1546 Offsets.push_back(offset);
1547 offset += GVs[i]->getName().length() + 1;
1548 }
Nate Begeman841c6a42009-03-11 07:03:43 +00001549 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1550 i != e; ++i) {
1551 Offsets.push_back(offset);
1552 offset += strlen(i->first()) + 1;
1553 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001554
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001555 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begemand6b7a242009-02-18 08:31:02 +00001556 JE->startGVStub(0, offset, 4);
1557
1558 // Emit the number of records
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001559 JE->emitInt32(nStubs);
Nate Begemand6b7a242009-02-18 08:31:02 +00001560
1561 // Emit the string offsets
Nate Begeman841c6a42009-03-11 07:03:43 +00001562 for (unsigned i = 0; i != nStubs; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001563 JE->emitInt32(Offsets[i]);
Nate Begemand6b7a242009-02-18 08:31:02 +00001564
Nate Begeman66941982009-03-04 19:10:38 +00001565 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1566 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1567 // relocation can write the relocated pointer at the appropriate place in
1568 // the stub.
1569 for (unsigned i = 0; i != GVs.size(); ++i) {
1570 intptr_t Ptr = (intptr_t)Ptrs[i];
1571 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1572
1573 if (isa<Function>(GVs[i]))
1574 Ptr |= (intptr_t)1;
1575
Nate Begeman841c6a42009-03-11 07:03:43 +00001576 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001577 JE->emitInt64(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001578 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001579 JE->emitInt32(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001580 }
1581 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1582 i != e; ++i) {
1583 intptr_t Ptr = (intptr_t)i->second | 1;
1584
1585 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001586 JE->emitInt64(Ptr);
Nate Begemand6b7a242009-02-18 08:31:02 +00001587 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001588 JE->emitInt32(Ptr);
Nate Begeman66941982009-03-04 19:10:38 +00001589 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001590
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001591 // Emit the strings.
Nate Begemand6b7a242009-02-18 08:31:02 +00001592 for (unsigned i = 0; i != GVs.size(); ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001593 JE->emitString(GVs[i]->getName());
Nate Begeman841c6a42009-03-11 07:03:43 +00001594 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1595 i != e; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001596 JE->emitString(i->first());
Nate Begemand6b7a242009-02-18 08:31:02 +00001597
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001598 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1599 // deallocate space for the old one, if one existed.
Nate Begemand6b7a242009-02-18 08:31:02 +00001600 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1601}
1602
Chris Lattnere993cc22006-05-11 23:08:08 +00001603/// freeMachineCodeForFunction - release machine code memory for given Function.
1604///
1605void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001606
Chris Lattnere993cc22006-05-11 23:08:08 +00001607 // Delete translation for this from the ExecutionEngine, so it will get
1608 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001609 void *OldPtr = updateGlobalMapping(F, 0);
1610
1611 if (OldPtr)
1612 RemoveFunctionFromSymbolTable(OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001613
1614 // Free the actual memory for the function body and related stuff.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001615 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1616 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001617}
1618