blob: e9ba96a6496f8678a4e3436d093e792b063cd4b0 [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"
Jim Grosbachf9229102011-03-22 01:06:42 +000013#include "llvm/ExecutionEngine/JITMemoryManager.h"
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000014#include "llvm/ExecutionEngine/MCJIT.h"
15#include "llvm/ExecutionEngine/ObjectBuffer.h"
16#include "llvm/ExecutionEngine/ObjectImage.h"
Andrew Kaylord2755af2013-04-29 17:49:40 +000017#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/Function.h"
Stephen Hines36b56882014-04-23 16:57:46 -070021#include "llvm/IR/Mangler.h"
Andrew Kaylor8e9ec012013-10-01 01:47:35 +000022#include "llvm/IR/Module.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000023#include "llvm/MC/MCAsmInfo.h"
Stephen Hines36b56882014-04-23 16:57:46 -070024#include "llvm/Object/Archive.h"
25#include "llvm/PassManager.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000026#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/Support/ErrorHandling.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000028#include "llvm/Support/MemoryBuffer.h"
Andrew Kaylorea708d12012-08-07 18:33:00 +000029#include "llvm/Support/MutexGuard.h"
Stephen Hines36b56882014-04-23 16:57:46 -070030#include "llvm/Target/TargetLowering.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
45ExecutionEngine *MCJIT::createJIT(Module *M,
46 std::string *ErrorStr,
Filip Pizlo13a3cf12013-05-14 19:29:00 +000047 RTDyldMemoryManager *MemMgr,
Daniel Dunbar6aec2982010-11-17 16:06:43 +000048 bool GVsWithCode,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000049 TargetMachine *TM) {
Daniel Dunbar6aec2982010-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.
Stephen Hinesdce4a402014-05-29 02:49:00 -070053 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
Daniel Dunbar6aec2982010-11-17 16:06:43 +000054
Filip Pizlo13a3cf12013-05-14 19:29:00 +000055 return new MCJIT(M, TM, MemMgr ? MemMgr : new SectionMemoryManager(),
56 GVsWithCode);
Daniel Dunbar6aec2982010-11-17 16:06:43 +000057}
58
Jim Grosbach8005bcd2012-08-21 15:42:49 +000059MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
60 bool AllocateGVsWithCode)
Stephen Hinesdce4a402014-05-29 02:49:00 -070061 : ExecutionEngine(m), TM(tm), Ctx(nullptr), MemMgr(this, MM), Dyld(&MemMgr),
62 ObjCache(nullptr) {
Jim Grosbach31649e62011-03-18 22:48:41 +000063
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +000064 OwnedModules.addModule(m);
Micah Villmow3574eca2012-10-08 16:38:25 +000065 setDataLayout(TM->getDataLayout());
Andrew Kaylorea708d12012-08-07 18:33:00 +000066}
67
68MCJIT::~MCJIT() {
Andrew Kaylor61694532013-10-21 17:42:06 +000069 MutexGuard locked(lock);
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +000070 // FIXME: We are managing our modules, so we do not want the base class
71 // ExecutionEngine to manage them as well. To avoid double destruction
72 // of the first (and only) module added in ExecutionEngine constructor
73 // we remove it from EE and will destruct it ourselves.
74 //
75 // It may make sense to move our module manager (based on SmallStPtr) back
76 // into EE if the JIT and Interpreter can live with it.
77 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
78 // runStaticConstructorsDestructors could be moved back to EE as well.
79 //
80 Modules.clear();
Andrew Kaylor43507d02013-10-16 00:14:21 +000081 Dyld.deregisterEHFrames();
Chandler Carruth81798732013-10-24 09:52:56 +000082
Stephen Hines36b56882014-04-23 16:57:46 -070083 LoadedObjectList::iterator it, end;
84 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
85 ObjectImage *Obj = *it;
Chandler Carruth81798732013-10-24 09:52:56 +000086 if (Obj) {
87 NotifyFreeingObject(*Obj);
88 delete Obj;
89 }
90 }
Andrew Kaylor8e9ec012013-10-01 01:47:35 +000091 LoadedObjects.clear();
Stephen Hines36b56882014-04-23 16:57:46 -070092
93
94 SmallVector<object::Archive *, 2>::iterator ArIt, ArEnd;
95 for (ArIt = Archives.begin(), ArEnd = Archives.end(); ArIt != ArEnd; ++ArIt) {
96 object::Archive *A = *ArIt;
97 delete A;
98 }
99 Archives.clear();
100
Andrew Kaylorea708d12012-08-07 18:33:00 +0000101 delete TM;
102}
103
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000104void MCJIT::addModule(Module *M) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000105 MutexGuard locked(lock);
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000106 OwnedModules.addModule(M);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000107}
108
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000109bool MCJIT::removeModule(Module *M) {
110 MutexGuard locked(lock);
111 return OwnedModules.removeModule(M);
112}
113
114
115
Stephen Hinesdce4a402014-05-29 02:49:00 -0700116void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
117 ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
Stephen Hines36b56882014-04-23 16:57:46 -0700118 if (!LoadedObject || Dyld.hasError())
119 report_fatal_error(Dyld.getErrorString());
120
121 LoadedObjects.push_back(LoadedObject);
122
123 NotifyObjectEmitted(*LoadedObject);
124}
125
126void MCJIT::addArchive(object::Archive *A) {
127 Archives.push_back(A);
128}
129
130
Andrew Kaylor1c489452013-04-25 21:02:36 +0000131void MCJIT::setObjectCache(ObjectCache* NewCache) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000132 MutexGuard locked(lock);
Andrew Kaylor1c489452013-04-25 21:02:36 +0000133 ObjCache = NewCache;
134}
135
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000136ObjectBufferStream* MCJIT::emitObject(Module *M) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000137 MutexGuard locked(lock);
138
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000139 // This must be a module which has already been added but not loaded to this
140 // MCJIT instance, since these conditions are tested by our caller,
141 // generateCodeForModule.
Andrew Kaylorea708d12012-08-07 18:33:00 +0000142
143 PassManager PM;
144
Stephen Hines36b56882014-04-23 16:57:46 -0700145 M->setDataLayout(TM->getDataLayout());
146 PM.add(new DataLayoutPass(M));
Jim Grosbach31649e62011-03-18 22:48:41 +0000147
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000148 // The RuntimeDyld will take ownership of this shortly
Stephen Hines36b56882014-04-23 16:57:46 -0700149 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000150
Jim Grosbach31649e62011-03-18 22:48:41 +0000151 // Turn the machine code intermediate representation into bytes in memory
152 // that may be executed.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700153 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
154 !getVerifyModules())) {
Jim Grosbach31649e62011-03-18 22:48:41 +0000155 report_fatal_error("Target does not support MC emission!");
156 }
157
158 // Initialize passes.
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000159 PM.run(*M);
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000160 // Flush the output buffer to get the generated code into memory
Andrew Kaylor1c489452013-04-25 21:02:36 +0000161 CompiledObject->flush();
162
163 // If we have an object cache, tell it about the new object.
164 // Note that we're using the compiled image, not the loaded image (as below).
165 if (ObjCache) {
166 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
167 // to create a temporary object here and delete it after the call.
Stephen Hines36b56882014-04-23 16:57:46 -0700168 std::unique_ptr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000169 ObjCache->notifyObjectCompiled(M, MB.get());
Andrew Kaylor1c489452013-04-25 21:02:36 +0000170 }
171
Stephen Hines36b56882014-04-23 16:57:46 -0700172 return CompiledObject.release();
Andrew Kaylor1c489452013-04-25 21:02:36 +0000173}
174
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000175void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000176 // Get a thread lock to make sure we aren't trying to load multiple times
177 MutexGuard locked(lock);
178
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000179 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000180 assert(OwnedModules.ownsModule(M) &&
181 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylor1c489452013-04-25 21:02:36 +0000182
Andrew Kaylor1c489452013-04-25 21:02:36 +0000183 // Re-compilation is not supported
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000184 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylor1c489452013-04-25 21:02:36 +0000185 return;
186
Stephen Hines36b56882014-04-23 16:57:46 -0700187 std::unique_ptr<ObjectBuffer> ObjectToLoad;
Andrew Kaylor1c489452013-04-25 21:02:36 +0000188 // Try to load the pre-compiled object from cache if possible
Stephen Hinesdce4a402014-05-29 02:49:00 -0700189 if (ObjCache) {
Stephen Hines36b56882014-04-23 16:57:46 -0700190 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
Stephen Hinesdce4a402014-05-29 02:49:00 -0700191 if (PreCompiledObject.get())
Stephen Hines36b56882014-04-23 16:57:46 -0700192 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
Andrew Kaylor1c489452013-04-25 21:02:36 +0000193 }
194
195 // If the cache did not contain a suitable object, compile the object
196 if (!ObjectToLoad) {
197 ObjectToLoad.reset(emitObject(M));
198 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
199 }
Jim Grosbachf9229102011-03-22 01:06:42 +0000200
201 // Load the object into the dynamic linker.
Stephen Hines36b56882014-04-23 16:57:46 -0700202 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
203 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
204 LoadedObjects.push_back(LoadedObject);
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000205 if (!LoadedObject)
Jim Grosbach8086f3b2011-03-23 19:51:34 +0000206 report_fatal_error(Dyld.getErrorString());
Andrew Kaylorea708d12012-08-07 18:33:00 +0000207
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000208 // FIXME: Make this optional, maybe even move it to a JIT event listener
209 LoadedObject->registerWithDebugger();
210
Andrew Kaylor776054d2012-11-06 18:51:59 +0000211 NotifyObjectEmitted(*LoadedObject);
212
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000213 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000214}
215
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000216void MCJIT::finalizeLoadedModules() {
Andrew Kaylor61694532013-10-21 17:42:06 +0000217 MutexGuard locked(lock);
218
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000219 // Resolve any outstanding relocations.
220 Dyld.resolveRelocations();
221
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000222 OwnedModules.markAllLoadedModulesAsFinalized();
223
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000224 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor528f6d72013-10-11 21:25:48 +0000225 Dyld.registerEHFrames();
226
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000227 // Set page permissions.
228 MemMgr.finalizeMemory();
229}
230
231// FIXME: Rename this.
232void MCJIT::finalizeObject() {
Andrew Kaylor61694532013-10-21 17:42:06 +0000233 MutexGuard locked(lock);
234
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000235 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
236 E = OwnedModules.end_added();
237 I != E; ++I) {
238 Module *M = *I;
239 generateCodeForModule(M);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000240 }
Andrew Kaylor53608a32012-11-15 23:50:01 +0000241
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000242 finalizeLoadedModules();
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000243}
244
245void MCJIT::finalizeModule(Module *M) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000246 MutexGuard locked(lock);
247
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000248 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000249 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000250
251 // If the module hasn't been compiled, just do that.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000252 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000253 generateCodeForModule(M);
254
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000255 finalizeLoadedModules();
Andrew Kaylor28989882012-11-05 20:57:16 +0000256}
257
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000258void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
259 report_fatal_error("not yet implemented");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000260}
261
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000262uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
Stephen Hines36b56882014-04-23 16:57:46 -0700263 Mangler Mang(TM->getDataLayout());
264 SmallString<128> FullName;
265 Mang.getNameWithPrefix(FullName, Name);
266 return Dyld.getSymbolLoadAddress(FullName);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000267}
Jim Grosbach35ed8422012-09-05 16:50:40 +0000268
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000269Module *MCJIT::findModuleForSymbol(const std::string &Name,
270 bool CheckFunctionsOnly) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000271 MutexGuard locked(lock);
272
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000273 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000274 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
275 E = OwnedModules.end_added();
276 I != E; ++I) {
277 Module *M = *I;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000278 Function *F = M->getFunction(Name);
Andrew Kaylor59bbf5a2013-11-15 22:10:21 +0000279 if (F && !F->isDeclaration())
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000280 return M;
281 if (!CheckFunctionsOnly) {
282 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor59bbf5a2013-11-15 22:10:21 +0000283 if (G && !G->isDeclaration())
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000284 return M;
285 // FIXME: Do we need to worry about global aliases?
286 }
287 }
288 // We didn't find the symbol in any of our modules.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700289 return nullptr;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000290}
291
292uint64_t MCJIT::getSymbolAddress(const std::string &Name,
293 bool CheckFunctionsOnly)
294{
Andrew Kaylor61694532013-10-21 17:42:06 +0000295 MutexGuard locked(lock);
296
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000297 // First, check to see if we already have this symbol.
298 uint64_t Addr = getExistingSymbolAddress(Name);
299 if (Addr)
300 return Addr;
301
Stephen Hines36b56882014-04-23 16:57:46 -0700302 SmallVector<object::Archive*, 2>::iterator I, E;
303 for (I = Archives.begin(), E = Archives.end(); I != E; ++I) {
304 object::Archive *A = *I;
305 // Look for our symbols in each Archive
306 object::Archive::child_iterator ChildIt = A->findSym(Name);
307 if (ChildIt != A->child_end()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700308 // FIXME: Support nested archives?
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700309 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
310 ChildIt->getAsBinary();
311 if (ChildBinOrErr.getError())
312 continue;
313 std::unique_ptr<object::Binary> ChildBin = std::move(ChildBinOrErr.get());
314 if (ChildBin->isObject()) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700315 std::unique_ptr<object::ObjectFile> OF(
316 static_cast<object::ObjectFile *>(ChildBin.release()));
Stephen Hines36b56882014-04-23 16:57:46 -0700317 // This causes the object file to be loaded.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700318 addObjectFile(std::move(OF));
Stephen Hines36b56882014-04-23 16:57:46 -0700319 // The address should be here now.
320 Addr = getExistingSymbolAddress(Name);
321 if (Addr)
322 return Addr;
323 }
324 }
325 }
326
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000327 // If it hasn't already been generated, see if it's in one of our modules.
328 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
329 if (!M)
330 return 0;
331
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000332 generateCodeForModule(M);
333
334 // Check the RuntimeDyld table again, it should be there now.
335 return getExistingSymbolAddress(Name);
336}
337
338uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000339 MutexGuard locked(lock);
Andrew Kaylor8e9ec012013-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) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000347 MutexGuard locked(lock);
Andrew Kaylor8e9ec012013-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) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000356 MutexGuard locked(lock);
Andrew Kaylorea708d12012-08-07 18:33:00 +0000357
Jim Grosbach34714a02011-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 Kaylor8e9ec012013-10-01 01:47:35 +0000365 Module *M = F->getParent();
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000366 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000367
368 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000369 if (HasBeenAddedButNotLoaded)
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000370 generateCodeForModule(M);
Andrew Kaylor2ad18ef2013-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.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700373 return nullptr;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000374
Andrew Kaylorea708d12012-08-07 18:33:00 +0000375 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbach35ed8422012-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.
Stephen Hines36b56882014-04-23 16:57:46 -0700379 Mangler Mang(TM->getDataLayout());
380 SmallString<128> Name;
381 TM->getNameWithPrefix(Name, F, Mang);
382 return (void*)Dyld.getSymbolLoadAddress(Name);
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000383}
384
385void *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 Kaylor2ad18ef2013-10-24 00:19:14 +0000393void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
394 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
395 for (; I != E; ++I) {
396 ExecutionEngine::runStaticConstructorsDestructors(*I, isDtors);
397 }
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 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700417 return nullptr;
Andrew Kaylor2ad18ef2013-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 Dunbar6aec2982010-11-17 16:06:43 +0000432GenericValue MCJIT::runFunction(Function *F,
433 const std::vector<GenericValue> &ArgValues) {
Jim Grosbach34714a02011-03-22 18:05:27 +0000434 assert(F && "Function *F was null at entry to run()");
435
Jim Grosbach31649e62011-03-18 22:48:41 +0000436 void *FPtr = getPointerToFunction(F);
Jim Grosbach34714a02011-03-22 18:05:27 +0000437 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000438 FunctionType *FTy = F->getFunctionType();
439 Type *RetTy = FTy->getReturnType();
Jim Grosbach34714a02011-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 Grosbach34714a02011-03-22 18:05:27 +0000524 case Type::PointerTyID:
525 return PTOGV(((void*(*)())(intptr_t)FPtr)());
526 }
527 }
528
Craig Topper85814382012-02-07 05:05:23 +0000529 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000530}
Danil Malyshev30b9e322012-03-28 21:46:36 +0000531
532void *MCJIT::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky5fe01982012-04-29 12:40:47 +0000533 bool AbortOnFailure) {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000534 if (!isSymbolSearchingDisabled()) {
535 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
Danil Malyshev30b9e322012-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 Bendersky5fe01982012-04-29 12:40:47 +0000547 "' which could not be resolved!");
Danil Malyshev30b9e322012-03-28 21:46:36 +0000548 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700549 return nullptr;
Danil Malyshev30b9e322012-03-28 21:46:36 +0000550}
Andrew Kaylor776054d2012-11-06 18:51:59 +0000551
552void MCJIT::RegisterJITEventListener(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);
556 EventListeners.push_back(L);
557}
558void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700559 if (!L)
Andrew Kaylor776054d2012-11-06 18:51:59 +0000560 return;
561 MutexGuard locked(lock);
562 SmallVector<JITEventListener*, 2>::reverse_iterator I=
563 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
564 if (I != EventListeners.rend()) {
565 std::swap(*I, EventListeners.back());
566 EventListeners.pop_back();
567 }
568}
569void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
570 MutexGuard locked(lock);
Andrew Kaylorb868e912013-10-04 00:49:38 +0000571 MemMgr.notifyObjectLoaded(this, &Obj);
Andrew Kaylor776054d2012-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) {
577 MutexGuard locked(lock);
578 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
579 EventListeners[I]->NotifyFreeingObject(Obj);
580 }
581}
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000582
583uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
584 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
Andrew Kaylor52c90162013-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 Kaylor8e9ec012013-10-01 01:47:35 +0000589 if (Result)
590 return Result;
591 return ClientMM->getSymbolAddress(Name);
592}