blob: 904a9e5830acf135d9b01622cd1ddf6526564acd [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
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/LLVMContext.h"
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +000017#include "RemoteMemoryManager.h"
Jim Grosbach0f435d02012-09-05 16:50:34 +000018#include "RemoteTarget.h"
Alp Tokerce4ab592014-01-23 19:57:16 +000019#include "RemoteTargetExternal.h"
Duncan Sands3bd97fe2010-08-28 01:30:02 +000020#include "llvm/ADT/Triple.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000021#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner5af6a3f2006-08-01 22:34:35 +000022#include "llvm/CodeGen/LinkAllCodegenComponents.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"
25#include "llvm/ExecutionEngine/JIT.h"
26#include "llvm/ExecutionEngine/JITEventListener.h"
Jim Grosbachbf570b92012-01-11 21:12:51 +000027#include "llvm/ExecutionEngine/JITMemoryManager.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000028#include "llvm/ExecutionEngine/MCJIT.h"
Lang Hames173c69f2014-01-08 04:09:09 +000029#include "llvm/ExecutionEngine/ObjectCache.h"
Andrew Kaylor58365b92012-11-27 19:49:00 +000030#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000031#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000034#include "llvm/IR/TypeBuilder.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000035#include "llvm/IRReader/IRReader.h"
Lang Hames173c69f2014-01-08 04:09:09 +000036#include "llvm/Object/Archive.h"
37#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000038#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000039#include "llvm/Support/Debug.h"
40#include "llvm/Support/DynamicLibrary.h"
41#include "llvm/Support/Format.h"
Chris Lattner76d46322006-12-06 01:18:01 +000042#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Support/MathExtras.h"
44#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000045#include "llvm/Support/MemoryBuffer.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000046#include "llvm/Support/PluginLoader.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000047#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000048#include "llvm/Support/Process.h"
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000049#include "llvm/Support/Program.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000050#include "llvm/Support/Signals.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000051#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000052#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000053#include "llvm/Support/raw_ostream.h"
Daniel Maleaa960c542013-06-28 19:11:40 +000054#include "llvm/Transforms/Instrumentation.h"
Chris Lattner4c522b92007-04-27 17:02:33 +000055#include <cerrno>
NAKAMURA Takumi15304872010-10-22 14:53:59 +000056
57#ifdef __CYGWIN__
58#include <cygwin/version.h>
59#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
60#define DO_NOTHING_ATEXIT 1
61#endif
62#endif
63
Brian Gaeke960707c2003-11-11 22:41:34 +000064using namespace llvm;
65
Chandler Carruthf98597a2014-04-22 03:10:36 +000066#define DEBUG_TYPE "lli"
67
Chris Lattnera0d7b082002-12-23 23:59:41 +000068namespace {
69 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000070 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000071
Chris Lattnera0d7b082002-12-23 23:59:41 +000072 cl::list<std::string>
73 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000074
Chris Lattnera0d7b082002-12-23 23:59:41 +000075 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000076 cl::desc("Force interpretation: disable JIT"),
77 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000078
Daniel Dunbar70ff8b02010-11-17 16:06:37 +000079 cl::opt<bool> UseMCJIT(
80 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
81 cl::init(false));
82
Daniel Maleaa960c542013-06-28 19:11:40 +000083 cl::opt<bool> DebugIR(
84 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
85 cl::init(false));
86
Jim Grosbach0f435d02012-09-05 16:50:34 +000087 // The MCJIT supports building for a target address space separate from
88 // the JIT compilation process. Use a forked process and a copying
89 // memory manager with IPC to execute using this functionality.
90 cl::opt<bool> RemoteMCJIT("remote-mcjit",
91 cl::desc("Execute MCJIT'ed code in a separate process."),
92 cl::init(false));
93
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000094 // Manually specify the child process for remote execution. This overrides
95 // the simulated remote execution that allocates address space for child
Andrew Kaylor89352582013-10-29 01:33:14 +000096 // execution. The child process will be executed and will communicate with
97 // lli via stdin/stdout pipes.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000098 cl::opt<std::string>
Alp Tokera1186382014-01-22 21:52:35 +000099 ChildExecPath("mcjit-remote-process",
100 cl::desc("Specify the filename of the process to launch "
101 "for remote MCJIT execution. If none is specified,"
102 "\n\tremote execution will be simulated in-process."),
103 cl::value_desc("filename"), cl::init(""));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000104
Evan Cheng09bd0b12009-05-04 23:05:19 +0000105 // Determine optimization level.
106 cl::opt<char>
107 OptLevel("O",
108 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
109 "(default = '-O2')"),
110 cl::Prefix,
111 cl::ZeroOrMore,
112 cl::init(' '));
Evan Cheng06d988e2008-08-08 08:12:06 +0000113
Chris Lattner76766cb2005-12-16 05:00:21 +0000114 cl::opt<std::string>
Chris Lattner78e9e102005-12-16 05:19:18 +0000115 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Cheng61582542008-11-05 23:21:52 +0000116
117 cl::opt<std::string>
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000118 MArch("march",
119 cl::desc("Architecture to generate assembly for (see --version)"));
120
121 cl::opt<std::string>
122 MCPU("mcpu",
123 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
124 cl::value_desc("cpu-name"),
125 cl::init(""));
126
127 cl::list<std::string>
128 MAttrs("mattr",
129 cl::CommaSeparated,
130 cl::desc("Target specific attributes (-mattr=help for details)"),
131 cl::value_desc("a1,+a2,-a3,..."));
132
133 cl::opt<std::string>
Evan Cheng61582542008-11-05 23:21:52 +0000134 EntryFunc("entry-function",
135 cl::desc("Specify the entry function (default = 'main') "
136 "of the executable"),
137 cl::value_desc("function"),
138 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000139
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000140 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000141 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000142 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000143 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000144
Lang Hames173c69f2014-01-08 04:09:09 +0000145 cl::list<std::string>
146 ExtraObjects("extra-object",
147 cl::desc("Extra object files to be loaded"),
148 cl::value_desc("input object"));
149
150 cl::list<std::string>
151 ExtraArchives("extra-archive",
152 cl::desc("Extra archive files to be loaded"),
153 cl::value_desc("input archive"));
154
155 cl::opt<bool>
156 EnableCacheManager("enable-cache-manager",
Lang Hames1ddecc02014-01-09 05:24:05 +0000157 cl::desc("Use cache manager to save/load mdoules"),
Lang Hames173c69f2014-01-08 04:09:09 +0000158 cl::init(false));
159
Chris Lattner55644062003-10-28 22:51:44 +0000160 cl::opt<std::string>
Lang Hames1ddecc02014-01-09 05:24:05 +0000161 ObjectCacheDir("object-cache-dir",
162 cl::desc("Directory to store cached object files "
163 "(must be user writable)"),
164 cl::init(""));
165
166 cl::opt<std::string>
Chris Lattner55644062003-10-28 22:51:44 +0000167 FakeArgv0("fake-argv0",
168 cl::desc("Override the 'argv[0]' value passed into the executing"
169 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000170
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000171 cl::opt<bool>
172 DisableCoreFiles("disable-core-files", cl::Hidden,
173 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000174
175 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000176 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000177 cl::desc("Disable JIT lazy compilation"),
178 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000179
180 cl::opt<Reloc::Model>
181 RelocModel("relocation-model",
182 cl::desc("Choose relocation model"),
183 cl::init(Reloc::Default),
184 cl::values(
185 clEnumValN(Reloc::Default, "default",
186 "Target default relocation model"),
187 clEnumValN(Reloc::Static, "static",
188 "Non-relocatable code"),
189 clEnumValN(Reloc::PIC_, "pic",
190 "Fully relocatable, position independent code"),
191 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
192 "Relocatable external references, non-relocatable code"),
193 clEnumValEnd));
Evan Chengefd9b422011-07-20 07:51:56 +0000194
195 cl::opt<llvm::CodeModel::Model>
196 CMModel("code-model",
197 cl::desc("Choose code model"),
198 cl::init(CodeModel::JITDefault),
199 cl::values(clEnumValN(CodeModel::JITDefault, "default",
200 "Target default JIT code model"),
201 clEnumValN(CodeModel::Small, "small",
202 "Small code model"),
203 clEnumValN(CodeModel::Kernel, "kernel",
204 "Kernel code model"),
205 clEnumValN(CodeModel::Medium, "medium",
206 "Medium code model"),
207 clEnumValN(CodeModel::Large, "large",
208 "Large code model"),
209 clEnumValEnd));
210
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000211 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000212 GenerateSoftFloatCalls("soft-float",
213 cl::desc("Generate software floating point library calls"),
214 cl::init(false));
215
216 cl::opt<llvm::FloatABI::ABIType>
217 FloatABIForCalls("float-abi",
218 cl::desc("Choose float ABI type"),
219 cl::init(FloatABI::Default),
220 cl::values(
221 clEnumValN(FloatABI::Default, "default",
222 "Target default float ABI type"),
223 clEnumValN(FloatABI::Soft, "soft",
224 "Soft float ABI (implied by -soft-float)"),
225 clEnumValN(FloatABI::Hard, "hard",
226 "Hard float ABI (uses FP registers)"),
227 clEnumValEnd));
228 cl::opt<bool>
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000229// In debug builds, make this default to true.
230#ifdef NDEBUG
231#define EMIT_DEBUG false
232#else
233#define EMIT_DEBUG true
234#endif
235 EmitJitDebugInfo("jit-emit-debug",
236 cl::desc("Emit debug information to debugger"),
237 cl::init(EMIT_DEBUG));
238#undef EMIT_DEBUG
239
240 static cl::opt<bool>
241 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
242 cl::Hidden,
243 cl::desc("Emit debug info objfiles to disk"),
244 cl::init(false));
Chris Lattnera0d7b082002-12-23 23:59:41 +0000245}
Chris Lattner009f8102001-10-27 08:43:52 +0000246
Lang Hames173c69f2014-01-08 04:09:09 +0000247//===----------------------------------------------------------------------===//
248// Object cache
249//
Lang Hames1ddecc02014-01-09 05:24:05 +0000250// This object cache implementation writes cached objects to disk to the
251// directory specified by CacheDir, using a filename provided in the module
252// descriptor. The cache tries to load a saved object using that path if the
253// file exists. CacheDir defaults to "", in which case objects are cached
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000254// alongside their originating bitcodes.
Lang Hames173c69f2014-01-08 04:09:09 +0000255//
256class LLIObjectCache : public ObjectCache {
257public:
Lang Hames1ddecc02014-01-09 05:24:05 +0000258 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
259 // Add trailing '/' to cache dir if necessary.
Lang Hamesf9dd8fd2014-01-09 05:29:59 +0000260 if (!this->CacheDir.empty() &&
261 this->CacheDir[this->CacheDir.size() - 1] != '/')
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000262 this->CacheDir += '/';
Lang Hames1ddecc02014-01-09 05:24:05 +0000263 }
Lang Hames173c69f2014-01-08 04:09:09 +0000264 virtual ~LLIObjectCache() {}
265
Craig Toppere56917c2014-03-08 08:27:28 +0000266 void notifyObjectCompiled(const Module *M, const MemoryBuffer *Obj) override {
Lang Hames173c69f2014-01-08 04:09:09 +0000267 const std::string ModuleID = M->getModuleIdentifier();
268 std::string CacheName;
269 if (!getCacheFilename(ModuleID, CacheName))
270 return;
Lang Hameseecd2dc2014-01-09 00:47:54 +0000271 std::string errStr;
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000272 if (!CacheDir.empty()) { // Create user-defined cache dir.
273 SmallString<128> dir(CacheName);
274 sys::path::remove_filename(dir);
275 sys::fs::create_directories(Twine(dir));
276 }
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000277 raw_fd_ostream outfile(CacheName.c_str(), errStr, sys::fs::F_None);
Lang Hames173c69f2014-01-08 04:09:09 +0000278 outfile.write(Obj->getBufferStart(), Obj->getBufferSize());
279 outfile.close();
280 }
281
Craig Toppere56917c2014-03-08 08:27:28 +0000282 MemoryBuffer* getObject(const Module* M) override {
Lang Hames173c69f2014-01-08 04:09:09 +0000283 const std::string ModuleID = M->getModuleIdentifier();
284 std::string CacheName;
285 if (!getCacheFilename(ModuleID, CacheName))
286 return NULL;
287 // Load the object from the cache filename
Ahmed Charles56440fd2014-03-06 05:51:42 +0000288 std::unique_ptr<MemoryBuffer> IRObjectBuffer;
Lang Hames173c69f2014-01-08 04:09:09 +0000289 MemoryBuffer::getFile(CacheName.c_str(), IRObjectBuffer, -1, false);
290 // If the file isn't there, that's OK.
291 if (!IRObjectBuffer)
292 return NULL;
293 // MCJIT will want to write into this buffer, and we don't want that
294 // because the file has probably just been mmapped. Instead we make
295 // a copy. The filed-based buffer will be released when it goes
296 // out of scope.
297 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer->getBuffer());
298 }
299
300private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000301 std::string CacheDir;
302
Lang Hames173c69f2014-01-08 04:09:09 +0000303 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
304 std::string Prefix("file:");
305 size_t PrefixLength = Prefix.length();
306 if (ModID.substr(0, PrefixLength) != Prefix)
307 return false;
NAKAMURA Takumid7fd6d92014-01-10 10:38:40 +0000308 std::string CacheSubdir = ModID.substr(PrefixLength);
309#if defined(_WIN32)
310 // Transform "X:\foo" => "/X\foo" for convenience.
311 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
312 CacheSubdir[1] = CacheSubdir[0];
313 CacheSubdir[0] = '/';
314 }
315#endif
316 CacheName = CacheDir + CacheSubdir;
Lang Hames173c69f2014-01-08 04:09:09 +0000317 size_t pos = CacheName.rfind('.');
318 CacheName.replace(pos, CacheName.length() - pos, ".o");
319 return true;
320 }
321};
322
Reid Spencere586f2e2007-03-03 18:21:44 +0000323static ExecutionEngine *EE = 0;
Lang Hames173c69f2014-01-08 04:09:09 +0000324static LLIObjectCache *CacheManager = 0;
Reid Spencere586f2e2007-03-03 18:21:44 +0000325
326static void do_shutdown() {
NAKAMURA Takumi15304872010-10-22 14:53:59 +0000327 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
328#ifndef DO_NOTHING_ATEXIT
Reid Spencere586f2e2007-03-03 18:21:44 +0000329 delete EE;
Lang Hames173c69f2014-01-08 04:09:09 +0000330 if (CacheManager)
331 delete CacheManager;
Reid Spencere586f2e2007-03-03 18:21:44 +0000332 llvm_shutdown();
NAKAMURA Takumi15304872010-10-22 14:53:59 +0000333#endif
Reid Spencere586f2e2007-03-03 18:21:44 +0000334}
335
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000336// On Mingw and Cygwin, an external symbol named '__main' is called from the
337// generated 'main' function to allow static intialization. To avoid linking
338// problems with remote targets (because lli's remote target support does not
339// currently handle external linking) we add a secondary module which defines
340// an empty '__main' function.
341static void addCygMingExtraModule(ExecutionEngine *EE,
342 LLVMContext &Context,
343 StringRef TargetTripleStr) {
344 IRBuilder<> Builder(Context);
345 Triple TargetTriple(TargetTripleStr);
346
347 // Create a new module.
348 Module *M = new Module("CygMingHelper", Context);
349 M->setTargetTriple(TargetTripleStr);
350
351 // Create an empty function named "__main".
352 Function *Result;
353 if (TargetTriple.isArch64Bit()) {
354 Result = Function::Create(
355 TypeBuilder<int64_t(void), false>::get(Context),
356 GlobalValue::ExternalLinkage, "__main", M);
357 } else {
358 Result = Function::Create(
359 TypeBuilder<int32_t(void), false>::get(Context),
360 GlobalValue::ExternalLinkage, "__main", M);
361 }
362 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
363 Builder.SetInsertPoint(BB);
364 Value *ReturnVal;
365 if (TargetTriple.isArch64Bit())
366 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
367 else
368 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
369 Builder.CreateRet(ReturnVal);
370
371 // Add this new module to the ExecutionEngine.
372 EE->addModule(M);
373}
374
375
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000376//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000377// main Driver function
378//
Misha Brukman5b255e52003-10-14 21:39:53 +0000379int main(int argc, char **argv, char * const *envp) {
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000380 sys::PrintStackTraceOnErrorSignal();
381 PrettyStackTraceProgram X(argc, argv);
Eli Bendersky4c647582012-01-16 08:56:09 +0000382
Owen Anderson19251ec2009-07-15 22:16:10 +0000383 LLVMContext &Context = getGlobalContext();
Reid Spencere586f2e2007-03-03 18:21:44 +0000384 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000385
386 // If we have a native target, initialize it to ensure it is linked in and
387 // usable by the JIT.
388 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000389 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000390 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000391
Chris Lattner2785bdb2007-05-06 04:58:26 +0000392 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000393 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000394
Chris Lattner2785bdb2007-05-06 04:58:26 +0000395 // If the user doesn't want core files, disable them.
396 if (DisableCoreFiles)
397 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000398
Gabor Greife16561c2007-07-05 17:07:56 +0000399 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000400 SMDiagnostic Err;
401 Module *Mod = ParseIRFile(InputFile, Err, Context);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000402 if (!Mod) {
Chris Lattnera3a06812011-10-16 04:47:35 +0000403 Err.print(argv[0], errs());
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000404 return 1;
Chris Lattner2785bdb2007-05-06 04:58:26 +0000405 }
406
Lang Hames173c69f2014-01-08 04:09:09 +0000407 if (EnableCacheManager) {
408 if (UseMCJIT) {
409 std::string CacheName("file:");
410 CacheName.append(InputFile);
411 Mod->setModuleIdentifier(CacheName);
412 } else
413 errs() << "warning: -enable-cache-manager can only be used with MCJIT.";
414 }
415
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000416 // If not jitting lazily, load the whole bitcode file eagerly too.
417 if (NoLazyCompilation) {
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000418 if (error_code EC = Mod->materializeAllPermanently()) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000419 errs() << argv[0] << ": bitcode didn't read correctly.\n";
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000420 errs() << "Reason: " << EC.message() << "\n";
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000421 exit(1);
422 }
Evan Cheng0422bef2008-04-22 06:51:41 +0000423 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000424
Daniel Maleaa960c542013-06-28 19:11:40 +0000425 if (DebugIR) {
426 if (!UseMCJIT) {
427 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
428 << " information will be emitted by the non-MC JIT engine. To see full"
429 << " source debug information, enable the flag '-use-mcjit'.\n";
430
431 }
432 ModulePass *DebugIRPass = createDebugIRPass();
433 DebugIRPass->runOnModule(*Mod);
434 }
435
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000436 std::string ErrorMsg;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000437 EngineBuilder builder(Mod);
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000438 builder.setMArch(MArch);
439 builder.setMCPU(MCPU);
440 builder.setMAttrs(MAttrs);
Evan Cheng2129f592011-07-19 06:37:02 +0000441 builder.setRelocationModel(RelocModel);
Evan Chengefd9b422011-07-20 07:51:56 +0000442 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000443 builder.setErrorStr(&ErrorMsg);
444 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000445 ? EngineKind::Interpreter
446 : EngineKind::JIT);
447
Chris Lattner2785bdb2007-05-06 04:58:26 +0000448 // If we are supposed to override the target triple, do so now.
449 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000450 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000451
Eli Bendersky4c647582012-01-16 08:56:09 +0000452 // Enable MCJIT if desired.
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000453 RTDyldMemoryManager *RTDyldMM = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000454 if (UseMCJIT && !ForceInterpreter) {
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000455 builder.setUseMCJIT(true);
Jim Grosbach0f435d02012-09-05 16:50:34 +0000456 if (RemoteMCJIT)
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000457 RTDyldMM = new RemoteMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000458 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000459 RTDyldMM = new SectionMemoryManager();
460 builder.setMCJITMemoryManager(RTDyldMM);
Benjamin Kramer76004e62012-05-20 17:24:08 +0000461 } else {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000462 if (RemoteMCJIT) {
463 errs() << "error: Remote process execution requires -use-mcjit\n";
464 exit(1);
465 }
Benjamin Kramer76004e62012-05-20 17:24:08 +0000466 builder.setJITMemoryManager(ForceInterpreter ? 0 :
467 JITMemoryManager::CreateDefaultMemManager());
Eli Bendersky4c647582012-01-16 08:56:09 +0000468 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000469
Evan Cheng09bd0b12009-05-04 23:05:19 +0000470 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
471 switch (OptLevel) {
472 default:
Dan Gohmand8db3762009-07-15 16:35:29 +0000473 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng09bd0b12009-05-04 23:05:19 +0000474 return 1;
475 case ' ': break;
476 case '0': OLvl = CodeGenOpt::None; break;
Evan Cheng5a286382009-10-16 21:02:20 +0000477 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng09bd0b12009-05-04 23:05:19 +0000478 case '2': OLvl = CodeGenOpt::Default; break;
479 case '3': OLvl = CodeGenOpt::Aggressive; break;
480 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000481 builder.setOptLevel(OLvl);
482
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000483 TargetOptions Options;
484 Options.UseSoftFloat = GenerateSoftFloatCalls;
485 if (FloatABIForCalls != FloatABI::Default)
486 Options.FloatABIType = FloatABIForCalls;
487 if (GenerateSoftFloatCalls)
488 FloatABIForCalls = FloatABI::Soft;
489
Jim Grosbach0f435d02012-09-05 16:50:34 +0000490 // Remote target execution doesn't handle EH or debug registration.
491 if (!RemoteMCJIT) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000492 Options.JITEmitDebugInfo = EmitJitDebugInfo;
493 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
Jim Grosbach0f435d02012-09-05 16:50:34 +0000494 }
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000495
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000496 builder.setTargetOptions(Options);
497
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000498 EE = builder.create();
Chris Lattnerf840ed72009-07-07 18:31:09 +0000499 if (!EE) {
500 if (!ErrorMsg.empty())
Dan Gohmand8db3762009-07-15 16:35:29 +0000501 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000502 else
Dan Gohmand8db3762009-07-15 16:35:29 +0000503 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000504 exit(1);
505 }
506
Lang Hames173c69f2014-01-08 04:09:09 +0000507 if (EnableCacheManager) {
Lang Hames1ddecc02014-01-09 05:24:05 +0000508 CacheManager = new LLIObjectCache(ObjectCacheDir);
Lang Hames173c69f2014-01-08 04:09:09 +0000509 EE->setObjectCache(CacheManager);
510 }
511
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000512 // Load any additional modules specified on the command line.
513 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
514 Module *XMod = ParseIRFile(ExtraModules[i], Err, Context);
515 if (!XMod) {
516 Err.print(argv[0], errs());
517 return 1;
518 }
Lang Hames173c69f2014-01-08 04:09:09 +0000519 if (EnableCacheManager) {
520 if (UseMCJIT) {
521 std::string CacheName("file:");
522 CacheName.append(ExtraModules[i]);
523 XMod->setModuleIdentifier(CacheName);
524 }
525 // else, we already printed a warning above.
526 }
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000527 EE->addModule(XMod);
528 }
529
Lang Hames173c69f2014-01-08 04:09:09 +0000530 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Rafael Espindola51cc3602014-01-22 00:14:49 +0000531 ErrorOr<object::ObjectFile *> Obj =
532 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames173c69f2014-01-08 04:09:09 +0000533 if (!Obj) {
534 Err.print(argv[0], errs());
535 return 1;
536 }
Rafael Espindola51cc3602014-01-22 00:14:49 +0000537 EE->addObjectFile(Obj.get());
Lang Hames173c69f2014-01-08 04:09:09 +0000538 }
539
540 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000541 std::unique_ptr<MemoryBuffer> ArBuf;
Lang Hames173c69f2014-01-08 04:09:09 +0000542 error_code ec;
543 ec = MemoryBuffer::getFileOrSTDIN(ExtraArchives[i], ArBuf);
544 if (ec) {
545 Err.print(argv[0], errs());
546 return 1;
547 }
Ahmed Charles96c9d952014-03-05 10:19:29 +0000548 object::Archive *Ar = new object::Archive(ArBuf.release(), ec);
Lang Hames173c69f2014-01-08 04:09:09 +0000549 if (ec || !Ar) {
550 Err.print(argv[0], errs());
551 return 1;
552 }
553 EE->addArchive(Ar);
554 }
555
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000556 // If the target is Cygwin/MingW and we are generating remote code, we
557 // need an extra module to help out with linking.
558 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
559 addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
560 }
561
Eli Bendersky5262ad22012-03-13 08:33:15 +0000562 // The following functions have no effect if their respective profiling
563 // support wasn't enabled in the build configuration.
564 EE->RegisterJITEventListener(
565 JITEventListener::createOProfileJITEventListener());
566 EE->RegisterJITEventListener(
567 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000568
Jim Grosbach0f435d02012-09-05 16:50:34 +0000569 if (!NoLazyCompilation && RemoteMCJIT) {
570 errs() << "warning: remote mcjit does not support lazy compilation\n";
571 NoLazyCompilation = true;
572 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000573 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000574
Chris Lattner2785bdb2007-05-06 04:58:26 +0000575 // If the user specifically requested an argv[0] to pass into the program,
576 // do it now.
577 if (!FakeArgv0.empty()) {
578 InputFile = FakeArgv0;
579 } else {
580 // Otherwise, if there is a .bc suffix on the executable strip it off, it
581 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000582 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000583 InputFile.erase(InputFile.length() - 3);
584 }
585
586 // Add the module's name to the start of the vector of arguments to main().
587 InputArgv.insert(InputArgv.begin(), InputFile);
588
589 // Call the main function from M as if its signature were:
590 // int main (int argc, char **argv, const char **envp)
591 // using the contents of Args to determine argc & argv, and the contents of
592 // EnvVars to determine envp.
593 //
Evan Cheng61582542008-11-05 23:21:52 +0000594 Function *EntryFn = Mod->getFunction(EntryFunc);
595 if (!EntryFn) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000596 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000597 return -1;
598 }
599
Chris Lattner2785bdb2007-05-06 04:58:26 +0000600 // Reset errno to zero on entry to main.
601 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000602
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000603 int Result;
604
Andrew Kaylor58365b92012-11-27 19:49:00 +0000605 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000606 // If the program doesn't explicitly call exit, we will need the Exit
607 // function later on to make an explicit call, so get the function now.
608 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
609 Type::getInt32Ty(Context),
610 NULL);
611
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000612 // Run static constructors.
Andrew Kaylorea395922013-10-01 01:47:35 +0000613 if (UseMCJIT && !ForceInterpreter) {
614 // Give MCJIT a chance to apply relocations and set page permissions.
615 EE->finalizeObject();
616 }
617 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000618
Andrew Kaylorea395922013-10-01 01:47:35 +0000619 if (!UseMCJIT && NoLazyCompilation) {
620 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
621 Function *Fn = &*I;
622 if (Fn != EntryFn && !Fn->isDeclaration())
623 EE->getPointerToFunction(Fn);
624 }
Evan Cheng0422bef2008-04-22 06:51:41 +0000625 }
Evan Cheng0422bef2008-04-22 06:51:41 +0000626
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000627 // Trigger compilation separately so code regions that need to be
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000628 // invalidated will be known.
629 (void)EE->getPointerToFunction(EntryFn);
630 // Clear instruction cache before code will be executed.
631 if (RTDyldMM)
632 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
633
634 // Run main.
635 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
636
637 // Run static destructors.
638 EE->runStaticConstructorsDestructors(true);
639
640 // If the program didn't call exit explicitly, we should call it now.
641 // This ensures that any atexit handlers get called correctly.
642 if (Function *ExitF = dyn_cast<Function>(Exit)) {
643 std::vector<GenericValue> Args;
644 GenericValue ResultGV;
645 ResultGV.IntVal = APInt(32, Result);
646 Args.push_back(ResultGV);
647 EE->runFunction(ExitF, Args);
648 errs() << "ERROR: exit(" << Result << ") returned!\n";
649 abort();
650 } else {
651 errs() << "ERROR: exit defined with wrong prototype!\n";
652 abort();
653 }
654 } else {
655 // else == "if (RemoteMCJIT)"
656
657 // Remote target MCJIT doesn't (yet) support static constructors. No reason
658 // it couldn't. This is a limitation of the LLI implemantation, not the
659 // MCJIT itself. FIXME.
660 //
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000661 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
Jim Grosbach0f435d02012-09-05 16:50:34 +0000662 // Everything is prepared now, so lay out our program for the target
663 // address space, assign the section addresses to resolve any relocations,
664 // and send it to the target.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000665
Ahmed Charles56440fd2014-03-06 05:51:42 +0000666 std::unique_ptr<RemoteTarget> Target;
Alp Tokera1186382014-01-22 21:52:35 +0000667 if (!ChildExecPath.empty()) { // Remote execution on a child process
Alp Tokerce4ab592014-01-23 19:57:16 +0000668#ifndef LLVM_ON_UNIX
669 // FIXME: Remove this pointless fallback mode which causes tests to "pass"
670 // on platforms where they should XFAIL.
671 errs() << "Warning: host does not support external remote targets.\n"
672 << " Defaulting to simulated remote execution\n";
673 Target.reset(new RemoteTarget);
674#else
675 if (!sys::fs::can_execute(ChildExecPath)) {
676 errs() << "Unable to find usable child executable: '" << ChildExecPath
677 << "'\n";
678 return -1;
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000679 }
Alp Tokerce4ab592014-01-23 19:57:16 +0000680 Target.reset(new RemoteTargetExternal(ChildExecPath));
681#endif
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000682 } else {
683 // No child process name provided, use simulated remote execution.
Alp Tokerce4ab592014-01-23 19:57:16 +0000684 Target.reset(new RemoteTarget);
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000685 }
686
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000687 // Give the memory manager a pointer to our remote target interface object.
688 MM->setRemoteTarget(Target.get());
689
690 // Create the remote target.
Renato Golin695895c2014-01-14 22:43:43 +0000691 if (!Target->create()) {
692 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
693 return EXIT_FAILURE;
694 }
Jim Grosbach748b9472012-08-28 23:22:30 +0000695
Jim Grosbach0f435d02012-09-05 16:50:34 +0000696 // Since we're executing in a (at least simulated) remote address space,
697 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
698 // grab the function address directly here and tell the remote target
699 // to execute the function.
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000700 //
701 // Our memory manager will map generated code into the remote address
702 // space as it is loaded and copy the bits over during the finalizeMemory
703 // operation.
704 //
Jim Grosbach0f435d02012-09-05 16:50:34 +0000705 // FIXME: argv and envp handling.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000706 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
Jim Grosbach0f435d02012-09-05 16:50:34 +0000707
Tim Northover79ab7f72013-05-19 09:55:06 +0000708 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
709 << format("%llx", Entry) << "\n");
Jim Grosbach0f435d02012-09-05 16:50:34 +0000710
Renato Golin695895c2014-01-14 22:43:43 +0000711 if (!Target->executeCode(Entry, Result))
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000712 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
Jim Grosbach0f435d02012-09-05 16:50:34 +0000713
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000714 // Like static constructors, the remote target MCJIT support doesn't handle
715 // this yet. It could. FIXME.
716
717 // Stop the remote target
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000718 Target->stop();
Chris Lattner2785bdb2007-05-06 04:58:26 +0000719 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000720
Jim Grosbach0f435d02012-09-05 16:50:34 +0000721 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000722}