blob: da5f03799e354326a2e31bcc2aea322a64cb8a09 [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"
11#include "llvm/ExecutionEngine/GenericValue.h"
Andrew Kaylor776054d2012-11-06 18:51:59 +000012#include "llvm/ExecutionEngine/JITEventListener.h"
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000013#include "llvm/ExecutionEngine/MCJIT.h"
14#include "llvm/ExecutionEngine/ObjectBuffer.h"
15#include "llvm/ExecutionEngine/ObjectImage.h"
Andrew Kaylord2755af2013-04-29 17:49:40 +000016#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000017#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/DerivedTypes.h"
19#include "llvm/IR/Function.h"
Stephen Hines36b56882014-04-23 16:57:46 -070020#include "llvm/IR/Mangler.h"
Andrew Kaylor8e9ec012013-10-01 01:47:35 +000021#include "llvm/IR/Module.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000022#include "llvm/MC/MCAsmInfo.h"
Stephen Hines36b56882014-04-23 16:57:46 -070023#include "llvm/Object/Archive.h"
24#include "llvm/PassManager.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000025#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000026#include "llvm/Support/ErrorHandling.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000027#include "llvm/Support/MemoryBuffer.h"
Andrew Kaylorea708d12012-08-07 18:33:00 +000028#include "llvm/Support/MutexGuard.h"
Stephen Hines36b56882014-04-23 16:57:46 -070029#include "llvm/Target/TargetLowering.h"
Stephen Hines37ed9c12014-12-01 14:51:49 -080030#include "llvm/Target/TargetSubtargetInfo.h"
Daniel Dunbar6aec2982010-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
Stephen Hines37ed9c12014-12-01 14:51:49 -080045ExecutionEngine *MCJIT::createJIT(std::unique_ptr<Module> M,
Daniel Dunbar6aec2982010-11-17 16:06:43 +000046 std::string *ErrorStr,
Filip Pizlo13a3cf12013-05-14 19:29:00 +000047 RTDyldMemoryManager *MemMgr,
Stephen Hines37ed9c12014-12-01 14:51:49 -080048 std::unique_ptr<TargetMachine> TM) {
Daniel Dunbar6aec2982010-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.
Stephen Hinesdce4a402014-05-29 02:49:00 -070052 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
Daniel Dunbar6aec2982010-11-17 16:06:43 +000053
Stephen Hines37ed9c12014-12-01 14:51:49 -080054 return new MCJIT(std::move(M), std::move(TM),
55 MemMgr ? MemMgr : new SectionMemoryManager());
Daniel Dunbar6aec2982010-11-17 16:06:43 +000056}
57
Stephen Hines37ed9c12014-12-01 14:51:49 -080058MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
59 RTDyldMemoryManager *MM)
60 : ExecutionEngine(std::move(M)), TM(std::move(tm)), Ctx(nullptr),
61 MemMgr(this, MM), Dyld(&MemMgr), ObjCache(nullptr) {
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +000062 // FIXME: We are managing our modules, so we do not want the base class
63 // ExecutionEngine to manage them as well. To avoid double destruction
64 // of the first (and only) module added in ExecutionEngine constructor
65 // we remove it from EE and will destruct it ourselves.
66 //
67 // It may make sense to move our module manager (based on SmallStPtr) back
68 // into EE if the JIT and Interpreter can live with it.
69 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
70 // runStaticConstructorsDestructors could be moved back to EE as well.
71 //
Stephen Hines37ed9c12014-12-01 14:51:49 -080072 std::unique_ptr<Module> First = std::move(Modules[0]);
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +000073 Modules.clear();
Chandler Carruth81798732013-10-24 09:52:56 +000074
Stephen Hines37ed9c12014-12-01 14:51:49 -080075 OwnedModules.addModule(std::move(First));
76 setDataLayout(TM->getSubtargetImpl()->getDataLayout());
Andrew Kaylorea708d12012-08-07 18:33:00 +000077}
78
Stephen Hines37ed9c12014-12-01 14:51:49 -080079MCJIT::~MCJIT() {
Andrew Kaylor61694532013-10-21 17:42:06 +000080 MutexGuard locked(lock);
Stephen Hines37ed9c12014-12-01 14:51:49 -080081
82 Dyld.deregisterEHFrames();
83
84 for (auto &Obj : LoadedObjects)
85 if (Obj)
86 NotifyFreeingObject(*Obj);
87
88 Archives.clear();
89}
90
91void MCJIT::addModule(std::unique_ptr<Module> M) {
92 MutexGuard locked(lock);
93 OwnedModules.addModule(std::move(M));
Andrew Kaylor8e9ec012013-10-01 01:47:35 +000094}
95
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +000096bool MCJIT::removeModule(Module *M) {
97 MutexGuard locked(lock);
98 return OwnedModules.removeModule(M);
99}
100
Stephen Hinesdce4a402014-05-29 02:49:00 -0700101void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800102 std::unique_ptr<ObjectImage> LoadedObject = Dyld.loadObject(std::move(Obj));
Stephen Hines36b56882014-04-23 16:57:46 -0700103 if (!LoadedObject || Dyld.hasError())
104 report_fatal_error(Dyld.getErrorString());
105
Stephen Hines36b56882014-04-23 16:57:46 -0700106 NotifyObjectEmitted(*LoadedObject);
Stephen Hines37ed9c12014-12-01 14:51:49 -0800107
108 LoadedObjects.push_back(std::move(LoadedObject));
Stephen Hines36b56882014-04-23 16:57:46 -0700109}
110
Stephen Hines37ed9c12014-12-01 14:51:49 -0800111void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
112 std::unique_ptr<object::ObjectFile> ObjFile;
113 std::unique_ptr<MemoryBuffer> MemBuf;
114 std::tie(ObjFile, MemBuf) = Obj.takeBinary();
115 addObjectFile(std::move(ObjFile));
116 Buffers.push_back(std::move(MemBuf));
Stephen Hines36b56882014-04-23 16:57:46 -0700117}
118
Stephen Hines37ed9c12014-12-01 14:51:49 -0800119void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
120 Archives.push_back(std::move(A));
121}
Stephen Hines36b56882014-04-23 16:57:46 -0700122
Andrew Kaylor1c489452013-04-25 21:02:36 +0000123void MCJIT::setObjectCache(ObjectCache* NewCache) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000124 MutexGuard locked(lock);
Andrew Kaylor1c489452013-04-25 21:02:36 +0000125 ObjCache = NewCache;
126}
127
Stephen Hines37ed9c12014-12-01 14:51:49 -0800128std::unique_ptr<ObjectBufferStream> MCJIT::emitObject(Module *M) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000129 MutexGuard locked(lock);
130
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000131 // This must be a module which has already been added but not loaded to this
132 // MCJIT instance, since these conditions are tested by our caller,
133 // generateCodeForModule.
Andrew Kaylorea708d12012-08-07 18:33:00 +0000134
135 PassManager PM;
136
Stephen Hines37ed9c12014-12-01 14:51:49 -0800137 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
138 PM.add(new DataLayoutPass());
Jim Grosbach31649e62011-03-18 22:48:41 +0000139
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000140 // The RuntimeDyld will take ownership of this shortly
Stephen Hines36b56882014-04-23 16:57:46 -0700141 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000142
Jim Grosbach31649e62011-03-18 22:48:41 +0000143 // Turn the machine code intermediate representation into bytes in memory
144 // that may be executed.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700145 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
146 !getVerifyModules())) {
Jim Grosbach31649e62011-03-18 22:48:41 +0000147 report_fatal_error("Target does not support MC emission!");
148 }
149
150 // Initialize passes.
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000151 PM.run(*M);
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000152 // Flush the output buffer to get the generated code into memory
Andrew Kaylor1c489452013-04-25 21:02:36 +0000153 CompiledObject->flush();
154
155 // If we have an object cache, tell it about the new object.
156 // Note that we're using the compiled image, not the loaded image (as below).
157 if (ObjCache) {
158 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
159 // to create a temporary object here and delete it after the call.
Stephen Hines37ed9c12014-12-01 14:51:49 -0800160 MemoryBufferRef MB = CompiledObject->getMemBuffer();
161 ObjCache->notifyObjectCompiled(M, MB);
Andrew Kaylor1c489452013-04-25 21:02:36 +0000162 }
163
Stephen Hines37ed9c12014-12-01 14:51:49 -0800164 return CompiledObject;
Andrew Kaylor1c489452013-04-25 21:02:36 +0000165}
166
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000167void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000168 // Get a thread lock to make sure we aren't trying to load multiple times
169 MutexGuard locked(lock);
170
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000171 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000172 assert(OwnedModules.ownsModule(M) &&
173 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylor1c489452013-04-25 21:02:36 +0000174
Andrew Kaylor1c489452013-04-25 21:02:36 +0000175 // Re-compilation is not supported
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000176 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylor1c489452013-04-25 21:02:36 +0000177 return;
178
Stephen Hines36b56882014-04-23 16:57:46 -0700179 std::unique_ptr<ObjectBuffer> ObjectToLoad;
Andrew Kaylor1c489452013-04-25 21:02:36 +0000180 // Try to load the pre-compiled object from cache if possible
Stephen Hinesdce4a402014-05-29 02:49:00 -0700181 if (ObjCache) {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800182 if (std::unique_ptr<MemoryBuffer> PreCompiledObject =
183 ObjCache->getObject(M))
184 ObjectToLoad =
185 llvm::make_unique<ObjectBuffer>(std::move(PreCompiledObject));
Andrew Kaylor1c489452013-04-25 21:02:36 +0000186 }
187
188 // If the cache did not contain a suitable object, compile the object
189 if (!ObjectToLoad) {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800190 ObjectToLoad = emitObject(M);
191 assert(ObjectToLoad && "Compilation did not produce an object.");
Andrew Kaylor1c489452013-04-25 21:02:36 +0000192 }
Jim Grosbachf9229102011-03-22 01:06:42 +0000193
194 // Load the object into the dynamic linker.
Stephen Hines36b56882014-04-23 16:57:46 -0700195 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Stephen Hines37ed9c12014-12-01 14:51:49 -0800196 std::unique_ptr<ObjectImage> LoadedObject =
197 Dyld.loadObject(std::move(ObjectToLoad));
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000198 if (!LoadedObject)
Jim Grosbach8086f3b2011-03-23 19:51:34 +0000199 report_fatal_error(Dyld.getErrorString());
Andrew Kaylorea708d12012-08-07 18:33:00 +0000200
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000201 // FIXME: Make this optional, maybe even move it to a JIT event listener
202 LoadedObject->registerWithDebugger();
203
Andrew Kaylor776054d2012-11-06 18:51:59 +0000204 NotifyObjectEmitted(*LoadedObject);
205
Stephen Hines37ed9c12014-12-01 14:51:49 -0800206 LoadedObjects.push_back(std::move(LoadedObject));
207
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000208 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000209}
210
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000211void MCJIT::finalizeLoadedModules() {
Andrew Kaylor61694532013-10-21 17:42:06 +0000212 MutexGuard locked(lock);
213
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000214 // Resolve any outstanding relocations.
215 Dyld.resolveRelocations();
216
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000217 OwnedModules.markAllLoadedModulesAsFinalized();
218
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000219 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor528f6d72013-10-11 21:25:48 +0000220 Dyld.registerEHFrames();
221
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000222 // Set page permissions.
223 MemMgr.finalizeMemory();
224}
225
226// FIXME: Rename this.
227void MCJIT::finalizeObject() {
Andrew Kaylor61694532013-10-21 17:42:06 +0000228 MutexGuard locked(lock);
229
Stephen Hines37ed9c12014-12-01 14:51:49 -0800230 // Generate code for module is going to move objects out of the 'added' list,
231 // so we need to copy that out before using it:
232 SmallVector<Module*, 16> ModsToAdd;
233 for (auto M : OwnedModules.added())
234 ModsToAdd.push_back(M);
235
236 for (auto M : ModsToAdd)
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000237 generateCodeForModule(M);
Andrew Kaylor53608a32012-11-15 23:50:01 +0000238
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000239 finalizeLoadedModules();
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000240}
241
242void MCJIT::finalizeModule(Module *M) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000243 MutexGuard locked(lock);
244
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000245 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000246 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000247
248 // If the module hasn't been compiled, just do that.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000249 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000250 generateCodeForModule(M);
251
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000252 finalizeLoadedModules();
Andrew Kaylor28989882012-11-05 20:57:16 +0000253}
254
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000255uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800256 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
Stephen Hines36b56882014-04-23 16:57:46 -0700257 SmallString<128> FullName;
258 Mang.getNameWithPrefix(FullName, Name);
259 return Dyld.getSymbolLoadAddress(FullName);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000260}
Jim Grosbach35ed8422012-09-05 16:50:40 +0000261
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000262Module *MCJIT::findModuleForSymbol(const std::string &Name,
263 bool CheckFunctionsOnly) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000264 MutexGuard locked(lock);
265
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000266 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000267 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
268 E = OwnedModules.end_added();
269 I != E; ++I) {
270 Module *M = *I;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000271 Function *F = M->getFunction(Name);
Andrew Kaylor59bbf5a2013-11-15 22:10:21 +0000272 if (F && !F->isDeclaration())
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000273 return M;
274 if (!CheckFunctionsOnly) {
275 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor59bbf5a2013-11-15 22:10:21 +0000276 if (G && !G->isDeclaration())
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000277 return M;
278 // FIXME: Do we need to worry about global aliases?
279 }
280 }
281 // We didn't find the symbol in any of our modules.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700282 return nullptr;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000283}
284
285uint64_t MCJIT::getSymbolAddress(const std::string &Name,
286 bool CheckFunctionsOnly)
287{
Andrew Kaylor61694532013-10-21 17:42:06 +0000288 MutexGuard locked(lock);
289
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000290 // First, check to see if we already have this symbol.
291 uint64_t Addr = getExistingSymbolAddress(Name);
292 if (Addr)
293 return Addr;
294
Stephen Hines37ed9c12014-12-01 14:51:49 -0800295 for (object::OwningBinary<object::Archive> &OB : Archives) {
296 object::Archive *A = OB.getBinary();
Stephen Hines36b56882014-04-23 16:57:46 -0700297 // Look for our symbols in each Archive
298 object::Archive::child_iterator ChildIt = A->findSym(Name);
299 if (ChildIt != A->child_end()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700300 // FIXME: Support nested archives?
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700301 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
302 ChildIt->getAsBinary();
303 if (ChildBinOrErr.getError())
304 continue;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800305 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700306 if (ChildBin->isObject()) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700307 std::unique_ptr<object::ObjectFile> OF(
308 static_cast<object::ObjectFile *>(ChildBin.release()));
Stephen Hines36b56882014-04-23 16:57:46 -0700309 // This causes the object file to be loaded.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700310 addObjectFile(std::move(OF));
Stephen Hines36b56882014-04-23 16:57:46 -0700311 // The address should be here now.
312 Addr = getExistingSymbolAddress(Name);
313 if (Addr)
314 return Addr;
315 }
316 }
317 }
318
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000319 // If it hasn't already been generated, see if it's in one of our modules.
320 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
Stephen Hines37ed9c12014-12-01 14:51:49 -0800321 if (M) {
322 generateCodeForModule(M);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000323
Stephen Hines37ed9c12014-12-01 14:51:49 -0800324 // Check the RuntimeDyld table again, it should be there now.
325 return getExistingSymbolAddress(Name);
326 }
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000327
Stephen Hines37ed9c12014-12-01 14:51:49 -0800328 // If a LazyFunctionCreator is installed, use it to get/create the function.
329 // FIXME: Should we instead have a LazySymbolCreator callback?
330 if (LazyFunctionCreator)
331 Addr = (uint64_t)LazyFunctionCreator(Name);
332
333 return Addr;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000334}
335
336uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000337 MutexGuard locked(lock);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000338 uint64_t Result = getSymbolAddress(Name, false);
339 if (Result != 0)
340 finalizeLoadedModules();
341 return Result;
342}
343
344uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000345 MutexGuard locked(lock);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000346 uint64_t Result = getSymbolAddress(Name, true);
347 if (Result != 0)
348 finalizeLoadedModules();
349 return Result;
350}
351
352// Deprecated. Use getFunctionAddress instead.
353void *MCJIT::getPointerToFunction(Function *F) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000354 MutexGuard locked(lock);
Andrew Kaylorea708d12012-08-07 18:33:00 +0000355
Stephen Hines37ed9c12014-12-01 14:51:49 -0800356 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
357 SmallString<128> Name;
358 TM->getNameWithPrefix(Name, F, Mang);
359
Jim Grosbach34714a02011-03-22 18:05:27 +0000360 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
361 bool AbortOnFailure = !F->hasExternalWeakLinkage();
Stephen Hines37ed9c12014-12-01 14:51:49 -0800362 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
363 updateGlobalMapping(F, Addr);
Jim Grosbach34714a02011-03-22 18:05:27 +0000364 return Addr;
365 }
366
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000367 Module *M = F->getParent();
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000368 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000369
370 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000371 if (HasBeenAddedButNotLoaded)
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000372 generateCodeForModule(M);
Stephen Hines37ed9c12014-12-01 14:51:49 -0800373 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000374 // If this function doesn't belong to one of our modules, we're done.
Stephen Hines37ed9c12014-12-01 14:51:49 -0800375 // FIXME: Asking for the pointer to a function that hasn't been registered,
376 // and isn't a declaration (which is handled above) should probably
377 // be an assertion.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700378 return nullptr;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800379 }
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000380
Andrew Kaylorea708d12012-08-07 18:33:00 +0000381 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbach35ed8422012-09-05 16:50:40 +0000382 //
383 // This is the accessor for the target address, so make sure to check the
384 // load address of the symbol, not the local address.
Stephen Hines36b56882014-04-23 16:57:46 -0700385 return (void*)Dyld.getSymbolLoadAddress(Name);
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000386}
387
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000388void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
389 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
390 for (; I != E; ++I) {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800391 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000392 }
393}
394
395void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
396 // Execute global ctors/dtors for each module in the program.
397 runStaticConstructorsDestructorsInModulePtrSet(
398 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
399 runStaticConstructorsDestructorsInModulePtrSet(
400 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
401 runStaticConstructorsDestructorsInModulePtrSet(
402 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
403}
404
405Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
406 ModulePtrSet::iterator I,
407 ModulePtrSet::iterator E) {
408 for (; I != E; ++I) {
409 if (Function *F = (*I)->getFunction(FnName))
410 return F;
411 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700412 return nullptr;
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000413}
414
415Function *MCJIT::FindFunctionNamed(const char *FnName) {
416 Function *F = FindFunctionNamedInModulePtrSet(
417 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
418 if (!F)
419 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
420 OwnedModules.end_loaded());
421 if (!F)
422 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
423 OwnedModules.end_finalized());
424 return F;
425}
426
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000427GenericValue MCJIT::runFunction(Function *F,
428 const std::vector<GenericValue> &ArgValues) {
Jim Grosbach34714a02011-03-22 18:05:27 +0000429 assert(F && "Function *F was null at entry to run()");
430
Jim Grosbach31649e62011-03-18 22:48:41 +0000431 void *FPtr = getPointerToFunction(F);
Jim Grosbach34714a02011-03-22 18:05:27 +0000432 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000433 FunctionType *FTy = F->getFunctionType();
434 Type *RetTy = FTy->getReturnType();
Jim Grosbach34714a02011-03-22 18:05:27 +0000435
436 assert((FTy->getNumParams() == ArgValues.size() ||
437 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
438 "Wrong number of arguments passed into function!");
439 assert(FTy->getNumParams() == ArgValues.size() &&
440 "This doesn't support passing arguments through varargs (yet)!");
441
442 // Handle some common cases first. These cases correspond to common `main'
443 // prototypes.
444 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
445 switch (ArgValues.size()) {
446 case 3:
447 if (FTy->getParamType(0)->isIntegerTy(32) &&
448 FTy->getParamType(1)->isPointerTy() &&
449 FTy->getParamType(2)->isPointerTy()) {
450 int (*PF)(int, char **, const char **) =
451 (int(*)(int, char **, const char **))(intptr_t)FPtr;
452
453 // Call the function.
454 GenericValue rv;
455 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
456 (char **)GVTOP(ArgValues[1]),
457 (const char **)GVTOP(ArgValues[2])));
458 return rv;
459 }
460 break;
461 case 2:
462 if (FTy->getParamType(0)->isIntegerTy(32) &&
463 FTy->getParamType(1)->isPointerTy()) {
464 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
465
466 // Call the function.
467 GenericValue rv;
468 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
469 (char **)GVTOP(ArgValues[1])));
470 return rv;
471 }
472 break;
473 case 1:
474 if (FTy->getNumParams() == 1 &&
475 FTy->getParamType(0)->isIntegerTy(32)) {
476 GenericValue rv;
477 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
478 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
479 return rv;
480 }
481 break;
482 }
483 }
484
485 // Handle cases where no arguments are passed first.
486 if (ArgValues.empty()) {
487 GenericValue rv;
488 switch (RetTy->getTypeID()) {
489 default: llvm_unreachable("Unknown return type for function call!");
490 case Type::IntegerTyID: {
491 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
492 if (BitWidth == 1)
493 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
494 else if (BitWidth <= 8)
495 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
496 else if (BitWidth <= 16)
497 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
498 else if (BitWidth <= 32)
499 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
500 else if (BitWidth <= 64)
501 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
502 else
503 llvm_unreachable("Integer types > 64 bits not supported");
504 return rv;
505 }
506 case Type::VoidTyID:
507 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
508 return rv;
509 case Type::FloatTyID:
510 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
511 return rv;
512 case Type::DoubleTyID:
513 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
514 return rv;
515 case Type::X86_FP80TyID:
516 case Type::FP128TyID:
517 case Type::PPC_FP128TyID:
518 llvm_unreachable("long double not supported yet");
Jim Grosbach34714a02011-03-22 18:05:27 +0000519 case Type::PointerTyID:
520 return PTOGV(((void*(*)())(intptr_t)FPtr)());
521 }
522 }
523
Craig Topper85814382012-02-07 05:05:23 +0000524 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000525}
Danil Malyshev30b9e322012-03-28 21:46:36 +0000526
Stephen Hines37ed9c12014-12-01 14:51:49 -0800527void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000528 if (!isSymbolSearchingDisabled()) {
529 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
Danil Malyshev30b9e322012-03-28 21:46:36 +0000530 if (ptr)
531 return ptr;
532 }
533
534 /// If a LazyFunctionCreator is installed, use it to get/create the function.
535 if (LazyFunctionCreator)
536 if (void *RP = LazyFunctionCreator(Name))
537 return RP;
538
539 if (AbortOnFailure) {
540 report_fatal_error("Program used external function '"+Name+
Eli Bendersky5fe01982012-04-29 12:40:47 +0000541 "' which could not be resolved!");
Danil Malyshev30b9e322012-03-28 21:46:36 +0000542 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700543 return nullptr;
Danil Malyshev30b9e322012-03-28 21:46:36 +0000544}
Andrew Kaylor776054d2012-11-06 18:51:59 +0000545
546void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700547 if (!L)
Andrew Kaylor776054d2012-11-06 18:51:59 +0000548 return;
549 MutexGuard locked(lock);
550 EventListeners.push_back(L);
551}
552void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700553 if (!L)
Andrew Kaylor776054d2012-11-06 18:51:59 +0000554 return;
555 MutexGuard locked(lock);
Stephen Hines37ed9c12014-12-01 14:51:49 -0800556 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
Andrew Kaylor776054d2012-11-06 18:51:59 +0000557 if (I != EventListeners.rend()) {
558 std::swap(*I, EventListeners.back());
559 EventListeners.pop_back();
560 }
561}
562void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
563 MutexGuard locked(lock);
Andrew Kaylorb868e912013-10-04 00:49:38 +0000564 MemMgr.notifyObjectLoaded(this, &Obj);
Andrew Kaylor776054d2012-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) {
570 MutexGuard locked(lock);
Stephen Hines37ed9c12014-12-01 14:51:49 -0800571 for (JITEventListener *L : EventListeners)
572 L->NotifyFreeingObject(Obj);
Andrew Kaylor776054d2012-11-06 18:51:59 +0000573}
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000574
575uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
576 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
Andrew Kaylor52c90162013-10-01 16:42:50 +0000577 // If the symbols wasn't found and it begins with an underscore, try again
578 // without the underscore.
579 if (!Result && Name[0] == '_')
580 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000581 if (Result)
582 return Result;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800583 if (ParentEngine->isSymbolSearchingDisabled())
584 return 0;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000585 return ClientMM->getSymbolAddress(Name);
586}