blob: 2ed267b316161ac213d016c02822fb64d55360b3 [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
90
Rafael Espindolab4599d32014-08-01 18:04:14 +000091 for (object::Archive *A : Archives)
Lang Hames173c69f2014-01-08 04:09:09 +000092 delete A;
Rafael Espindolab4599d32014-08-01 18:04:14 +000093
Lang Hames173c69f2014-01-08 04:09:09 +000094 Archives.clear();
95
Andrew Kaylor1a568c32012-08-07 18:33:00 +000096 delete TM;
97}
98
Andrew Kaylorea395922013-10-01 01:47:35 +000099void MCJIT::addModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000100 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000101 OwnedModules.addModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000102}
103
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000104bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000105 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000106 return OwnedModules.removeModule(M);
107}
108
109
110
David Blaikie7a1e7752014-04-29 21:52:46 +0000111void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
112 ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
Juergen Ributzka6ff29a72014-03-26 18:19:27 +0000113 if (!LoadedObject || Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000114 report_fatal_error(Dyld.getErrorString());
115
116 LoadedObjects.push_back(LoadedObject);
117
118 NotifyObjectEmitted(*LoadedObject);
119}
120
121void MCJIT::addArchive(object::Archive *A) {
122 Archives.push_back(A);
123}
124
125
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000126void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000127 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000128 ObjCache = NewCache;
129}
130
Andrew Kaylorea395922013-10-01 01:47:35 +0000131ObjectBufferStream* MCJIT::emitObject(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000132 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000133
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000134 // This must be a module which has already been added but not loaded to this
135 // MCJIT instance, since these conditions are tested by our caller,
136 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000137
138 PassManager PM;
139
Rafael Espindola339430f2014-02-25 23:25:17 +0000140 M->setDataLayout(TM->getDataLayout());
141 PM.add(new DataLayoutPass(M));
Jim Grosbach7b162492011-03-18 22:48:41 +0000142
Andrew Kayloradc70562012-10-02 21:18:39 +0000143 // The RuntimeDyld will take ownership of this shortly
Ahmed Charles56440fd2014-03-06 05:51:42 +0000144 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
Andrew Kayloradc70562012-10-02 21:18:39 +0000145
Jim Grosbach7b162492011-03-18 22:48:41 +0000146 // Turn the machine code intermediate representation into bytes in memory
147 // that may be executed.
Lang Hamesbc876012014-04-18 06:48:23 +0000148 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
149 !getVerifyModules())) {
Jim Grosbach7b162492011-03-18 22:48:41 +0000150 report_fatal_error("Target does not support MC emission!");
151 }
152
153 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000154 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000155 // Flush the output buffer to get the generated code into memory
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000156 CompiledObject->flush();
157
158 // If we have an object cache, tell it about the new object.
159 // Note that we're using the compiled image, not the loaded image (as below).
160 if (ObjCache) {
161 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
162 // to create a temporary object here and delete it after the call.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000163 std::unique_ptr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
Andrew Kaylorea395922013-10-01 01:47:35 +0000164 ObjCache->notifyObjectCompiled(M, MB.get());
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000165 }
166
Ahmed Charles96c9d952014-03-05 10:19:29 +0000167 return CompiledObject.release();
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000168}
169
Andrew Kaylorea395922013-10-01 01:47:35 +0000170void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000171 // Get a thread lock to make sure we aren't trying to load multiple times
Zachary Turnerc04b8922014-06-20 21:07:14 +0000172 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000173
Andrew Kaylorea395922013-10-01 01:47:35 +0000174 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000175 assert(OwnedModules.ownsModule(M) &&
176 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000177
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000178 // Re-compilation is not supported
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000179 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000180 return;
181
Ahmed Charles56440fd2014-03-06 05:51:42 +0000182 std::unique_ptr<ObjectBuffer> ObjectToLoad;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000183 // Try to load the pre-compiled object from cache if possible
Craig Topper353eda42014-04-24 06:44:33 +0000184 if (ObjCache) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000185 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
Craig Topper353eda42014-04-24 06:44:33 +0000186 if (PreCompiledObject.get())
Ahmed Charles96c9d952014-03-05 10:19:29 +0000187 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000188 }
189
190 // If the cache did not contain a suitable object, compile the object
191 if (!ObjectToLoad) {
192 ObjectToLoad.reset(emitObject(M));
193 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
194 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000195
196 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000197 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Ahmed Charles96c9d952014-03-05 10:19:29 +0000198 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
Lang Hames173c69f2014-01-08 04:09:09 +0000199 LoadedObjects.push_back(LoadedObject);
Andrew Kayloradc70562012-10-02 21:18:39 +0000200 if (!LoadedObject)
Jim Grosbachc114d892011-03-23 19:51:34 +0000201 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000202
Andrew Kayloradc70562012-10-02 21:18:39 +0000203 // FIXME: Make this optional, maybe even move it to a JIT event listener
204 LoadedObject->registerWithDebugger();
205
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000206 NotifyObjectEmitted(*LoadedObject);
207
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000208 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000209}
210
Andrew Kaylorea395922013-10-01 01:47:35 +0000211void MCJIT::finalizeLoadedModules() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000212 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000213
Andrew Kaylorea395922013-10-01 01:47:35 +0000214 // Resolve any outstanding relocations.
215 Dyld.resolveRelocations();
216
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000217 OwnedModules.markAllLoadedModulesAsFinalized();
218
Andrew Kaylorea395922013-10-01 01:47:35 +0000219 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000220 Dyld.registerEHFrames();
221
Andrew Kaylorea395922013-10-01 01:47:35 +0000222 // Set page permissions.
223 MemMgr.finalizeMemory();
224}
225
226// FIXME: Rename this.
227void MCJIT::finalizeObject() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000228 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000229
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000230 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
231 E = OwnedModules.end_added();
232 I != E; ++I) {
233 Module *M = *I;
234 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000235 }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000236
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000237 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000238}
239
240void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000241 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000242
Andrew Kaylorea395922013-10-01 01:47:35 +0000243 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000244 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000245
246 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000247 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000248 generateCodeForModule(M);
249
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000250 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000251}
252
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000253void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
254 report_fatal_error("not yet implemented");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000255}
256
Andrew Kaylorea395922013-10-01 01:47:35 +0000257uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
Rafael Espindola58873562014-01-03 19:21:54 +0000258 Mangler Mang(TM->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000259 SmallString<128> FullName;
260 Mang.getNameWithPrefix(FullName, Name);
261 return Dyld.getSymbolLoadAddress(FullName);
Andrew Kaylorea395922013-10-01 01:47:35 +0000262}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000263
Andrew Kaylorea395922013-10-01 01:47:35 +0000264Module *MCJIT::findModuleForSymbol(const std::string &Name,
265 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000266 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000267
Andrew Kaylorea395922013-10-01 01:47:35 +0000268 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000269 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
270 E = OwnedModules.end_added();
271 I != E; ++I) {
272 Module *M = *I;
Andrew Kaylorea395922013-10-01 01:47:35 +0000273 Function *F = M->getFunction(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000274 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000275 return M;
276 if (!CheckFunctionsOnly) {
277 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000278 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000279 return M;
280 // FIXME: Do we need to worry about global aliases?
281 }
282 }
283 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000284 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000285}
286
287uint64_t MCJIT::getSymbolAddress(const std::string &Name,
288 bool CheckFunctionsOnly)
289{
Zachary Turnerc04b8922014-06-20 21:07:14 +0000290 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000291
Andrew Kaylorea395922013-10-01 01:47:35 +0000292 // First, check to see if we already have this symbol.
293 uint64_t Addr = getExistingSymbolAddress(Name);
294 if (Addr)
295 return Addr;
296
Rafael Espindolab4599d32014-08-01 18:04:14 +0000297 for (object::Archive *A : Archives) {
Lang Hames173c69f2014-01-08 04:09:09 +0000298 // Look for our symbols in each Archive
299 object::Archive::child_iterator ChildIt = A->findSym(Name);
Rafael Espindola23a97502014-01-21 16:09:45 +0000300 if (ChildIt != A->child_end()) {
Lang Hames173c69f2014-01-08 04:09:09 +0000301 // FIXME: Support nested archives?
Rafael Espindolaae460022014-06-16 16:08:36 +0000302 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
303 ChildIt->getAsBinary();
304 if (ChildBinOrErr.getError())
305 continue;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000306 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
Rafael Espindolaae460022014-06-16 16:08:36 +0000307 if (ChildBin->isObject()) {
David Blaikie7a1e7752014-04-29 21:52:46 +0000308 std::unique_ptr<object::ObjectFile> OF(
309 static_cast<object::ObjectFile *>(ChildBin.release()));
Lang Hames173c69f2014-01-08 04:09:09 +0000310 // This causes the object file to be loaded.
David Blaikie7a1e7752014-04-29 21:52:46 +0000311 addObjectFile(std::move(OF));
Lang Hames173c69f2014-01-08 04:09:09 +0000312 // The address should be here now.
313 Addr = getExistingSymbolAddress(Name);
314 if (Addr)
315 return Addr;
316 }
317 }
318 }
319
Andrew Kaylorea395922013-10-01 01:47:35 +0000320 // If it hasn't already been generated, see if it's in one of our modules.
321 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
322 if (!M)
323 return 0;
324
Andrew Kaylorea395922013-10-01 01:47:35 +0000325 generateCodeForModule(M);
326
327 // Check the RuntimeDyld table again, it should be there now.
328 return getExistingSymbolAddress(Name);
329}
330
331uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000332 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000333 uint64_t Result = getSymbolAddress(Name, false);
334 if (Result != 0)
335 finalizeLoadedModules();
336 return Result;
337}
338
339uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000340 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000341 uint64_t Result = getSymbolAddress(Name, true);
342 if (Result != 0)
343 finalizeLoadedModules();
344 return Result;
345}
346
347// Deprecated. Use getFunctionAddress instead.
348void *MCJIT::getPointerToFunction(Function *F) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000349 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000350
Jim Grosbachd5274402011-03-22 18:05:27 +0000351 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
352 bool AbortOnFailure = !F->hasExternalWeakLinkage();
353 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
354 addGlobalMapping(F, Addr);
355 return Addr;
356 }
357
Andrew Kaylorea395922013-10-01 01:47:35 +0000358 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000359 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000360
361 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000362 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000363 generateCodeForModule(M);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000364 else if (!OwnedModules.hasModuleBeenLoaded(M))
365 // If this function doesn't belong to one of our modules, we're done.
Craig Topper353eda42014-04-24 06:44:33 +0000366 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000367
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000368 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000369 //
370 // This is the accessor for the target address, so make sure to check the
371 // load address of the symbol, not the local address.
Rafael Espindola58873562014-01-03 19:21:54 +0000372 Mangler Mang(TM->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000373 SmallString<128> Name;
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000374 TM->getNameWithPrefix(Name, F, Mang);
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000375 return (void*)Dyld.getSymbolLoadAddress(Name);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000376}
377
378void *MCJIT::recompileAndRelinkFunction(Function *F) {
379 report_fatal_error("not yet implemented");
380}
381
382void MCJIT::freeMachineCodeForFunction(Function *F) {
383 report_fatal_error("not yet implemented");
384}
385
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000386void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
387 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
388 for (; I != E; ++I) {
389 ExecutionEngine::runStaticConstructorsDestructors(*I, isDtors);
390 }
391}
392
393void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
394 // Execute global ctors/dtors for each module in the program.
395 runStaticConstructorsDestructorsInModulePtrSet(
396 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
397 runStaticConstructorsDestructorsInModulePtrSet(
398 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
399 runStaticConstructorsDestructorsInModulePtrSet(
400 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
401}
402
403Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
404 ModulePtrSet::iterator I,
405 ModulePtrSet::iterator E) {
406 for (; I != E; ++I) {
407 if (Function *F = (*I)->getFunction(FnName))
408 return F;
409 }
Craig Topper353eda42014-04-24 06:44:33 +0000410 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000411}
412
413Function *MCJIT::FindFunctionNamed(const char *FnName) {
414 Function *F = FindFunctionNamedInModulePtrSet(
415 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
416 if (!F)
417 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
418 OwnedModules.end_loaded());
419 if (!F)
420 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
421 OwnedModules.end_finalized());
422 return F;
423}
424
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000425GenericValue MCJIT::runFunction(Function *F,
426 const std::vector<GenericValue> &ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000427 assert(F && "Function *F was null at entry to run()");
428
Jim Grosbach7b162492011-03-18 22:48:41 +0000429 void *FPtr = getPointerToFunction(F);
Jim Grosbachd5274402011-03-22 18:05:27 +0000430 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000431 FunctionType *FTy = F->getFunctionType();
432 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000433
434 assert((FTy->getNumParams() == ArgValues.size() ||
435 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
436 "Wrong number of arguments passed into function!");
437 assert(FTy->getNumParams() == ArgValues.size() &&
438 "This doesn't support passing arguments through varargs (yet)!");
439
440 // Handle some common cases first. These cases correspond to common `main'
441 // prototypes.
442 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
443 switch (ArgValues.size()) {
444 case 3:
445 if (FTy->getParamType(0)->isIntegerTy(32) &&
446 FTy->getParamType(1)->isPointerTy() &&
447 FTy->getParamType(2)->isPointerTy()) {
448 int (*PF)(int, char **, const char **) =
449 (int(*)(int, char **, const char **))(intptr_t)FPtr;
450
451 // Call the function.
452 GenericValue rv;
453 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
454 (char **)GVTOP(ArgValues[1]),
455 (const char **)GVTOP(ArgValues[2])));
456 return rv;
457 }
458 break;
459 case 2:
460 if (FTy->getParamType(0)->isIntegerTy(32) &&
461 FTy->getParamType(1)->isPointerTy()) {
462 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
463
464 // Call the function.
465 GenericValue rv;
466 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
467 (char **)GVTOP(ArgValues[1])));
468 return rv;
469 }
470 break;
471 case 1:
472 if (FTy->getNumParams() == 1 &&
473 FTy->getParamType(0)->isIntegerTy(32)) {
474 GenericValue rv;
475 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
476 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
477 return rv;
478 }
479 break;
480 }
481 }
482
483 // Handle cases where no arguments are passed first.
484 if (ArgValues.empty()) {
485 GenericValue rv;
486 switch (RetTy->getTypeID()) {
487 default: llvm_unreachable("Unknown return type for function call!");
488 case Type::IntegerTyID: {
489 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
490 if (BitWidth == 1)
491 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
492 else if (BitWidth <= 8)
493 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
494 else if (BitWidth <= 16)
495 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
496 else if (BitWidth <= 32)
497 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
498 else if (BitWidth <= 64)
499 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
500 else
501 llvm_unreachable("Integer types > 64 bits not supported");
502 return rv;
503 }
504 case Type::VoidTyID:
505 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
506 return rv;
507 case Type::FloatTyID:
508 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
509 return rv;
510 case Type::DoubleTyID:
511 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
512 return rv;
513 case Type::X86_FP80TyID:
514 case Type::FP128TyID:
515 case Type::PPC_FP128TyID:
516 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000517 case Type::PointerTyID:
518 return PTOGV(((void*(*)())(intptr_t)FPtr)());
519 }
520 }
521
Craig Toppera2886c22012-02-07 05:05:23 +0000522 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000523}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000524
525void *MCJIT::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000526 bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000527 if (!isSymbolSearchingDisabled()) {
528 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
Danil Malyshevbfee5422012-03-28 21:46:36 +0000529 if (ptr)
530 return ptr;
531 }
532
533 /// If a LazyFunctionCreator is installed, use it to get/create the function.
534 if (LazyFunctionCreator)
535 if (void *RP = LazyFunctionCreator(Name))
536 return RP;
537
538 if (AbortOnFailure) {
539 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000540 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000541 }
Craig Topper353eda42014-04-24 06:44:33 +0000542 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000543}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000544
545void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000546 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000547 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000548 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000549 EventListeners.push_back(L);
550}
551void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000552 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000553 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000554 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000555 SmallVector<JITEventListener*, 2>::reverse_iterator I=
556 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
557 if (I != EventListeners.rend()) {
558 std::swap(*I, EventListeners.back());
559 EventListeners.pop_back();
560 }
561}
562void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000563 MutexGuard locked(lock);
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000564 MemMgr.notifyObjectLoaded(this, &Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000565 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
566 EventListeners[I]->NotifyObjectEmitted(Obj);
567 }
568}
569void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000570 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000571 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
572 EventListeners[I]->NotifyFreeingObject(Obj);
573 }
574}
Andrew Kaylorea395922013-10-01 01:47:35 +0000575
576uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
577 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
Andrew Kaylor89bdd102013-10-01 16:42:50 +0000578 // If the symbols wasn't found and it begins with an underscore, try again
579 // without the underscore.
580 if (!Result && Name[0] == '_')
581 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000582 if (Result)
583 return Result;
584 return ClientMM->getSymbolAddress(Name);
585}