blob: 1cdd91b6938b8298a8dd8ad7e8f7fa8774eed1ea [file] [log] [blame]
Chris Lattnerfe11a972002-12-23 23:59:41 +00001//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +00009//
Chris Lattner7efea1d2003-12-26 05:07:35 +000010// This utility provides a simple wrapper around the LLVM Execution Engines,
11// which allow the direct execution of LLVM programs through a Just-In-Time
Torok Edwindb9c0282009-07-03 12:11:32 +000012// compiler, or through an interpreter if no JIT is available for this platform.
Chris Lattner92101ac2001-08-23 17:05:04 +000013//
14//===----------------------------------------------------------------------===//
15
Jim Grosbach706f03a2012-09-05 16:50:34 +000016#define DEBUG_TYPE "lli"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000017#include "llvm/IR/LLVMContext.h"
Jim Grosbach706f03a2012-09-05 16:50:34 +000018#include "RecordingMemoryManager.h"
19#include "RemoteTarget.h"
Duncan Sands75ebbce2010-08-28 01:30:02 +000020#include "llvm/ADT/Triple.h"
Chris Lattnerc1e6d682007-05-06 04:58:26 +000021#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnerd3a680a2006-08-01 22:34:35 +000022#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Brian Gaeked1cab3e2003-09-05 19:42:34 +000023#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +000024#include "llvm/ExecutionEngine/Interpreter.h"
25#include "llvm/ExecutionEngine/JIT.h"
26#include "llvm/ExecutionEngine/JITEventListener.h"
Jim Grosbachbf9ab932012-01-11 21:12:51 +000027#include "llvm/ExecutionEngine/JITMemoryManager.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000028#include "llvm/ExecutionEngine/MCJIT.h"
Andrew Kaylor257a0092012-11-27 19:49:00 +000029#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/Module.h"
31#include "llvm/IR/Type.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000032#include "llvm/IRReader/IRReader.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/CommandLine.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/DynamicLibrary.h"
36#include "llvm/Support/Format.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000037#include "llvm/Support/ManagedStatic.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000038#include "llvm/Support/MathExtras.h"
39#include "llvm/Support/Memory.h"
Chris Lattnerc1e6d682007-05-06 04:58:26 +000040#include "llvm/Support/MemoryBuffer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000041#include "llvm/Support/PluginLoader.h"
Chris Lattnercc14d252009-03-06 05:34:10 +000042#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000043#include "llvm/Support/Process.h"
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +000044#include "llvm/Support/Program.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000045#include "llvm/Support/Signals.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000046#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000047#include "llvm/Support/TargetSelect.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000048#include "llvm/Support/raw_ostream.h"
Daniel Maleae16e6872013-06-28 19:11:40 +000049#include "llvm/Transforms/Instrumentation.h"
Chris Lattner02040322007-04-27 17:02:33 +000050#include <cerrno>
NAKAMURA Takumia13d14a2010-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 Gaeked0fde302003-11-11 22:41:34 +000059using namespace llvm;
60
Chris Lattnerfe11a972002-12-23 23:59:41 +000061namespace {
62 cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000063 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000064
Chris Lattnerfe11a972002-12-23 23:59:41 +000065 cl::list<std::string>
66 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattner5ff62e92002-07-22 02:10:13 +000067
Chris Lattnerfe11a972002-12-23 23:59:41 +000068 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukman3d8a54d2003-09-25 18:10:34 +000069 cl::desc("Force interpretation: disable JIT"),
70 cl::init(false));
Evan Chenge1a4eda2008-08-08 08:12:06 +000071
Daniel Dunbar6d135972010-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 Maleae16e6872013-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 Grosbach706f03a2012-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 Kaylor0ab5c6c2013-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 Cheng712e80e2009-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 Chenge1a4eda2008-08-08 08:12:06 +0000107
Chris Lattner3015e602005-12-16 05:00:21 +0000108 cl::opt<std::string>
Chris Lattner60844d42005-12-16 05:19:18 +0000109 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Chengec740e32008-11-05 23:21:52 +0000110
111 cl::opt<std::string>
Jeffrey Yasskin46882612010-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 Chengec740e32008-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 Benderskya66a1852012-01-16 08:56:09 +0000133
Chris Lattnere69671d2003-10-28 22:51:44 +0000134 cl::opt<std::string>
135 FakeArgv0("fake-argv0",
136 cl::desc("Override the 'argv[0]' value passed into the executing"
137 " program"), cl::value_desc("executable"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000138
Chris Lattner43f249a2006-09-14 06:17:09 +0000139 cl::opt<bool>
140 DisableCoreFiles("disable-core-files", cl::Hidden,
141 cl::desc("Disable emission of core files if possible"));
Evan Chengc290a5b2008-04-22 06:51:41 +0000142
143 cl::opt<bool>
Evan Cheng03dace82008-05-21 18:20:21 +0000144 NoLazyCompilation("disable-lazy-compilation",
Evan Chengc290a5b2008-04-22 06:51:41 +0000145 cl::desc("Disable JIT lazy compilation"),
146 cl::init(false));
Evan Cheng43966132011-07-19 06:37:02 +0000147
148 cl::opt<Reloc::Model>
149 RelocModel("relocation-model",
150 cl::desc("Choose relocation model"),
151 cl::init(Reloc::Default),
152 cl::values(
153 clEnumValN(Reloc::Default, "default",
154 "Target default relocation model"),
155 clEnumValN(Reloc::Static, "static",
156 "Non-relocatable code"),
157 clEnumValN(Reloc::PIC_, "pic",
158 "Fully relocatable, position independent code"),
159 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
160 "Relocatable external references, non-relocatable code"),
161 clEnumValEnd));
Evan Cheng34ad6db2011-07-20 07:51:56 +0000162
163 cl::opt<llvm::CodeModel::Model>
164 CMModel("code-model",
165 cl::desc("Choose code model"),
166 cl::init(CodeModel::JITDefault),
167 cl::values(clEnumValN(CodeModel::JITDefault, "default",
168 "Target default JIT code model"),
169 clEnumValN(CodeModel::Small, "small",
170 "Small code model"),
171 clEnumValN(CodeModel::Kernel, "kernel",
172 "Kernel code model"),
173 clEnumValN(CodeModel::Medium, "medium",
174 "Medium code model"),
175 clEnumValN(CodeModel::Large, "large",
176 "Large code model"),
177 clEnumValEnd));
178
Nick Lewycky9a148412012-04-18 08:34:12 +0000179 cl::opt<bool>
Tim Northover77b4c692012-10-12 09:55:13 +0000180 GenerateSoftFloatCalls("soft-float",
181 cl::desc("Generate software floating point library calls"),
182 cl::init(false));
183
184 cl::opt<llvm::FloatABI::ABIType>
185 FloatABIForCalls("float-abi",
186 cl::desc("Choose float ABI type"),
187 cl::init(FloatABI::Default),
188 cl::values(
189 clEnumValN(FloatABI::Default, "default",
190 "Target default float ABI type"),
191 clEnumValN(FloatABI::Soft, "soft",
192 "Soft float ABI (implied by -soft-float)"),
193 clEnumValN(FloatABI::Hard, "hard",
194 "Hard float ABI (uses FP registers)"),
195 clEnumValEnd));
196 cl::opt<bool>
Nick Lewycky9a148412012-04-18 08:34:12 +0000197// In debug builds, make this default to true.
198#ifdef NDEBUG
199#define EMIT_DEBUG false
200#else
201#define EMIT_DEBUG true
202#endif
203 EmitJitDebugInfo("jit-emit-debug",
204 cl::desc("Emit debug information to debugger"),
205 cl::init(EMIT_DEBUG));
206#undef EMIT_DEBUG
207
208 static cl::opt<bool>
209 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
210 cl::Hidden,
211 cl::desc("Emit debug info objfiles to disk"),
212 cl::init(false));
Chris Lattnerfe11a972002-12-23 23:59:41 +0000213}
Chris Lattner43e3f7c2001-10-27 08:43:52 +0000214
Reid Spencerf70d6772007-03-03 18:21:44 +0000215static ExecutionEngine *EE = 0;
216
217static void do_shutdown() {
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000218 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
219#ifndef DO_NOTHING_ATEXIT
Reid Spencerf70d6772007-03-03 18:21:44 +0000220 delete EE;
221 llvm_shutdown();
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000222#endif
Reid Spencerf70d6772007-03-03 18:21:44 +0000223}
224
Jim Grosbach706f03a2012-09-05 16:50:34 +0000225void layoutRemoteTargetMemory(RemoteTarget *T, RecordingMemoryManager *JMM) {
226 // Lay out our sections in order, with all the code sections first, then
227 // all the data sections.
228 uint64_t CurOffset = 0;
229 unsigned MaxAlign = T->getPageAlignment();
230 SmallVector<std::pair<const void*, uint64_t>, 16> Offsets;
231 SmallVector<unsigned, 16> Sizes;
232 for (RecordingMemoryManager::const_code_iterator I = JMM->code_begin(),
233 E = JMM->code_end();
234 I != E; ++I) {
235 DEBUG(dbgs() << "code region: size " << I->first.size()
236 << ", alignment " << I->second << "\n");
237 // Align the current offset up to whatever is needed for the next
238 // section.
239 unsigned Align = I->second;
240 CurOffset = (CurOffset + Align - 1) / Align * Align;
241 // Save off the address of the new section and allocate its space.
242 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
243 Sizes.push_back(I->first.size());
244 CurOffset += I->first.size();
245 }
246 // Adjust to keep code and data aligned on seperate pages.
247 CurOffset = (CurOffset + MaxAlign - 1) / MaxAlign * MaxAlign;
248 unsigned FirstDataIndex = Offsets.size();
249 for (RecordingMemoryManager::const_data_iterator I = JMM->data_begin(),
250 E = JMM->data_end();
251 I != E; ++I) {
252 DEBUG(dbgs() << "data region: size " << I->first.size()
253 << ", alignment " << I->second << "\n");
254 // Align the current offset up to whatever is needed for the next
255 // section.
256 unsigned Align = I->second;
257 CurOffset = (CurOffset + Align - 1) / Align * Align;
258 // Save off the address of the new section and allocate its space.
259 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
260 Sizes.push_back(I->first.size());
261 CurOffset += I->first.size();
262 }
263
264 // Allocate space in the remote target.
265 uint64_t RemoteAddr;
266 if (T->allocateSpace(CurOffset, MaxAlign, RemoteAddr))
267 report_fatal_error(T->getErrorMsg());
268 // Map the section addresses so relocations will get updated in the local
269 // copies of the sections.
270 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
271 uint64_t Addr = RemoteAddr + Offsets[i].second;
272 EE->mapSectionAddress(const_cast<void*>(Offsets[i].first), Addr);
273
274 DEBUG(dbgs() << " Mapping local: " << Offsets[i].first
Tim Northovera73a6142013-05-19 09:55:06 +0000275 << " to remote: 0x" << format("%llx", Addr) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000276
277 }
Andrew Kaylor28989882012-11-05 20:57:16 +0000278
279 // Trigger application of relocations
280 EE->finalizeObject();
281
Jim Grosbach706f03a2012-09-05 16:50:34 +0000282 // Now load it all to the target.
283 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
284 uint64_t Addr = RemoteAddr + Offsets[i].second;
285
286 if (i < FirstDataIndex) {
287 T->loadCode(Addr, Offsets[i].first, Sizes[i]);
288
289 DEBUG(dbgs() << " loading code: " << Offsets[i].first
Tim Northovera73a6142013-05-19 09:55:06 +0000290 << " to remote: 0x" << format("%llx", Addr) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000291 } else {
292 T->loadData(Addr, Offsets[i].first, Sizes[i]);
293
294 DEBUG(dbgs() << " loading data: " << Offsets[i].first
Tim Northovera73a6142013-05-19 09:55:06 +0000295 << " to remote: 0x" << format("%llx", Addr) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000296 }
297
298 }
299}
300
Chris Lattner92101ac2001-08-23 17:05:04 +0000301//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +0000302// main Driver function
303//
Misha Brukmanc4fb6fd2003-10-14 21:39:53 +0000304int main(int argc, char **argv, char * const *envp) {
Chris Lattnercc14d252009-03-06 05:34:10 +0000305 sys::PrintStackTraceOnErrorSignal();
306 PrettyStackTraceProgram X(argc, argv);
Eli Benderskya66a1852012-01-16 08:56:09 +0000307
Owen Anderson0d7c6952009-07-15 22:16:10 +0000308 LLVMContext &Context = getGlobalContext();
Reid Spencerf70d6772007-03-03 18:21:44 +0000309 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar494d6632009-07-16 02:04:54 +0000310
311 // If we have a native target, initialize it to ensure it is linked in and
312 // usable by the JIT.
313 InitializeNativeTarget();
Jim Grosbach31649e62011-03-18 22:48:41 +0000314 InitializeNativeTargetAsmPrinter();
Jim Grosbach68372322012-11-05 19:06:05 +0000315 InitializeNativeTargetAsmParser();
Daniel Dunbar494d6632009-07-16 02:04:54 +0000316
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000317 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000318 "llvm interpreter & dynamic compiler\n");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000319
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000320 // If the user doesn't want core files, disable them.
321 if (DisableCoreFiles)
322 sys::Process::PreventCoreFiles();
Eli Benderskya66a1852012-01-16 08:56:09 +0000323
Gabor Greifa99be512007-07-05 17:07:56 +0000324 // Load the bitcode...
Daniel Dunbar46a27162010-11-13 00:28:01 +0000325 SMDiagnostic Err;
326 Module *Mod = ParseIRFile(InputFile, Err, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000327 if (!Mod) {
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000328 Err.print(argv[0], errs());
Daniel Dunbar46a27162010-11-13 00:28:01 +0000329 return 1;
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000330 }
331
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000332 // If not jitting lazily, load the whole bitcode file eagerly too.
Daniel Dunbar46a27162010-11-13 00:28:01 +0000333 std::string ErrorMsg;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000334 if (NoLazyCompilation) {
335 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
336 errs() << argv[0] << ": bitcode didn't read correctly.\n";
337 errs() << "Reason: " << ErrorMsg << "\n";
338 exit(1);
339 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000340 }
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000341
Daniel Maleae16e6872013-06-28 19:11:40 +0000342 if (DebugIR) {
343 if (!UseMCJIT) {
344 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
345 << " information will be emitted by the non-MC JIT engine. To see full"
346 << " source debug information, enable the flag '-use-mcjit'.\n";
347
348 }
349 ModulePass *DebugIRPass = createDebugIRPass();
350 DebugIRPass->runOnModule(*Mod);
351 }
352
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000353 EngineBuilder builder(Mod);
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000354 builder.setMArch(MArch);
355 builder.setMCPU(MCPU);
356 builder.setMAttrs(MAttrs);
Evan Cheng43966132011-07-19 06:37:02 +0000357 builder.setRelocationModel(RelocModel);
Evan Cheng34ad6db2011-07-20 07:51:56 +0000358 builder.setCodeModel(CMModel);
Daniel Dunbar4dc31362009-07-18 08:07:13 +0000359 builder.setErrorStr(&ErrorMsg);
360 builder.setEngineKind(ForceInterpreter
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000361 ? EngineKind::Interpreter
362 : EngineKind::JIT);
363
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000364 // If we are supposed to override the target triple, do so now.
365 if (!TargetTriple.empty())
Duncan Sands75ebbce2010-08-28 01:30:02 +0000366 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Chengc290a5b2008-04-22 06:51:41 +0000367
Eli Benderskya66a1852012-01-16 08:56:09 +0000368 // Enable MCJIT if desired.
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000369 RTDyldMemoryManager *RTDyldMM = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000370 if (UseMCJIT && !ForceInterpreter) {
Daniel Dunbar6d135972010-11-17 16:06:37 +0000371 builder.setUseMCJIT(true);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000372 if (RemoteMCJIT)
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000373 RTDyldMM = new RecordingMemoryManager();
Jim Grosbach706f03a2012-09-05 16:50:34 +0000374 else
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000375 RTDyldMM = new SectionMemoryManager();
376 builder.setMCJITMemoryManager(RTDyldMM);
Benjamin Kramer65145512012-05-20 17:24:08 +0000377 } else {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000378 if (RemoteMCJIT) {
379 errs() << "error: Remote process execution requires -use-mcjit\n";
380 exit(1);
381 }
Benjamin Kramer65145512012-05-20 17:24:08 +0000382 builder.setJITMemoryManager(ForceInterpreter ? 0 :
383 JITMemoryManager::CreateDefaultMemManager());
Eli Benderskya66a1852012-01-16 08:56:09 +0000384 }
Daniel Dunbar6d135972010-11-17 16:06:37 +0000385
Evan Cheng712e80e2009-05-04 23:05:19 +0000386 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
387 switch (OptLevel) {
388 default:
Dan Gohman65f57c22009-07-15 16:35:29 +0000389 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng712e80e2009-05-04 23:05:19 +0000390 return 1;
391 case ' ': break;
392 case '0': OLvl = CodeGenOpt::None; break;
Evan Chengbf57b522009-10-16 21:02:20 +0000393 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng712e80e2009-05-04 23:05:19 +0000394 case '2': OLvl = CodeGenOpt::Default; break;
395 case '3': OLvl = CodeGenOpt::Aggressive; break;
396 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000397 builder.setOptLevel(OLvl);
398
Tim Northover77b4c692012-10-12 09:55:13 +0000399 TargetOptions Options;
400 Options.UseSoftFloat = GenerateSoftFloatCalls;
401 if (FloatABIForCalls != FloatABI::Default)
402 Options.FloatABIType = FloatABIForCalls;
403 if (GenerateSoftFloatCalls)
404 FloatABIForCalls = FloatABI::Soft;
405
Jim Grosbach706f03a2012-09-05 16:50:34 +0000406 // Remote target execution doesn't handle EH or debug registration.
407 if (!RemoteMCJIT) {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000408 Options.JITEmitDebugInfo = EmitJitDebugInfo;
409 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
Jim Grosbach706f03a2012-09-05 16:50:34 +0000410 }
Nick Lewycky9a148412012-04-18 08:34:12 +0000411
Tim Northover77b4c692012-10-12 09:55:13 +0000412 builder.setTargetOptions(Options);
413
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000414 EE = builder.create();
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000415 if (!EE) {
416 if (!ErrorMsg.empty())
Dan Gohman65f57c22009-07-15 16:35:29 +0000417 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000418 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000419 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000420 exit(1);
421 }
422
Eli Bendersky61b18512012-03-13 08:33:15 +0000423 // The following functions have no effect if their respective profiling
424 // support wasn't enabled in the build configuration.
425 EE->RegisterJITEventListener(
426 JITEventListener::createOProfileJITEventListener());
427 EE->RegisterJITEventListener(
428 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000429
Jim Grosbach706f03a2012-09-05 16:50:34 +0000430 if (!NoLazyCompilation && RemoteMCJIT) {
431 errs() << "warning: remote mcjit does not support lazy compilation\n";
432 NoLazyCompilation = true;
433 }
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000434 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Chengc290a5b2008-04-22 06:51:41 +0000435
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000436 // If the user specifically requested an argv[0] to pass into the program,
437 // do it now.
438 if (!FakeArgv0.empty()) {
439 InputFile = FakeArgv0;
440 } else {
441 // Otherwise, if there is a .bc suffix on the executable strip it off, it
442 // might confuse the program.
Benjamin Kramer3bb37e92010-04-15 11:33:14 +0000443 if (StringRef(InputFile).endswith(".bc"))
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000444 InputFile.erase(InputFile.length() - 3);
445 }
446
447 // Add the module's name to the start of the vector of arguments to main().
448 InputArgv.insert(InputArgv.begin(), InputFile);
449
450 // Call the main function from M as if its signature were:
451 // int main (int argc, char **argv, const char **envp)
452 // using the contents of Args to determine argc & argv, and the contents of
453 // EnvVars to determine envp.
454 //
Evan Chengec740e32008-11-05 23:21:52 +0000455 Function *EntryFn = Mod->getFunction(EntryFunc);
456 if (!EntryFn) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000457 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000458 return -1;
459 }
460
Eli Benderskya66a1852012-01-16 08:56:09 +0000461 // If the program doesn't explicitly call exit, we will need the Exit
462 // function later on to make an explicit call, so get the function now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000463 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
464 Type::getInt32Ty(Context),
465 NULL);
Eli Benderskya66a1852012-01-16 08:56:09 +0000466
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000467 // Reset errno to zero on entry to main.
468 errno = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000469
Andrew Kaylorf1881562013-10-02 18:04:40 +0000470 int Result;
471
Andrew Kaylor257a0092012-11-27 19:49:00 +0000472 if (!RemoteMCJIT) {
Andrew Kaylorf1881562013-10-02 18:04:40 +0000473 // Run static constructors.
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000474 if (UseMCJIT && !ForceInterpreter) {
475 // Give MCJIT a chance to apply relocations and set page permissions.
476 EE->finalizeObject();
477 }
478 EE->runStaticConstructorsDestructors(false);
Evan Chengc290a5b2008-04-22 06:51:41 +0000479
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000480 if (!UseMCJIT && NoLazyCompilation) {
481 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
482 Function *Fn = &*I;
483 if (Fn != EntryFn && !Fn->isDeclaration())
484 EE->getPointerToFunction(Fn);
485 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000486 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000487
Andrew Kaylorf1881562013-10-02 18:04:40 +0000488 // Trigger compilation separately so code regions that need to be
489 // invalidated will be known.
490 (void)EE->getPointerToFunction(EntryFn);
491 // Clear instruction cache before code will be executed.
492 if (RTDyldMM)
493 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
494
495 // Run main.
496 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
497
498 // Run static destructors.
499 EE->runStaticConstructorsDestructors(true);
500
501 // If the program didn't call exit explicitly, we should call it now.
502 // This ensures that any atexit handlers get called correctly.
503 if (Function *ExitF = dyn_cast<Function>(Exit)) {
504 std::vector<GenericValue> Args;
505 GenericValue ResultGV;
506 ResultGV.IntVal = APInt(32, Result);
507 Args.push_back(ResultGV);
508 EE->runFunction(ExitF, Args);
509 errs() << "ERROR: exit(" << Result << ") returned!\n";
510 abort();
511 } else {
512 errs() << "ERROR: exit defined with wrong prototype!\n";
513 abort();
514 }
515 } else {
516 // else == "if (RemoteMCJIT)"
517
518 // Remote target MCJIT doesn't (yet) support static constructors. No reason
519 // it couldn't. This is a limitation of the LLI implemantation, not the
520 // MCJIT itself. FIXME.
521 //
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000522 RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(RTDyldMM);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000523 // Everything is prepared now, so lay out our program for the target
524 // address space, assign the section addresses to resolve any relocations,
525 // and send it to the target.
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000526
527 OwningPtr<RemoteTarget> Target;
528 if (!MCJITRemoteProcess.empty()) { // Remote execution on a child process
529 if (!RemoteTarget::hostSupportsExternalRemoteTarget()) {
530 errs() << "Warning: host does not support external remote targets.\n"
531 << " Defaulting to simulated remote execution\n";
532 Target.reset(RemoteTarget::createRemoteTarget());
533 } else {
534 std::string ChildEXE = sys::FindProgramByName(MCJITRemoteProcess);
535 if (ChildEXE == "") {
536 errs() << "Unable to find child target: '\''" << MCJITRemoteProcess << "\'\n";
537 return -1;
538 }
Richard Smithd34a4d62013-10-02 21:33:12 +0000539 Target.reset(RemoteTarget::createExternalRemoteTarget(ChildEXE));
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000540 }
541 } else {
542 // No child process name provided, use simulated remote execution.
543 Target.reset(RemoteTarget::createRemoteTarget());
544 }
545
546 // Create the remote target
547 Target->create();
Jim Grosbach5da959d2012-08-28 23:22:30 +0000548
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000549 // Trigger compilation.
550 EE->generateCodeForModule(Mod);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000551
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000552 // Layout the target memory.
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000553 layoutRemoteTargetMemory(Target.get(), MM);
Eli Benderskya66a1852012-01-16 08:56:09 +0000554
Jim Grosbach706f03a2012-09-05 16:50:34 +0000555 // Since we're executing in a (at least simulated) remote address space,
556 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
557 // grab the function address directly here and tell the remote target
558 // to execute the function.
559 // FIXME: argv and envp handling.
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000560 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
Jim Grosbach706f03a2012-09-05 16:50:34 +0000561
Tim Northovera73a6142013-05-19 09:55:06 +0000562 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
563 << format("%llx", Entry) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000564
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000565 if (Target->executeCode(Entry, Result))
566 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
Jim Grosbach706f03a2012-09-05 16:50:34 +0000567
Andrew Kaylorf1881562013-10-02 18:04:40 +0000568 // Like static constructors, the remote target MCJIT support doesn't handle
569 // this yet. It could. FIXME.
570
571 // Stop the remote target
Andrew Kaylor0ab5c6c2013-10-02 17:12:36 +0000572 Target->stop();
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000573 }
Jim Grosbach706f03a2012-09-05 16:50:34 +0000574
Jim Grosbach706f03a2012-09-05 16:50:34 +0000575 return Result;
Chris Lattner92101ac2001-08-23 17:05:04 +0000576}