blob: d7b9368a32753ebd19b861a32f3ccc9b60e11664 [file] [log] [blame]
Chris Lattnera0d7b082002-12-23 23:59:41 +00001//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukman650ba8e2005-04-22 00:00:37 +00006//
John Criswell09344dc2003-10-20 17:47:21 +00007//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +00008//
Chris Lattner141ea3a2003-12-26 05:07:35 +00009// This utility provides a simple wrapper around the LLVM Execution Engines,
10// which allow the direct execution of LLVM programs through a Just-In-Time
Torok Edwinf011f282009-07-03 12:11:32 +000011// compiler, or through an interpreter if no JIT is available for this platform.
Chris Lattnerd7ff5782001-08-23 17:05:04 +000012//
13//===----------------------------------------------------------------------===//
14
Lang Hames9d7a2692016-01-11 16:35:55 +000015#include "RemoteJITUtils.h"
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +000016#include "llvm/ADT/StringExtras.h"
Duncan Sands3bd97fe2010-08-28 01:30:02 +000017#include "llvm/ADT/Triple.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000018#include "llvm/Bitcode/BitcodeReader.h"
David Blaikie4333f972018-04-11 18:49:37 +000019#include "llvm/CodeGen/CommandFlags.inc"
Chris Lattner5af6a3f2006-08-01 22:34:35 +000020#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Nico Weber432a3882018-04-30 14:59:11 +000021#include "llvm/Config/llvm-config.h"
Brian Gaekee99ca442003-09-05 19:42:34 +000022#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000023#include "llvm/ExecutionEngine/Interpreter.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000024#include "llvm/ExecutionEngine/JITEventListener.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000025#include "llvm/ExecutionEngine/MCJIT.h"
Lang Hames173c69f2014-01-08 04:09:09 +000026#include "llvm/ExecutionEngine/ObjectCache.h"
Lang Hames6a941342018-06-26 21:35:48 +000027#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
Lang Hamesd435ce42018-09-30 19:12:23 +000028#include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
Lang Hames6a941342018-06-26 21:35:48 +000029#include "llvm/ExecutionEngine/Orc/LLJIT.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000030#include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
Lang Hames93de2a12015-01-23 21:25:00 +000031#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
Andrew Kaylor58365b92012-11-27 19:49:00 +000032#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000033#include "llvm/IR/IRBuilder.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000034#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Module.h"
36#include "llvm/IR/Type.h"
Lang Hamesadae9bf2018-07-02 22:30:18 +000037#include "llvm/IR/Verifier.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000038#include "llvm/IRReader/IRReader.h"
Lang Hames173c69f2014-01-08 04:09:09 +000039#include "llvm/Object/Archive.h"
40#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000041#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000042#include "llvm/Support/Debug.h"
43#include "llvm/Support/DynamicLibrary.h"
44#include "llvm/Support/Format.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000045#include "llvm/Support/InitLLVM.h"
Chris Lattner76d46322006-12-06 01:18:01 +000046#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000047#include "llvm/Support/MathExtras.h"
48#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000049#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000050#include "llvm/Support/Path.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000051#include "llvm/Support/PluginLoader.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000052#include "llvm/Support/Process.h"
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000053#include "llvm/Support/Program.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000054#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000055#include "llvm/Support/TargetSelect.h"
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +000056#include "llvm/Support/WithColor.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000057#include "llvm/Support/raw_ostream.h"
Daniel Maleaa960c542013-06-28 19:11:40 +000058#include "llvm/Transforms/Instrumentation.h"
Chris Lattner4c522b92007-04-27 17:02:33 +000059#include <cerrno>
NAKAMURA Takumi15304872010-10-22 14:53:59 +000060
61#ifdef __CYGWIN__
62#include <cygwin/version.h>
63#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
64#define DO_NOTHING_ATEXIT 1
65#endif
66#endif
67
Brian Gaeke960707c2003-11-11 22:41:34 +000068using namespace llvm;
69
Chandler Carruthf98597a2014-04-22 03:10:36 +000070#define DEBUG_TYPE "lli"
71
Chris Lattnera0d7b082002-12-23 23:59:41 +000072namespace {
Lang Hames9528bba2015-03-25 12:11:48 +000073
74 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
75
Chris Lattnera0d7b082002-12-23 23:59:41 +000076 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000077 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000078
Chris Lattnera0d7b082002-12-23 23:59:41 +000079 cl::list<std::string>
80 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000081
Chris Lattnera0d7b082002-12-23 23:59:41 +000082 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000083 cl::desc("Force interpretation: disable JIT"),
84 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000085
Lang Hames9528bba2015-03-25 12:11:48 +000086 cl::opt<JITKind> UseJITKind("jit-kind",
87 cl::desc("Choose underlying JIT kind."),
88 cl::init(JITKind::MCJIT),
89 cl::values(
90 clEnumValN(JITKind::MCJIT, "mcjit",
91 "MCJIT"),
92 clEnumValN(JITKind::OrcMCJITReplacement,
93 "orc-mcjit",
94 "Orc-based MCJIT replacement"),
95 clEnumValN(JITKind::OrcLazy,
96 "orc-lazy",
Mehdi Amini732afdd2016-10-08 19:41:06 +000097 "Orc-based lazy JIT.")));
Lang Hames93de2a12015-01-23 21:25:00 +000098
Lang Hamesf0a3fd882018-09-26 16:26:59 +000099 cl::opt<unsigned>
100 LazyJITCompileThreads("compile-threads",
101 cl::desc("Choose the number of compile threads "
102 "(jit-kind=orc-lazy only)"),
103 cl::init(0));
104
105 cl::list<std::string>
106 ThreadEntryPoints("thread-entry",
107 cl::desc("calls the given entry-point on a new thread "
108 "(jit-kind=orc-lazy only)"));
109
Lang Hames98440292018-09-29 23:49:57 +0000110 cl::opt<bool> PerModuleLazy(
111 "per-module-lazy",
112 cl::desc("Performs lazy compilation on whole module boundaries "
113 "rather than individual functions"),
114 cl::init(false));
115
Lang Hames23cb2e72018-10-23 23:01:39 +0000116 cl::list<std::string>
117 JITDylibs("jd",
118 cl::desc("Specifies the JITDylib to be used for any subsequent "
119 "-extra-module arguments."));
120
Jim Grosbach0f435d02012-09-05 16:50:34 +0000121 // The MCJIT supports building for a target address space separate from
122 // the JIT compilation process. Use a forked process and a copying
123 // memory manager with IPC to execute using this functionality.
124 cl::opt<bool> RemoteMCJIT("remote-mcjit",
125 cl::desc("Execute MCJIT'ed code in a separate process."),
126 cl::init(false));
127
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000128 // Manually specify the child process for remote execution. This overrides
129 // the simulated remote execution that allocates address space for child
Andrew Kaylor89352582013-10-29 01:33:14 +0000130 // execution. The child process will be executed and will communicate with
131 // lli via stdin/stdout pipes.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000132 cl::opt<std::string>
Alp Tokera1186382014-01-22 21:52:35 +0000133 ChildExecPath("mcjit-remote-process",
134 cl::desc("Specify the filename of the process to launch "
135 "for remote MCJIT execution. If none is specified,"
136 "\n\tremote execution will be simulated in-process."),
137 cl::value_desc("filename"), cl::init(""));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000138
Evan Cheng09bd0b12009-05-04 23:05:19 +0000139 // Determine optimization level.
140 cl::opt<char>
141 OptLevel("O",
142 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
143 "(default = '-O2')"),
144 cl::Prefix,
145 cl::ZeroOrMore,
146 cl::init(' '));
Evan Cheng06d988e2008-08-08 08:12:06 +0000147
Chris Lattner76766cb2005-12-16 05:00:21 +0000148 cl::opt<std::string>
Chris Lattner78e9e102005-12-16 05:19:18 +0000149 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Cheng61582542008-11-05 23:21:52 +0000150
151 cl::opt<std::string>
152 EntryFunc("entry-function",
153 cl::desc("Specify the entry function (default = 'main') "
154 "of the executable"),
155 cl::value_desc("function"),
156 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000157
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000158 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000159 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000160 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000161 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000162
Lang Hames173c69f2014-01-08 04:09:09 +0000163 cl::list<std::string>
164 ExtraObjects("extra-object",
165 cl::desc("Extra object files to be loaded"),
166 cl::value_desc("input object"));
167
168 cl::list<std::string>
169 ExtraArchives("extra-archive",
170 cl::desc("Extra archive files to be loaded"),
171 cl::value_desc("input archive"));
172
173 cl::opt<bool>
174 EnableCacheManager("enable-cache-manager",
Lang Hames1ddecc02014-01-09 05:24:05 +0000175 cl::desc("Use cache manager to save/load mdoules"),
Lang Hames173c69f2014-01-08 04:09:09 +0000176 cl::init(false));
177
Chris Lattner55644062003-10-28 22:51:44 +0000178 cl::opt<std::string>
Lang Hames1ddecc02014-01-09 05:24:05 +0000179 ObjectCacheDir("object-cache-dir",
180 cl::desc("Directory to store cached object files "
181 "(must be user writable)"),
182 cl::init(""));
183
184 cl::opt<std::string>
Chris Lattner55644062003-10-28 22:51:44 +0000185 FakeArgv0("fake-argv0",
186 cl::desc("Override the 'argv[0]' value passed into the executing"
187 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000188
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000189 cl::opt<bool>
190 DisableCoreFiles("disable-core-files", cl::Hidden,
191 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000192
193 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000194 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000195 cl::desc("Disable JIT lazy compilation"),
196 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000197
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000198 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000199 GenerateSoftFloatCalls("soft-float",
200 cl::desc("Generate software floating point library calls"),
201 cl::init(false));
202
Lang Hames6a941342018-06-26 21:35:48 +0000203 enum class DumpKind {
204 NoDump,
205 DumpFuncsToStdOut,
206 DumpModsToStdOut,
207 DumpModsToDisk
208 };
209
210 cl::opt<DumpKind> OrcDumpKind(
211 "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
212 cl::init(DumpKind::NoDump),
213 cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
214 "Don't dump anything."),
215 clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
216 "Dump function names to stdout."),
217 clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
218 "Dump modules to stdout."),
219 clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
220 "Dump modules to the current "
221 "working directory. (WARNING: "
222 "will overwrite existing files).")),
223 cl::Hidden);
224
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000225 ExitOnError ExitOnErr;
Chris Lattnera0d7b082002-12-23 23:59:41 +0000226}
Chris Lattner009f8102001-10-27 08:43:52 +0000227
Lang Hames173c69f2014-01-08 04:09:09 +0000228//===----------------------------------------------------------------------===//
229// Object cache
230//
Lang Hames1ddecc02014-01-09 05:24:05 +0000231// This object cache implementation writes cached objects to disk to the
232// directory specified by CacheDir, using a filename provided in the module
233// descriptor. The cache tries to load a saved object using that path if the
234// file exists. CacheDir defaults to "", in which case objects are cached
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000235// alongside their originating bitcodes.
Lang Hames173c69f2014-01-08 04:09:09 +0000236//
237class LLIObjectCache : public ObjectCache {
238public:
Lang Hames1ddecc02014-01-09 05:24:05 +0000239 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
240 // Add trailing '/' to cache dir if necessary.
Lang Hamesf9dd8fd2014-01-09 05:29:59 +0000241 if (!this->CacheDir.empty() &&
242 this->CacheDir[this->CacheDir.size() - 1] != '/')
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000243 this->CacheDir += '/';
Lang Hames1ddecc02014-01-09 05:24:05 +0000244 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000245 ~LLIObjectCache() override {}
Lang Hames173c69f2014-01-08 04:09:09 +0000246
Rafael Espindola48af1c22014-08-19 18:44:46 +0000247 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000248 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000249 std::string CacheName;
250 if (!getCacheFilename(ModuleID, CacheName))
251 return;
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000252 if (!CacheDir.empty()) { // Create user-defined cache dir.
Rafael Espindolaf662e002015-07-15 21:24:07 +0000253 SmallString<128> dir(sys::path::parent_path(CacheName));
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000254 sys::fs::create_directories(Twine(dir));
255 }
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000256 std::error_code EC;
257 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000258 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
Lang Hames173c69f2014-01-08 04:09:09 +0000259 outfile.close();
260 }
261
Rafael Espindola5f2bb7d2014-08-13 18:49:01 +0000262 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000263 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000264 std::string CacheName;
265 if (!getCacheFilename(ModuleID, CacheName))
Craig Toppere6cb63e2014-04-25 04:24:47 +0000266 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000267 // Load the object from the cache filename
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000268 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000269 MemoryBuffer::getFile(CacheName, -1, false);
Lang Hames173c69f2014-01-08 04:09:09 +0000270 // If the file isn't there, that's OK.
271 if (!IRObjectBuffer)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000272 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000273 // MCJIT will want to write into this buffer, and we don't want that
274 // because the file has probably just been mmapped. Instead we make
275 // a copy. The filed-based buffer will be released when it goes
276 // out of scope.
Rafael Espindola3560ff22014-08-27 20:03:13 +0000277 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
Lang Hames173c69f2014-01-08 04:09:09 +0000278 }
279
280private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000281 std::string CacheDir;
282
Lang Hames173c69f2014-01-08 04:09:09 +0000283 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
284 std::string Prefix("file:");
285 size_t PrefixLength = Prefix.length();
286 if (ModID.substr(0, PrefixLength) != Prefix)
287 return false;
NAKAMURA Takumid7fd6d92014-01-10 10:38:40 +0000288 std::string CacheSubdir = ModID.substr(PrefixLength);
289#if defined(_WIN32)
290 // Transform "X:\foo" => "/X\foo" for convenience.
291 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
292 CacheSubdir[1] = CacheSubdir[0];
293 CacheSubdir[0] = '/';
294 }
295#endif
296 CacheName = CacheDir + CacheSubdir;
Lang Hames173c69f2014-01-08 04:09:09 +0000297 size_t pos = CacheName.rfind('.');
298 CacheName.replace(pos, CacheName.length() - pos, ".o");
299 return true;
300 }
301};
302
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000303// On Mingw and Cygwin, an external symbol named '__main' is called from the
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000304// generated 'main' function to allow static initialization. To avoid linking
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000305// problems with remote targets (because lli's remote target support does not
306// currently handle external linking) we add a secondary module which defines
307// an empty '__main' function.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000308static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000309 StringRef TargetTripleStr) {
310 IRBuilder<> Builder(Context);
311 Triple TargetTriple(TargetTripleStr);
312
313 // Create a new module.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000314 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000315 M->setTargetTriple(TargetTripleStr);
316
317 // Create an empty function named "__main".
James Y Knightc0044112019-01-13 16:09:28 +0000318 Type *ReturnTy;
319 if (TargetTriple.isArch64Bit())
320 ReturnTy = Type::getInt64Ty(Context);
321 else
322 ReturnTy = Type::getInt32Ty(Context);
323 Function *Result =
324 Function::Create(FunctionType::get(ReturnTy, {}, false),
325 GlobalValue::ExternalLinkage, "__main", M.get());
326
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000327 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
328 Builder.SetInsertPoint(BB);
James Y Knightc0044112019-01-13 16:09:28 +0000329 Value *ReturnVal = ConstantInt::get(ReturnTy, 0);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000330 Builder.CreateRet(ReturnVal);
331
332 // Add this new module to the ExecutionEngine.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000333 EE.addModule(std::move(M));
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000334}
335
Lang Hames1899d0c2015-06-09 02:43:27 +0000336CodeGenOpt::Level getOptLevel() {
337 switch (OptLevel) {
338 default:
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000339 WithColor::error(errs(), "lli") << "invalid optimization level.\n";
Lang Hames1899d0c2015-06-09 02:43:27 +0000340 exit(1);
341 case '0': return CodeGenOpt::None;
342 case '1': return CodeGenOpt::Less;
343 case ' ':
344 case '2': return CodeGenOpt::Default;
345 case '3': return CodeGenOpt::Aggressive;
346 }
347 llvm_unreachable("Unrecognized opt level.");
348}
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000349
Davide Italianoda8e6b22016-11-17 22:58:13 +0000350LLVM_ATTRIBUTE_NORETURN
351static void reportError(SMDiagnostic Err, const char *ProgName) {
352 Err.print(ProgName, errs());
353 exit(1);
354}
355
Lang Hames37a66412018-08-28 20:20:31 +0000356int runOrcLazyJIT(const char *ProgName);
Lang Hames98440292018-09-29 23:49:57 +0000357void disallowOrcOptions();
Lang Hames6a941342018-06-26 21:35:48 +0000358
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000359//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000360// main Driver function
361//
Misha Brukman5b255e52003-10-14 21:39:53 +0000362int main(int argc, char **argv, char * const *envp) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000363 InitLLVM X(argc, argv);
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000364
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000365 if (argc > 1)
366 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
367
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000368 // If we have a native target, initialize it to ensure it is linked in and
369 // usable by the JIT.
370 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000371 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000372 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000373
Chris Lattner2785bdb2007-05-06 04:58:26 +0000374 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000375 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000376
Chris Lattner2785bdb2007-05-06 04:58:26 +0000377 // If the user doesn't want core files, disable them.
378 if (DisableCoreFiles)
379 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000380
Lang Hames37a66412018-08-28 20:20:31 +0000381 if (UseJITKind == JITKind::OrcLazy)
382 return runOrcLazyJIT(argv[0]);
Lang Hames98440292018-09-29 23:49:57 +0000383 else
384 disallowOrcOptions();
Lang Hames37a66412018-08-28 20:20:31 +0000385
Mehdi Aminia7de8202016-04-18 18:52:39 +0000386 LLVMContext Context;
387
Gabor Greife16561c2007-07-05 17:07:56 +0000388 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000389 SMDiagnostic Err;
Rafael Espindolad233b062014-08-26 17:29:46 +0000390 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000391 Module *Mod = Owner.get();
Davide Italianoda8e6b22016-11-17 22:58:13 +0000392 if (!Mod)
393 reportError(Err, argv[0]);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000394
Lang Hames173c69f2014-01-08 04:09:09 +0000395 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000396 std::string CacheName("file:");
397 CacheName.append(InputFile);
398 Mod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000399 }
400
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000401 // If not jitting lazily, load the whole bitcode file eagerly too.
402 if (NoLazyCompilation) {
Davide Italianob0e067b2016-11-09 21:30:33 +0000403 // Use *argv instead of argv[0] to work around a wrong GCC warning.
404 ExitOnError ExitOnErr(std::string(*argv) +
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000405 ": bitcode didn't read correctly: ");
406 ExitOnErr(Mod->materializeAll());
Evan Cheng0422bef2008-04-22 06:51:41 +0000407 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000408
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000409 std::string ErrorMsg;
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000410 EngineBuilder builder(std::move(Owner));
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000411 builder.setMArch(MArch);
Craig Topper243f20f2018-01-09 18:14:18 +0000412 builder.setMCPU(getCPUStr());
413 builder.setMAttrs(getFeatureList());
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000414 if (RelocModel.getNumOccurrences())
415 builder.setRelocationModel(RelocModel);
Rafael Espindola79e238a2017-08-03 02:16:21 +0000416 if (CMModel.getNumOccurrences())
417 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000418 builder.setErrorStr(&ErrorMsg);
419 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000420 ? EngineKind::Interpreter
421 : EngineKind::JIT);
Lang Hames9528bba2015-03-25 12:11:48 +0000422 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000423
Chris Lattner2785bdb2007-05-06 04:58:26 +0000424 // If we are supposed to override the target triple, do so now.
425 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000426 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000427
Eli Bendersky4c647582012-01-16 08:56:09 +0000428 // Enable MCJIT if desired.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000429 RTDyldMemoryManager *RTDyldMM = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000430 if (!ForceInterpreter) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000431 if (RemoteMCJIT)
Lang Hames9d7a2692016-01-11 16:35:55 +0000432 RTDyldMM = new ForwardingMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000433 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000434 RTDyldMM = new SectionMemoryManager();
Lang Hames4a5697e2014-12-03 00:51:19 +0000435
436 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
437 // RTDyldMM: We still use it below, even though we don't own it.
438 builder.setMCJITMemoryManager(
439 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
Lang Hames0f154902014-09-23 16:56:02 +0000440 } else if (RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000441 WithColor::error(errs(), argv[0])
442 << "remote process execution does not work with the interpreter.\n";
Lang Hames0f154902014-09-23 16:56:02 +0000443 exit(1);
Eli Bendersky4c647582012-01-16 08:56:09 +0000444 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000445
Lang Hames1899d0c2015-06-09 02:43:27 +0000446 builder.setOptLevel(getOptLevel());
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000447
David Blaikiec14bfec2017-11-27 19:43:58 +0000448 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000449 if (FloatABIForCalls != FloatABI::Default)
450 Options.FloatABIType = FloatABIForCalls;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000451
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000452 builder.setTargetOptions(Options);
453
Mehdi Aminia7de8202016-04-18 18:52:39 +0000454 std::unique_ptr<ExecutionEngine> EE(builder.create());
Chris Lattnerf840ed72009-07-07 18:31:09 +0000455 if (!EE) {
456 if (!ErrorMsg.empty())
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000457 WithColor::error(errs(), argv[0])
458 << "error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000459 else
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000460 WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000461 exit(1);
462 }
463
Mehdi Aminia7de8202016-04-18 18:52:39 +0000464 std::unique_ptr<LLIObjectCache> CacheManager;
Lang Hames173c69f2014-01-08 04:09:09 +0000465 if (EnableCacheManager) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000466 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
467 EE->setObjectCache(CacheManager.get());
Lang Hames173c69f2014-01-08 04:09:09 +0000468 }
469
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000470 // Load any additional modules specified on the command line.
471 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
Rafael Espindolad233b062014-08-26 17:29:46 +0000472 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000473 if (!XMod)
474 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000475 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000476 std::string CacheName("file:");
477 CacheName.append(ExtraModules[i]);
478 XMod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000479 }
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000480 EE->addModule(std::move(XMod));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000481 }
482
Lang Hames173c69f2014-01-08 04:09:09 +0000483 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000484 Expected<object::OwningBinary<object::ObjectFile>> Obj =
Rafael Espindola51cc3602014-01-22 00:14:49 +0000485 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames173c69f2014-01-08 04:09:09 +0000486 if (!Obj) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000487 // TODO: Actually report errors helpfully.
488 consumeError(Obj.takeError());
Davide Italianoda8e6b22016-11-17 22:58:13 +0000489 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000490 }
Rafael Espindola061beab2014-08-20 15:19:37 +0000491 object::OwningBinary<object::ObjectFile> &O = Obj.get();
Rafael Espindola7271c192014-08-26 21:04:04 +0000492 EE->addObjectFile(std::move(O));
Lang Hames173c69f2014-01-08 04:09:09 +0000493 }
494
495 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000496 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000497 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000498 if (!ArBufOrErr)
499 reportError(Err, argv[0]);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000500 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
Rafael Espindolae1923412014-08-01 18:31:17 +0000501
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000502 Expected<std::unique_ptr<object::Archive>> ArOrErr =
Rafael Espindola48af1c22014-08-19 18:44:46 +0000503 object::Archive::create(ArBuf->getMemBufferRef());
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000504 if (!ArOrErr) {
505 std::string Buf;
506 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000507 logAllUnhandledErrors(ArOrErr.takeError(), OS);
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000508 OS.flush();
509 errs() << Buf;
Davide Italiano86511442016-11-17 22:59:13 +0000510 exit(1);
Lang Hames173c69f2014-01-08 04:09:09 +0000511 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000512 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
513
514 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
515
516 EE->addArchive(std::move(OB));
Lang Hames173c69f2014-01-08 04:09:09 +0000517 }
518
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000519 // If the target is Cygwin/MingW and we are generating remote code, we
520 // need an extra module to help out with linking.
521 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000522 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000523 }
524
Eli Bendersky5262ad22012-03-13 08:33:15 +0000525 // The following functions have no effect if their respective profiling
526 // support wasn't enabled in the build configuration.
527 EE->RegisterJITEventListener(
528 JITEventListener::createOProfileJITEventListener());
529 EE->RegisterJITEventListener(
530 JITEventListener::createIntelJITEventListener());
Andres Freund376a3d32018-07-24 00:54:06 +0000531 if (!RemoteMCJIT)
532 EE->RegisterJITEventListener(
533 JITEventListener::createPerfJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000534
Jim Grosbach0f435d02012-09-05 16:50:34 +0000535 if (!NoLazyCompilation && RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000536 WithColor::warning(errs(), argv[0])
537 << "remote mcjit does not support lazy compilation\n";
Jim Grosbach0f435d02012-09-05 16:50:34 +0000538 NoLazyCompilation = true;
539 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000540 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000541
Chris Lattner2785bdb2007-05-06 04:58:26 +0000542 // If the user specifically requested an argv[0] to pass into the program,
543 // do it now.
544 if (!FakeArgv0.empty()) {
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000545 InputFile = static_cast<std::string>(FakeArgv0);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000546 } else {
547 // Otherwise, if there is a .bc suffix on the executable strip it off, it
548 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000549 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000550 InputFile.erase(InputFile.length() - 3);
551 }
552
553 // Add the module's name to the start of the vector of arguments to main().
554 InputArgv.insert(InputArgv.begin(), InputFile);
555
556 // Call the main function from M as if its signature were:
557 // int main (int argc, char **argv, const char **envp)
558 // using the contents of Args to determine argc & argv, and the contents of
559 // EnvVars to determine envp.
560 //
Evan Cheng61582542008-11-05 23:21:52 +0000561 Function *EntryFn = Mod->getFunction(EntryFunc);
562 if (!EntryFn) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000563 WithColor::error(errs(), argv[0])
564 << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000565 return -1;
566 }
567
Chris Lattner2785bdb2007-05-06 04:58:26 +0000568 // Reset errno to zero on entry to main.
569 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000570
Lang Hames3fde6522016-04-18 19:55:43 +0000571 int Result = -1;
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000572
Lang Hames9d7a2692016-01-11 16:35:55 +0000573 // Sanity check use of remote-jit: LLI currently only supports use of the
574 // remote JIT on Unix platforms.
Lang Hames9d7a2692016-01-11 16:35:55 +0000575 if (RemoteMCJIT) {
576#ifndef LLVM_ON_UNIX
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000577 WithColor::warning(errs(), argv[0])
Jonas Devlieghere7b5fa242018-04-22 08:35:00 +0000578 << "host does not support external remote targets.\n";
579 WithColor::note() << "defaulting to local execution\n";
Lang Hames4b6e0212016-01-11 21:41:34 +0000580 return -1;
Lang Hames9d7a2692016-01-11 16:35:55 +0000581#else
582 if (ChildExecPath.empty()) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000583 WithColor::error(errs(), argv[0])
584 << "-remote-mcjit requires -mcjit-remote-process.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000585 exit(1);
586 } else if (!sys::fs::can_execute(ChildExecPath)) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000587 WithColor::error(errs(), argv[0])
588 << "unable to find usable child executable: '" << ChildExecPath
589 << "'\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000590 return -1;
591 }
592#endif
593 }
594
Andrew Kaylor58365b92012-11-27 19:49:00 +0000595 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000596 // If the program doesn't explicitly call exit, we will need the Exit
597 // function later on to make an explicit call, so get the function now.
598 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000599 Type::getInt32Ty(Context));
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000600
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000601 // Run static constructors.
Eric Christopher79cc1e32014-09-02 22:28:02 +0000602 if (!ForceInterpreter) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000603 // Give MCJIT a chance to apply relocations and set page permissions.
604 EE->finalizeObject();
605 }
606 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000607
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000608 // Trigger compilation separately so code regions that need to be
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000609 // invalidated will be known.
610 (void)EE->getPointerToFunction(EntryFn);
611 // Clear instruction cache before code will be executed.
612 if (RTDyldMM)
613 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
614
615 // Run main.
616 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
617
618 // Run static destructors.
619 EE->runStaticConstructorsDestructors(true);
620
621 // If the program didn't call exit explicitly, we should call it now.
622 // This ensures that any atexit handlers get called correctly.
623 if (Function *ExitF = dyn_cast<Function>(Exit)) {
624 std::vector<GenericValue> Args;
625 GenericValue ResultGV;
626 ResultGV.IntVal = APInt(32, Result);
627 Args.push_back(ResultGV);
628 EE->runFunction(ExitF, Args);
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000629 WithColor::error(errs(), argv[0]) << "exit(" << Result << ") returned!\n";
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000630 abort();
631 } else {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000632 WithColor::error(errs(), argv[0])
633 << "exit defined with wrong prototype!\n";
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000634 abort();
635 }
636 } else {
637 // else == "if (RemoteMCJIT)"
638
639 // Remote target MCJIT doesn't (yet) support static constructors. No reason
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000640 // it couldn't. This is a limitation of the LLI implementation, not the
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000641 // MCJIT itself. FIXME.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000642
Lang Hames9d7a2692016-01-11 16:35:55 +0000643 // Lanch the remote process and get a channel to it.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000644 std::unique_ptr<FDRawChannel> C = launchRemote();
Lang Hames9d7a2692016-01-11 16:35:55 +0000645 if (!C) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000646 WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000647 exit(1);
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000648 }
649
Lang Hames9d7a2692016-01-11 16:35:55 +0000650 // Create a remote target client running over the channel.
Lang Hamesbd0cb782018-05-30 01:57:45 +0000651 llvm::orc::ExecutionSession ES;
652 ES.setErrorReporter([&](Error Err) { ExitOnErr(std::move(Err)); });
Lang Hames9e68b7342017-09-04 20:54:46 +0000653 typedef orc::remote::OrcRemoteTargetClient MyRemote;
Lang Hamesbd0cb782018-05-30 01:57:45 +0000654 auto R = ExitOnErr(MyRemote::Create(*C, ES));
Jim Grosbach748b9472012-08-28 23:22:30 +0000655
Lang Hames9d7a2692016-01-11 16:35:55 +0000656 // Create a remote memory manager.
Lang Hames9e68b7342017-09-04 20:54:46 +0000657 auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
Lang Hames9d7a2692016-01-11 16:35:55 +0000658
659 // Forward MCJIT's memory manager calls to the remote memory manager.
660 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
661 std::move(RemoteMM));
662
663 // Forward MCJIT's symbol resolution calls to the remote.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000664 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
665 orc::createLambdaResolver(
666 [](const std::string &Name) { return nullptr; },
667 [&](const std::string &Name) {
668 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
669 return JITSymbol(Addr, JITSymbolFlags::Exported);
670 return JITSymbol(nullptr);
671 }));
Lang Hames9d7a2692016-01-11 16:35:55 +0000672
673 // Grab the target address of the JIT'd main function on the remote and call
674 // it.
Jim Grosbach0f435d02012-09-05 16:50:34 +0000675 // FIXME: argv and envp handling.
Lang Hamesad4a9112016-08-01 20:49:11 +0000676 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
Lang Hames9d7a2692016-01-11 16:35:55 +0000677 EE->finalizeObject();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000678 LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
679 << format("%llx", Entry) << "\n");
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000680 Result = ExitOnErr(R->callIntVoid(Entry));
Jim Grosbach0f435d02012-09-05 16:50:34 +0000681
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000682 // Like static constructors, the remote target MCJIT support doesn't handle
683 // this yet. It could. FIXME.
684
Lang Hames9d7a2692016-01-11 16:35:55 +0000685 // Delete the EE - we need to tear it down *before* we terminate the session
686 // with the remote, otherwise it'll crash when it tries to release resources
687 // on a remote that has already been disconnected.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000688 EE.reset();
Lang Hames9d7a2692016-01-11 16:35:55 +0000689
690 // Signal the remote target that we're done JITing.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000691 ExitOnErr(R->terminateSession());
Chris Lattner2785bdb2007-05-06 04:58:26 +0000692 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000693
Jim Grosbach0f435d02012-09-05 16:50:34 +0000694 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000695}
Lang Hames9d7a2692016-01-11 16:35:55 +0000696
Lang Hames079df9a2018-10-15 22:56:10 +0000697static orc::IRTransformLayer::TransformFunction createDebugDumper() {
Lang Hames6a941342018-06-26 21:35:48 +0000698 switch (OrcDumpKind) {
699 case DumpKind::NoDump:
Lang Hames3e709d52018-09-28 21:49:53 +0000700 return [](orc::ThreadSafeModule TSM,
701 const orc::MaterializationResponsibility &R) { return TSM; };
Lang Hames6a941342018-06-26 21:35:48 +0000702
703 case DumpKind::DumpFuncsToStdOut:
Lang Hames3e709d52018-09-28 21:49:53 +0000704 return [](orc::ThreadSafeModule TSM,
705 const orc::MaterializationResponsibility &R) {
Lang Hames6a941342018-06-26 21:35:48 +0000706 printf("[ ");
707
Lang Hames8d76c712018-09-26 01:24:12 +0000708 for (const auto &F : *TSM.getModule()) {
Lang Hames6a941342018-06-26 21:35:48 +0000709 if (F.isDeclaration())
710 continue;
711
712 if (F.hasName()) {
713 std::string Name(F.getName());
714 printf("%s ", Name.c_str());
715 } else
716 printf("<anon> ");
717 }
718
719 printf("]\n");
Lang Hames8d76c712018-09-26 01:24:12 +0000720 return TSM;
Lang Hames6a941342018-06-26 21:35:48 +0000721 };
722
723 case DumpKind::DumpModsToStdOut:
Lang Hames3e709d52018-09-28 21:49:53 +0000724 return [](orc::ThreadSafeModule TSM,
725 const orc::MaterializationResponsibility &R) {
Lang Hames6a941342018-06-26 21:35:48 +0000726 outs() << "----- Module Start -----\n"
Lang Hames8d76c712018-09-26 01:24:12 +0000727 << *TSM.getModule() << "----- Module End -----\n";
Lang Hames6a941342018-06-26 21:35:48 +0000728
Lang Hames8d76c712018-09-26 01:24:12 +0000729 return TSM;
Lang Hames6a941342018-06-26 21:35:48 +0000730 };
731
732 case DumpKind::DumpModsToDisk:
Lang Hames3e709d52018-09-28 21:49:53 +0000733 return [](orc::ThreadSafeModule TSM,
734 const orc::MaterializationResponsibility &R) {
Lang Hames6a941342018-06-26 21:35:48 +0000735 std::error_code EC;
Lang Hames8d76c712018-09-26 01:24:12 +0000736 raw_fd_ostream Out(TSM.getModule()->getModuleIdentifier() + ".ll", EC,
737 sys::fs::F_Text);
Lang Hames6a941342018-06-26 21:35:48 +0000738 if (EC) {
Lang Hames8d76c712018-09-26 01:24:12 +0000739 errs() << "Couldn't open " << TSM.getModule()->getModuleIdentifier()
Lang Hames6a941342018-06-26 21:35:48 +0000740 << " for dumping.\nError:" << EC.message() << "\n";
741 exit(1);
742 }
Lang Hames8d76c712018-09-26 01:24:12 +0000743 Out << *TSM.getModule();
744 return TSM;
Lang Hames6a941342018-06-26 21:35:48 +0000745 };
746 }
747 llvm_unreachable("Unknown DumpKind");
748}
749
Lang Hames23cb2e72018-10-23 23:01:39 +0000750static void exitOnLazyCallThroughFailure() { exit(1); }
751
Lang Hames37a66412018-08-28 20:20:31 +0000752int runOrcLazyJIT(const char *ProgName) {
753 // Start setting up the JIT environment.
Lang Hames6a941342018-06-26 21:35:48 +0000754
Lang Hames37a66412018-08-28 20:20:31 +0000755 // Parse the main module.
Lang Hames8d76c712018-09-26 01:24:12 +0000756 orc::ThreadSafeContext TSCtx(llvm::make_unique<LLVMContext>());
Lang Hames37a66412018-08-28 20:20:31 +0000757 SMDiagnostic Err;
Lang Hames8d76c712018-09-26 01:24:12 +0000758 auto MainModule = orc::ThreadSafeModule(
759 parseIRFile(InputFile, Err, *TSCtx.getContext()), TSCtx);
Lang Hames37a66412018-08-28 20:20:31 +0000760 if (!MainModule)
761 reportError(Err, ProgName);
762
Lang Hames8d76c712018-09-26 01:24:12 +0000763 const auto &TT = MainModule.getModule()->getTargetTriple();
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000764 orc::JITTargetMachineBuilder JTMB =
Lang Hames6a941342018-06-26 21:35:48 +0000765 TT.empty() ? ExitOnErr(orc::JITTargetMachineBuilder::detectHost())
766 : orc::JITTargetMachineBuilder(Triple(TT));
767
Lang Hamesd435ce42018-09-30 19:12:23 +0000768 if (!MArch.empty())
769 JTMB.getTargetTriple().setArchName(MArch);
770
771 JTMB.setCPU(getCPUStr())
Lang Hames6a941342018-06-26 21:35:48 +0000772 .addFeatures(getFeatureList())
773 .setRelocationModel(RelocModel.getNumOccurrences()
774 ? Optional<Reloc::Model>(RelocModel)
775 : None)
776 .setCodeModel(CMModel.getNumOccurrences()
777 ? Optional<CodeModel::Model>(CMModel)
778 : None);
Lang Hamesd435ce42018-09-30 19:12:23 +0000779
Lang Hamesd89c2732018-10-01 00:59:26 +0000780 DataLayout DL = ExitOnErr(JTMB.getDefaultDataLayoutForTarget());
Lang Hames23cb2e72018-10-23 23:01:39 +0000781
782 auto J = ExitOnErr(orc::LLLazyJIT::Create(
783 std::move(JTMB), DL,
784 pointerToJITTargetAddress(exitOnLazyCallThroughFailure),
785 LazyJITCompileThreads));
Lang Hames6a941342018-06-26 21:35:48 +0000786
Lang Hames98440292018-09-29 23:49:57 +0000787 if (PerModuleLazy)
Lang Hames079df9a2018-10-15 22:56:10 +0000788 J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);
Lang Hames98440292018-09-29 23:49:57 +0000789
Lang Hamesadae9bf2018-07-02 22:30:18 +0000790 auto Dump = createDebugDumper();
791
Lang Hames3e709d52018-09-28 21:49:53 +0000792 J->setLazyCompileTransform([&](orc::ThreadSafeModule TSM,
793 const orc::MaterializationResponsibility &R) {
Lang Hames8d76c712018-09-26 01:24:12 +0000794 if (verifyModule(*TSM.getModule(), &dbgs())) {
795 dbgs() << "Bad module: " << *TSM.getModule() << "\n";
796 exit(1);
797 }
Lang Hames3e709d52018-09-28 21:49:53 +0000798 return Dump(std::move(TSM), R);
Lang Hames8d76c712018-09-26 01:24:12 +0000799 });
Lang Hamesa5157d62018-10-15 05:07:54 +0000800 J->getMainJITDylib().setGenerator(
801 ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(DL)));
Lang Hames6a941342018-06-26 21:35:48 +0000802
803 orc::MangleAndInterner Mangle(J->getExecutionSession(), DL);
Lang Hames079df9a2018-10-15 22:56:10 +0000804 orc::LocalCXXRuntimeOverrides CXXRuntimeOverrides;
Lang Hamesd5f56c52018-08-17 21:18:18 +0000805 ExitOnErr(CXXRuntimeOverrides.enable(J->getMainJITDylib(), Mangle));
Lang Hames6a941342018-06-26 21:35:48 +0000806
Lang Hames37a66412018-08-28 20:20:31 +0000807 // Add the main module.
808 ExitOnErr(J->addLazyIRModule(std::move(MainModule)));
809
Lang Hames23cb2e72018-10-23 23:01:39 +0000810 // Create JITDylibs and add any extra modules.
811 {
812 // Create JITDylibs, keep a map from argument index to dylib. We will use
813 // -extra-module argument indexes to determine what dylib to use for each
814 // -extra-module.
815 std::map<unsigned, orc::JITDylib *> IdxToDylib;
816 IdxToDylib[0] = &J->getMainJITDylib();
817 for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
818 JDItr != JDEnd; ++JDItr) {
819 IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] =
820 &J->createJITDylib(*JDItr);
821 }
Lang Hames37a66412018-08-28 20:20:31 +0000822
Lang Hames23cb2e72018-10-23 23:01:39 +0000823 for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
824 EMItr != EMEnd; ++EMItr) {
825 auto M = parseIRFile(*EMItr, Err, *TSCtx.getContext());
826 if (!M)
827 reportError(Err, ProgName);
828
829 auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin());
830 assert(EMIdx != 0 && "ExtraModule should have index > 0");
831 auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx));
832 auto &JD = *JDItr->second;
833 ExitOnErr(
834 J->addLazyIRModule(JD, orc::ThreadSafeModule(std::move(M), TSCtx)));
835 }
Lang Hamesadae9bf2018-07-02 22:30:18 +0000836 }
Lang Hames6a941342018-06-26 21:35:48 +0000837
Lang Hames37a66412018-08-28 20:20:31 +0000838 // Add the objects.
839 for (auto &ObjPath : ExtraObjects) {
840 auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));
841 ExitOnErr(J->addObjectFile(std::move(Obj)));
842 }
843
844 // Generate a argument string.
845 std::vector<std::string> Args;
846 Args.push_back(InputFile);
847 for (auto &Arg : InputArgv)
848 Args.push_back(Arg);
849
850 // Run any static constructors.
Lang Hames6a941342018-06-26 21:35:48 +0000851 ExitOnErr(J->runConstructors());
852
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000853 // Run any -thread-entry points.
854 std::vector<std::thread> AltEntryThreads;
855 for (auto &ThreadEntryPoint : ThreadEntryPoints) {
856 auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));
857 typedef void (*EntryPointPtr)();
858 auto EntryPoint =
859 reinterpret_cast<EntryPointPtr>(static_cast<uintptr_t>(EntryPointSym.getAddress()));
860 AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));
861 }
862
Lang Hames23cb2e72018-10-23 23:01:39 +0000863 J->getExecutionSession().dump(llvm::dbgs());
864
Lang Hames37a66412018-08-28 20:20:31 +0000865 // Run main.
Lang Hames6a941342018-06-26 21:35:48 +0000866 auto MainSym = ExitOnErr(J->lookup("main"));
867 typedef int (*MainFnPtr)(int, const char *[]);
868 std::vector<const char *> ArgV;
869 for (auto &Arg : Args)
870 ArgV.push_back(Arg.c_str());
Lang Hames94fe9d42018-09-27 19:27:19 +0000871 ArgV.push_back(nullptr);
872
873 int ArgC = ArgV.size() - 1;
Lang Hames6a941342018-06-26 21:35:48 +0000874 auto Main =
875 reinterpret_cast<MainFnPtr>(static_cast<uintptr_t>(MainSym.getAddress()));
Lang Hames94fe9d42018-09-27 19:27:19 +0000876 auto Result = Main(ArgC, (const char **)ArgV.data());
Lang Hames6a941342018-06-26 21:35:48 +0000877
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000878 // Wait for -entry-point threads.
879 for (auto &AltEntryThread : AltEntryThreads)
880 AltEntryThread.join();
Hans Wennborg20b5abe2018-09-26 12:15:23 +0000881
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000882 // Run destructors.
883 ExitOnErr(J->runDestructors());
Lang Hames6a941342018-06-26 21:35:48 +0000884 CXXRuntimeOverrides.runDestructors();
885
886 return Result;
887}
888
Lang Hames98440292018-09-29 23:49:57 +0000889void disallowOrcOptions() {
890 // Make sure nobody used an orc-lazy specific option accidentally.
891
892 if (LazyJITCompileThreads != 0) {
893 errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
894 exit(1);
895 }
896
897 if (!ThreadEntryPoints.empty()) {
898 errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
899 exit(1);
900 }
901
902 if (PerModuleLazy) {
903 errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
904 exit(1);
905 }
906}
907
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000908std::unique_ptr<FDRawChannel> launchRemote() {
Lang Hames9d7a2692016-01-11 16:35:55 +0000909#ifndef LLVM_ON_UNIX
910 llvm_unreachable("launchRemote not supported on non-Unix platforms");
911#else
912 int PipeFD[2][2];
913 pid_t ChildPID;
914
915 // Create two pipes.
916 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
917 perror("Error creating pipe: ");
918
919 ChildPID = fork();
920
921 if (ChildPID == 0) {
922 // In the child...
923
924 // Close the parent ends of the pipes
925 close(PipeFD[0][1]);
926 close(PipeFD[1][0]);
927
928
929 // Execute the child process.
930 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
931 {
932 ChildPath.reset(new char[ChildExecPath.size() + 1]);
933 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
934 ChildPath[ChildExecPath.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000935 std::string ChildInStr = utostr(PipeFD[0][0]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000936 ChildIn.reset(new char[ChildInStr.size() + 1]);
937 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
938 ChildIn[ChildInStr.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000939 std::string ChildOutStr = utostr(PipeFD[1][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000940 ChildOut.reset(new char[ChildOutStr.size() + 1]);
941 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
942 ChildOut[ChildOutStr.size()] = '\0';
943 }
944
945 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
946 int rc = execv(ChildExecPath.c_str(), args);
947 if (rc != 0)
948 perror("Error executing child process: ");
949 llvm_unreachable("Error executing child process");
950 }
951 // else we're the parent...
952
953 // Close the child ends of the pipes
954 close(PipeFD[0][0]);
955 close(PipeFD[1][1]);
956
957 // Return an RPC channel connected to our end of the pipes.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000958 return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000959#endif
960}