blob: 58cf4e5e6dd8c23c88cc4de678c24079ba4ff4f0 [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"
Andrew Kayloradc70562012-10-02 21:18:39 +000013#include "llvm/ExecutionEngine/MCJIT.h"
Andrew Kaylor31be5ef2013-04-29 17:49:40 +000014#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000015#include "llvm/IR/DataLayout.h"
16#include "llvm/IR/DerivedTypes.h"
17#include "llvm/IR/Function.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000018#include "llvm/IR/Mangler.h"
Andrew Kaylorea395922013-10-01 01:47:35 +000019#include "llvm/IR/Module.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000020#include "llvm/MC/MCAsmInfo.h"
Lang Hames173c69f2014-01-08 04:09:09 +000021#include "llvm/Object/Archive.h"
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000022#include "llvm/Object/ObjectFile.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000023#include "llvm/PassManager.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000024#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Support/ErrorHandling.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000026#include "llvm/Support/MemoryBuffer.h"
Zachary Turnerc04b8922014-06-20 21:07:14 +000027#include "llvm/Support/MutexGuard.h"
Rafael Espindoladaeafb42014-02-19 17:23:20 +000028#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000029#include "llvm/Target/TargetSubtargetInfo.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000030
31using namespace llvm;
32
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000033void ObjectCache::anchor() {}
34
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000035namespace {
36
37static struct RegisterJIT {
38 RegisterJIT() { MCJIT::Register(); }
39} JITRegistrator;
40
41}
42
43extern "C" void LLVMLinkInMCJIT() {
44}
45
Rafael Espindola2a8a2792014-08-19 04:04:25 +000046ExecutionEngine *MCJIT::createJIT(std::unique_ptr<Module> M,
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000047 std::string *ErrorStr,
Filip Pizlo9bc53e82013-05-14 19:29:00 +000048 RTDyldMemoryManager *MemMgr,
David Blaikie196e3232014-09-02 22:41:07 +000049 std::unique_ptr<TargetMachine> TM) {
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000050 // Try to register the program as a source of symbols to resolve against.
51 //
52 // FIXME: Don't do this here.
Craig Topper353eda42014-04-24 06:44:33 +000053 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000054
David Blaikie196e3232014-09-02 22:41:07 +000055 return new MCJIT(std::move(M), std::move(TM),
Rafael Espindola2a8a2792014-08-19 04:04:25 +000056 MemMgr ? MemMgr : new SectionMemoryManager());
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000057}
58
David Blaikie196e3232014-09-02 22:41:07 +000059MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
Rafael Espindola2a8a2792014-08-19 04:04:25 +000060 RTDyldMemoryManager *MM)
David Blaikie196e3232014-09-02 22:41:07 +000061 : ExecutionEngine(std::move(M)), TM(std::move(tm)), Ctx(nullptr),
62 MemMgr(this, MM), Dyld(&MemMgr), ObjCache(nullptr) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +000063 // FIXME: We are managing our modules, so we do not want the base class
64 // ExecutionEngine to manage them as well. To avoid double destruction
65 // of the first (and only) module added in ExecutionEngine constructor
66 // we remove it from EE and will destruct it ourselves.
67 //
68 // It may make sense to move our module manager (based on SmallStPtr) back
69 // into EE if the JIT and Interpreter can live with it.
70 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
71 // runStaticConstructorsDestructors could be moved back to EE as well.
72 //
Rafael Espindola2a8a2792014-08-19 04:04:25 +000073 std::unique_ptr<Module> First = std::move(Modules[0]);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000074 Modules.clear();
Rafael Espindola2a8a2792014-08-19 04:04:25 +000075
76 OwnedModules.addModule(std::move(First));
77 setDataLayout(TM->getSubtargetImpl()->getDataLayout());
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000078 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
Rafael Espindola2a8a2792014-08-19 04:04:25 +000079}
80
81MCJIT::~MCJIT() {
82 MutexGuard locked(lock);
83
Andrew Kaylorc442a762013-10-16 00:14:21 +000084 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000085
David Blaikieed9709d2014-09-03 19:48:09 +000086 for (auto &Obj : LoadedObjects)
87 if (Obj)
Chandler Carruthd55d1592013-10-24 09:52:56 +000088 NotifyFreeingObject(*Obj);
Lang Hames173c69f2014-01-08 04:09:09 +000089
Lang Hames173c69f2014-01-08 04:09:09 +000090 Archives.clear();
Andrew Kaylor1a568c32012-08-07 18:33:00 +000091}
92
Rafael Espindola2a8a2792014-08-19 04:04:25 +000093void MCJIT::addModule(std::unique_ptr<Module> M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +000094 MutexGuard locked(lock);
Rafael Espindola2a8a2792014-08-19 04:04:25 +000095 OwnedModules.addModule(std::move(M));
Andrew Kaylorea395922013-10-01 01:47:35 +000096}
97
Andrew Kaylorc89fc822013-10-24 00:19:14 +000098bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +000099 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000100 return OwnedModules.removeModule(M);
101}
102
David Blaikie7a1e7752014-04-29 21:52:46 +0000103void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000104 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
105 if (Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000106 report_fatal_error(Dyld.getErrorString());
107
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000108 NotifyObjectEmitted(*Obj, *L);
David Blaikie168861a2014-09-04 18:37:31 +0000109
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000110 LoadedObjects.push_back(std::move(Obj));
Lang Hames173c69f2014-01-08 04:09:09 +0000111}
112
Rafael Espindola7271c192014-08-26 21:04:04 +0000113void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000114 std::unique_ptr<object::ObjectFile> ObjFile;
115 std::unique_ptr<MemoryBuffer> MemBuf;
116 std::tie(ObjFile, MemBuf) = Obj.takeBinary();
117 addObjectFile(std::move(ObjFile));
118 Buffers.push_back(std::move(MemBuf));
Rafael Espindola7271c192014-08-26 21:04:04 +0000119}
120
Rafael Espindola48af1c22014-08-19 18:44:46 +0000121void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolace47a052014-08-01 18:09:32 +0000122 Archives.push_back(std::move(A));
Lang Hames173c69f2014-01-08 04:09:09 +0000123}
124
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000125void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000126 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000127 ObjCache = NewCache;
128}
129
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000130std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000131 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000132
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000133 // This must be a module which has already been added but not loaded to this
134 // MCJIT instance, since these conditions are tested by our caller,
135 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000136
137 PassManager PM;
138
Eric Christopherd9134482014-08-04 21:25:23 +0000139 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
Rafael Espindolac435adc2014-09-10 21:27:43 +0000140 PM.add(new DataLayoutPass());
Jim Grosbach7b162492011-03-18 22:48:41 +0000141
Andrew Kayloradc70562012-10-02 21:18:39 +0000142 // The RuntimeDyld will take ownership of this shortly
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000143 SmallVector<char, 4096> ObjBufferSV;
144 raw_svector_ostream ObjStream(ObjBufferSV);
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 Hamesb5c7b1f2014-11-26 16:54:40 +0000148 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
Jim Grosbach7b162492011-03-18 22:48:41 +0000149 report_fatal_error("Target does not support MC emission!");
Jim Grosbach7b162492011-03-18 22:48:41 +0000150
151 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000152 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000153 // Flush the output buffer to get the generated code into memory
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000154 ObjStream.flush();
155
156 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
157 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000158
159 // If we have an object cache, tell it about the new object.
160 // Note that we're using the compiled image, not the loaded image (as below).
161 if (ObjCache) {
162 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
163 // to create a temporary object here and delete it after the call.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000164 MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
Rafael Espindola48af1c22014-08-19 18:44:46 +0000165 ObjCache->notifyObjectCompiled(M, MB);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000166 }
167
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000168 return CompiledObjBuffer;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000169}
170
Andrew Kaylorea395922013-10-01 01:47:35 +0000171void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000172 // Get a thread lock to make sure we aren't trying to load multiple times
Zachary Turnerc04b8922014-06-20 21:07:14 +0000173 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000174
Andrew Kaylorea395922013-10-01 01:47:35 +0000175 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000176 assert(OwnedModules.ownsModule(M) &&
177 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000178
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000179 // Re-compilation is not supported
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000180 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000181 return;
182
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000183 std::unique_ptr<MemoryBuffer> ObjectToLoad;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000184 // Try to load the pre-compiled object from cache if possible
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000185 if (ObjCache)
186 ObjectToLoad = ObjCache->getObject(M);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000187
188 // If the cache did not contain a suitable object, compile the object
189 if (!ObjectToLoad) {
David Blaikied1101572014-09-03 19:57:35 +0000190 ObjectToLoad = emitObject(M);
191 assert(ObjectToLoad && "Compilation did not produce an object.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000192 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000193
194 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000195 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000196 ErrorOr<std::unique_ptr<object::ObjectFile>> LoadedObject =
197 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
198 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
199 Dyld.loadObject(*LoadedObject.get());
200
201 if (Dyld.hasError())
Jim Grosbachc114d892011-03-23 19:51:34 +0000202 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000203
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000204 NotifyObjectEmitted(*LoadedObject.get(), *L);
Andrew Kayloradc70562012-10-02 21:18:39 +0000205
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000206 Buffers.push_back(std::move(ObjectToLoad));
207 LoadedObjects.push_back(std::move(*LoadedObject));
David Blaikieed9709d2014-09-03 19:48:09 +0000208
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000209 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000210}
211
Andrew Kaylorea395922013-10-01 01:47:35 +0000212void MCJIT::finalizeLoadedModules() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000213 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000214
Andrew Kaylorea395922013-10-01 01:47:35 +0000215 // Resolve any outstanding relocations.
216 Dyld.resolveRelocations();
217
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000218 OwnedModules.markAllLoadedModulesAsFinalized();
219
Andrew Kaylorea395922013-10-01 01:47:35 +0000220 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000221 Dyld.registerEHFrames();
222
Andrew Kaylorea395922013-10-01 01:47:35 +0000223 // Set page permissions.
224 MemMgr.finalizeMemory();
225}
226
227// FIXME: Rename this.
228void MCJIT::finalizeObject() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000229 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000230
Lang Hames018452e2014-09-05 23:38:35 +0000231 // Generate code for module is going to move objects out of the 'added' list,
232 // so we need to copy that out before using it:
233 SmallVector<Module*, 16> ModsToAdd;
234 for (auto M : OwnedModules.added())
235 ModsToAdd.push_back(M);
236
237 for (auto M : ModsToAdd)
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000238 generateCodeForModule(M);
Andrew Kaylora342cb92012-11-15 23:50:01 +0000239
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000240 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000241}
242
243void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000244 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000245
Andrew Kaylorea395922013-10-01 01:47:35 +0000246 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000247 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000248
249 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000250 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000251 generateCodeForModule(M);
252
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000253 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000254}
255
Andrew Kaylorea395922013-10-01 01:47:35 +0000256uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
Eric Christopherd9134482014-08-04 21:25:23 +0000257 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000258 SmallString<128> FullName;
259 Mang.getNameWithPrefix(FullName, Name);
260 return Dyld.getSymbolLoadAddress(FullName);
Andrew Kaylorea395922013-10-01 01:47:35 +0000261}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000262
Andrew Kaylorea395922013-10-01 01:47:35 +0000263Module *MCJIT::findModuleForSymbol(const std::string &Name,
264 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000265 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000266
Andrew Kaylorea395922013-10-01 01:47:35 +0000267 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000268 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
269 E = OwnedModules.end_added();
270 I != E; ++I) {
271 Module *M = *I;
Andrew Kaylorea395922013-10-01 01:47:35 +0000272 Function *F = M->getFunction(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000273 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000274 return M;
275 if (!CheckFunctionsOnly) {
276 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000277 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000278 return M;
279 // FIXME: Do we need to worry about global aliases?
280 }
281 }
282 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000283 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000284}
285
286uint64_t MCJIT::getSymbolAddress(const std::string &Name,
287 bool CheckFunctionsOnly)
288{
Zachary Turnerc04b8922014-06-20 21:07:14 +0000289 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000290
Andrew Kaylorea395922013-10-01 01:47:35 +0000291 // First, check to see if we already have this symbol.
292 uint64_t Addr = getExistingSymbolAddress(Name);
293 if (Addr)
294 return Addr;
295
Rafael Espindola48af1c22014-08-19 18:44:46 +0000296 for (object::OwningBinary<object::Archive> &OB : Archives) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000297 object::Archive *A = OB.getBinary();
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);
Lang Hamesea800ca2014-08-14 02:38:20 +0000322 if (M) {
323 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000324
Lang Hamesea800ca2014-08-14 02:38:20 +0000325 // Check the RuntimeDyld table again, it should be there now.
326 return getExistingSymbolAddress(Name);
327 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000328
Lang Hamesea800ca2014-08-14 02:38:20 +0000329 // If a LazyFunctionCreator is installed, use it to get/create the function.
330 // FIXME: Should we instead have a LazySymbolCreator callback?
331 if (LazyFunctionCreator)
332 Addr = (uint64_t)LazyFunctionCreator(Name);
333
334 return Addr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000335}
336
337uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000338 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000339 uint64_t Result = getSymbolAddress(Name, false);
340 if (Result != 0)
341 finalizeLoadedModules();
342 return Result;
343}
344
345uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000346 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000347 uint64_t Result = getSymbolAddress(Name, true);
348 if (Result != 0)
349 finalizeLoadedModules();
350 return Result;
351}
352
353// Deprecated. Use getFunctionAddress instead.
354void *MCJIT::getPointerToFunction(Function *F) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000355 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000356
Lang Hamesb7fbf592014-09-20 17:44:56 +0000357 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
358 SmallString<128> Name;
359 TM->getNameWithPrefix(Name, F, Mang);
360
Jim Grosbachd5274402011-03-22 18:05:27 +0000361 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
362 bool AbortOnFailure = !F->hasExternalWeakLinkage();
Lang Hamesb7fbf592014-09-20 17:44:56 +0000363 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
Lang Hamesefe7e222014-10-22 23:18:42 +0000364 updateGlobalMapping(F, Addr);
Jim Grosbachd5274402011-03-22 18:05:27 +0000365 return Addr;
366 }
367
Andrew Kaylorea395922013-10-01 01:47:35 +0000368 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000369 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000370
371 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000372 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000373 generateCodeForModule(M);
Lang Hamesb7fbf592014-09-20 17:44:56 +0000374 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000375 // If this function doesn't belong to one of our modules, we're done.
Lang Hamesb7fbf592014-09-20 17:44:56 +0000376 // FIXME: Asking for the pointer to a function that hasn't been registered,
377 // and isn't a declaration (which is handled above) should probably
378 // be an assertion.
Craig Topper353eda42014-04-24 06:44:33 +0000379 return nullptr;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000380 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000381
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000382 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000383 //
384 // This is the accessor for the target address, so make sure to check the
385 // load address of the symbol, not the local address.
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000386 return (void*)Dyld.getSymbolLoadAddress(Name);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000387}
388
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000389void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
390 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
391 for (; I != E; ++I) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000392 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000393 }
394}
395
396void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
397 // Execute global ctors/dtors for each module in the program.
398 runStaticConstructorsDestructorsInModulePtrSet(
399 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
400 runStaticConstructorsDestructorsInModulePtrSet(
401 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
402 runStaticConstructorsDestructorsInModulePtrSet(
403 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
404}
405
406Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
407 ModulePtrSet::iterator I,
408 ModulePtrSet::iterator E) {
409 for (; I != E; ++I) {
410 if (Function *F = (*I)->getFunction(FnName))
411 return F;
412 }
Craig Topper353eda42014-04-24 06:44:33 +0000413 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000414}
415
416Function *MCJIT::FindFunctionNamed(const char *FnName) {
417 Function *F = FindFunctionNamedInModulePtrSet(
418 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
419 if (!F)
420 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
421 OwnedModules.end_loaded());
422 if (!F)
423 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
424 OwnedModules.end_finalized());
425 return F;
426}
427
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000428GenericValue MCJIT::runFunction(Function *F,
429 const std::vector<GenericValue> &ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000430 assert(F && "Function *F was null at entry to run()");
431
Jim Grosbach7b162492011-03-18 22:48:41 +0000432 void *FPtr = getPointerToFunction(F);
Jim Grosbachd5274402011-03-22 18:05:27 +0000433 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000434 FunctionType *FTy = F->getFunctionType();
435 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000436
437 assert((FTy->getNumParams() == ArgValues.size() ||
438 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
439 "Wrong number of arguments passed into function!");
440 assert(FTy->getNumParams() == ArgValues.size() &&
441 "This doesn't support passing arguments through varargs (yet)!");
442
443 // Handle some common cases first. These cases correspond to common `main'
444 // prototypes.
445 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
446 switch (ArgValues.size()) {
447 case 3:
448 if (FTy->getParamType(0)->isIntegerTy(32) &&
449 FTy->getParamType(1)->isPointerTy() &&
450 FTy->getParamType(2)->isPointerTy()) {
451 int (*PF)(int, char **, const char **) =
452 (int(*)(int, char **, const char **))(intptr_t)FPtr;
453
454 // Call the function.
455 GenericValue rv;
456 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
457 (char **)GVTOP(ArgValues[1]),
458 (const char **)GVTOP(ArgValues[2])));
459 return rv;
460 }
461 break;
462 case 2:
463 if (FTy->getParamType(0)->isIntegerTy(32) &&
464 FTy->getParamType(1)->isPointerTy()) {
465 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
466
467 // Call the function.
468 GenericValue rv;
469 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
470 (char **)GVTOP(ArgValues[1])));
471 return rv;
472 }
473 break;
474 case 1:
475 if (FTy->getNumParams() == 1 &&
476 FTy->getParamType(0)->isIntegerTy(32)) {
477 GenericValue rv;
478 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
479 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
480 return rv;
481 }
482 break;
483 }
484 }
485
486 // Handle cases where no arguments are passed first.
487 if (ArgValues.empty()) {
488 GenericValue rv;
489 switch (RetTy->getTypeID()) {
490 default: llvm_unreachable("Unknown return type for function call!");
491 case Type::IntegerTyID: {
492 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
493 if (BitWidth == 1)
494 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
495 else if (BitWidth <= 8)
496 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
497 else if (BitWidth <= 16)
498 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
499 else if (BitWidth <= 32)
500 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
501 else if (BitWidth <= 64)
502 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
503 else
504 llvm_unreachable("Integer types > 64 bits not supported");
505 return rv;
506 }
507 case Type::VoidTyID:
508 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
509 return rv;
510 case Type::FloatTyID:
511 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
512 return rv;
513 case Type::DoubleTyID:
514 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
515 return rv;
516 case Type::X86_FP80TyID:
517 case Type::FP128TyID:
518 case Type::PPC_FP128TyID:
519 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000520 case Type::PointerTyID:
521 return PTOGV(((void*(*)())(intptr_t)FPtr)());
522 }
523 }
524
Craig Toppera2886c22012-02-07 05:05:23 +0000525 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000526}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000527
Lang Hames9a783342014-09-15 17:50:22 +0000528void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000529 if (!isSymbolSearchingDisabled()) {
530 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
Danil Malyshevbfee5422012-03-28 21:46:36 +0000531 if (ptr)
532 return ptr;
533 }
534
535 /// If a LazyFunctionCreator is installed, use it to get/create the function.
536 if (LazyFunctionCreator)
537 if (void *RP = LazyFunctionCreator(Name))
538 return RP;
539
540 if (AbortOnFailure) {
541 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000542 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000543 }
Craig Topper353eda42014-04-24 06:44:33 +0000544 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000545}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000546
547void MCJIT::RegisterJITEventListener(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 EventListeners.push_back(L);
552}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000553
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000554void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000555 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000556 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000557 MutexGuard locked(lock);
Eric Christopher79cc1e32014-09-02 22:28:02 +0000558 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000559 if (I != EventListeners.rend()) {
560 std::swap(*I, EventListeners.back());
561 EventListeners.pop_back();
562 }
563}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000564
565void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
566 const RuntimeDyld::LoadedObjectInfo &L) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000567 MutexGuard locked(lock);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000568 MemMgr.notifyObjectLoaded(this, Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000569 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000570 EventListeners[I]->NotifyObjectEmitted(Obj, L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000571 }
572}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000573
574void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000575 MutexGuard locked(lock);
David Blaikieed9709d2014-09-03 19:48:09 +0000576 for (JITEventListener *L : EventListeners)
Eric Christopher79cc1e32014-09-02 22:28:02 +0000577 L->NotifyFreeingObject(Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000578}
Andrew Kaylorea395922013-10-01 01:47:35 +0000579
580uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
581 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
Andrew Kaylor89bdd102013-10-01 16:42:50 +0000582 // If the symbols wasn't found and it begins with an underscore, try again
583 // without the underscore.
584 if (!Result && Name[0] == '_')
585 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000586 if (Result)
587 return Result;
Lang Hamesea800ca2014-08-14 02:38:20 +0000588 if (ParentEngine->isSymbolSearchingDisabled())
589 return 0;
Andrew Kaylorea395922013-10-01 01:47:35 +0000590 return ClientMM->getSymbolAddress(Name);
591}