blob: fab7b3505b3e619ac96a372c0261149f0b2df30f [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//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner345353d2007-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 Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +00009//
Chris Lattner141ea3a2003-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 Edwinf011f282009-07-03 12:11:32 +000012// compiler, or through an interpreter if no JIT is available for this platform.
Chris Lattnerd7ff5782001-08-23 17:05:04 +000013//
14//===----------------------------------------------------------------------===//
15
Lang Hames9d7a2692016-01-11 16:35:55 +000016#include "RemoteJITUtils.h"
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +000017#include "llvm/ADT/StringExtras.h"
Duncan Sands3bd97fe2010-08-28 01:30:02 +000018#include "llvm/ADT/Triple.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000019#include "llvm/Bitcode/BitcodeReader.h"
David Blaikie4333f972018-04-11 18:49:37 +000020#include "llvm/CodeGen/CommandFlags.inc"
Chris Lattner5af6a3f2006-08-01 22:34:35 +000021#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Nico Weber432a3882018-04-30 14:59:11 +000022#include "llvm/Config/llvm-config.h"
Brian Gaekee99ca442003-09-05 19:42:34 +000023#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000024#include "llvm/ExecutionEngine/Interpreter.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000025#include "llvm/ExecutionEngine/JITEventListener.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000026#include "llvm/ExecutionEngine/MCJIT.h"
Lang Hames173c69f2014-01-08 04:09:09 +000027#include "llvm/ExecutionEngine/ObjectCache.h"
Lang Hames6a941342018-06-26 21:35:48 +000028#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
29#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"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000037#include "llvm/IR/TypeBuilder.h"
Lang Hamesadae9bf2018-07-02 22:30:18 +000038#include "llvm/IR/Verifier.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000039#include "llvm/IRReader/IRReader.h"
Lang Hames173c69f2014-01-08 04:09:09 +000040#include "llvm/Object/Archive.h"
41#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000042#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/DynamicLibrary.h"
45#include "llvm/Support/Format.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000046#include "llvm/Support/InitLLVM.h"
Chris Lattner76d46322006-12-06 01:18:01 +000047#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000048#include "llvm/Support/MathExtras.h"
49#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000050#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000051#include "llvm/Support/Path.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/Support/PluginLoader.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000053#include "llvm/Support/Process.h"
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000054#include "llvm/Support/Program.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000055#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000056#include "llvm/Support/TargetSelect.h"
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +000057#include "llvm/Support/WithColor.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000058#include "llvm/Support/raw_ostream.h"
Daniel Maleaa960c542013-06-28 19:11:40 +000059#include "llvm/Transforms/Instrumentation.h"
Chris Lattner4c522b92007-04-27 17:02:33 +000060#include <cerrno>
NAKAMURA Takumi15304872010-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 Gaeke960707c2003-11-11 22:41:34 +000069using namespace llvm;
70
Chandler Carruthf98597a2014-04-22 03:10:36 +000071#define DEBUG_TYPE "lli"
72
Chris Lattnera0d7b082002-12-23 23:59:41 +000073namespace {
Lang Hames9528bba2015-03-25 12:11:48 +000074
75 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
76
Chris Lattnera0d7b082002-12-23 23:59:41 +000077 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000078 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000079
Chris Lattnera0d7b082002-12-23 23:59:41 +000080 cl::list<std::string>
81 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000082
Chris Lattnera0d7b082002-12-23 23:59:41 +000083 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000084 cl::desc("Force interpretation: disable JIT"),
85 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000086
Lang Hames9528bba2015-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 Amini732afdd2016-10-08 19:41:06 +000098 "Orc-based lazy JIT.")));
Lang Hames93de2a12015-01-23 21:25:00 +000099
Lang Hamesf0a3fd882018-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
Jim Grosbach0f435d02012-09-05 16:50:34 +0000111 // The MCJIT supports building for a target address space separate from
112 // the JIT compilation process. Use a forked process and a copying
113 // memory manager with IPC to execute using this functionality.
114 cl::opt<bool> RemoteMCJIT("remote-mcjit",
115 cl::desc("Execute MCJIT'ed code in a separate process."),
116 cl::init(false));
117
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000118 // Manually specify the child process for remote execution. This overrides
119 // the simulated remote execution that allocates address space for child
Andrew Kaylor89352582013-10-29 01:33:14 +0000120 // execution. The child process will be executed and will communicate with
121 // lli via stdin/stdout pipes.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000122 cl::opt<std::string>
Alp Tokera1186382014-01-22 21:52:35 +0000123 ChildExecPath("mcjit-remote-process",
124 cl::desc("Specify the filename of the process to launch "
125 "for remote MCJIT execution. If none is specified,"
126 "\n\tremote execution will be simulated in-process."),
127 cl::value_desc("filename"), cl::init(""));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000128
Evan Cheng09bd0b12009-05-04 23:05:19 +0000129 // Determine optimization level.
130 cl::opt<char>
131 OptLevel("O",
132 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
133 "(default = '-O2')"),
134 cl::Prefix,
135 cl::ZeroOrMore,
136 cl::init(' '));
Evan Cheng06d988e2008-08-08 08:12:06 +0000137
Chris Lattner76766cb2005-12-16 05:00:21 +0000138 cl::opt<std::string>
Chris Lattner78e9e102005-12-16 05:19:18 +0000139 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Cheng61582542008-11-05 23:21:52 +0000140
141 cl::opt<std::string>
142 EntryFunc("entry-function",
143 cl::desc("Specify the entry function (default = 'main') "
144 "of the executable"),
145 cl::value_desc("function"),
146 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000147
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000148 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000149 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000150 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000151 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000152
Lang Hames173c69f2014-01-08 04:09:09 +0000153 cl::list<std::string>
154 ExtraObjects("extra-object",
155 cl::desc("Extra object files to be loaded"),
156 cl::value_desc("input object"));
157
158 cl::list<std::string>
159 ExtraArchives("extra-archive",
160 cl::desc("Extra archive files to be loaded"),
161 cl::value_desc("input archive"));
162
163 cl::opt<bool>
164 EnableCacheManager("enable-cache-manager",
Lang Hames1ddecc02014-01-09 05:24:05 +0000165 cl::desc("Use cache manager to save/load mdoules"),
Lang Hames173c69f2014-01-08 04:09:09 +0000166 cl::init(false));
167
Chris Lattner55644062003-10-28 22:51:44 +0000168 cl::opt<std::string>
Lang Hames1ddecc02014-01-09 05:24:05 +0000169 ObjectCacheDir("object-cache-dir",
170 cl::desc("Directory to store cached object files "
171 "(must be user writable)"),
172 cl::init(""));
173
174 cl::opt<std::string>
Chris Lattner55644062003-10-28 22:51:44 +0000175 FakeArgv0("fake-argv0",
176 cl::desc("Override the 'argv[0]' value passed into the executing"
177 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000178
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000179 cl::opt<bool>
180 DisableCoreFiles("disable-core-files", cl::Hidden,
181 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000182
183 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000184 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000185 cl::desc("Disable JIT lazy compilation"),
186 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000187
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000188 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000189 GenerateSoftFloatCalls("soft-float",
190 cl::desc("Generate software floating point library calls"),
191 cl::init(false));
192
Lang Hames6a941342018-06-26 21:35:48 +0000193 enum class DumpKind {
194 NoDump,
195 DumpFuncsToStdOut,
196 DumpModsToStdOut,
197 DumpModsToDisk
198 };
199
200 cl::opt<DumpKind> OrcDumpKind(
201 "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
202 cl::init(DumpKind::NoDump),
203 cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
204 "Don't dump anything."),
205 clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
206 "Dump function names to stdout."),
207 clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
208 "Dump modules to stdout."),
209 clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
210 "Dump modules to the current "
211 "working directory. (WARNING: "
212 "will overwrite existing files).")),
213 cl::Hidden);
214
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000215 ExitOnError ExitOnErr;
Chris Lattnera0d7b082002-12-23 23:59:41 +0000216}
Chris Lattner009f8102001-10-27 08:43:52 +0000217
Lang Hames173c69f2014-01-08 04:09:09 +0000218//===----------------------------------------------------------------------===//
219// Object cache
220//
Lang Hames1ddecc02014-01-09 05:24:05 +0000221// This object cache implementation writes cached objects to disk to the
222// directory specified by CacheDir, using a filename provided in the module
223// descriptor. The cache tries to load a saved object using that path if the
224// file exists. CacheDir defaults to "", in which case objects are cached
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000225// alongside their originating bitcodes.
Lang Hames173c69f2014-01-08 04:09:09 +0000226//
227class LLIObjectCache : public ObjectCache {
228public:
Lang Hames1ddecc02014-01-09 05:24:05 +0000229 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
230 // Add trailing '/' to cache dir if necessary.
Lang Hamesf9dd8fd2014-01-09 05:29:59 +0000231 if (!this->CacheDir.empty() &&
232 this->CacheDir[this->CacheDir.size() - 1] != '/')
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000233 this->CacheDir += '/';
Lang Hames1ddecc02014-01-09 05:24:05 +0000234 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000235 ~LLIObjectCache() override {}
Lang Hames173c69f2014-01-08 04:09:09 +0000236
Rafael Espindola48af1c22014-08-19 18:44:46 +0000237 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000238 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000239 std::string CacheName;
240 if (!getCacheFilename(ModuleID, CacheName))
241 return;
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000242 if (!CacheDir.empty()) { // Create user-defined cache dir.
Rafael Espindolaf662e002015-07-15 21:24:07 +0000243 SmallString<128> dir(sys::path::parent_path(CacheName));
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000244 sys::fs::create_directories(Twine(dir));
245 }
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000246 std::error_code EC;
247 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000248 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
Lang Hames173c69f2014-01-08 04:09:09 +0000249 outfile.close();
250 }
251
Rafael Espindola5f2bb7d2014-08-13 18:49:01 +0000252 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000253 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000254 std::string CacheName;
255 if (!getCacheFilename(ModuleID, CacheName))
Craig Toppere6cb63e2014-04-25 04:24:47 +0000256 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000257 // Load the object from the cache filename
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000258 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000259 MemoryBuffer::getFile(CacheName, -1, false);
Lang Hames173c69f2014-01-08 04:09:09 +0000260 // If the file isn't there, that's OK.
261 if (!IRObjectBuffer)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000262 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000263 // MCJIT will want to write into this buffer, and we don't want that
264 // because the file has probably just been mmapped. Instead we make
265 // a copy. The filed-based buffer will be released when it goes
266 // out of scope.
Rafael Espindola3560ff22014-08-27 20:03:13 +0000267 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
Lang Hames173c69f2014-01-08 04:09:09 +0000268 }
269
270private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000271 std::string CacheDir;
272
Lang Hames173c69f2014-01-08 04:09:09 +0000273 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
274 std::string Prefix("file:");
275 size_t PrefixLength = Prefix.length();
276 if (ModID.substr(0, PrefixLength) != Prefix)
277 return false;
NAKAMURA Takumid7fd6d92014-01-10 10:38:40 +0000278 std::string CacheSubdir = ModID.substr(PrefixLength);
279#if defined(_WIN32)
280 // Transform "X:\foo" => "/X\foo" for convenience.
281 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
282 CacheSubdir[1] = CacheSubdir[0];
283 CacheSubdir[0] = '/';
284 }
285#endif
286 CacheName = CacheDir + CacheSubdir;
Lang Hames173c69f2014-01-08 04:09:09 +0000287 size_t pos = CacheName.rfind('.');
288 CacheName.replace(pos, CacheName.length() - pos, ".o");
289 return true;
290 }
291};
292
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000293// On Mingw and Cygwin, an external symbol named '__main' is called from the
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000294// generated 'main' function to allow static initialization. To avoid linking
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000295// problems with remote targets (because lli's remote target support does not
296// currently handle external linking) we add a secondary module which defines
297// an empty '__main' function.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000298static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000299 StringRef TargetTripleStr) {
300 IRBuilder<> Builder(Context);
301 Triple TargetTriple(TargetTripleStr);
302
303 // Create a new module.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000304 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000305 M->setTargetTriple(TargetTripleStr);
306
307 // Create an empty function named "__main".
308 Function *Result;
309 if (TargetTriple.isArch64Bit()) {
310 Result = Function::Create(
311 TypeBuilder<int64_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000312 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000313 } else {
314 Result = Function::Create(
315 TypeBuilder<int32_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000316 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000317 }
318 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
319 Builder.SetInsertPoint(BB);
320 Value *ReturnVal;
321 if (TargetTriple.isArch64Bit())
322 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
323 else
324 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
325 Builder.CreateRet(ReturnVal);
326
327 // Add this new module to the ExecutionEngine.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000328 EE.addModule(std::move(M));
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000329}
330
Lang Hames1899d0c2015-06-09 02:43:27 +0000331CodeGenOpt::Level getOptLevel() {
332 switch (OptLevel) {
333 default:
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000334 WithColor::error(errs(), "lli") << "invalid optimization level.\n";
Lang Hames1899d0c2015-06-09 02:43:27 +0000335 exit(1);
336 case '0': return CodeGenOpt::None;
337 case '1': return CodeGenOpt::Less;
338 case ' ':
339 case '2': return CodeGenOpt::Default;
340 case '3': return CodeGenOpt::Aggressive;
341 }
342 llvm_unreachable("Unrecognized opt level.");
343}
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000344
Davide Italianoda8e6b22016-11-17 22:58:13 +0000345LLVM_ATTRIBUTE_NORETURN
346static void reportError(SMDiagnostic Err, const char *ProgName) {
347 Err.print(ProgName, errs());
348 exit(1);
349}
350
Lang Hames37a66412018-08-28 20:20:31 +0000351int runOrcLazyJIT(const char *ProgName);
Lang Hames6a941342018-06-26 21:35:48 +0000352
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000353//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000354// main Driver function
355//
Misha Brukman5b255e52003-10-14 21:39:53 +0000356int main(int argc, char **argv, char * const *envp) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000357 InitLLVM X(argc, argv);
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000358
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000359 if (argc > 1)
360 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
361
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000362 // If we have a native target, initialize it to ensure it is linked in and
363 // usable by the JIT.
364 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000365 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000366 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000367
Chris Lattner2785bdb2007-05-06 04:58:26 +0000368 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000369 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000370
Chris Lattner2785bdb2007-05-06 04:58:26 +0000371 // If the user doesn't want core files, disable them.
372 if (DisableCoreFiles)
373 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000374
Lang Hames37a66412018-08-28 20:20:31 +0000375 if (UseJITKind == JITKind::OrcLazy)
376 return runOrcLazyJIT(argv[0]);
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000377 else {
378 // Make sure nobody used an orc-lazy specific option accidentally.
379
380 if (LazyJITCompileThreads != 0) {
381 errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
382 exit(1);
383 }
384
385 if (!ThreadEntryPoints.empty()) {
386 errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
387 exit(1);
388 }
389 }
Lang Hames37a66412018-08-28 20:20:31 +0000390
Mehdi Aminia7de8202016-04-18 18:52:39 +0000391 LLVMContext Context;
392
Gabor Greife16561c2007-07-05 17:07:56 +0000393 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000394 SMDiagnostic Err;
Rafael Espindolad233b062014-08-26 17:29:46 +0000395 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000396 Module *Mod = Owner.get();
Davide Italianoda8e6b22016-11-17 22:58:13 +0000397 if (!Mod)
398 reportError(Err, argv[0]);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000399
Lang Hames173c69f2014-01-08 04:09:09 +0000400 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000401 std::string CacheName("file:");
402 CacheName.append(InputFile);
403 Mod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000404 }
405
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000406 // If not jitting lazily, load the whole bitcode file eagerly too.
407 if (NoLazyCompilation) {
Davide Italianob0e067b2016-11-09 21:30:33 +0000408 // Use *argv instead of argv[0] to work around a wrong GCC warning.
409 ExitOnError ExitOnErr(std::string(*argv) +
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000410 ": bitcode didn't read correctly: ");
411 ExitOnErr(Mod->materializeAll());
Evan Cheng0422bef2008-04-22 06:51:41 +0000412 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000413
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000414 std::string ErrorMsg;
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000415 EngineBuilder builder(std::move(Owner));
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000416 builder.setMArch(MArch);
Craig Topper243f20f2018-01-09 18:14:18 +0000417 builder.setMCPU(getCPUStr());
418 builder.setMAttrs(getFeatureList());
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000419 if (RelocModel.getNumOccurrences())
420 builder.setRelocationModel(RelocModel);
Rafael Espindola79e238a2017-08-03 02:16:21 +0000421 if (CMModel.getNumOccurrences())
422 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000423 builder.setErrorStr(&ErrorMsg);
424 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000425 ? EngineKind::Interpreter
426 : EngineKind::JIT);
Lang Hames9528bba2015-03-25 12:11:48 +0000427 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000428
Chris Lattner2785bdb2007-05-06 04:58:26 +0000429 // If we are supposed to override the target triple, do so now.
430 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000431 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000432
Eli Bendersky4c647582012-01-16 08:56:09 +0000433 // Enable MCJIT if desired.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000434 RTDyldMemoryManager *RTDyldMM = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000435 if (!ForceInterpreter) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000436 if (RemoteMCJIT)
Lang Hames9d7a2692016-01-11 16:35:55 +0000437 RTDyldMM = new ForwardingMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000438 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000439 RTDyldMM = new SectionMemoryManager();
Lang Hames4a5697e2014-12-03 00:51:19 +0000440
441 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
442 // RTDyldMM: We still use it below, even though we don't own it.
443 builder.setMCJITMemoryManager(
444 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
Lang Hames0f154902014-09-23 16:56:02 +0000445 } else if (RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000446 WithColor::error(errs(), argv[0])
447 << "remote process execution does not work with the interpreter.\n";
Lang Hames0f154902014-09-23 16:56:02 +0000448 exit(1);
Eli Bendersky4c647582012-01-16 08:56:09 +0000449 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000450
Lang Hames1899d0c2015-06-09 02:43:27 +0000451 builder.setOptLevel(getOptLevel());
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000452
David Blaikiec14bfec2017-11-27 19:43:58 +0000453 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000454 if (FloatABIForCalls != FloatABI::Default)
455 Options.FloatABIType = FloatABIForCalls;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000456
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000457 builder.setTargetOptions(Options);
458
Mehdi Aminia7de8202016-04-18 18:52:39 +0000459 std::unique_ptr<ExecutionEngine> EE(builder.create());
Chris Lattnerf840ed72009-07-07 18:31:09 +0000460 if (!EE) {
461 if (!ErrorMsg.empty())
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000462 WithColor::error(errs(), argv[0])
463 << "error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000464 else
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000465 WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000466 exit(1);
467 }
468
Mehdi Aminia7de8202016-04-18 18:52:39 +0000469 std::unique_ptr<LLIObjectCache> CacheManager;
Lang Hames173c69f2014-01-08 04:09:09 +0000470 if (EnableCacheManager) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000471 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
472 EE->setObjectCache(CacheManager.get());
Lang Hames173c69f2014-01-08 04:09:09 +0000473 }
474
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000475 // Load any additional modules specified on the command line.
476 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
Rafael Espindolad233b062014-08-26 17:29:46 +0000477 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000478 if (!XMod)
479 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000480 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000481 std::string CacheName("file:");
482 CacheName.append(ExtraModules[i]);
483 XMod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000484 }
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000485 EE->addModule(std::move(XMod));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000486 }
487
Lang Hames173c69f2014-01-08 04:09:09 +0000488 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000489 Expected<object::OwningBinary<object::ObjectFile>> Obj =
Rafael Espindola51cc3602014-01-22 00:14:49 +0000490 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames173c69f2014-01-08 04:09:09 +0000491 if (!Obj) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000492 // TODO: Actually report errors helpfully.
493 consumeError(Obj.takeError());
Davide Italianoda8e6b22016-11-17 22:58:13 +0000494 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000495 }
Rafael Espindola061beab2014-08-20 15:19:37 +0000496 object::OwningBinary<object::ObjectFile> &O = Obj.get();
Rafael Espindola7271c192014-08-26 21:04:04 +0000497 EE->addObjectFile(std::move(O));
Lang Hames173c69f2014-01-08 04:09:09 +0000498 }
499
500 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000501 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000502 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000503 if (!ArBufOrErr)
504 reportError(Err, argv[0]);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000505 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
Rafael Espindolae1923412014-08-01 18:31:17 +0000506
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000507 Expected<std::unique_ptr<object::Archive>> ArOrErr =
Rafael Espindola48af1c22014-08-19 18:44:46 +0000508 object::Archive::create(ArBuf->getMemBufferRef());
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000509 if (!ArOrErr) {
510 std::string Buf;
511 raw_string_ostream OS(Buf);
512 logAllUnhandledErrors(ArOrErr.takeError(), OS, "");
513 OS.flush();
514 errs() << Buf;
Davide Italiano86511442016-11-17 22:59:13 +0000515 exit(1);
Lang Hames173c69f2014-01-08 04:09:09 +0000516 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000517 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
518
519 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
520
521 EE->addArchive(std::move(OB));
Lang Hames173c69f2014-01-08 04:09:09 +0000522 }
523
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000524 // If the target is Cygwin/MingW and we are generating remote code, we
525 // need an extra module to help out with linking.
526 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000527 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000528 }
529
Eli Bendersky5262ad22012-03-13 08:33:15 +0000530 // The following functions have no effect if their respective profiling
531 // support wasn't enabled in the build configuration.
532 EE->RegisterJITEventListener(
533 JITEventListener::createOProfileJITEventListener());
534 EE->RegisterJITEventListener(
535 JITEventListener::createIntelJITEventListener());
Andres Freund376a3d32018-07-24 00:54:06 +0000536 if (!RemoteMCJIT)
537 EE->RegisterJITEventListener(
538 JITEventListener::createPerfJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000539
Jim Grosbach0f435d02012-09-05 16:50:34 +0000540 if (!NoLazyCompilation && RemoteMCJIT) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000541 WithColor::warning(errs(), argv[0])
542 << "remote mcjit does not support lazy compilation\n";
Jim Grosbach0f435d02012-09-05 16:50:34 +0000543 NoLazyCompilation = true;
544 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000545 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000546
Chris Lattner2785bdb2007-05-06 04:58:26 +0000547 // If the user specifically requested an argv[0] to pass into the program,
548 // do it now.
549 if (!FakeArgv0.empty()) {
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000550 InputFile = static_cast<std::string>(FakeArgv0);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000551 } else {
552 // Otherwise, if there is a .bc suffix on the executable strip it off, it
553 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000554 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000555 InputFile.erase(InputFile.length() - 3);
556 }
557
558 // Add the module's name to the start of the vector of arguments to main().
559 InputArgv.insert(InputArgv.begin(), InputFile);
560
561 // Call the main function from M as if its signature were:
562 // int main (int argc, char **argv, const char **envp)
563 // using the contents of Args to determine argc & argv, and the contents of
564 // EnvVars to determine envp.
565 //
Evan Cheng61582542008-11-05 23:21:52 +0000566 Function *EntryFn = Mod->getFunction(EntryFunc);
567 if (!EntryFn) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000568 WithColor::error(errs(), argv[0])
569 << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000570 return -1;
571 }
572
Chris Lattner2785bdb2007-05-06 04:58:26 +0000573 // Reset errno to zero on entry to main.
574 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000575
Lang Hames3fde6522016-04-18 19:55:43 +0000576 int Result = -1;
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000577
Lang Hames9d7a2692016-01-11 16:35:55 +0000578 // Sanity check use of remote-jit: LLI currently only supports use of the
579 // remote JIT on Unix platforms.
Lang Hames9d7a2692016-01-11 16:35:55 +0000580 if (RemoteMCJIT) {
581#ifndef LLVM_ON_UNIX
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000582 WithColor::warning(errs(), argv[0])
Jonas Devlieghere7b5fa242018-04-22 08:35:00 +0000583 << "host does not support external remote targets.\n";
584 WithColor::note() << "defaulting to local execution\n";
Lang Hames4b6e0212016-01-11 21:41:34 +0000585 return -1;
Lang Hames9d7a2692016-01-11 16:35:55 +0000586#else
587 if (ChildExecPath.empty()) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000588 WithColor::error(errs(), argv[0])
589 << "-remote-mcjit requires -mcjit-remote-process.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000590 exit(1);
591 } else if (!sys::fs::can_execute(ChildExecPath)) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000592 WithColor::error(errs(), argv[0])
593 << "unable to find usable child executable: '" << ChildExecPath
594 << "'\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000595 return -1;
596 }
597#endif
598 }
599
Andrew Kaylor58365b92012-11-27 19:49:00 +0000600 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000601 // If the program doesn't explicitly call exit, we will need the Exit
602 // function later on to make an explicit call, so get the function now.
603 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000604 Type::getInt32Ty(Context));
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000605
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000606 // Run static constructors.
Eric Christopher79cc1e32014-09-02 22:28:02 +0000607 if (!ForceInterpreter) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000608 // Give MCJIT a chance to apply relocations and set page permissions.
609 EE->finalizeObject();
610 }
611 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000612
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000613 // Trigger compilation separately so code regions that need to be
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000614 // invalidated will be known.
615 (void)EE->getPointerToFunction(EntryFn);
616 // Clear instruction cache before code will be executed.
617 if (RTDyldMM)
618 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
619
620 // Run main.
621 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
622
623 // Run static destructors.
624 EE->runStaticConstructorsDestructors(true);
625
626 // If the program didn't call exit explicitly, we should call it now.
627 // This ensures that any atexit handlers get called correctly.
628 if (Function *ExitF = dyn_cast<Function>(Exit)) {
629 std::vector<GenericValue> Args;
630 GenericValue ResultGV;
631 ResultGV.IntVal = APInt(32, Result);
632 Args.push_back(ResultGV);
633 EE->runFunction(ExitF, Args);
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000634 WithColor::error(errs(), argv[0]) << "exit(" << Result << ") returned!\n";
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000635 abort();
636 } else {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000637 WithColor::error(errs(), argv[0])
638 << "exit defined with wrong prototype!\n";
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000639 abort();
640 }
641 } else {
642 // else == "if (RemoteMCJIT)"
643
644 // Remote target MCJIT doesn't (yet) support static constructors. No reason
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000645 // it couldn't. This is a limitation of the LLI implementation, not the
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000646 // MCJIT itself. FIXME.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000647
Lang Hames9d7a2692016-01-11 16:35:55 +0000648 // Lanch the remote process and get a channel to it.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000649 std::unique_ptr<FDRawChannel> C = launchRemote();
Lang Hames9d7a2692016-01-11 16:35:55 +0000650 if (!C) {
Jonas Devlieghere4a2863c2018-04-22 08:02:11 +0000651 WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
Lang Hames9d7a2692016-01-11 16:35:55 +0000652 exit(1);
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000653 }
654
Lang Hames9d7a2692016-01-11 16:35:55 +0000655 // Create a remote target client running over the channel.
Lang Hamesbd0cb782018-05-30 01:57:45 +0000656 llvm::orc::ExecutionSession ES;
657 ES.setErrorReporter([&](Error Err) { ExitOnErr(std::move(Err)); });
Lang Hames9e68b7342017-09-04 20:54:46 +0000658 typedef orc::remote::OrcRemoteTargetClient MyRemote;
Lang Hamesbd0cb782018-05-30 01:57:45 +0000659 auto R = ExitOnErr(MyRemote::Create(*C, ES));
Jim Grosbach748b9472012-08-28 23:22:30 +0000660
Lang Hames9d7a2692016-01-11 16:35:55 +0000661 // Create a remote memory manager.
Lang Hames9e68b7342017-09-04 20:54:46 +0000662 auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
Lang Hames9d7a2692016-01-11 16:35:55 +0000663
664 // Forward MCJIT's memory manager calls to the remote memory manager.
665 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
666 std::move(RemoteMM));
667
668 // Forward MCJIT's symbol resolution calls to the remote.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000669 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
670 orc::createLambdaResolver(
671 [](const std::string &Name) { return nullptr; },
672 [&](const std::string &Name) {
673 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
674 return JITSymbol(Addr, JITSymbolFlags::Exported);
675 return JITSymbol(nullptr);
676 }));
Lang Hames9d7a2692016-01-11 16:35:55 +0000677
678 // Grab the target address of the JIT'd main function on the remote and call
679 // it.
Jim Grosbach0f435d02012-09-05 16:50:34 +0000680 // FIXME: argv and envp handling.
Lang Hamesad4a9112016-08-01 20:49:11 +0000681 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
Lang Hames9d7a2692016-01-11 16:35:55 +0000682 EE->finalizeObject();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000683 LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
684 << format("%llx", Entry) << "\n");
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000685 Result = ExitOnErr(R->callIntVoid(Entry));
Jim Grosbach0f435d02012-09-05 16:50:34 +0000686
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000687 // Like static constructors, the remote target MCJIT support doesn't handle
688 // this yet. It could. FIXME.
689
Lang Hames9d7a2692016-01-11 16:35:55 +0000690 // Delete the EE - we need to tear it down *before* we terminate the session
691 // with the remote, otherwise it'll crash when it tries to release resources
692 // on a remote that has already been disconnected.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000693 EE.reset();
Lang Hames9d7a2692016-01-11 16:35:55 +0000694
695 // Signal the remote target that we're done JITing.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000696 ExitOnErr(R->terminateSession());
Chris Lattner2785bdb2007-05-06 04:58:26 +0000697 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000698
Jim Grosbach0f435d02012-09-05 16:50:34 +0000699 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000700}
Lang Hames9d7a2692016-01-11 16:35:55 +0000701
Lang Hames6a941342018-06-26 21:35:48 +0000702static orc::IRTransformLayer2::TransformFunction createDebugDumper() {
703 switch (OrcDumpKind) {
704 case DumpKind::NoDump:
Lang Hames3e709d52018-09-28 21:49:53 +0000705 return [](orc::ThreadSafeModule TSM,
706 const orc::MaterializationResponsibility &R) { return TSM; };
Lang Hames6a941342018-06-26 21:35:48 +0000707
708 case DumpKind::DumpFuncsToStdOut:
Lang Hames3e709d52018-09-28 21:49:53 +0000709 return [](orc::ThreadSafeModule TSM,
710 const orc::MaterializationResponsibility &R) {
Lang Hames6a941342018-06-26 21:35:48 +0000711 printf("[ ");
712
Lang Hames8d76c712018-09-26 01:24:12 +0000713 for (const auto &F : *TSM.getModule()) {
Lang Hames6a941342018-06-26 21:35:48 +0000714 if (F.isDeclaration())
715 continue;
716
717 if (F.hasName()) {
718 std::string Name(F.getName());
719 printf("%s ", Name.c_str());
720 } else
721 printf("<anon> ");
722 }
723
724 printf("]\n");
Lang Hames8d76c712018-09-26 01:24:12 +0000725 return TSM;
Lang Hames6a941342018-06-26 21:35:48 +0000726 };
727
728 case DumpKind::DumpModsToStdOut:
Lang Hames3e709d52018-09-28 21:49:53 +0000729 return [](orc::ThreadSafeModule TSM,
730 const orc::MaterializationResponsibility &R) {
Lang Hames6a941342018-06-26 21:35:48 +0000731 outs() << "----- Module Start -----\n"
Lang Hames8d76c712018-09-26 01:24:12 +0000732 << *TSM.getModule() << "----- Module End -----\n";
Lang Hames6a941342018-06-26 21:35:48 +0000733
Lang Hames8d76c712018-09-26 01:24:12 +0000734 return TSM;
Lang Hames6a941342018-06-26 21:35:48 +0000735 };
736
737 case DumpKind::DumpModsToDisk:
Lang Hames3e709d52018-09-28 21:49:53 +0000738 return [](orc::ThreadSafeModule TSM,
739 const orc::MaterializationResponsibility &R) {
Lang Hames6a941342018-06-26 21:35:48 +0000740 std::error_code EC;
Lang Hames8d76c712018-09-26 01:24:12 +0000741 raw_fd_ostream Out(TSM.getModule()->getModuleIdentifier() + ".ll", EC,
742 sys::fs::F_Text);
Lang Hames6a941342018-06-26 21:35:48 +0000743 if (EC) {
Lang Hames8d76c712018-09-26 01:24:12 +0000744 errs() << "Couldn't open " << TSM.getModule()->getModuleIdentifier()
Lang Hames6a941342018-06-26 21:35:48 +0000745 << " for dumping.\nError:" << EC.message() << "\n";
746 exit(1);
747 }
Lang Hames8d76c712018-09-26 01:24:12 +0000748 Out << *TSM.getModule();
749 return TSM;
Lang Hames6a941342018-06-26 21:35:48 +0000750 };
751 }
752 llvm_unreachable("Unknown DumpKind");
753}
754
Lang Hames37a66412018-08-28 20:20:31 +0000755int runOrcLazyJIT(const char *ProgName) {
756 // Start setting up the JIT environment.
Lang Hames6a941342018-06-26 21:35:48 +0000757
Lang Hames37a66412018-08-28 20:20:31 +0000758 // First add lli's symbols into the JIT's search space.
Lang Hames6a941342018-06-26 21:35:48 +0000759 std::string ErrMsg;
760 sys::DynamicLibrary LibLLI =
761 sys::DynamicLibrary::getPermanentLibrary(nullptr, &ErrMsg);
762 if (!LibLLI.isValid()) {
763 errs() << "Error loading lli symbols: " << ErrMsg << ".\n";
764 return 1;
765 }
766
Lang Hames37a66412018-08-28 20:20:31 +0000767 // Parse the main module.
Lang Hames8d76c712018-09-26 01:24:12 +0000768 orc::ThreadSafeContext TSCtx(llvm::make_unique<LLVMContext>());
Lang Hames37a66412018-08-28 20:20:31 +0000769 SMDiagnostic Err;
Lang Hames8d76c712018-09-26 01:24:12 +0000770 auto MainModule = orc::ThreadSafeModule(
771 parseIRFile(InputFile, Err, *TSCtx.getContext()), TSCtx);
Lang Hames37a66412018-08-28 20:20:31 +0000772 if (!MainModule)
773 reportError(Err, ProgName);
774
Lang Hames8d76c712018-09-26 01:24:12 +0000775 const auto &TT = MainModule.getModule()->getTargetTriple();
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000776 orc::JITTargetMachineBuilder JTMB =
Lang Hames6a941342018-06-26 21:35:48 +0000777 TT.empty() ? ExitOnErr(orc::JITTargetMachineBuilder::detectHost())
778 : orc::JITTargetMachineBuilder(Triple(TT));
779
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000780 JTMB.setArch(MArch)
Lang Hames6a941342018-06-26 21:35:48 +0000781 .setCPU(getCPUStr())
782 .addFeatures(getFeatureList())
783 .setRelocationModel(RelocModel.getNumOccurrences()
784 ? Optional<Reloc::Model>(RelocModel)
785 : None)
786 .setCodeModel(CMModel.getNumOccurrences()
787 ? Optional<CodeModel::Model>(CMModel)
788 : None);
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000789 DataLayout DL("");
790 {
791 // Create a throwaway TargetMachine to get the data layout.
792 auto TM = ExitOnErr(JTMB.createTargetMachine());
793 DL = TM->createDataLayout();
794 }
795 auto J = ExitOnErr(orc::LLLazyJIT::Create(std::move(JTMB), DL, LazyJITCompileThreads));
Lang Hames6a941342018-06-26 21:35:48 +0000796
Lang Hamesadae9bf2018-07-02 22:30:18 +0000797 auto Dump = createDebugDumper();
798
Lang Hames3e709d52018-09-28 21:49:53 +0000799 J->setLazyCompileTransform([&](orc::ThreadSafeModule TSM,
800 const orc::MaterializationResponsibility &R) {
Lang Hames8d76c712018-09-26 01:24:12 +0000801 if (verifyModule(*TSM.getModule(), &dbgs())) {
802 dbgs() << "Bad module: " << *TSM.getModule() << "\n";
803 exit(1);
804 }
Lang Hames3e709d52018-09-28 21:49:53 +0000805 return Dump(std::move(TSM), R);
Lang Hames8d76c712018-09-26 01:24:12 +0000806 });
Lang Hamesd5f56c52018-08-17 21:18:18 +0000807 J->getMainJITDylib().setFallbackDefinitionGenerator(
Lang Hames6a941342018-06-26 21:35:48 +0000808 orc::DynamicLibraryFallbackGenerator(
809 std::move(LibLLI), DL, [](orc::SymbolStringPtr) { return true; }));
810
811 orc::MangleAndInterner Mangle(J->getExecutionSession(), DL);
812 orc::LocalCXXRuntimeOverrides2 CXXRuntimeOverrides;
Lang Hamesd5f56c52018-08-17 21:18:18 +0000813 ExitOnErr(CXXRuntimeOverrides.enable(J->getMainJITDylib(), Mangle));
Lang Hames6a941342018-06-26 21:35:48 +0000814
Lang Hames37a66412018-08-28 20:20:31 +0000815 // Add the main module.
816 ExitOnErr(J->addLazyIRModule(std::move(MainModule)));
817
818 // Add any extra modules.
819 for (auto &ModulePath : ExtraModules) {
Lang Hames8d76c712018-09-26 01:24:12 +0000820 auto M = parseIRFile(ModulePath, Err, *TSCtx.getContext());
Lang Hames37a66412018-08-28 20:20:31 +0000821 if (!M)
822 reportError(Err, ProgName);
823
Lang Hames8d76c712018-09-26 01:24:12 +0000824 ExitOnErr(J->addLazyIRModule(orc::ThreadSafeModule(std::move(M), TSCtx)));
Lang Hamesadae9bf2018-07-02 22:30:18 +0000825 }
Lang Hames6a941342018-06-26 21:35:48 +0000826
Lang Hames37a66412018-08-28 20:20:31 +0000827 // Add the objects.
828 for (auto &ObjPath : ExtraObjects) {
829 auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));
830 ExitOnErr(J->addObjectFile(std::move(Obj)));
831 }
832
833 // Generate a argument string.
834 std::vector<std::string> Args;
835 Args.push_back(InputFile);
836 for (auto &Arg : InputArgv)
837 Args.push_back(Arg);
838
839 // Run any static constructors.
Lang Hames6a941342018-06-26 21:35:48 +0000840 ExitOnErr(J->runConstructors());
841
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000842 // Run any -thread-entry points.
843 std::vector<std::thread> AltEntryThreads;
844 for (auto &ThreadEntryPoint : ThreadEntryPoints) {
845 auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));
846 typedef void (*EntryPointPtr)();
847 auto EntryPoint =
848 reinterpret_cast<EntryPointPtr>(static_cast<uintptr_t>(EntryPointSym.getAddress()));
849 AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));
850 }
851
Lang Hames37a66412018-08-28 20:20:31 +0000852 // Run main.
Lang Hames6a941342018-06-26 21:35:48 +0000853 auto MainSym = ExitOnErr(J->lookup("main"));
854 typedef int (*MainFnPtr)(int, const char *[]);
855 std::vector<const char *> ArgV;
856 for (auto &Arg : Args)
857 ArgV.push_back(Arg.c_str());
Lang Hames94fe9d42018-09-27 19:27:19 +0000858 ArgV.push_back(nullptr);
859
860 int ArgC = ArgV.size() - 1;
Lang Hames6a941342018-06-26 21:35:48 +0000861 auto Main =
862 reinterpret_cast<MainFnPtr>(static_cast<uintptr_t>(MainSym.getAddress()));
Lang Hames94fe9d42018-09-27 19:27:19 +0000863 auto Result = Main(ArgC, (const char **)ArgV.data());
Lang Hames6a941342018-06-26 21:35:48 +0000864
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000865 // Wait for -entry-point threads.
866 for (auto &AltEntryThread : AltEntryThreads)
867 AltEntryThread.join();
Hans Wennborg20b5abe2018-09-26 12:15:23 +0000868
Lang Hamesf0a3fd882018-09-26 16:26:59 +0000869 // Run destructors.
870 ExitOnErr(J->runDestructors());
Lang Hames6a941342018-06-26 21:35:48 +0000871 CXXRuntimeOverrides.runDestructors();
872
873 return Result;
874}
875
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000876std::unique_ptr<FDRawChannel> launchRemote() {
Lang Hames9d7a2692016-01-11 16:35:55 +0000877#ifndef LLVM_ON_UNIX
878 llvm_unreachable("launchRemote not supported on non-Unix platforms");
879#else
880 int PipeFD[2][2];
881 pid_t ChildPID;
882
883 // Create two pipes.
884 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
885 perror("Error creating pipe: ");
886
887 ChildPID = fork();
888
889 if (ChildPID == 0) {
890 // In the child...
891
892 // Close the parent ends of the pipes
893 close(PipeFD[0][1]);
894 close(PipeFD[1][0]);
895
896
897 // Execute the child process.
898 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
899 {
900 ChildPath.reset(new char[ChildExecPath.size() + 1]);
901 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
902 ChildPath[ChildExecPath.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000903 std::string ChildInStr = utostr(PipeFD[0][0]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000904 ChildIn.reset(new char[ChildInStr.size() + 1]);
905 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
906 ChildIn[ChildInStr.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000907 std::string ChildOutStr = utostr(PipeFD[1][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000908 ChildOut.reset(new char[ChildOutStr.size() + 1]);
909 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
910 ChildOut[ChildOutStr.size()] = '\0';
911 }
912
913 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
914 int rc = execv(ChildExecPath.c_str(), args);
915 if (rc != 0)
916 perror("Error executing child process: ");
917 llvm_unreachable("Error executing child process");
918 }
919 // else we're the parent...
920
921 // Close the child ends of the pipes
922 close(PipeFD[0][0]);
923 close(PipeFD[1][1]);
924
925 // Return an RPC channel connected to our end of the pipes.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000926 return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000927#endif
928}