blob: 435ffd7cdfaa9b26b04e2f25b58e491846ed6c1b [file] [log] [blame]
Eric Christopher5c896f72011-04-22 03:07:06 +00001//===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
Daniel Dunbar7e5d8a72010-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"
11#include "llvm/ExecutionEngine/GenericValue.h"
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +000012#include "llvm/ExecutionEngine/JITEventListener.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000013#include "llvm/ExecutionEngine/JITMemoryManager.h"
Andrew Kayloradc70562012-10-02 21:18:39 +000014#include "llvm/ExecutionEngine/MCJIT.h"
15#include "llvm/ExecutionEngine/ObjectBuffer.h"
16#include "llvm/ExecutionEngine/ObjectImage.h"
Andrew Kaylor31be5ef2013-04-29 17:49:40 +000017#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/Function.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000021#include "llvm/IR/Mangler.h"
Andrew Kaylorea395922013-10-01 01:47:35 +000022#include "llvm/IR/Module.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000023#include "llvm/MC/MCAsmInfo.h"
Lang Hames173c69f2014-01-08 04:09:09 +000024#include "llvm/Object/Archive.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000025#include "llvm/PassManager.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000026#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Support/ErrorHandling.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000028#include "llvm/Support/MemoryBuffer.h"
Zachary Turnerc04b8922014-06-20 21:07:14 +000029#include "llvm/Support/MutexGuard.h"
Rafael Espindoladaeafb42014-02-19 17:23:20 +000030#include "llvm/Target/TargetLowering.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000031
32using namespace llvm;
33
34namespace {
35
36static struct RegisterJIT {
37 RegisterJIT() { MCJIT::Register(); }
38} JITRegistrator;
39
40}
41
42extern "C" void LLVMLinkInMCJIT() {
43}
44
45ExecutionEngine *MCJIT::createJIT(Module *M,
46 std::string *ErrorStr,
Filip Pizlo9bc53e82013-05-14 19:29:00 +000047 RTDyldMemoryManager *MemMgr,
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000048 TargetMachine *TM) {
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000049 // Try to register the program as a source of symbols to resolve against.
50 //
51 // FIXME: Don't do this here.
Craig Topper353eda42014-04-24 06:44:33 +000052 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000053
Rafael Espindolab9a23cd2014-07-31 01:14:09 +000054 return new MCJIT(M, TM, MemMgr ? MemMgr : new SectionMemoryManager());
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000055}
56
Rafael Espindolab9a23cd2014-07-31 01:14:09 +000057MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM)
Craig Topper353eda42014-04-24 06:44:33 +000058 : ExecutionEngine(m), TM(tm), Ctx(nullptr), MemMgr(this, MM), Dyld(&MemMgr),
59 ObjCache(nullptr) {
Jim Grosbach7b162492011-03-18 22:48:41 +000060
Andrew Kaylorc89fc822013-10-24 00:19:14 +000061 OwnedModules.addModule(m);
Micah Villmowcdfe20b2012-10-08 16:38:25 +000062 setDataLayout(TM->getDataLayout());
Andrew Kaylor1a568c32012-08-07 18:33:00 +000063}
64
65MCJIT::~MCJIT() {
Zachary Turnerc04b8922014-06-20 21:07:14 +000066 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000067 // FIXME: We are managing our modules, so we do not want the base class
68 // ExecutionEngine to manage them as well. To avoid double destruction
69 // of the first (and only) module added in ExecutionEngine constructor
70 // we remove it from EE and will destruct it ourselves.
71 //
72 // It may make sense to move our module manager (based on SmallStPtr) back
73 // into EE if the JIT and Interpreter can live with it.
74 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
75 // runStaticConstructorsDestructors could be moved back to EE as well.
76 //
77 Modules.clear();
Andrew Kaylorc442a762013-10-16 00:14:21 +000078 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000079
Lang Hames173c69f2014-01-08 04:09:09 +000080 LoadedObjectList::iterator it, end;
81 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
82 ObjectImage *Obj = *it;
Chandler Carruthd55d1592013-10-24 09:52:56 +000083 if (Obj) {
84 NotifyFreeingObject(*Obj);
85 delete Obj;
86 }
87 }
Andrew Kaylorea395922013-10-01 01:47:35 +000088 LoadedObjects.clear();
Lang Hames173c69f2014-01-08 04:09:09 +000089
Lang Hames173c69f2014-01-08 04:09:09 +000090 Archives.clear();
91
Andrew Kaylor1a568c32012-08-07 18:33:00 +000092 delete TM;
93}
94
Andrew Kaylorea395922013-10-01 01:47:35 +000095void MCJIT::addModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +000096 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000097 OwnedModules.addModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +000098}
99
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000100bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000101 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000102 return OwnedModules.removeModule(M);
103}
104
105
106
David Blaikie7a1e7752014-04-29 21:52:46 +0000107void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
108 ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
Juergen Ributzka6ff29a72014-03-26 18:19:27 +0000109 if (!LoadedObject || Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000110 report_fatal_error(Dyld.getErrorString());
111
112 LoadedObjects.push_back(LoadedObject);
113
114 NotifyObjectEmitted(*LoadedObject);
115}
116
Rafael Espindolace47a052014-08-01 18:09:32 +0000117void MCJIT::addArchive(std::unique_ptr<object::Archive> A) {
118 Archives.push_back(std::move(A));
Lang Hames173c69f2014-01-08 04:09:09 +0000119}
120
121
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000122void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000123 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000124 ObjCache = NewCache;
125}
126
Andrew Kaylorea395922013-10-01 01:47:35 +0000127ObjectBufferStream* MCJIT::emitObject(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000128 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000129
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000130 // This must be a module which has already been added but not loaded to this
131 // MCJIT instance, since these conditions are tested by our caller,
132 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000133
134 PassManager PM;
135
Rafael Espindola339430f2014-02-25 23:25:17 +0000136 M->setDataLayout(TM->getDataLayout());
137 PM.add(new DataLayoutPass(M));
Jim Grosbach7b162492011-03-18 22:48:41 +0000138
Andrew Kayloradc70562012-10-02 21:18:39 +0000139 // The RuntimeDyld will take ownership of this shortly
Ahmed Charles56440fd2014-03-06 05:51:42 +0000140 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
Andrew Kayloradc70562012-10-02 21:18:39 +0000141
Jim Grosbach7b162492011-03-18 22:48:41 +0000142 // Turn the machine code intermediate representation into bytes in memory
143 // that may be executed.
Lang Hamesbc876012014-04-18 06:48:23 +0000144 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
145 !getVerifyModules())) {
Jim Grosbach7b162492011-03-18 22:48:41 +0000146 report_fatal_error("Target does not support MC emission!");
147 }
148
149 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000150 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000151 // Flush the output buffer to get the generated code into memory
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000152 CompiledObject->flush();
153
154 // If we have an object cache, tell it about the new object.
155 // Note that we're using the compiled image, not the loaded image (as below).
156 if (ObjCache) {
157 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
158 // to create a temporary object here and delete it after the call.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000159 std::unique_ptr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
Andrew Kaylorea395922013-10-01 01:47:35 +0000160 ObjCache->notifyObjectCompiled(M, MB.get());
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000161 }
162
Ahmed Charles96c9d952014-03-05 10:19:29 +0000163 return CompiledObject.release();
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000164}
165
Andrew Kaylorea395922013-10-01 01:47:35 +0000166void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000167 // Get a thread lock to make sure we aren't trying to load multiple times
Zachary Turnerc04b8922014-06-20 21:07:14 +0000168 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000169
Andrew Kaylorea395922013-10-01 01:47:35 +0000170 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000171 assert(OwnedModules.ownsModule(M) &&
172 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000173
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000174 // Re-compilation is not supported
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000175 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000176 return;
177
Ahmed Charles56440fd2014-03-06 05:51:42 +0000178 std::unique_ptr<ObjectBuffer> ObjectToLoad;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000179 // Try to load the pre-compiled object from cache if possible
Craig Topper353eda42014-04-24 06:44:33 +0000180 if (ObjCache) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000181 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
Craig Topper353eda42014-04-24 06:44:33 +0000182 if (PreCompiledObject.get())
Ahmed Charles96c9d952014-03-05 10:19:29 +0000183 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000184 }
185
186 // If the cache did not contain a suitable object, compile the object
187 if (!ObjectToLoad) {
188 ObjectToLoad.reset(emitObject(M));
189 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
190 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000191
192 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000193 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Ahmed Charles96c9d952014-03-05 10:19:29 +0000194 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
Lang Hames173c69f2014-01-08 04:09:09 +0000195 LoadedObjects.push_back(LoadedObject);
Andrew Kayloradc70562012-10-02 21:18:39 +0000196 if (!LoadedObject)
Jim Grosbachc114d892011-03-23 19:51:34 +0000197 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000198
Andrew Kayloradc70562012-10-02 21:18:39 +0000199 // FIXME: Make this optional, maybe even move it to a JIT event listener
200 LoadedObject->registerWithDebugger();
201
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000202 NotifyObjectEmitted(*LoadedObject);
203
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000204 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000205}
206
Andrew Kaylorea395922013-10-01 01:47:35 +0000207void MCJIT::finalizeLoadedModules() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000208 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000209
Andrew Kaylorea395922013-10-01 01:47:35 +0000210 // Resolve any outstanding relocations.
211 Dyld.resolveRelocations();
212
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000213 OwnedModules.markAllLoadedModulesAsFinalized();
214
Andrew Kaylorea395922013-10-01 01:47:35 +0000215 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000216 Dyld.registerEHFrames();
217
Andrew Kaylorea395922013-10-01 01:47:35 +0000218 // Set page permissions.
219 MemMgr.finalizeMemory();
220}
221
222// FIXME: Rename this.
223void MCJIT::finalizeObject() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000224 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000225
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000226 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
227 E = OwnedModules.end_added();
228 I != E; ++I) {
229 Module *M = *I;
230 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000231 }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000232
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000233 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000234}
235
236void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000237 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000238
Andrew Kaylorea395922013-10-01 01:47:35 +0000239 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000240 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000241
242 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000243 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000244 generateCodeForModule(M);
245
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000246 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000247}
248
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000249void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
250 report_fatal_error("not yet implemented");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000251}
252
Andrew Kaylorea395922013-10-01 01:47:35 +0000253uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
Rafael Espindola58873562014-01-03 19:21:54 +0000254 Mangler Mang(TM->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000255 SmallString<128> FullName;
256 Mang.getNameWithPrefix(FullName, Name);
257 return Dyld.getSymbolLoadAddress(FullName);
Andrew Kaylorea395922013-10-01 01:47:35 +0000258}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000259
Andrew Kaylorea395922013-10-01 01:47:35 +0000260Module *MCJIT::findModuleForSymbol(const std::string &Name,
261 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000262 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000263
Andrew Kaylorea395922013-10-01 01:47:35 +0000264 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000265 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
266 E = OwnedModules.end_added();
267 I != E; ++I) {
268 Module *M = *I;
Andrew Kaylorea395922013-10-01 01:47:35 +0000269 Function *F = M->getFunction(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000270 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000271 return M;
272 if (!CheckFunctionsOnly) {
273 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000274 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000275 return M;
276 // FIXME: Do we need to worry about global aliases?
277 }
278 }
279 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000280 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000281}
282
283uint64_t MCJIT::getSymbolAddress(const std::string &Name,
284 bool CheckFunctionsOnly)
285{
Zachary Turnerc04b8922014-06-20 21:07:14 +0000286 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000287
Andrew Kaylorea395922013-10-01 01:47:35 +0000288 // First, check to see if we already have this symbol.
289 uint64_t Addr = getExistingSymbolAddress(Name);
290 if (Addr)
291 return Addr;
292
Rafael Espindolace47a052014-08-01 18:09:32 +0000293 for (std::unique_ptr<object::Archive> &A : Archives) {
Lang Hames173c69f2014-01-08 04:09:09 +0000294 // Look for our symbols in each Archive
295 object::Archive::child_iterator ChildIt = A->findSym(Name);
Rafael Espindola23a97502014-01-21 16:09:45 +0000296 if (ChildIt != A->child_end()) {
Lang Hames173c69f2014-01-08 04:09:09 +0000297 // FIXME: Support nested archives?
Rafael Espindolaae460022014-06-16 16:08:36 +0000298 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
299 ChildIt->getAsBinary();
300 if (ChildBinOrErr.getError())
301 continue;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000302 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
Rafael Espindolaae460022014-06-16 16:08:36 +0000303 if (ChildBin->isObject()) {
David Blaikie7a1e7752014-04-29 21:52:46 +0000304 std::unique_ptr<object::ObjectFile> OF(
305 static_cast<object::ObjectFile *>(ChildBin.release()));
Lang Hames173c69f2014-01-08 04:09:09 +0000306 // This causes the object file to be loaded.
David Blaikie7a1e7752014-04-29 21:52:46 +0000307 addObjectFile(std::move(OF));
Lang Hames173c69f2014-01-08 04:09:09 +0000308 // The address should be here now.
309 Addr = getExistingSymbolAddress(Name);
310 if (Addr)
311 return Addr;
312 }
313 }
314 }
315
Andrew Kaylorea395922013-10-01 01:47:35 +0000316 // If it hasn't already been generated, see if it's in one of our modules.
317 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
318 if (!M)
319 return 0;
320
Andrew Kaylorea395922013-10-01 01:47:35 +0000321 generateCodeForModule(M);
322
323 // Check the RuntimeDyld table again, it should be there now.
324 return getExistingSymbolAddress(Name);
325}
326
327uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000328 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000329 uint64_t Result = getSymbolAddress(Name, false);
330 if (Result != 0)
331 finalizeLoadedModules();
332 return Result;
333}
334
335uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000336 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000337 uint64_t Result = getSymbolAddress(Name, true);
338 if (Result != 0)
339 finalizeLoadedModules();
340 return Result;
341}
342
343// Deprecated. Use getFunctionAddress instead.
344void *MCJIT::getPointerToFunction(Function *F) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000345 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000346
Jim Grosbachd5274402011-03-22 18:05:27 +0000347 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
348 bool AbortOnFailure = !F->hasExternalWeakLinkage();
349 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
350 addGlobalMapping(F, Addr);
351 return Addr;
352 }
353
Andrew Kaylorea395922013-10-01 01:47:35 +0000354 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000355 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000356
357 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000358 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000359 generateCodeForModule(M);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000360 else if (!OwnedModules.hasModuleBeenLoaded(M))
361 // If this function doesn't belong to one of our modules, we're done.
Craig Topper353eda42014-04-24 06:44:33 +0000362 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000363
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000364 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000365 //
366 // This is the accessor for the target address, so make sure to check the
367 // load address of the symbol, not the local address.
Rafael Espindola58873562014-01-03 19:21:54 +0000368 Mangler Mang(TM->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000369 SmallString<128> Name;
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000370 TM->getNameWithPrefix(Name, F, Mang);
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000371 return (void*)Dyld.getSymbolLoadAddress(Name);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000372}
373
374void *MCJIT::recompileAndRelinkFunction(Function *F) {
375 report_fatal_error("not yet implemented");
376}
377
378void MCJIT::freeMachineCodeForFunction(Function *F) {
379 report_fatal_error("not yet implemented");
380}
381
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000382void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
383 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
384 for (; I != E; ++I) {
385 ExecutionEngine::runStaticConstructorsDestructors(*I, isDtors);
386 }
387}
388
389void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
390 // Execute global ctors/dtors for each module in the program.
391 runStaticConstructorsDestructorsInModulePtrSet(
392 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
393 runStaticConstructorsDestructorsInModulePtrSet(
394 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
395 runStaticConstructorsDestructorsInModulePtrSet(
396 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
397}
398
399Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
400 ModulePtrSet::iterator I,
401 ModulePtrSet::iterator E) {
402 for (; I != E; ++I) {
403 if (Function *F = (*I)->getFunction(FnName))
404 return F;
405 }
Craig Topper353eda42014-04-24 06:44:33 +0000406 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000407}
408
409Function *MCJIT::FindFunctionNamed(const char *FnName) {
410 Function *F = FindFunctionNamedInModulePtrSet(
411 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
412 if (!F)
413 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
414 OwnedModules.end_loaded());
415 if (!F)
416 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
417 OwnedModules.end_finalized());
418 return F;
419}
420
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000421GenericValue MCJIT::runFunction(Function *F,
422 const std::vector<GenericValue> &ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000423 assert(F && "Function *F was null at entry to run()");
424
Jim Grosbach7b162492011-03-18 22:48:41 +0000425 void *FPtr = getPointerToFunction(F);
Jim Grosbachd5274402011-03-22 18:05:27 +0000426 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000427 FunctionType *FTy = F->getFunctionType();
428 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000429
430 assert((FTy->getNumParams() == ArgValues.size() ||
431 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
432 "Wrong number of arguments passed into function!");
433 assert(FTy->getNumParams() == ArgValues.size() &&
434 "This doesn't support passing arguments through varargs (yet)!");
435
436 // Handle some common cases first. These cases correspond to common `main'
437 // prototypes.
438 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
439 switch (ArgValues.size()) {
440 case 3:
441 if (FTy->getParamType(0)->isIntegerTy(32) &&
442 FTy->getParamType(1)->isPointerTy() &&
443 FTy->getParamType(2)->isPointerTy()) {
444 int (*PF)(int, char **, const char **) =
445 (int(*)(int, char **, const char **))(intptr_t)FPtr;
446
447 // Call the function.
448 GenericValue rv;
449 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
450 (char **)GVTOP(ArgValues[1]),
451 (const char **)GVTOP(ArgValues[2])));
452 return rv;
453 }
454 break;
455 case 2:
456 if (FTy->getParamType(0)->isIntegerTy(32) &&
457 FTy->getParamType(1)->isPointerTy()) {
458 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
459
460 // Call the function.
461 GenericValue rv;
462 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
463 (char **)GVTOP(ArgValues[1])));
464 return rv;
465 }
466 break;
467 case 1:
468 if (FTy->getNumParams() == 1 &&
469 FTy->getParamType(0)->isIntegerTy(32)) {
470 GenericValue rv;
471 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
472 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
473 return rv;
474 }
475 break;
476 }
477 }
478
479 // Handle cases where no arguments are passed first.
480 if (ArgValues.empty()) {
481 GenericValue rv;
482 switch (RetTy->getTypeID()) {
483 default: llvm_unreachable("Unknown return type for function call!");
484 case Type::IntegerTyID: {
485 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
486 if (BitWidth == 1)
487 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
488 else if (BitWidth <= 8)
489 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
490 else if (BitWidth <= 16)
491 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
492 else if (BitWidth <= 32)
493 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
494 else if (BitWidth <= 64)
495 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
496 else
497 llvm_unreachable("Integer types > 64 bits not supported");
498 return rv;
499 }
500 case Type::VoidTyID:
501 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
502 return rv;
503 case Type::FloatTyID:
504 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
505 return rv;
506 case Type::DoubleTyID:
507 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
508 return rv;
509 case Type::X86_FP80TyID:
510 case Type::FP128TyID:
511 case Type::PPC_FP128TyID:
512 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000513 case Type::PointerTyID:
514 return PTOGV(((void*(*)())(intptr_t)FPtr)());
515 }
516 }
517
Craig Toppera2886c22012-02-07 05:05:23 +0000518 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000519}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000520
521void *MCJIT::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000522 bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000523 if (!isSymbolSearchingDisabled()) {
524 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
Danil Malyshevbfee5422012-03-28 21:46:36 +0000525 if (ptr)
526 return ptr;
527 }
528
529 /// If a LazyFunctionCreator is installed, use it to get/create the function.
530 if (LazyFunctionCreator)
531 if (void *RP = LazyFunctionCreator(Name))
532 return RP;
533
534 if (AbortOnFailure) {
535 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000536 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000537 }
Craig Topper353eda42014-04-24 06:44:33 +0000538 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000539}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000540
541void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000542 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000543 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000544 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000545 EventListeners.push_back(L);
546}
547void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000548 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000549 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000550 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000551 SmallVector<JITEventListener*, 2>::reverse_iterator I=
552 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
553 if (I != EventListeners.rend()) {
554 std::swap(*I, EventListeners.back());
555 EventListeners.pop_back();
556 }
557}
558void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000559 MutexGuard locked(lock);
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000560 MemMgr.notifyObjectLoaded(this, &Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000561 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
562 EventListeners[I]->NotifyObjectEmitted(Obj);
563 }
564}
565void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000566 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000567 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
568 EventListeners[I]->NotifyFreeingObject(Obj);
569 }
570}
Andrew Kaylorea395922013-10-01 01:47:35 +0000571
572uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
573 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
Andrew Kaylor89bdd102013-10-01 16:42:50 +0000574 // If the symbols wasn't found and it begins with an underscore, try again
575 // without the underscore.
576 if (!Result && Name[0] == '_')
577 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000578 if (Result)
579 return Result;
580 return ClientMM->getSymbolAddress(Name);
581}