blob: 65e2aba29ee4e7c63daabd8c93ceed2de9ef2c43 [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"
Eric Christopherd9134482014-08-04 21:25:23 +000031#include "llvm/Target/TargetSubtargetInfo.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000032
33using namespace llvm;
34
35namespace {
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,
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000049 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
Rafael Espindola2a8a2792014-08-19 04:04:25 +000055 return new MCJIT(std::move(M), TM,
56 MemMgr ? MemMgr : new SectionMemoryManager());
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000057}
58
Rafael Espindola2a8a2792014-08-19 04:04:25 +000059MCJIT::MCJIT(std::unique_ptr<Module> M, TargetMachine *tm,
60 RTDyldMemoryManager *MM)
61 : ExecutionEngine(std::move(M)), TM(tm), Ctx(nullptr), MemMgr(this, MM),
62 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());
78}
79
80MCJIT::~MCJIT() {
81 MutexGuard locked(lock);
82
Andrew Kaylorc442a762013-10-16 00:14:21 +000083 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000084
Lang Hames173c69f2014-01-08 04:09:09 +000085 LoadedObjectList::iterator it, end;
86 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
87 ObjectImage *Obj = *it;
Chandler Carruthd55d1592013-10-24 09:52:56 +000088 if (Obj) {
89 NotifyFreeingObject(*Obj);
90 delete Obj;
91 }
92 }
Andrew Kaylorea395922013-10-01 01:47:35 +000093 LoadedObjects.clear();
Lang Hames173c69f2014-01-08 04:09:09 +000094
Lang Hames173c69f2014-01-08 04:09:09 +000095 Archives.clear();
96
Andrew Kaylor1a568c32012-08-07 18:33:00 +000097 delete TM;
98}
99
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000100void MCJIT::addModule(std::unique_ptr<Module> M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000101 MutexGuard locked(lock);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000102 OwnedModules.addModule(std::move(M));
Andrew Kaylorea395922013-10-01 01:47:35 +0000103}
104
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000105bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000106 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000107 return OwnedModules.removeModule(M);
108}
109
110
111
David Blaikie7a1e7752014-04-29 21:52:46 +0000112void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
113 ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
Juergen Ributzka6ff29a72014-03-26 18:19:27 +0000114 if (!LoadedObject || Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000115 report_fatal_error(Dyld.getErrorString());
116
117 LoadedObjects.push_back(LoadedObject);
118
119 NotifyObjectEmitted(*LoadedObject);
120}
121
Rafael Espindolace47a052014-08-01 18:09:32 +0000122void MCJIT::addArchive(std::unique_ptr<object::Archive> A) {
123 Archives.push_back(std::move(A));
Lang Hames173c69f2014-01-08 04:09:09 +0000124}
125
126
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000127void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000128 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000129 ObjCache = NewCache;
130}
131
Andrew Kaylorea395922013-10-01 01:47:35 +0000132ObjectBufferStream* MCJIT::emitObject(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000133 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000134
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000135 // This must be a module which has already been added but not loaded to this
136 // MCJIT instance, since these conditions are tested by our caller,
137 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000138
139 PassManager PM;
140
Eric Christopherd9134482014-08-04 21:25:23 +0000141 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
Rafael Espindola339430f2014-02-25 23:25:17 +0000142 PM.add(new DataLayoutPass(M));
Jim Grosbach7b162492011-03-18 22:48:41 +0000143
Andrew Kayloradc70562012-10-02 21:18:39 +0000144 // The RuntimeDyld will take ownership of this shortly
Ahmed Charles56440fd2014-03-06 05:51:42 +0000145 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
Andrew Kayloradc70562012-10-02 21:18:39 +0000146
Jim Grosbach7b162492011-03-18 22:48:41 +0000147 // Turn the machine code intermediate representation into bytes in memory
148 // that may be executed.
Lang Hamesbc876012014-04-18 06:48:23 +0000149 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
150 !getVerifyModules())) {
Jim Grosbach7b162492011-03-18 22:48:41 +0000151 report_fatal_error("Target does not support MC emission!");
152 }
153
154 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000155 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000156 // Flush the output buffer to get the generated code into memory
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000157 CompiledObject->flush();
158
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.
Rafael Espindola3a1623f2014-08-17 23:38:08 +0000164 std::unique_ptr<MemoryBuffer> MB = CompiledObject->getMemBuffer();
Andrew Kaylorea395922013-10-01 01:47:35 +0000165 ObjCache->notifyObjectCompiled(M, MB.get());
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000166 }
167
Ahmed Charles96c9d952014-03-05 10:19:29 +0000168 return CompiledObject.release();
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
Ahmed Charles56440fd2014-03-06 05:51:42 +0000183 std::unique_ptr<ObjectBuffer> ObjectToLoad;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000184 // Try to load the pre-compiled object from cache if possible
Craig Topper353eda42014-04-24 06:44:33 +0000185 if (ObjCache) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000186 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
Craig Topper353eda42014-04-24 06:44:33 +0000187 if (PreCompiledObject.get())
Ahmed Charles96c9d952014-03-05 10:19:29 +0000188 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000189 }
190
191 // If the cache did not contain a suitable object, compile the object
192 if (!ObjectToLoad) {
193 ObjectToLoad.reset(emitObject(M));
194 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
195 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000196
197 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000198 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Ahmed Charles96c9d952014-03-05 10:19:29 +0000199 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
Lang Hames173c69f2014-01-08 04:09:09 +0000200 LoadedObjects.push_back(LoadedObject);
Andrew Kayloradc70562012-10-02 21:18:39 +0000201 if (!LoadedObject)
Jim Grosbachc114d892011-03-23 19:51:34 +0000202 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000203
Andrew Kayloradc70562012-10-02 21:18:39 +0000204 // FIXME: Make this optional, maybe even move it to a JIT event listener
205 LoadedObject->registerWithDebugger();
206
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000207 NotifyObjectEmitted(*LoadedObject);
208
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
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000231 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
232 E = OwnedModules.end_added();
233 I != E; ++I) {
234 Module *M = *I;
235 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000236 }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000237
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000238 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000239}
240
241void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000242 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000243
Andrew Kaylorea395922013-10-01 01:47:35 +0000244 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000245 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000246
247 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000248 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000249 generateCodeForModule(M);
250
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000251 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000252}
253
Eric Christopherb9fd9ed2014-08-07 22:02:54 +0000254void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
255 report_fatal_error("not yet implemented");
256}
257
Andrew Kaylorea395922013-10-01 01:47:35 +0000258uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
Eric Christopherd9134482014-08-04 21:25:23 +0000259 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000260 SmallString<128> FullName;
261 Mang.getNameWithPrefix(FullName, Name);
262 return Dyld.getSymbolLoadAddress(FullName);
Andrew Kaylorea395922013-10-01 01:47:35 +0000263}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000264
Andrew Kaylorea395922013-10-01 01:47:35 +0000265Module *MCJIT::findModuleForSymbol(const std::string &Name,
266 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000267 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000268
Andrew Kaylorea395922013-10-01 01:47:35 +0000269 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000270 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
271 E = OwnedModules.end_added();
272 I != E; ++I) {
273 Module *M = *I;
Andrew Kaylorea395922013-10-01 01:47:35 +0000274 Function *F = M->getFunction(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000275 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000276 return M;
277 if (!CheckFunctionsOnly) {
278 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000279 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000280 return M;
281 // FIXME: Do we need to worry about global aliases?
282 }
283 }
284 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000285 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000286}
287
288uint64_t MCJIT::getSymbolAddress(const std::string &Name,
289 bool CheckFunctionsOnly)
290{
Zachary Turnerc04b8922014-06-20 21:07:14 +0000291 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000292
Andrew Kaylorea395922013-10-01 01:47:35 +0000293 // First, check to see if we already have this symbol.
294 uint64_t Addr = getExistingSymbolAddress(Name);
295 if (Addr)
296 return Addr;
297
Rafael Espindolace47a052014-08-01 18:09:32 +0000298 for (std::unique_ptr<object::Archive> &A : Archives) {
Lang Hames173c69f2014-01-08 04:09:09 +0000299 // Look for our symbols in each Archive
300 object::Archive::child_iterator ChildIt = A->findSym(Name);
Rafael Espindola23a97502014-01-21 16:09:45 +0000301 if (ChildIt != A->child_end()) {
Lang Hames173c69f2014-01-08 04:09:09 +0000302 // FIXME: Support nested archives?
Rafael Espindolaae460022014-06-16 16:08:36 +0000303 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
304 ChildIt->getAsBinary();
305 if (ChildBinOrErr.getError())
306 continue;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000307 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
Rafael Espindolaae460022014-06-16 16:08:36 +0000308 if (ChildBin->isObject()) {
David Blaikie7a1e7752014-04-29 21:52:46 +0000309 std::unique_ptr<object::ObjectFile> OF(
310 static_cast<object::ObjectFile *>(ChildBin.release()));
Lang Hames173c69f2014-01-08 04:09:09 +0000311 // This causes the object file to be loaded.
David Blaikie7a1e7752014-04-29 21:52:46 +0000312 addObjectFile(std::move(OF));
Lang Hames173c69f2014-01-08 04:09:09 +0000313 // The address should be here now.
314 Addr = getExistingSymbolAddress(Name);
315 if (Addr)
316 return Addr;
317 }
318 }
319 }
320
Andrew Kaylorea395922013-10-01 01:47:35 +0000321 // If it hasn't already been generated, see if it's in one of our modules.
322 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
Lang Hamesea800ca2014-08-14 02:38:20 +0000323 if (M) {
324 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000325
Lang Hamesea800ca2014-08-14 02:38:20 +0000326 // Check the RuntimeDyld table again, it should be there now.
327 return getExistingSymbolAddress(Name);
328 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000329
Lang Hamesea800ca2014-08-14 02:38:20 +0000330 // If a LazyFunctionCreator is installed, use it to get/create the function.
331 // FIXME: Should we instead have a LazySymbolCreator callback?
332 if (LazyFunctionCreator)
333 Addr = (uint64_t)LazyFunctionCreator(Name);
334
335 return Addr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000336}
337
338uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000339 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000340 uint64_t Result = getSymbolAddress(Name, false);
341 if (Result != 0)
342 finalizeLoadedModules();
343 return Result;
344}
345
346uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000347 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000348 uint64_t Result = getSymbolAddress(Name, true);
349 if (Result != 0)
350 finalizeLoadedModules();
351 return Result;
352}
353
354// Deprecated. Use getFunctionAddress instead.
355void *MCJIT::getPointerToFunction(Function *F) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000356 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000357
Jim Grosbachd5274402011-03-22 18:05:27 +0000358 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
359 bool AbortOnFailure = !F->hasExternalWeakLinkage();
360 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
361 addGlobalMapping(F, Addr);
362 return Addr;
363 }
364
Andrew Kaylorea395922013-10-01 01:47:35 +0000365 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000366 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000367
368 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000369 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000370 generateCodeForModule(M);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000371 else if (!OwnedModules.hasModuleBeenLoaded(M))
372 // If this function doesn't belong to one of our modules, we're done.
Craig Topper353eda42014-04-24 06:44:33 +0000373 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000374
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000375 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000376 //
377 // This is the accessor for the target address, so make sure to check the
378 // load address of the symbol, not the local address.
Eric Christopherd9134482014-08-04 21:25:23 +0000379 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000380 SmallString<128> Name;
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000381 TM->getNameWithPrefix(Name, F, Mang);
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000382 return (void*)Dyld.getSymbolLoadAddress(Name);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000383}
384
Eric Christopherb9fd9ed2014-08-07 22:02:54 +0000385void *MCJIT::recompileAndRelinkFunction(Function *F) {
386 report_fatal_error("not yet implemented");
387}
388
389void MCJIT::freeMachineCodeForFunction(Function *F) {
390 report_fatal_error("not yet implemented");
391}
392
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000393void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
394 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
395 for (; I != E; ++I) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000396 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000397 }
398}
399
400void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
401 // Execute global ctors/dtors for each module in the program.
402 runStaticConstructorsDestructorsInModulePtrSet(
403 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
404 runStaticConstructorsDestructorsInModulePtrSet(
405 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
406 runStaticConstructorsDestructorsInModulePtrSet(
407 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
408}
409
410Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
411 ModulePtrSet::iterator I,
412 ModulePtrSet::iterator E) {
413 for (; I != E; ++I) {
414 if (Function *F = (*I)->getFunction(FnName))
415 return F;
416 }
Craig Topper353eda42014-04-24 06:44:33 +0000417 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000418}
419
420Function *MCJIT::FindFunctionNamed(const char *FnName) {
421 Function *F = FindFunctionNamedInModulePtrSet(
422 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
423 if (!F)
424 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
425 OwnedModules.end_loaded());
426 if (!F)
427 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
428 OwnedModules.end_finalized());
429 return F;
430}
431
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000432GenericValue MCJIT::runFunction(Function *F,
433 const std::vector<GenericValue> &ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000434 assert(F && "Function *F was null at entry to run()");
435
Jim Grosbach7b162492011-03-18 22:48:41 +0000436 void *FPtr = getPointerToFunction(F);
Jim Grosbachd5274402011-03-22 18:05:27 +0000437 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000438 FunctionType *FTy = F->getFunctionType();
439 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000440
441 assert((FTy->getNumParams() == ArgValues.size() ||
442 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
443 "Wrong number of arguments passed into function!");
444 assert(FTy->getNumParams() == ArgValues.size() &&
445 "This doesn't support passing arguments through varargs (yet)!");
446
447 // Handle some common cases first. These cases correspond to common `main'
448 // prototypes.
449 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
450 switch (ArgValues.size()) {
451 case 3:
452 if (FTy->getParamType(0)->isIntegerTy(32) &&
453 FTy->getParamType(1)->isPointerTy() &&
454 FTy->getParamType(2)->isPointerTy()) {
455 int (*PF)(int, char **, const char **) =
456 (int(*)(int, char **, const char **))(intptr_t)FPtr;
457
458 // Call the function.
459 GenericValue rv;
460 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
461 (char **)GVTOP(ArgValues[1]),
462 (const char **)GVTOP(ArgValues[2])));
463 return rv;
464 }
465 break;
466 case 2:
467 if (FTy->getParamType(0)->isIntegerTy(32) &&
468 FTy->getParamType(1)->isPointerTy()) {
469 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
470
471 // Call the function.
472 GenericValue rv;
473 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
474 (char **)GVTOP(ArgValues[1])));
475 return rv;
476 }
477 break;
478 case 1:
479 if (FTy->getNumParams() == 1 &&
480 FTy->getParamType(0)->isIntegerTy(32)) {
481 GenericValue rv;
482 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
483 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
484 return rv;
485 }
486 break;
487 }
488 }
489
490 // Handle cases where no arguments are passed first.
491 if (ArgValues.empty()) {
492 GenericValue rv;
493 switch (RetTy->getTypeID()) {
494 default: llvm_unreachable("Unknown return type for function call!");
495 case Type::IntegerTyID: {
496 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
497 if (BitWidth == 1)
498 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
499 else if (BitWidth <= 8)
500 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
501 else if (BitWidth <= 16)
502 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
503 else if (BitWidth <= 32)
504 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
505 else if (BitWidth <= 64)
506 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
507 else
508 llvm_unreachable("Integer types > 64 bits not supported");
509 return rv;
510 }
511 case Type::VoidTyID:
512 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
513 return rv;
514 case Type::FloatTyID:
515 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
516 return rv;
517 case Type::DoubleTyID:
518 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
519 return rv;
520 case Type::X86_FP80TyID:
521 case Type::FP128TyID:
522 case Type::PPC_FP128TyID:
523 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000524 case Type::PointerTyID:
525 return PTOGV(((void*(*)())(intptr_t)FPtr)());
526 }
527 }
528
Craig Toppera2886c22012-02-07 05:05:23 +0000529 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000530}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000531
532void *MCJIT::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000533 bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000534 if (!isSymbolSearchingDisabled()) {
535 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
Danil Malyshevbfee5422012-03-28 21:46:36 +0000536 if (ptr)
537 return ptr;
538 }
539
540 /// If a LazyFunctionCreator is installed, use it to get/create the function.
541 if (LazyFunctionCreator)
542 if (void *RP = LazyFunctionCreator(Name))
543 return RP;
544
545 if (AbortOnFailure) {
546 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000547 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000548 }
Craig Topper353eda42014-04-24 06:44:33 +0000549 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000550}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000551
552void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000553 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000554 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000555 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000556 EventListeners.push_back(L);
557}
558void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000559 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000560 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000561 MutexGuard locked(lock);
Eric Christopherb9fd9ed2014-08-07 22:02:54 +0000562 SmallVector<JITEventListener*, 2>::reverse_iterator I=
563 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000564 if (I != EventListeners.rend()) {
565 std::swap(*I, EventListeners.back());
566 EventListeners.pop_back();
567 }
568}
569void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000570 MutexGuard locked(lock);
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000571 MemMgr.notifyObjectLoaded(this, &Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000572 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
573 EventListeners[I]->NotifyObjectEmitted(Obj);
574 }
575}
576void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000577 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000578 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
Eric Christopherb9fd9ed2014-08-07 22:02:54 +0000579 EventListeners[I]->NotifyFreeingObject(Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000580 }
581}
Andrew Kaylorea395922013-10-01 01:47:35 +0000582
583uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
584 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
Andrew Kaylor89bdd102013-10-01 16:42:50 +0000585 // If the symbols wasn't found and it begins with an underscore, try again
586 // without the underscore.
587 if (!Result && Name[0] == '_')
588 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000589 if (Result)
590 return Result;
Lang Hamesea800ca2014-08-14 02:38:20 +0000591 if (ParentEngine->isSymbolSearchingDisabled())
592 return 0;
Andrew Kaylorea395922013-10-01 01:47:35 +0000593 return ClientMM->getSymbolAddress(Name);
594}