blob: 9e0a78f66188e83239329f56db77c10ad2a42bc7 [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
Jim Grosbach0f435d02012-09-05 16:50:34 +000016#define DEBUG_TYPE "lli"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/LLVMContext.h"
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +000018#include "RemoteMemoryManager.h"
Jim Grosbach0f435d02012-09-05 16:50:34 +000019#include "RemoteTarget.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"
Andrew Kaylor58365b92012-11-27 19:49:00 +000029#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Module.h"
31#include "llvm/IR/Type.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000032#include "llvm/IRReader/IRReader.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000033#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/DynamicLibrary.h"
36#include "llvm/Support/Format.h"
Chris Lattner76d46322006-12-06 01:18:01 +000037#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Support/MathExtras.h"
39#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000040#include "llvm/Support/MemoryBuffer.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000041#include "llvm/Support/PluginLoader.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000042#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000043#include "llvm/Support/Process.h"
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000044#include "llvm/Support/Program.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000045#include "llvm/Support/Signals.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000046#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000047#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000048#include "llvm/Support/raw_ostream.h"
Daniel Maleaa960c542013-06-28 19:11:40 +000049#include "llvm/Transforms/Instrumentation.h"
Chris Lattner4c522b92007-04-27 17:02:33 +000050#include <cerrno>
NAKAMURA Takumi15304872010-10-22 14:53:59 +000051
52#ifdef __CYGWIN__
53#include <cygwin/version.h>
54#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
55#define DO_NOTHING_ATEXIT 1
56#endif
57#endif
58
Brian Gaeke960707c2003-11-11 22:41:34 +000059using namespace llvm;
60
Chris Lattnera0d7b082002-12-23 23:59:41 +000061namespace {
62 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000063 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000064
Chris Lattnera0d7b082002-12-23 23:59:41 +000065 cl::list<std::string>
66 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000067
Chris Lattnera0d7b082002-12-23 23:59:41 +000068 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000069 cl::desc("Force interpretation: disable JIT"),
70 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000071
Daniel Dunbar70ff8b02010-11-17 16:06:37 +000072 cl::opt<bool> UseMCJIT(
73 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
74 cl::init(false));
75
Daniel Maleaa960c542013-06-28 19:11:40 +000076 cl::opt<bool> DebugIR(
77 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
78 cl::init(false));
79
Jim Grosbach0f435d02012-09-05 16:50:34 +000080 // The MCJIT supports building for a target address space separate from
81 // the JIT compilation process. Use a forked process and a copying
82 // memory manager with IPC to execute using this functionality.
83 cl::opt<bool> RemoteMCJIT("remote-mcjit",
84 cl::desc("Execute MCJIT'ed code in a separate process."),
85 cl::init(false));
86
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000087 // Manually specify the child process for remote execution. This overrides
88 // the simulated remote execution that allocates address space for child
89 // execution. The child process resides in the disk and communicates with lli
90 // via stdin/stdout pipes.
91 cl::opt<std::string>
92 MCJITRemoteProcess("mcjit-remote-process",
93 cl::desc("Specify the filename of the process to launch "
94 "for remote MCJIT execution. If none is specified,"
95 "\n\tremote execution will be simulated in-process."),
96 cl::value_desc("filename"),
97 cl::init(""));
98
Evan Cheng09bd0b12009-05-04 23:05:19 +000099 // Determine optimization level.
100 cl::opt<char>
101 OptLevel("O",
102 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
103 "(default = '-O2')"),
104 cl::Prefix,
105 cl::ZeroOrMore,
106 cl::init(' '));
Evan Cheng06d988e2008-08-08 08:12:06 +0000107
Chris Lattner76766cb2005-12-16 05:00:21 +0000108 cl::opt<std::string>
Chris Lattner78e9e102005-12-16 05:19:18 +0000109 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Cheng61582542008-11-05 23:21:52 +0000110
111 cl::opt<std::string>
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000112 MArch("march",
113 cl::desc("Architecture to generate assembly for (see --version)"));
114
115 cl::opt<std::string>
116 MCPU("mcpu",
117 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
118 cl::value_desc("cpu-name"),
119 cl::init(""));
120
121 cl::list<std::string>
122 MAttrs("mattr",
123 cl::CommaSeparated,
124 cl::desc("Target specific attributes (-mattr=help for details)"),
125 cl::value_desc("a1,+a2,-a3,..."));
126
127 cl::opt<std::string>
Evan Cheng61582542008-11-05 23:21:52 +0000128 EntryFunc("entry-function",
129 cl::desc("Specify the entry function (default = 'main') "
130 "of the executable"),
131 cl::value_desc("function"),
132 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000133
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000134 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000135 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000136 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000137 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000138
Chris Lattner55644062003-10-28 22:51:44 +0000139 cl::opt<std::string>
140 FakeArgv0("fake-argv0",
141 cl::desc("Override the 'argv[0]' value passed into the executing"
142 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000143
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000144 cl::opt<bool>
145 DisableCoreFiles("disable-core-files", cl::Hidden,
146 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000147
148 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000149 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000150 cl::desc("Disable JIT lazy compilation"),
151 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000152
153 cl::opt<Reloc::Model>
154 RelocModel("relocation-model",
155 cl::desc("Choose relocation model"),
156 cl::init(Reloc::Default),
157 cl::values(
158 clEnumValN(Reloc::Default, "default",
159 "Target default relocation model"),
160 clEnumValN(Reloc::Static, "static",
161 "Non-relocatable code"),
162 clEnumValN(Reloc::PIC_, "pic",
163 "Fully relocatable, position independent code"),
164 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
165 "Relocatable external references, non-relocatable code"),
166 clEnumValEnd));
Evan Chengefd9b422011-07-20 07:51:56 +0000167
168 cl::opt<llvm::CodeModel::Model>
169 CMModel("code-model",
170 cl::desc("Choose code model"),
171 cl::init(CodeModel::JITDefault),
172 cl::values(clEnumValN(CodeModel::JITDefault, "default",
173 "Target default JIT code model"),
174 clEnumValN(CodeModel::Small, "small",
175 "Small code model"),
176 clEnumValN(CodeModel::Kernel, "kernel",
177 "Kernel code model"),
178 clEnumValN(CodeModel::Medium, "medium",
179 "Medium code model"),
180 clEnumValN(CodeModel::Large, "large",
181 "Large code model"),
182 clEnumValEnd));
183
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000184 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000185 GenerateSoftFloatCalls("soft-float",
186 cl::desc("Generate software floating point library calls"),
187 cl::init(false));
188
189 cl::opt<llvm::FloatABI::ABIType>
190 FloatABIForCalls("float-abi",
191 cl::desc("Choose float ABI type"),
192 cl::init(FloatABI::Default),
193 cl::values(
194 clEnumValN(FloatABI::Default, "default",
195 "Target default float ABI type"),
196 clEnumValN(FloatABI::Soft, "soft",
197 "Soft float ABI (implied by -soft-float)"),
198 clEnumValN(FloatABI::Hard, "hard",
199 "Hard float ABI (uses FP registers)"),
200 clEnumValEnd));
201 cl::opt<bool>
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000202// In debug builds, make this default to true.
203#ifdef NDEBUG
204#define EMIT_DEBUG false
205#else
206#define EMIT_DEBUG true
207#endif
208 EmitJitDebugInfo("jit-emit-debug",
209 cl::desc("Emit debug information to debugger"),
210 cl::init(EMIT_DEBUG));
211#undef EMIT_DEBUG
212
213 static cl::opt<bool>
214 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
215 cl::Hidden,
216 cl::desc("Emit debug info objfiles to disk"),
217 cl::init(false));
Chris Lattnera0d7b082002-12-23 23:59:41 +0000218}
Chris Lattner009f8102001-10-27 08:43:52 +0000219
Reid Spencere586f2e2007-03-03 18:21:44 +0000220static ExecutionEngine *EE = 0;
221
222static void do_shutdown() {
NAKAMURA Takumi15304872010-10-22 14:53:59 +0000223 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
224#ifndef DO_NOTHING_ATEXIT
Reid Spencere586f2e2007-03-03 18:21:44 +0000225 delete EE;
226 llvm_shutdown();
NAKAMURA Takumi15304872010-10-22 14:53:59 +0000227#endif
Reid Spencere586f2e2007-03-03 18:21:44 +0000228}
229
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000230//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000231// main Driver function
232//
Misha Brukman5b255e52003-10-14 21:39:53 +0000233int main(int argc, char **argv, char * const *envp) {
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000234 sys::PrintStackTraceOnErrorSignal();
235 PrettyStackTraceProgram X(argc, argv);
Eli Bendersky4c647582012-01-16 08:56:09 +0000236
Owen Anderson19251ec2009-07-15 22:16:10 +0000237 LLVMContext &Context = getGlobalContext();
Reid Spencere586f2e2007-03-03 18:21:44 +0000238 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000239
240 // If we have a native target, initialize it to ensure it is linked in and
241 // usable by the JIT.
242 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000243 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000244 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000245
Chris Lattner2785bdb2007-05-06 04:58:26 +0000246 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000247 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000248
Chris Lattner2785bdb2007-05-06 04:58:26 +0000249 // If the user doesn't want core files, disable them.
250 if (DisableCoreFiles)
251 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000252
Gabor Greife16561c2007-07-05 17:07:56 +0000253 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000254 SMDiagnostic Err;
255 Module *Mod = ParseIRFile(InputFile, Err, Context);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000256 if (!Mod) {
Chris Lattnera3a06812011-10-16 04:47:35 +0000257 Err.print(argv[0], errs());
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000258 return 1;
Chris Lattner2785bdb2007-05-06 04:58:26 +0000259 }
260
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000261 // If not jitting lazily, load the whole bitcode file eagerly too.
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000262 std::string ErrorMsg;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000263 if (NoLazyCompilation) {
264 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
265 errs() << argv[0] << ": bitcode didn't read correctly.\n";
266 errs() << "Reason: " << ErrorMsg << "\n";
267 exit(1);
268 }
Evan Cheng0422bef2008-04-22 06:51:41 +0000269 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000270
Daniel Maleaa960c542013-06-28 19:11:40 +0000271 if (DebugIR) {
272 if (!UseMCJIT) {
273 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
274 << " information will be emitted by the non-MC JIT engine. To see full"
275 << " source debug information, enable the flag '-use-mcjit'.\n";
276
277 }
278 ModulePass *DebugIRPass = createDebugIRPass();
279 DebugIRPass->runOnModule(*Mod);
280 }
281
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000282 EngineBuilder builder(Mod);
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000283 builder.setMArch(MArch);
284 builder.setMCPU(MCPU);
285 builder.setMAttrs(MAttrs);
Evan Cheng2129f592011-07-19 06:37:02 +0000286 builder.setRelocationModel(RelocModel);
Evan Chengefd9b422011-07-20 07:51:56 +0000287 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000288 builder.setErrorStr(&ErrorMsg);
289 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000290 ? EngineKind::Interpreter
291 : EngineKind::JIT);
292
Chris Lattner2785bdb2007-05-06 04:58:26 +0000293 // If we are supposed to override the target triple, do so now.
294 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000295 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000296
Eli Bendersky4c647582012-01-16 08:56:09 +0000297 // Enable MCJIT if desired.
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000298 RTDyldMemoryManager *RTDyldMM = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000299 if (UseMCJIT && !ForceInterpreter) {
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000300 builder.setUseMCJIT(true);
Jim Grosbach0f435d02012-09-05 16:50:34 +0000301 if (RemoteMCJIT)
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000302 RTDyldMM = new RemoteMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000303 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000304 RTDyldMM = new SectionMemoryManager();
305 builder.setMCJITMemoryManager(RTDyldMM);
Benjamin Kramer76004e62012-05-20 17:24:08 +0000306 } else {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000307 if (RemoteMCJIT) {
308 errs() << "error: Remote process execution requires -use-mcjit\n";
309 exit(1);
310 }
Benjamin Kramer76004e62012-05-20 17:24:08 +0000311 builder.setJITMemoryManager(ForceInterpreter ? 0 :
312 JITMemoryManager::CreateDefaultMemManager());
Eli Bendersky4c647582012-01-16 08:56:09 +0000313 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000314
Evan Cheng09bd0b12009-05-04 23:05:19 +0000315 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
316 switch (OptLevel) {
317 default:
Dan Gohmand8db3762009-07-15 16:35:29 +0000318 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng09bd0b12009-05-04 23:05:19 +0000319 return 1;
320 case ' ': break;
321 case '0': OLvl = CodeGenOpt::None; break;
Evan Cheng5a286382009-10-16 21:02:20 +0000322 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng09bd0b12009-05-04 23:05:19 +0000323 case '2': OLvl = CodeGenOpt::Default; break;
324 case '3': OLvl = CodeGenOpt::Aggressive; break;
325 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000326 builder.setOptLevel(OLvl);
327
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000328 TargetOptions Options;
329 Options.UseSoftFloat = GenerateSoftFloatCalls;
330 if (FloatABIForCalls != FloatABI::Default)
331 Options.FloatABIType = FloatABIForCalls;
332 if (GenerateSoftFloatCalls)
333 FloatABIForCalls = FloatABI::Soft;
334
Jim Grosbach0f435d02012-09-05 16:50:34 +0000335 // Remote target execution doesn't handle EH or debug registration.
336 if (!RemoteMCJIT) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000337 Options.JITEmitDebugInfo = EmitJitDebugInfo;
338 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
Jim Grosbach0f435d02012-09-05 16:50:34 +0000339 }
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000340
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000341 builder.setTargetOptions(Options);
342
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000343 EE = builder.create();
Chris Lattnerf840ed72009-07-07 18:31:09 +0000344 if (!EE) {
345 if (!ErrorMsg.empty())
Dan Gohmand8db3762009-07-15 16:35:29 +0000346 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000347 else
Dan Gohmand8db3762009-07-15 16:35:29 +0000348 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000349 exit(1);
350 }
351
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000352 // Load any additional modules specified on the command line.
353 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
354 Module *XMod = ParseIRFile(ExtraModules[i], Err, Context);
355 if (!XMod) {
356 Err.print(argv[0], errs());
357 return 1;
358 }
359 EE->addModule(XMod);
360 }
361
Eli Bendersky5262ad22012-03-13 08:33:15 +0000362 // The following functions have no effect if their respective profiling
363 // support wasn't enabled in the build configuration.
364 EE->RegisterJITEventListener(
365 JITEventListener::createOProfileJITEventListener());
366 EE->RegisterJITEventListener(
367 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000368
Jim Grosbach0f435d02012-09-05 16:50:34 +0000369 if (!NoLazyCompilation && RemoteMCJIT) {
370 errs() << "warning: remote mcjit does not support lazy compilation\n";
371 NoLazyCompilation = true;
372 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000373 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000374
Chris Lattner2785bdb2007-05-06 04:58:26 +0000375 // If the user specifically requested an argv[0] to pass into the program,
376 // do it now.
377 if (!FakeArgv0.empty()) {
378 InputFile = FakeArgv0;
379 } else {
380 // Otherwise, if there is a .bc suffix on the executable strip it off, it
381 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000382 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000383 InputFile.erase(InputFile.length() - 3);
384 }
385
386 // Add the module's name to the start of the vector of arguments to main().
387 InputArgv.insert(InputArgv.begin(), InputFile);
388
389 // Call the main function from M as if its signature were:
390 // int main (int argc, char **argv, const char **envp)
391 // using the contents of Args to determine argc & argv, and the contents of
392 // EnvVars to determine envp.
393 //
Evan Cheng61582542008-11-05 23:21:52 +0000394 Function *EntryFn = Mod->getFunction(EntryFunc);
395 if (!EntryFn) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000396 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000397 return -1;
398 }
399
Chris Lattner2785bdb2007-05-06 04:58:26 +0000400 // Reset errno to zero on entry to main.
401 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000402
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000403 int Result;
404
Andrew Kaylor58365b92012-11-27 19:49:00 +0000405 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000406 // If the program doesn't explicitly call exit, we will need the Exit
407 // function later on to make an explicit call, so get the function now.
408 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
409 Type::getInt32Ty(Context),
410 NULL);
411
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000412 // Run static constructors.
Andrew Kaylorea395922013-10-01 01:47:35 +0000413 if (UseMCJIT && !ForceInterpreter) {
414 // Give MCJIT a chance to apply relocations and set page permissions.
415 EE->finalizeObject();
416 }
417 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000418
Andrew Kaylorea395922013-10-01 01:47:35 +0000419 if (!UseMCJIT && NoLazyCompilation) {
420 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
421 Function *Fn = &*I;
422 if (Fn != EntryFn && !Fn->isDeclaration())
423 EE->getPointerToFunction(Fn);
424 }
Evan Cheng0422bef2008-04-22 06:51:41 +0000425 }
Evan Cheng0422bef2008-04-22 06:51:41 +0000426
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000427 // Trigger compilation separately so code regions that need to be
428 // invalidated will be known.
429 (void)EE->getPointerToFunction(EntryFn);
430 // Clear instruction cache before code will be executed.
431 if (RTDyldMM)
432 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
433
434 // Run main.
435 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
436
437 // Run static destructors.
438 EE->runStaticConstructorsDestructors(true);
439
440 // If the program didn't call exit explicitly, we should call it now.
441 // This ensures that any atexit handlers get called correctly.
442 if (Function *ExitF = dyn_cast<Function>(Exit)) {
443 std::vector<GenericValue> Args;
444 GenericValue ResultGV;
445 ResultGV.IntVal = APInt(32, Result);
446 Args.push_back(ResultGV);
447 EE->runFunction(ExitF, Args);
448 errs() << "ERROR: exit(" << Result << ") returned!\n";
449 abort();
450 } else {
451 errs() << "ERROR: exit defined with wrong prototype!\n";
452 abort();
453 }
454 } else {
455 // else == "if (RemoteMCJIT)"
456
457 // Remote target MCJIT doesn't (yet) support static constructors. No reason
458 // it couldn't. This is a limitation of the LLI implemantation, not the
459 // MCJIT itself. FIXME.
460 //
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000461 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
Jim Grosbach0f435d02012-09-05 16:50:34 +0000462 // Everything is prepared now, so lay out our program for the target
463 // address space, assign the section addresses to resolve any relocations,
464 // and send it to the target.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000465
466 OwningPtr<RemoteTarget> Target;
467 if (!MCJITRemoteProcess.empty()) { // Remote execution on a child process
468 if (!RemoteTarget::hostSupportsExternalRemoteTarget()) {
469 errs() << "Warning: host does not support external remote targets.\n"
470 << " Defaulting to simulated remote execution\n";
471 Target.reset(RemoteTarget::createRemoteTarget());
472 } else {
473 std::string ChildEXE = sys::FindProgramByName(MCJITRemoteProcess);
474 if (ChildEXE == "") {
475 errs() << "Unable to find child target: '\''" << MCJITRemoteProcess << "\'\n";
476 return -1;
477 }
Richard Smith2f1c87b2013-10-02 21:33:12 +0000478 Target.reset(RemoteTarget::createExternalRemoteTarget(ChildEXE));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000479 }
480 } else {
481 // No child process name provided, use simulated remote execution.
482 Target.reset(RemoteTarget::createRemoteTarget());
483 }
484
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000485 // Give the memory manager a pointer to our remote target interface object.
486 MM->setRemoteTarget(Target.get());
487
488 // Create the remote target.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000489 Target->create();
Jim Grosbach748b9472012-08-28 23:22:30 +0000490
Jim Grosbach0f435d02012-09-05 16:50:34 +0000491 // Since we're executing in a (at least simulated) remote address space,
492 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
493 // grab the function address directly here and tell the remote target
494 // to execute the function.
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000495 //
496 // Our memory manager will map generated code into the remote address
497 // space as it is loaded and copy the bits over during the finalizeMemory
498 // operation.
499 //
Jim Grosbach0f435d02012-09-05 16:50:34 +0000500 // FIXME: argv and envp handling.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000501 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
Jim Grosbach0f435d02012-09-05 16:50:34 +0000502
Tim Northover79ab7f72013-05-19 09:55:06 +0000503 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
504 << format("%llx", Entry) << "\n");
Jim Grosbach0f435d02012-09-05 16:50:34 +0000505
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000506 if (Target->executeCode(Entry, Result))
507 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
Jim Grosbach0f435d02012-09-05 16:50:34 +0000508
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000509 // Like static constructors, the remote target MCJIT support doesn't handle
510 // this yet. It could. FIXME.
511
512 // Stop the remote target
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000513 Target->stop();
Chris Lattner2785bdb2007-05-06 04:58:26 +0000514 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000515
Jim Grosbach0f435d02012-09-05 16:50:34 +0000516 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000517}