blob: 7e93d31361aa12f8a2e60074f3e53ecc157f8696 [file] [log] [blame]
Chris Lattnerfe11a972002-12-23 23:59:41 +00001//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +00009//
Chris Lattner7efea1d2003-12-26 05:07:35 +000010// This utility provides a simple wrapper around the LLVM Execution Engines,
11// which allow the direct execution of LLVM programs through a Just-In-Time
Torok Edwindb9c0282009-07-03 12:11:32 +000012// compiler, or through an interpreter if no JIT is available for this platform.
Chris Lattner92101ac2001-08-23 17:05:04 +000013//
14//===----------------------------------------------------------------------===//
15
Lang Hamesb20e09c2016-01-11 16:35:55 +000016#include "RemoteJITUtils.h"
NAKAMURA Takumi23b90232016-01-15 02:14:46 +000017#include "llvm/ADT/StringExtras.h"
Duncan Sands75ebbce2010-08-28 01:30:02 +000018#include "llvm/ADT/Triple.h"
Teresa Johnsona5479192016-11-11 05:34:58 +000019#include "llvm/Bitcode/BitcodeReader.h"
David Blaikie461bf522018-04-11 18:49:37 +000020#include "llvm/CodeGen/CommandFlags.inc"
Chris Lattnerd3a680a2006-08-01 22:34:35 +000021#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Nico Weber0f38c602018-04-30 14:59:11 +000022#include "llvm/Config/llvm-config.h"
Brian Gaeked1cab3e2003-09-05 19:42:34 +000023#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +000024#include "llvm/ExecutionEngine/Interpreter.h"
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +000025#include "llvm/ExecutionEngine/JITEventListener.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000026#include "llvm/ExecutionEngine/MCJIT.h"
Lang Hames42fdb1f2014-01-08 04:09:09 +000027#include "llvm/ExecutionEngine/ObjectCache.h"
Lang Hames9f1c2392018-06-26 21:35:48 +000028#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
Lang Hames04756ee2018-09-30 19:12:23 +000029#include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
Lang Hames9f1c2392018-06-26 21:35:48 +000030#include "llvm/ExecutionEngine/Orc/LLJIT.h"
Rafael Espindola9aafb852017-08-03 02:16:21 +000031#include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
Lang Hames63cc4f52015-01-23 21:25:00 +000032#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
Andrew Kaylor257a0092012-11-27 19:49:00 +000033#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Andrew Kaylor47b7fd52013-10-29 01:29:56 +000034#include "llvm/IR/IRBuilder.h"
Rafael Espindola9aafb852017-08-03 02:16:21 +000035#include "llvm/IR/LLVMContext.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000036#include "llvm/IR/Module.h"
37#include "llvm/IR/Type.h"
Lang Hamesd7b82812018-07-02 22:30:18 +000038#include "llvm/IR/Verifier.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000039#include "llvm/IRReader/IRReader.h"
Lang Hames42fdb1f2014-01-08 04:09:09 +000040#include "llvm/Object/Archive.h"
41#include "llvm/Object/ObjectFile.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000042#include "llvm/Support/CommandLine.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/DynamicLibrary.h"
45#include "llvm/Support/Format.h"
Rui Ueyama0b9d56a2018-04-13 18:26:06 +000046#include "llvm/Support/InitLLVM.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000047#include "llvm/Support/ManagedStatic.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000048#include "llvm/Support/MathExtras.h"
49#include "llvm/Support/Memory.h"
Chris Lattnerc1e6d682007-05-06 04:58:26 +000050#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramerdf93f4b2015-03-23 18:07:13 +000051#include "llvm/Support/Path.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/Support/PluginLoader.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000053#include "llvm/Support/Process.h"
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +000054#include "llvm/Support/Program.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000055#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000056#include "llvm/Support/TargetSelect.h"
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +000057#include "llvm/Support/WithColor.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000058#include "llvm/Support/raw_ostream.h"
Daniel Maleae16e6872013-06-28 19:11:40 +000059#include "llvm/Transforms/Instrumentation.h"
Chris Lattner02040322007-04-27 17:02:33 +000060#include <cerrno>
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +000061
62#ifdef __CYGWIN__
63#include <cygwin/version.h>
64#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
65#define DO_NOTHING_ATEXIT 1
66#endif
67#endif
68
Brian Gaeked0fde302003-11-11 22:41:34 +000069using namespace llvm;
70
Chandler Carruth843eb0c2014-04-22 03:10:36 +000071#define DEBUG_TYPE "lli"
72
Chris Lattnerfe11a972002-12-23 23:59:41 +000073namespace {
Lang Hames47fd5632015-03-25 12:11:48 +000074
75 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
76
Chris Lattnerfe11a972002-12-23 23:59:41 +000077 cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000078 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000079
Chris Lattnerfe11a972002-12-23 23:59:41 +000080 cl::list<std::string>
81 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattner5ff62e92002-07-22 02:10:13 +000082
Chris Lattnerfe11a972002-12-23 23:59:41 +000083 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukman3d8a54d2003-09-25 18:10:34 +000084 cl::desc("Force interpretation: disable JIT"),
85 cl::init(false));
Evan Chenge1a4eda2008-08-08 08:12:06 +000086
Lang Hames47fd5632015-03-25 12:11:48 +000087 cl::opt<JITKind> UseJITKind("jit-kind",
88 cl::desc("Choose underlying JIT kind."),
89 cl::init(JITKind::MCJIT),
90 cl::values(
91 clEnumValN(JITKind::MCJIT, "mcjit",
92 "MCJIT"),
93 clEnumValN(JITKind::OrcMCJITReplacement,
94 "orc-mcjit",
95 "Orc-based MCJIT replacement"),
96 clEnumValN(JITKind::OrcLazy,
97 "orc-lazy",
Mehdi Amini3ffe1132016-10-08 19:41:06 +000098 "Orc-based lazy JIT.")));
Lang Hames63cc4f52015-01-23 21:25:00 +000099
Lang Hames91c25db2018-09-26 16:26:59 +0000100 cl::opt<unsigned>
101 LazyJITCompileThreads("compile-threads",
102 cl::desc("Choose the number of compile threads "
103 "(jit-kind=orc-lazy only)"),
104 cl::init(0));
105
106 cl::list<std::string>
107 ThreadEntryPoints("thread-entry",
108 cl::desc("calls the given entry-point on a new thread "
109 "(jit-kind=orc-lazy only)"));
110
Lang Hames90c32712018-09-29 23:49:57 +0000111 cl::opt<bool> PerModuleLazy(
112 "per-module-lazy",
113 cl::desc("Performs lazy compilation on whole module boundaries "
114 "rather than individual functions"),
115 cl::init(false));
116
Lang Hames8b9cbda2018-10-23 23:01:39 +0000117 cl::list<std::string>
118 JITDylibs("jd",
119 cl::desc("Specifies the JITDylib to be used for any subsequent "
120 "-extra-module arguments."));
121
Jim Grosbach706f03a2012-09-05 16:50:34 +0000122 // The MCJIT supports building for a target address space separate from
123 // the JIT compilation process. Use a forked process and a copying
124 // memory manager with IPC to execute using this functionality.
125 cl::opt<bool> RemoteMCJIT("remote-mcjit",
126 cl::desc("Execute MCJIT'ed code in a separate process."),
127 cl::init(false));
128
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000129 // Manually specify the child process for remote execution. This overrides
130 // the simulated remote execution that allocates address space for child
Andrew Kaylor5f7a5772013-10-29 01:33:14 +0000131 // execution. The child process will be executed and will communicate with
132 // lli via stdin/stdout pipes.
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000133 cl::opt<std::string>
Alp Toker1214e712014-01-22 21:52:35 +0000134 ChildExecPath("mcjit-remote-process",
135 cl::desc("Specify the filename of the process to launch "
136 "for remote MCJIT execution. If none is specified,"
137 "\n\tremote execution will be simulated in-process."),
138 cl::value_desc("filename"), cl::init(""));
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000139
Evan Cheng712e80e2009-05-04 23:05:19 +0000140 // Determine optimization level.
141 cl::opt<char>
142 OptLevel("O",
143 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
144 "(default = '-O2')"),
145 cl::Prefix,
146 cl::ZeroOrMore,
147 cl::init(' '));
Evan Chenge1a4eda2008-08-08 08:12:06 +0000148
Chris Lattner3015e602005-12-16 05:00:21 +0000149 cl::opt<std::string>
Chris Lattner60844d42005-12-16 05:19:18 +0000150 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Chengec740e32008-11-05 23:21:52 +0000151
152 cl::opt<std::string>
153 EntryFunc("entry-function",
154 cl::desc("Specify the entry function (default = 'main') "
155 "of the executable"),
156 cl::value_desc("function"),
157 cl::init("main"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000158
Andrew Kaylorb868e912013-10-04 00:49:38 +0000159 cl::list<std::string>
Andrew Kaylor61abf152013-10-28 21:58:15 +0000160 ExtraModules("extra-module",
Andrew Kaylorb868e912013-10-04 00:49:38 +0000161 cl::desc("Extra modules to be loaded"),
Alp Toker730e3c62013-10-28 22:51:25 +0000162 cl::value_desc("input bitcode"));
Andrew Kaylorb868e912013-10-04 00:49:38 +0000163
Lang Hames42fdb1f2014-01-08 04:09:09 +0000164 cl::list<std::string>
165 ExtraObjects("extra-object",
166 cl::desc("Extra object files to be loaded"),
167 cl::value_desc("input object"));
168
169 cl::list<std::string>
170 ExtraArchives("extra-archive",
171 cl::desc("Extra archive files to be loaded"),
172 cl::value_desc("input archive"));
173
174 cl::opt<bool>
175 EnableCacheManager("enable-cache-manager",
Lang Hames4442b6e2014-01-09 05:24:05 +0000176 cl::desc("Use cache manager to save/load mdoules"),
Lang Hames42fdb1f2014-01-08 04:09:09 +0000177 cl::init(false));
178
Chris Lattnere69671d2003-10-28 22:51:44 +0000179 cl::opt<std::string>
Lang Hames4442b6e2014-01-09 05:24:05 +0000180 ObjectCacheDir("object-cache-dir",
181 cl::desc("Directory to store cached object files "
182 "(must be user writable)"),
183 cl::init(""));
184
185 cl::opt<std::string>
Chris Lattnere69671d2003-10-28 22:51:44 +0000186 FakeArgv0("fake-argv0",
187 cl::desc("Override the 'argv[0]' value passed into the executing"
188 " program"), cl::value_desc("executable"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000189
Chris Lattner43f249a2006-09-14 06:17:09 +0000190 cl::opt<bool>
191 DisableCoreFiles("disable-core-files", cl::Hidden,
192 cl::desc("Disable emission of core files if possible"));
Evan Chengc290a5b2008-04-22 06:51:41 +0000193
194 cl::opt<bool>
Evan Cheng03dace82008-05-21 18:20:21 +0000195 NoLazyCompilation("disable-lazy-compilation",
Evan Chengc290a5b2008-04-22 06:51:41 +0000196 cl::desc("Disable JIT lazy compilation"),
197 cl::init(false));
Evan Cheng43966132011-07-19 06:37:02 +0000198
Nick Lewycky9a148412012-04-18 08:34:12 +0000199 cl::opt<bool>
Tim Northover77b4c692012-10-12 09:55:13 +0000200 GenerateSoftFloatCalls("soft-float",
201 cl::desc("Generate software floating point library calls"),
202 cl::init(false));
203
Lang Hames9f1c2392018-06-26 21:35:48 +0000204 enum class DumpKind {
205 NoDump,
206 DumpFuncsToStdOut,
207 DumpModsToStdOut,
208 DumpModsToDisk
209 };
210
211 cl::opt<DumpKind> OrcDumpKind(
212 "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
213 cl::init(DumpKind::NoDump),
214 cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
215 "Don't dump anything."),
216 clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
217 "Dump function names to stdout."),
218 clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
219 "Dump modules to stdout."),
220 clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
221 "Dump modules to the current "
222 "working directory. (WARNING: "
223 "will overwrite existing files).")),
224 cl::Hidden);
225
Lang Hames1ddbb0f2016-04-25 19:56:45 +0000226 ExitOnError ExitOnErr;
Chris Lattnerfe11a972002-12-23 23:59:41 +0000227}
Chris Lattner43e3f7c2001-10-27 08:43:52 +0000228
Lang Hames42fdb1f2014-01-08 04:09:09 +0000229//===----------------------------------------------------------------------===//
230// Object cache
231//
Lang Hames4442b6e2014-01-09 05:24:05 +0000232// This object cache implementation writes cached objects to disk to the
233// directory specified by CacheDir, using a filename provided in the module
234// descriptor. The cache tries to load a saved object using that path if the
235// file exists. CacheDir defaults to "", in which case objects are cached
NAKAMURA Takumi9f456a92014-01-10 10:38:28 +0000236// alongside their originating bitcodes.
Lang Hames42fdb1f2014-01-08 04:09:09 +0000237//
238class LLIObjectCache : public ObjectCache {
239public:
Lang Hames4442b6e2014-01-09 05:24:05 +0000240 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
241 // Add trailing '/' to cache dir if necessary.
Lang Hames0ee9bc72014-01-09 05:29:59 +0000242 if (!this->CacheDir.empty() &&
243 this->CacheDir[this->CacheDir.size() - 1] != '/')
NAKAMURA Takumi9f456a92014-01-10 10:38:28 +0000244 this->CacheDir += '/';
Lang Hames4442b6e2014-01-09 05:24:05 +0000245 }
Alexander Kornienkoc16fc542015-04-11 02:11:45 +0000246 ~LLIObjectCache() override {}
Lang Hames42fdb1f2014-01-08 04:09:09 +0000247
Rafael Espindola548f2b62014-08-19 18:44:46 +0000248 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
Benjamin Kramer04a303b2016-06-08 10:01:20 +0000249 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames42fdb1f2014-01-08 04:09:09 +0000250 std::string CacheName;
251 if (!getCacheFilename(ModuleID, CacheName))
252 return;
NAKAMURA Takumi32712c72014-01-10 10:38:34 +0000253 if (!CacheDir.empty()) { // Create user-defined cache dir.
Rafael Espindolaa0458b62015-07-15 21:24:07 +0000254 SmallString<128> dir(sys::path::parent_path(CacheName));
NAKAMURA Takumi32712c72014-01-10 10:38:34 +0000255 sys::fs::create_directories(Twine(dir));
256 }
Rafael Espindola8c968622014-08-25 18:16:47 +0000257 std::error_code EC;
258 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
Rafael Espindola548f2b62014-08-19 18:44:46 +0000259 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
Lang Hames42fdb1f2014-01-08 04:09:09 +0000260 outfile.close();
261 }
262
Rafael Espindolad6448b22014-08-13 18:49:01 +0000263 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
Benjamin Kramer04a303b2016-06-08 10:01:20 +0000264 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames42fdb1f2014-01-08 04:09:09 +0000265 std::string CacheName;
266 if (!getCacheFilename(ModuleID, CacheName))
Craig Topper573faec2014-04-25 04:24:47 +0000267 return nullptr;
Lang Hames42fdb1f2014-01-08 04:09:09 +0000268 // Load the object from the cache filename
Rafael Espindola7cba2a92014-07-06 17:43:13 +0000269 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
Malcolm Parsons4c127322016-11-02 16:43:50 +0000270 MemoryBuffer::getFile(CacheName, -1, false);
Lang Hames42fdb1f2014-01-08 04:09:09 +0000271 // If the file isn't there, that's OK.
272 if (!IRObjectBuffer)
Craig Topper573faec2014-04-25 04:24:47 +0000273 return nullptr;
Lang Hames42fdb1f2014-01-08 04:09:09 +0000274 // MCJIT will want to write into this buffer, and we don't want that
275 // because the file has probably just been mmapped. Instead we make
276 // a copy. The filed-based buffer will be released when it goes
277 // out of scope.
Rafael Espindola1a7f7052014-08-27 20:03:13 +0000278 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
Lang Hames42fdb1f2014-01-08 04:09:09 +0000279 }
280
281private:
Lang Hames4442b6e2014-01-09 05:24:05 +0000282 std::string CacheDir;
283
Lang Hames42fdb1f2014-01-08 04:09:09 +0000284 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
285 std::string Prefix("file:");
286 size_t PrefixLength = Prefix.length();
287 if (ModID.substr(0, PrefixLength) != Prefix)
288 return false;
NAKAMURA Takumi744f8162014-01-10 10:38:40 +0000289 std::string CacheSubdir = ModID.substr(PrefixLength);
290#if defined(_WIN32)
291 // Transform "X:\foo" => "/X\foo" for convenience.
292 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
293 CacheSubdir[1] = CacheSubdir[0];
294 CacheSubdir[0] = '/';
295 }
296#endif
297 CacheName = CacheDir + CacheSubdir;
Lang Hames42fdb1f2014-01-08 04:09:09 +0000298 size_t pos = CacheName.rfind('.');
299 CacheName.replace(pos, CacheName.length() - pos, ".o");
300 return true;
301 }
302};
303
Andrew Kaylor47b7fd52013-10-29 01:29:56 +0000304// On Mingw and Cygwin, an external symbol named '__main' is called from the
Simon Pilgrim84354d92016-11-20 13:31:13 +0000305// generated 'main' function to allow static initialization. To avoid linking
Andrew Kaylor47b7fd52013-10-29 01:29:56 +0000306// problems with remote targets (because lli's remote target support does not
307// currently handle external linking) we add a secondary module which defines
308// an empty '__main' function.
Mehdi Amini14e40082016-04-18 18:52:39 +0000309static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
Andrew Kaylor47b7fd52013-10-29 01:29:56 +0000310 StringRef TargetTripleStr) {
311 IRBuilder<> Builder(Context);
312 Triple TargetTriple(TargetTripleStr);
313
314 // Create a new module.
Rafael Espindola3f4ed322014-08-19 04:04:25 +0000315 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
Andrew Kaylor47b7fd52013-10-29 01:29:56 +0000316 M->setTargetTriple(TargetTripleStr);
317
318 // Create an empty function named "__main".
James Y Knight28a460d2019-01-13 16:09:28 +0000319 Type *ReturnTy;
320 if (TargetTriple.isArch64Bit())
321 ReturnTy = Type::getInt64Ty(Context);
322 else
323 ReturnTy = Type::getInt32Ty(Context);
324 Function *Result =
325 Function::Create(FunctionType::get(ReturnTy, {}, false),
326 GlobalValue::ExternalLinkage, "__main", M.get());
327
Andrew Kaylor47b7fd52013-10-29 01:29:56 +0000328 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
329 Builder.SetInsertPoint(BB);
James Y Knight28a460d2019-01-13 16:09:28 +0000330 Value *ReturnVal = ConstantInt::get(ReturnTy, 0);
Andrew Kaylor47b7fd52013-10-29 01:29:56 +0000331 Builder.CreateRet(ReturnVal);
332
333 // Add this new module to the ExecutionEngine.
Mehdi Amini14e40082016-04-18 18:52:39 +0000334 EE.addModule(std::move(M));
Andrew Kaylor47b7fd52013-10-29 01:29:56 +0000335}
336
Lang Hames657c6972015-06-09 02:43:27 +0000337CodeGenOpt::Level getOptLevel() {
338 switch (OptLevel) {
339 default:
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +0000340 WithColor::error(errs(), "lli") << "invalid optimization level.\n";
Lang Hames657c6972015-06-09 02:43:27 +0000341 exit(1);
342 case '0': return CodeGenOpt::None;
343 case '1': return CodeGenOpt::Less;
344 case ' ':
345 case '2': return CodeGenOpt::Default;
346 case '3': return CodeGenOpt::Aggressive;
347 }
348 llvm_unreachable("Unrecognized opt level.");
349}
Andrew Kaylor47b7fd52013-10-29 01:29:56 +0000350
Davide Italiano9754b3b2016-11-17 22:58:13 +0000351LLVM_ATTRIBUTE_NORETURN
352static void reportError(SMDiagnostic Err, const char *ProgName) {
353 Err.print(ProgName, errs());
354 exit(1);
355}
356
Lang Hames592e4c72018-08-28 20:20:31 +0000357int runOrcLazyJIT(const char *ProgName);
Lang Hames90c32712018-09-29 23:49:57 +0000358void disallowOrcOptions();
Lang Hames9f1c2392018-06-26 21:35:48 +0000359
Chris Lattner92101ac2001-08-23 17:05:04 +0000360//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +0000361// main Driver function
362//
Misha Brukmanc4fb6fd2003-10-14 21:39:53 +0000363int main(int argc, char **argv, char * const *envp) {
Rui Ueyama0b9d56a2018-04-13 18:26:06 +0000364 InitLLVM X(argc, argv);
Daniel Dunbar494d6632009-07-16 02:04:54 +0000365
Lang Hames1ddbb0f2016-04-25 19:56:45 +0000366 if (argc > 1)
367 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
368
Daniel Dunbar494d6632009-07-16 02:04:54 +0000369 // If we have a native target, initialize it to ensure it is linked in and
370 // usable by the JIT.
371 InitializeNativeTarget();
Jim Grosbach31649e62011-03-18 22:48:41 +0000372 InitializeNativeTargetAsmPrinter();
Jim Grosbach68372322012-11-05 19:06:05 +0000373 InitializeNativeTargetAsmParser();
Daniel Dunbar494d6632009-07-16 02:04:54 +0000374
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000375 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000376 "llvm interpreter & dynamic compiler\n");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000377
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000378 // If the user doesn't want core files, disable them.
379 if (DisableCoreFiles)
380 sys::Process::PreventCoreFiles();
Eli Benderskya66a1852012-01-16 08:56:09 +0000381
Lang Hames592e4c72018-08-28 20:20:31 +0000382 if (UseJITKind == JITKind::OrcLazy)
383 return runOrcLazyJIT(argv[0]);
Lang Hames90c32712018-09-29 23:49:57 +0000384 else
385 disallowOrcOptions();
Lang Hames592e4c72018-08-28 20:20:31 +0000386
Mehdi Amini14e40082016-04-18 18:52:39 +0000387 LLVMContext Context;
388
Gabor Greifa99be512007-07-05 17:07:56 +0000389 // Load the bitcode...
Daniel Dunbar46a27162010-11-13 00:28:01 +0000390 SMDiagnostic Err;
Rafael Espindola81e49922014-08-26 17:29:46 +0000391 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
Rafael Espindola3f4ed322014-08-19 04:04:25 +0000392 Module *Mod = Owner.get();
Davide Italiano9754b3b2016-11-17 22:58:13 +0000393 if (!Mod)
394 reportError(Err, argv[0]);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000395
Lang Hames42fdb1f2014-01-08 04:09:09 +0000396 if (EnableCacheManager) {
Eric Christopherd5dd8ce2014-09-02 22:28:02 +0000397 std::string CacheName("file:");
398 CacheName.append(InputFile);
399 Mod->setModuleIdentifier(CacheName);
Lang Hames42fdb1f2014-01-08 04:09:09 +0000400 }
401
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000402 // If not jitting lazily, load the whole bitcode file eagerly too.
403 if (NoLazyCompilation) {
Davide Italiano00347282016-11-09 21:30:33 +0000404 // Use *argv instead of argv[0] to work around a wrong GCC warning.
405 ExitOnError ExitOnErr(std::string(*argv) +
Peter Collingbourne76c218e2016-11-09 17:49:19 +0000406 ": bitcode didn't read correctly: ");
407 ExitOnErr(Mod->materializeAll());
Evan Chengc290a5b2008-04-22 06:51:41 +0000408 }
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000409
Rafael Espindola1dc66082014-01-14 23:51:27 +0000410 std::string ErrorMsg;
Rafael Espindola3f4ed322014-08-19 04:04:25 +0000411 EngineBuilder builder(std::move(Owner));
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000412 builder.setMArch(MArch);
Craig Topper3db29f72018-01-09 18:14:18 +0000413 builder.setMCPU(getCPUStr());
414 builder.setMAttrs(getFeatureList());
Rafael Espindolaac8db592016-05-18 22:04:49 +0000415 if (RelocModel.getNumOccurrences())
416 builder.setRelocationModel(RelocModel);
Rafael Espindola9aafb852017-08-03 02:16:21 +0000417 if (CMModel.getNumOccurrences())
418 builder.setCodeModel(CMModel);
Daniel Dunbar4dc31362009-07-18 08:07:13 +0000419 builder.setErrorStr(&ErrorMsg);
420 builder.setEngineKind(ForceInterpreter
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000421 ? EngineKind::Interpreter
422 : EngineKind::JIT);
Lang Hames47fd5632015-03-25 12:11:48 +0000423 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000424
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000425 // If we are supposed to override the target triple, do so now.
426 if (!TargetTriple.empty())
Duncan Sands75ebbce2010-08-28 01:30:02 +0000427 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Chengc290a5b2008-04-22 06:51:41 +0000428
Eli Benderskya66a1852012-01-16 08:56:09 +0000429 // Enable MCJIT if desired.
Craig Topper573faec2014-04-25 04:24:47 +0000430 RTDyldMemoryManager *RTDyldMM = nullptr;
Eric Christopherd5dd8ce2014-09-02 22:28:02 +0000431 if (!ForceInterpreter) {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000432 if (RemoteMCJIT)
Lang Hamesb20e09c2016-01-11 16:35:55 +0000433 RTDyldMM = new ForwardingMemoryManager();
Jim Grosbach706f03a2012-09-05 16:50:34 +0000434 else
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000435 RTDyldMM = new SectionMemoryManager();
Lang Hames5ab94e72014-12-03 00:51:19 +0000436
437 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
438 // RTDyldMM: We still use it below, even though we don't own it.
439 builder.setMCJITMemoryManager(
440 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
Lang Hames0717be92014-09-23 16:56:02 +0000441 } else if (RemoteMCJIT) {
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +0000442 WithColor::error(errs(), argv[0])
443 << "remote process execution does not work with the interpreter.\n";
Lang Hames0717be92014-09-23 16:56:02 +0000444 exit(1);
Eli Benderskya66a1852012-01-16 08:56:09 +0000445 }
Daniel Dunbar6d135972010-11-17 16:06:37 +0000446
Lang Hames657c6972015-06-09 02:43:27 +0000447 builder.setOptLevel(getOptLevel());
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000448
David Blaikied7eaf512017-11-27 19:43:58 +0000449 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Tim Northover77b4c692012-10-12 09:55:13 +0000450 if (FloatABIForCalls != FloatABI::Default)
451 Options.FloatABIType = FloatABIForCalls;
Tim Northover77b4c692012-10-12 09:55:13 +0000452
Tim Northover77b4c692012-10-12 09:55:13 +0000453 builder.setTargetOptions(Options);
454
Mehdi Amini14e40082016-04-18 18:52:39 +0000455 std::unique_ptr<ExecutionEngine> EE(builder.create());
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000456 if (!EE) {
457 if (!ErrorMsg.empty())
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +0000458 WithColor::error(errs(), argv[0])
459 << "error creating EE: " << ErrorMsg << "\n";
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000460 else
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +0000461 WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000462 exit(1);
463 }
464
Mehdi Amini14e40082016-04-18 18:52:39 +0000465 std::unique_ptr<LLIObjectCache> CacheManager;
Lang Hames42fdb1f2014-01-08 04:09:09 +0000466 if (EnableCacheManager) {
Mehdi Amini14e40082016-04-18 18:52:39 +0000467 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
468 EE->setObjectCache(CacheManager.get());
Lang Hames42fdb1f2014-01-08 04:09:09 +0000469 }
470
Andrew Kaylorb868e912013-10-04 00:49:38 +0000471 // Load any additional modules specified on the command line.
472 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
Rafael Espindola81e49922014-08-26 17:29:46 +0000473 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
Davide Italiano9754b3b2016-11-17 22:58:13 +0000474 if (!XMod)
475 reportError(Err, argv[0]);
Lang Hames42fdb1f2014-01-08 04:09:09 +0000476 if (EnableCacheManager) {
Eric Christopherd5dd8ce2014-09-02 22:28:02 +0000477 std::string CacheName("file:");
478 CacheName.append(ExtraModules[i]);
479 XMod->setModuleIdentifier(CacheName);
Lang Hames42fdb1f2014-01-08 04:09:09 +0000480 }
Rafael Espindola3f4ed322014-08-19 04:04:25 +0000481 EE->addModule(std::move(XMod));
Andrew Kaylorb868e912013-10-04 00:49:38 +0000482 }
483
Lang Hames42fdb1f2014-01-08 04:09:09 +0000484 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Kevin Enderbyc6bf9be2016-04-06 22:14:09 +0000485 Expected<object::OwningBinary<object::ObjectFile>> Obj =
Rafael Espindola825fc312014-01-22 00:14:49 +0000486 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames42fdb1f2014-01-08 04:09:09 +0000487 if (!Obj) {
Kevin Enderbyc6bf9be2016-04-06 22:14:09 +0000488 // TODO: Actually report errors helpfully.
489 consumeError(Obj.takeError());
Davide Italiano9754b3b2016-11-17 22:58:13 +0000490 reportError(Err, argv[0]);
Lang Hames42fdb1f2014-01-08 04:09:09 +0000491 }
Rafael Espindola4b67b5a2014-08-20 15:19:37 +0000492 object::OwningBinary<object::ObjectFile> &O = Obj.get();
Rafael Espindolaaf074032014-08-26 21:04:04 +0000493 EE->addObjectFile(std::move(O));
Lang Hames42fdb1f2014-01-08 04:09:09 +0000494 }
495
496 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Rafael Espindola548f2b62014-08-19 18:44:46 +0000497 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
Rafael Espindola7cba2a92014-07-06 17:43:13 +0000498 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
Davide Italiano9754b3b2016-11-17 22:58:13 +0000499 if (!ArBufOrErr)
500 reportError(Err, argv[0]);
Rafael Espindola548f2b62014-08-19 18:44:46 +0000501 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
Rafael Espindolafff7ba32014-08-01 18:31:17 +0000502
Kevin Enderby0b21d882016-06-29 20:35:44 +0000503 Expected<std::unique_ptr<object::Archive>> ArOrErr =
Rafael Espindola548f2b62014-08-19 18:44:46 +0000504 object::Archive::create(ArBuf->getMemBufferRef());
Kevin Enderby0b21d882016-06-29 20:35:44 +0000505 if (!ArOrErr) {
506 std::string Buf;
507 raw_string_ostream OS(Buf);
Jonas Devlieghere686dfe32018-11-11 01:46:03 +0000508 logAllUnhandledErrors(ArOrErr.takeError(), OS);
Kevin Enderby0b21d882016-06-29 20:35:44 +0000509 OS.flush();
510 errs() << Buf;
Davide Italiano5ef12782016-11-17 22:59:13 +0000511 exit(1);
Lang Hames42fdb1f2014-01-08 04:09:09 +0000512 }
Rafael Espindola548f2b62014-08-19 18:44:46 +0000513 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
514
515 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
516
517 EE->addArchive(std::move(OB));
Lang Hames42fdb1f2014-01-08 04:09:09 +0000518 }
519
Andrew Kaylor47b7fd52013-10-29 01:29:56 +0000520 // If the target is Cygwin/MingW and we are generating remote code, we
521 // need an extra module to help out with linking.
522 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
Mehdi Amini14e40082016-04-18 18:52:39 +0000523 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
Andrew Kaylor47b7fd52013-10-29 01:29:56 +0000524 }
525
Eli Bendersky61b18512012-03-13 08:33:15 +0000526 // The following functions have no effect if their respective profiling
527 // support wasn't enabled in the build configuration.
528 EE->RegisterJITEventListener(
529 JITEventListener::createOProfileJITEventListener());
530 EE->RegisterJITEventListener(
531 JITEventListener::createIntelJITEventListener());
Andres Freundc4c8d7b2018-07-24 00:54:06 +0000532 if (!RemoteMCJIT)
533 EE->RegisterJITEventListener(
534 JITEventListener::createPerfJITEventListener());
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000535
Jim Grosbach706f03a2012-09-05 16:50:34 +0000536 if (!NoLazyCompilation && RemoteMCJIT) {
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +0000537 WithColor::warning(errs(), argv[0])
538 << "remote mcjit does not support lazy compilation\n";
Jim Grosbach706f03a2012-09-05 16:50:34 +0000539 NoLazyCompilation = true;
540 }
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000541 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Chengc290a5b2008-04-22 06:51:41 +0000542
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000543 // If the user specifically requested an argv[0] to pass into the program,
544 // do it now.
545 if (!FakeArgv0.empty()) {
Chris Bienemane84c7b12015-01-22 01:49:59 +0000546 InputFile = static_cast<std::string>(FakeArgv0);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000547 } else {
548 // Otherwise, if there is a .bc suffix on the executable strip it off, it
549 // might confuse the program.
Benjamin Kramer3bb37e92010-04-15 11:33:14 +0000550 if (StringRef(InputFile).endswith(".bc"))
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000551 InputFile.erase(InputFile.length() - 3);
552 }
553
554 // Add the module's name to the start of the vector of arguments to main().
555 InputArgv.insert(InputArgv.begin(), InputFile);
556
557 // Call the main function from M as if its signature were:
558 // int main (int argc, char **argv, const char **envp)
559 // using the contents of Args to determine argc & argv, and the contents of
560 // EnvVars to determine envp.
561 //
Evan Chengec740e32008-11-05 23:21:52 +0000562 Function *EntryFn = Mod->getFunction(EntryFunc);
563 if (!EntryFn) {
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +0000564 WithColor::error(errs(), argv[0])
565 << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000566 return -1;
567 }
568
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000569 // Reset errno to zero on entry to main.
570 errno = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000571
Lang Hames6320b782016-04-18 19:55:43 +0000572 int Result = -1;
Andrew Kaylorf1881562013-10-02 18:04:40 +0000573
Lang Hamesb20e09c2016-01-11 16:35:55 +0000574 // Sanity check use of remote-jit: LLI currently only supports use of the
575 // remote JIT on Unix platforms.
Lang Hamesb20e09c2016-01-11 16:35:55 +0000576 if (RemoteMCJIT) {
577#ifndef LLVM_ON_UNIX
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +0000578 WithColor::warning(errs(), argv[0])
Jonas Devliegherea9bcdb12018-04-22 08:35:00 +0000579 << "host does not support external remote targets.\n";
580 WithColor::note() << "defaulting to local execution\n";
Lang Hames7ab54fc2016-01-11 21:41:34 +0000581 return -1;
Lang Hamesb20e09c2016-01-11 16:35:55 +0000582#else
583 if (ChildExecPath.empty()) {
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +0000584 WithColor::error(errs(), argv[0])
585 << "-remote-mcjit requires -mcjit-remote-process.\n";
Lang Hamesb20e09c2016-01-11 16:35:55 +0000586 exit(1);
587 } else if (!sys::fs::can_execute(ChildExecPath)) {
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +0000588 WithColor::error(errs(), argv[0])
589 << "unable to find usable child executable: '" << ChildExecPath
590 << "'\n";
Lang Hamesb20e09c2016-01-11 16:35:55 +0000591 return -1;
592 }
593#endif
594 }
595
Andrew Kaylor257a0092012-11-27 19:49:00 +0000596 if (!RemoteMCJIT) {
Andrew Kaylor4bad07f2013-10-11 22:47:10 +0000597 // If the program doesn't explicitly call exit, we will need the Exit
598 // function later on to make an explicit call, so get the function now.
599 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
Serge Guelton9d544002017-04-11 15:01:18 +0000600 Type::getInt32Ty(Context));
Andrew Kaylor4bad07f2013-10-11 22:47:10 +0000601
Andrew Kaylorf1881562013-10-02 18:04:40 +0000602 // Run static constructors.
Eric Christopherd5dd8ce2014-09-02 22:28:02 +0000603 if (!ForceInterpreter) {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000604 // Give MCJIT a chance to apply relocations and set page permissions.
605 EE->finalizeObject();
606 }
607 EE->runStaticConstructorsDestructors(false);
Evan Chengc290a5b2008-04-22 06:51:41 +0000608
NAKAMURA Takumidfe327f2013-12-07 11:21:42 +0000609 // Trigger compilation separately so code regions that need to be
Andrew Kaylorf1881562013-10-02 18:04:40 +0000610 // invalidated will be known.
611 (void)EE->getPointerToFunction(EntryFn);
612 // Clear instruction cache before code will be executed.
613 if (RTDyldMM)
614 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
615
616 // Run main.
617 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
618
619 // Run static destructors.
620 EE->runStaticConstructorsDestructors(true);
621
622 // If the program didn't call exit explicitly, we should call it now.
623 // This ensures that any atexit handlers get called correctly.
624 if (Function *ExitF = dyn_cast<Function>(Exit)) {
625 std::vector<GenericValue> Args;
626 GenericValue ResultGV;
627 ResultGV.IntVal = APInt(32, Result);
628 Args.push_back(ResultGV);
629 EE->runFunction(ExitF, Args);
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +0000630 WithColor::error(errs(), argv[0]) << "exit(" << Result << ") returned!\n";
Andrew Kaylorf1881562013-10-02 18:04:40 +0000631 abort();
632 } else {
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +0000633 WithColor::error(errs(), argv[0])
634 << "exit defined with wrong prototype!\n";
Andrew Kaylorf1881562013-10-02 18:04:40 +0000635 abort();
636 }
637 } else {
638 // else == "if (RemoteMCJIT)"
639
640 // Remote target MCJIT doesn't (yet) support static constructors. No reason
Hiroshi Inoue0eb884f2017-07-11 06:04:59 +0000641 // it couldn't. This is a limitation of the LLI implementation, not the
Andrew Kaylorf1881562013-10-02 18:04:40 +0000642 // MCJIT itself. FIXME.
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000643
Lang Hamesb20e09c2016-01-11 16:35:55 +0000644 // Lanch the remote process and get a channel to it.
Lang Hames085827f2016-11-11 21:42:09 +0000645 std::unique_ptr<FDRawChannel> C = launchRemote();
Lang Hamesb20e09c2016-01-11 16:35:55 +0000646 if (!C) {
Jonas Devliegheref79bdbd2018-04-22 08:02:11 +0000647 WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
Lang Hamesb20e09c2016-01-11 16:35:55 +0000648 exit(1);
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000649 }
650
Lang Hamesb20e09c2016-01-11 16:35:55 +0000651 // Create a remote target client running over the channel.
Lang Hames543cda42018-05-30 01:57:45 +0000652 llvm::orc::ExecutionSession ES;
653 ES.setErrorReporter([&](Error Err) { ExitOnErr(std::move(Err)); });
Lang Hames30e9aa62017-09-04 20:54:46 +0000654 typedef orc::remote::OrcRemoteTargetClient MyRemote;
Lang Hames543cda42018-05-30 01:57:45 +0000655 auto R = ExitOnErr(MyRemote::Create(*C, ES));
Jim Grosbach5da959d2012-08-28 23:22:30 +0000656
Lang Hamesb20e09c2016-01-11 16:35:55 +0000657 // Create a remote memory manager.
Lang Hames30e9aa62017-09-04 20:54:46 +0000658 auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
Lang Hamesb20e09c2016-01-11 16:35:55 +0000659
660 // Forward MCJIT's memory manager calls to the remote memory manager.
661 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
662 std::move(RemoteMM));
663
664 // Forward MCJIT's symbol resolution calls to the remote.
NAKAMURA Takumief15f2c2017-08-28 06:47:47 +0000665 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
666 orc::createLambdaResolver(
667 [](const std::string &Name) { return nullptr; },
668 [&](const std::string &Name) {
669 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
670 return JITSymbol(Addr, JITSymbolFlags::Exported);
671 return JITSymbol(nullptr);
672 }));
Lang Hamesb20e09c2016-01-11 16:35:55 +0000673
674 // Grab the target address of the JIT'd main function on the remote and call
675 // it.
Jim Grosbach706f03a2012-09-05 16:50:34 +0000676 // FIXME: argv and envp handling.
Lang Hames075c1e22016-08-01 20:49:11 +0000677 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
Lang Hamesb20e09c2016-01-11 16:35:55 +0000678 EE->finalizeObject();
Nicola Zaghen0818e782018-05-14 12:53:11 +0000679 LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
680 << format("%llx", Entry) << "\n");
Lang Hames085827f2016-11-11 21:42:09 +0000681 Result = ExitOnErr(R->callIntVoid(Entry));
Jim Grosbach706f03a2012-09-05 16:50:34 +0000682
Andrew Kaylorf1881562013-10-02 18:04:40 +0000683 // Like static constructors, the remote target MCJIT support doesn't handle
684 // this yet. It could. FIXME.
685
Lang Hamesb20e09c2016-01-11 16:35:55 +0000686 // Delete the EE - we need to tear it down *before* we terminate the session
687 // with the remote, otherwise it'll crash when it tries to release resources
688 // on a remote that has already been disconnected.
Mehdi Amini14e40082016-04-18 18:52:39 +0000689 EE.reset();
Lang Hamesb20e09c2016-01-11 16:35:55 +0000690
691 // Signal the remote target that we're done JITing.
Lang Hames085827f2016-11-11 21:42:09 +0000692 ExitOnErr(R->terminateSession());
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000693 }
Jim Grosbach706f03a2012-09-05 16:50:34 +0000694
Jim Grosbach706f03a2012-09-05 16:50:34 +0000695 return Result;
Chris Lattner92101ac2001-08-23 17:05:04 +0000696}
Lang Hamesb20e09c2016-01-11 16:35:55 +0000697
Lang Hames582b1192018-10-15 22:56:10 +0000698static orc::IRTransformLayer::TransformFunction createDebugDumper() {
Lang Hames9f1c2392018-06-26 21:35:48 +0000699 switch (OrcDumpKind) {
700 case DumpKind::NoDump:
Lang Hames73737922018-09-28 21:49:53 +0000701 return [](orc::ThreadSafeModule TSM,
702 const orc::MaterializationResponsibility &R) { return TSM; };
Lang Hames9f1c2392018-06-26 21:35:48 +0000703
704 case DumpKind::DumpFuncsToStdOut:
Lang Hames73737922018-09-28 21:49:53 +0000705 return [](orc::ThreadSafeModule TSM,
706 const orc::MaterializationResponsibility &R) {
Lang Hames9f1c2392018-06-26 21:35:48 +0000707 printf("[ ");
708
Lang Hamesd813c352018-09-26 01:24:12 +0000709 for (const auto &F : *TSM.getModule()) {
Lang Hames9f1c2392018-06-26 21:35:48 +0000710 if (F.isDeclaration())
711 continue;
712
713 if (F.hasName()) {
714 std::string Name(F.getName());
715 printf("%s ", Name.c_str());
716 } else
717 printf("<anon> ");
718 }
719
720 printf("]\n");
Lang Hamesd813c352018-09-26 01:24:12 +0000721 return TSM;
Lang Hames9f1c2392018-06-26 21:35:48 +0000722 };
723
724 case DumpKind::DumpModsToStdOut:
Lang Hames73737922018-09-28 21:49:53 +0000725 return [](orc::ThreadSafeModule TSM,
726 const orc::MaterializationResponsibility &R) {
Lang Hames9f1c2392018-06-26 21:35:48 +0000727 outs() << "----- Module Start -----\n"
Lang Hamesd813c352018-09-26 01:24:12 +0000728 << *TSM.getModule() << "----- Module End -----\n";
Lang Hames9f1c2392018-06-26 21:35:48 +0000729
Lang Hamesd813c352018-09-26 01:24:12 +0000730 return TSM;
Lang Hames9f1c2392018-06-26 21:35:48 +0000731 };
732
733 case DumpKind::DumpModsToDisk:
Lang Hames73737922018-09-28 21:49:53 +0000734 return [](orc::ThreadSafeModule TSM,
735 const orc::MaterializationResponsibility &R) {
Lang Hames9f1c2392018-06-26 21:35:48 +0000736 std::error_code EC;
Lang Hamesd813c352018-09-26 01:24:12 +0000737 raw_fd_ostream Out(TSM.getModule()->getModuleIdentifier() + ".ll", EC,
738 sys::fs::F_Text);
Lang Hames9f1c2392018-06-26 21:35:48 +0000739 if (EC) {
Lang Hamesd813c352018-09-26 01:24:12 +0000740 errs() << "Couldn't open " << TSM.getModule()->getModuleIdentifier()
Lang Hames9f1c2392018-06-26 21:35:48 +0000741 << " for dumping.\nError:" << EC.message() << "\n";
742 exit(1);
743 }
Lang Hamesd813c352018-09-26 01:24:12 +0000744 Out << *TSM.getModule();
745 return TSM;
Lang Hames9f1c2392018-06-26 21:35:48 +0000746 };
747 }
748 llvm_unreachable("Unknown DumpKind");
749}
750
Lang Hames8b9cbda2018-10-23 23:01:39 +0000751static void exitOnLazyCallThroughFailure() { exit(1); }
752
Lang Hames592e4c72018-08-28 20:20:31 +0000753int runOrcLazyJIT(const char *ProgName) {
754 // Start setting up the JIT environment.
Lang Hames9f1c2392018-06-26 21:35:48 +0000755
Lang Hames592e4c72018-08-28 20:20:31 +0000756 // Parse the main module.
Lang Hamesd813c352018-09-26 01:24:12 +0000757 orc::ThreadSafeContext TSCtx(llvm::make_unique<LLVMContext>());
Lang Hames592e4c72018-08-28 20:20:31 +0000758 SMDiagnostic Err;
Lang Hamesd813c352018-09-26 01:24:12 +0000759 auto MainModule = orc::ThreadSafeModule(
760 parseIRFile(InputFile, Err, *TSCtx.getContext()), TSCtx);
Lang Hames592e4c72018-08-28 20:20:31 +0000761 if (!MainModule)
762 reportError(Err, ProgName);
763
Lang Hamesd813c352018-09-26 01:24:12 +0000764 const auto &TT = MainModule.getModule()->getTargetTriple();
Lang Hames91c25db2018-09-26 16:26:59 +0000765 orc::JITTargetMachineBuilder JTMB =
Lang Hames9f1c2392018-06-26 21:35:48 +0000766 TT.empty() ? ExitOnErr(orc::JITTargetMachineBuilder::detectHost())
767 : orc::JITTargetMachineBuilder(Triple(TT));
768
Lang Hames04756ee2018-09-30 19:12:23 +0000769 if (!MArch.empty())
770 JTMB.getTargetTriple().setArchName(MArch);
771
772 JTMB.setCPU(getCPUStr())
Lang Hames9f1c2392018-06-26 21:35:48 +0000773 .addFeatures(getFeatureList())
774 .setRelocationModel(RelocModel.getNumOccurrences()
775 ? Optional<Reloc::Model>(RelocModel)
776 : None)
777 .setCodeModel(CMModel.getNumOccurrences()
778 ? Optional<CodeModel::Model>(CMModel)
779 : None);
Lang Hames04756ee2018-09-30 19:12:23 +0000780
Lang Hames4e8d0ef2018-10-01 00:59:26 +0000781 DataLayout DL = ExitOnErr(JTMB.getDefaultDataLayoutForTarget());
Lang Hames8b9cbda2018-10-23 23:01:39 +0000782
783 auto J = ExitOnErr(orc::LLLazyJIT::Create(
784 std::move(JTMB), DL,
785 pointerToJITTargetAddress(exitOnLazyCallThroughFailure),
786 LazyJITCompileThreads));
Lang Hames9f1c2392018-06-26 21:35:48 +0000787
Lang Hames90c32712018-09-29 23:49:57 +0000788 if (PerModuleLazy)
Lang Hames582b1192018-10-15 22:56:10 +0000789 J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);
Lang Hames90c32712018-09-29 23:49:57 +0000790
Lang Hamesd7b82812018-07-02 22:30:18 +0000791 auto Dump = createDebugDumper();
792
Lang Hames73737922018-09-28 21:49:53 +0000793 J->setLazyCompileTransform([&](orc::ThreadSafeModule TSM,
794 const orc::MaterializationResponsibility &R) {
Lang Hamesd813c352018-09-26 01:24:12 +0000795 if (verifyModule(*TSM.getModule(), &dbgs())) {
796 dbgs() << "Bad module: " << *TSM.getModule() << "\n";
797 exit(1);
798 }
Lang Hames73737922018-09-28 21:49:53 +0000799 return Dump(std::move(TSM), R);
Lang Hamesd813c352018-09-26 01:24:12 +0000800 });
Lang Hamesaa8c49d2018-10-15 05:07:54 +0000801 J->getMainJITDylib().setGenerator(
802 ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(DL)));
Lang Hames9f1c2392018-06-26 21:35:48 +0000803
804 orc::MangleAndInterner Mangle(J->getExecutionSession(), DL);
Lang Hames582b1192018-10-15 22:56:10 +0000805 orc::LocalCXXRuntimeOverrides CXXRuntimeOverrides;
Lang Hames7aacef02018-08-17 21:18:18 +0000806 ExitOnErr(CXXRuntimeOverrides.enable(J->getMainJITDylib(), Mangle));
Lang Hames9f1c2392018-06-26 21:35:48 +0000807
Lang Hames592e4c72018-08-28 20:20:31 +0000808 // Add the main module.
809 ExitOnErr(J->addLazyIRModule(std::move(MainModule)));
810
Lang Hames8b9cbda2018-10-23 23:01:39 +0000811 // Create JITDylibs and add any extra modules.
812 {
813 // Create JITDylibs, keep a map from argument index to dylib. We will use
814 // -extra-module argument indexes to determine what dylib to use for each
815 // -extra-module.
816 std::map<unsigned, orc::JITDylib *> IdxToDylib;
817 IdxToDylib[0] = &J->getMainJITDylib();
818 for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
819 JDItr != JDEnd; ++JDItr) {
820 IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] =
821 &J->createJITDylib(*JDItr);
822 }
Lang Hames592e4c72018-08-28 20:20:31 +0000823
Lang Hames8b9cbda2018-10-23 23:01:39 +0000824 for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
825 EMItr != EMEnd; ++EMItr) {
826 auto M = parseIRFile(*EMItr, Err, *TSCtx.getContext());
827 if (!M)
828 reportError(Err, ProgName);
829
830 auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin());
831 assert(EMIdx != 0 && "ExtraModule should have index > 0");
832 auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx));
833 auto &JD = *JDItr->second;
834 ExitOnErr(
835 J->addLazyIRModule(JD, orc::ThreadSafeModule(std::move(M), TSCtx)));
836 }
Lang Hamesd7b82812018-07-02 22:30:18 +0000837 }
Lang Hames9f1c2392018-06-26 21:35:48 +0000838
Lang Hames592e4c72018-08-28 20:20:31 +0000839 // Add the objects.
840 for (auto &ObjPath : ExtraObjects) {
841 auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));
842 ExitOnErr(J->addObjectFile(std::move(Obj)));
843 }
844
845 // Generate a argument string.
846 std::vector<std::string> Args;
847 Args.push_back(InputFile);
848 for (auto &Arg : InputArgv)
849 Args.push_back(Arg);
850
851 // Run any static constructors.
Lang Hames9f1c2392018-06-26 21:35:48 +0000852 ExitOnErr(J->runConstructors());
853
Lang Hames91c25db2018-09-26 16:26:59 +0000854 // Run any -thread-entry points.
855 std::vector<std::thread> AltEntryThreads;
856 for (auto &ThreadEntryPoint : ThreadEntryPoints) {
857 auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));
858 typedef void (*EntryPointPtr)();
859 auto EntryPoint =
860 reinterpret_cast<EntryPointPtr>(static_cast<uintptr_t>(EntryPointSym.getAddress()));
861 AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));
862 }
863
Lang Hames8b9cbda2018-10-23 23:01:39 +0000864 J->getExecutionSession().dump(llvm::dbgs());
865
Lang Hames592e4c72018-08-28 20:20:31 +0000866 // Run main.
Lang Hames9f1c2392018-06-26 21:35:48 +0000867 auto MainSym = ExitOnErr(J->lookup("main"));
868 typedef int (*MainFnPtr)(int, const char *[]);
869 std::vector<const char *> ArgV;
870 for (auto &Arg : Args)
871 ArgV.push_back(Arg.c_str());
Lang Hames37645102018-09-27 19:27:19 +0000872 ArgV.push_back(nullptr);
873
874 int ArgC = ArgV.size() - 1;
Lang Hames9f1c2392018-06-26 21:35:48 +0000875 auto Main =
876 reinterpret_cast<MainFnPtr>(static_cast<uintptr_t>(MainSym.getAddress()));
Lang Hames37645102018-09-27 19:27:19 +0000877 auto Result = Main(ArgC, (const char **)ArgV.data());
Lang Hames9f1c2392018-06-26 21:35:48 +0000878
Lang Hames91c25db2018-09-26 16:26:59 +0000879 // Wait for -entry-point threads.
880 for (auto &AltEntryThread : AltEntryThreads)
881 AltEntryThread.join();
Hans Wennborg3fccee22018-09-26 12:15:23 +0000882
Lang Hames91c25db2018-09-26 16:26:59 +0000883 // Run destructors.
884 ExitOnErr(J->runDestructors());
Lang Hames9f1c2392018-06-26 21:35:48 +0000885 CXXRuntimeOverrides.runDestructors();
886
887 return Result;
888}
889
Lang Hames90c32712018-09-29 23:49:57 +0000890void disallowOrcOptions() {
891 // Make sure nobody used an orc-lazy specific option accidentally.
892
893 if (LazyJITCompileThreads != 0) {
894 errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
895 exit(1);
896 }
897
898 if (!ThreadEntryPoints.empty()) {
899 errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
900 exit(1);
901 }
902
903 if (PerModuleLazy) {
904 errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
905 exit(1);
906 }
907}
908
Lang Hames085827f2016-11-11 21:42:09 +0000909std::unique_ptr<FDRawChannel> launchRemote() {
Lang Hamesb20e09c2016-01-11 16:35:55 +0000910#ifndef LLVM_ON_UNIX
911 llvm_unreachable("launchRemote not supported on non-Unix platforms");
912#else
913 int PipeFD[2][2];
914 pid_t ChildPID;
915
916 // Create two pipes.
917 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
918 perror("Error creating pipe: ");
919
920 ChildPID = fork();
921
922 if (ChildPID == 0) {
923 // In the child...
924
925 // Close the parent ends of the pipes
926 close(PipeFD[0][1]);
927 close(PipeFD[1][0]);
928
929
930 // Execute the child process.
931 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
932 {
933 ChildPath.reset(new char[ChildExecPath.size() + 1]);
934 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
935 ChildPath[ChildExecPath.size()] = '\0';
NAKAMURA Takumi23b90232016-01-15 02:14:46 +0000936 std::string ChildInStr = utostr(PipeFD[0][0]);
Lang Hamesb20e09c2016-01-11 16:35:55 +0000937 ChildIn.reset(new char[ChildInStr.size() + 1]);
938 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
939 ChildIn[ChildInStr.size()] = '\0';
NAKAMURA Takumi23b90232016-01-15 02:14:46 +0000940 std::string ChildOutStr = utostr(PipeFD[1][1]);
Lang Hamesb20e09c2016-01-11 16:35:55 +0000941 ChildOut.reset(new char[ChildOutStr.size() + 1]);
942 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
943 ChildOut[ChildOutStr.size()] = '\0';
944 }
945
946 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
947 int rc = execv(ChildExecPath.c_str(), args);
948 if (rc != 0)
949 perror("Error executing child process: ");
950 llvm_unreachable("Error executing child process");
951 }
952 // else we're the parent...
953
954 // Close the child ends of the pipes
955 close(PipeFD[0][0]);
956 close(PipeFD[1][1]);
957
958 // Return an RPC channel connected to our end of the pipes.
Lang Hames085827f2016-11-11 21:42:09 +0000959 return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
Lang Hamesb20e09c2016-01-11 16:35:55 +0000960#endif
961}