blob: 91d9441b46778be38424019160d59e87fcfed8dc [file] [log] [blame]
Eric Christopherbb498ca2011-04-22 03:07:06 +00001//===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
Daniel Dunbar6aec2982010-11-17 16:06:43 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "MCJIT.h"
Jim Grosbach34714a02011-03-22 18:05:27 +000011#include "llvm/DerivedTypes.h"
Jim Grosbach31649e62011-03-18 22:48:41 +000012#include "llvm/Function.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000013#include "llvm/ExecutionEngine/GenericValue.h"
Andrew Kaylor776054d2012-11-06 18:51:59 +000014#include "llvm/ExecutionEngine/JITEventListener.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000015#include "llvm/ExecutionEngine/JITMemoryManager.h"
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000016#include "llvm/ExecutionEngine/MCJIT.h"
17#include "llvm/ExecutionEngine/ObjectBuffer.h"
18#include "llvm/ExecutionEngine/ObjectImage.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000020#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000021#include "llvm/Support/DynamicLibrary.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000022#include "llvm/Support/MemoryBuffer.h"
Andrew Kaylorea708d12012-08-07 18:33:00 +000023#include "llvm/Support/MutexGuard.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000024#include "llvm/DataLayout.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000025
26using namespace llvm;
27
28namespace {
29
30static struct RegisterJIT {
31 RegisterJIT() { MCJIT::Register(); }
32} JITRegistrator;
33
34}
35
36extern "C" void LLVMLinkInMCJIT() {
37}
38
39ExecutionEngine *MCJIT::createJIT(Module *M,
40 std::string *ErrorStr,
41 JITMemoryManager *JMM,
Daniel Dunbar6aec2982010-11-17 16:06:43 +000042 bool GVsWithCode,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000043 TargetMachine *TM) {
Daniel Dunbar6aec2982010-11-17 16:06:43 +000044 // Try to register the program as a source of symbols to resolve against.
45 //
46 // FIXME: Don't do this here.
47 sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
48
Andrew Kaylor647d6d72012-11-01 00:46:04 +000049 return new MCJIT(M, TM, JMM, GVsWithCode);
Daniel Dunbar6aec2982010-11-17 16:06:43 +000050}
51
Jim Grosbach8005bcd2012-08-21 15:42:49 +000052MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
53 bool AllocateGVsWithCode)
54 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(MM), Dyld(MM),
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000055 isCompiled(false), M(m) {
Jim Grosbach31649e62011-03-18 22:48:41 +000056
Micah Villmow3574eca2012-10-08 16:38:25 +000057 setDataLayout(TM->getDataLayout());
Andrew Kaylorea708d12012-08-07 18:33:00 +000058}
59
60MCJIT::~MCJIT() {
Andrew Kaylor776054d2012-11-06 18:51:59 +000061 if (LoadedObject)
62 NotifyFreeingObject(LoadedObject.get());
Andrew Kaylorea708d12012-08-07 18:33:00 +000063 delete MemMgr;
64 delete TM;
65}
66
67void MCJIT::emitObject(Module *m) {
68 /// Currently, MCJIT only supports a single module and the module passed to
69 /// this function call is expected to be the contained module. The module
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000070 /// is passed as a parameter here to prepare for multiple module support in
Andrew Kaylorea708d12012-08-07 18:33:00 +000071 /// the future.
72 assert(M == m);
73
74 // Get a thread lock to make sure we aren't trying to compile multiple times
75 MutexGuard locked(lock);
76
77 // FIXME: Track compilation state on a per-module basis when multiple modules
78 // are supported.
79 // Re-compilation is not supported
80 if (isCompiled)
81 return;
82
83 PassManager PM;
84
Micah Villmow3574eca2012-10-08 16:38:25 +000085 PM.add(new DataLayout(*TM->getDataLayout()));
Jim Grosbach31649e62011-03-18 22:48:41 +000086
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000087 // The RuntimeDyld will take ownership of this shortly
88 OwningPtr<ObjectBufferStream> Buffer(new ObjectBufferStream());
89
Jim Grosbach31649e62011-03-18 22:48:41 +000090 // Turn the machine code intermediate representation into bytes in memory
91 // that may be executed.
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000092 if (TM->addPassesToEmitMC(PM, Ctx, Buffer->getOStream(), false)) {
Jim Grosbach31649e62011-03-18 22:48:41 +000093 report_fatal_error("Target does not support MC emission!");
94 }
95
96 // Initialize passes.
Andrew Kaylorea708d12012-08-07 18:33:00 +000097 PM.run(*m);
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000098 // Flush the output buffer to get the generated code into memory
99 Buffer->flush();
Jim Grosbachf9229102011-03-22 01:06:42 +0000100
101 // Load the object into the dynamic linker.
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000102 // handing off ownership of the buffer
103 LoadedObject.reset(Dyld.loadObject(Buffer.take()));
104 if (!LoadedObject)
Jim Grosbach8086f3b2011-03-23 19:51:34 +0000105 report_fatal_error(Dyld.getErrorString());
Andrew Kaylorea708d12012-08-07 18:33:00 +0000106
Jim Grosbach69e81322011-04-13 15:28:10 +0000107 // Resolve any relocations.
108 Dyld.resolveRelocations();
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000109
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000110 // FIXME: Make this optional, maybe even move it to a JIT event listener
111 LoadedObject->registerWithDebugger();
112
Andrew Kaylor776054d2012-11-06 18:51:59 +0000113 NotifyObjectEmitted(*LoadedObject);
114
Andrew Kaylorea708d12012-08-07 18:33:00 +0000115 // FIXME: Add support for per-module compilation state
116 isCompiled = true;
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000117}
118
Andrew Kaylor28989882012-11-05 20:57:16 +0000119// FIXME: Add a parameter to identify which object is being finalized when
120// MCJIT supports multiple modules.
121void MCJIT::finalizeObject() {
122 // If the module hasn't been compiled, just do that.
123 if (!isCompiled) {
124 // If the call to Dyld.resolveRelocations() is removed from emitObject()
125 // we'll need to do that here.
126 emitObject(M);
127 return;
128 }
129
130 // Resolve any relocations.
131 Dyld.resolveRelocations();
132}
133
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000134void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
135 report_fatal_error("not yet implemented");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000136}
137
138void *MCJIT::getPointerToFunction(Function *F) {
Jim Grosbach35ed8422012-09-05 16:50:40 +0000139 // FIXME: This should really return a uint64_t since it's a pointer in the
140 // target address space, not our local address space. That's part of the
141 // ExecutionEngine interface, though. Fix that when the old JIT finally
142 // dies.
143
Andrew Kaylorea708d12012-08-07 18:33:00 +0000144 // FIXME: Add support for per-module compilation state
145 if (!isCompiled)
146 emitObject(M);
147
Jim Grosbach34714a02011-03-22 18:05:27 +0000148 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
149 bool AbortOnFailure = !F->hasExternalWeakLinkage();
150 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
151 addGlobalMapping(F, Addr);
152 return Addr;
153 }
154
Andrew Kaylorea708d12012-08-07 18:33:00 +0000155 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbach3ec2c7c2011-05-18 23:53:21 +0000156 // FIXME: Should we be using the mangler for this? Probably.
Jim Grosbach35ed8422012-09-05 16:50:40 +0000157 //
158 // This is the accessor for the target address, so make sure to check the
159 // load address of the symbol, not the local address.
Jim Grosbach3ec2c7c2011-05-18 23:53:21 +0000160 StringRef BaseName = F->getName();
161 if (BaseName[0] == '\1')
Jim Grosbach35ed8422012-09-05 16:50:40 +0000162 return (void*)Dyld.getSymbolLoadAddress(BaseName.substr(1));
163 return (void*)Dyld.getSymbolLoadAddress((TM->getMCAsmInfo()->getGlobalPrefix()
Jim Grosbachc0ceedb2011-05-19 00:45:05 +0000164 + BaseName).str());
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000165}
166
167void *MCJIT::recompileAndRelinkFunction(Function *F) {
168 report_fatal_error("not yet implemented");
169}
170
171void MCJIT::freeMachineCodeForFunction(Function *F) {
172 report_fatal_error("not yet implemented");
173}
174
175GenericValue MCJIT::runFunction(Function *F,
176 const std::vector<GenericValue> &ArgValues) {
Jim Grosbach34714a02011-03-22 18:05:27 +0000177 assert(F && "Function *F was null at entry to run()");
178
Jim Grosbach31649e62011-03-18 22:48:41 +0000179 void *FPtr = getPointerToFunction(F);
Jim Grosbach34714a02011-03-22 18:05:27 +0000180 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000181 FunctionType *FTy = F->getFunctionType();
182 Type *RetTy = FTy->getReturnType();
Jim Grosbach34714a02011-03-22 18:05:27 +0000183
184 assert((FTy->getNumParams() == ArgValues.size() ||
185 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
186 "Wrong number of arguments passed into function!");
187 assert(FTy->getNumParams() == ArgValues.size() &&
188 "This doesn't support passing arguments through varargs (yet)!");
189
190 // Handle some common cases first. These cases correspond to common `main'
191 // prototypes.
192 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
193 switch (ArgValues.size()) {
194 case 3:
195 if (FTy->getParamType(0)->isIntegerTy(32) &&
196 FTy->getParamType(1)->isPointerTy() &&
197 FTy->getParamType(2)->isPointerTy()) {
198 int (*PF)(int, char **, const char **) =
199 (int(*)(int, char **, const char **))(intptr_t)FPtr;
200
201 // Call the function.
202 GenericValue rv;
203 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
204 (char **)GVTOP(ArgValues[1]),
205 (const char **)GVTOP(ArgValues[2])));
206 return rv;
207 }
208 break;
209 case 2:
210 if (FTy->getParamType(0)->isIntegerTy(32) &&
211 FTy->getParamType(1)->isPointerTy()) {
212 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
213
214 // Call the function.
215 GenericValue rv;
216 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
217 (char **)GVTOP(ArgValues[1])));
218 return rv;
219 }
220 break;
221 case 1:
222 if (FTy->getNumParams() == 1 &&
223 FTy->getParamType(0)->isIntegerTy(32)) {
224 GenericValue rv;
225 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
226 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
227 return rv;
228 }
229 break;
230 }
231 }
232
233 // Handle cases where no arguments are passed first.
234 if (ArgValues.empty()) {
235 GenericValue rv;
236 switch (RetTy->getTypeID()) {
237 default: llvm_unreachable("Unknown return type for function call!");
238 case Type::IntegerTyID: {
239 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
240 if (BitWidth == 1)
241 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
242 else if (BitWidth <= 8)
243 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
244 else if (BitWidth <= 16)
245 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
246 else if (BitWidth <= 32)
247 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
248 else if (BitWidth <= 64)
249 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
250 else
251 llvm_unreachable("Integer types > 64 bits not supported");
252 return rv;
253 }
254 case Type::VoidTyID:
255 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
256 return rv;
257 case Type::FloatTyID:
258 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
259 return rv;
260 case Type::DoubleTyID:
261 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
262 return rv;
263 case Type::X86_FP80TyID:
264 case Type::FP128TyID:
265 case Type::PPC_FP128TyID:
266 llvm_unreachable("long double not supported yet");
Jim Grosbach34714a02011-03-22 18:05:27 +0000267 case Type::PointerTyID:
268 return PTOGV(((void*(*)())(intptr_t)FPtr)());
269 }
270 }
271
Craig Topper85814382012-02-07 05:05:23 +0000272 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000273}
Danil Malyshev30b9e322012-03-28 21:46:36 +0000274
275void *MCJIT::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky5fe01982012-04-29 12:40:47 +0000276 bool AbortOnFailure) {
Andrew Kaylorea708d12012-08-07 18:33:00 +0000277 // FIXME: Add support for per-module compilation state
278 if (!isCompiled)
279 emitObject(M);
280
Danil Malyshev30b9e322012-03-28 21:46:36 +0000281 if (!isSymbolSearchingDisabled() && MemMgr) {
282 void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
283 if (ptr)
284 return ptr;
285 }
286
287 /// If a LazyFunctionCreator is installed, use it to get/create the function.
288 if (LazyFunctionCreator)
289 if (void *RP = LazyFunctionCreator(Name))
290 return RP;
291
292 if (AbortOnFailure) {
293 report_fatal_error("Program used external function '"+Name+
Eli Bendersky5fe01982012-04-29 12:40:47 +0000294 "' which could not be resolved!");
Danil Malyshev30b9e322012-03-28 21:46:36 +0000295 }
296 return 0;
297}
Andrew Kaylor776054d2012-11-06 18:51:59 +0000298
299void MCJIT::RegisterJITEventListener(JITEventListener *L) {
300 if (L == NULL)
301 return;
302 MutexGuard locked(lock);
303 EventListeners.push_back(L);
304}
305void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
306 if (L == NULL)
307 return;
308 MutexGuard locked(lock);
309 SmallVector<JITEventListener*, 2>::reverse_iterator I=
310 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
311 if (I != EventListeners.rend()) {
312 std::swap(*I, EventListeners.back());
313 EventListeners.pop_back();
314 }
315}
316void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
317 MutexGuard locked(lock);
318 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
319 EventListeners[I]->NotifyObjectEmitted(Obj);
320 }
321}
322void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
323 MutexGuard locked(lock);
324 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
325 EventListeners[I]->NotifyFreeingObject(Obj);
326 }
327}