1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // 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
12 // compiler, or through an interpreter if no JIT is available for this platform.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "lli"
17 #include "llvm/IR/LLVMContext.h"
18 #include "RecordingMemoryManager.h"
19 #include "RemoteTarget.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Bitcode/ReaderWriter.h"
22 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/ExecutionEngine/Interpreter.h"
25 #include "llvm/ExecutionEngine/JIT.h"
26 #include "llvm/ExecutionEngine/JITEventListener.h"
27 #include "llvm/ExecutionEngine/JITMemoryManager.h"
28 #include "llvm/ExecutionEngine/MCJIT.h"
29 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IRReader/IRReader.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/DynamicLibrary.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/Memory.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/PluginLoader.h"
42 #include "llvm/Support/PrettyStackTrace.h"
43 #include "llvm/Support/Process.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/raw_ostream.h"
51 #include <cygwin/version.h>
52 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
53 #define DO_NOTHING_ATEXIT 1
61 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
64 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
66 cl::opt<bool> ForceInterpreter("force-interpreter",
67 cl::desc("Force interpretation: disable JIT"),
70 cl::opt<bool> UseMCJIT(
71 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
74 // The MCJIT supports building for a target address space separate from
75 // the JIT compilation process. Use a forked process and a copying
76 // memory manager with IPC to execute using this functionality.
77 cl::opt<bool> RemoteMCJIT("remote-mcjit",
78 cl::desc("Execute MCJIT'ed code in a separate process."),
81 // Determine optimization level.
84 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
91 TargetTriple("mtriple", cl::desc("Override target triple for module"));
95 cl::desc("Architecture to generate assembly for (see --version)"));
99 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
100 cl::value_desc("cpu-name"),
103 cl::list<std::string>
106 cl::desc("Target specific attributes (-mattr=help for details)"),
107 cl::value_desc("a1,+a2,-a3,..."));
110 EntryFunc("entry-function",
111 cl::desc("Specify the entry function (default = 'main') "
112 "of the executable"),
113 cl::value_desc("function"),
117 FakeArgv0("fake-argv0",
118 cl::desc("Override the 'argv[0]' value passed into the executing"
119 " program"), cl::value_desc("executable"));
122 DisableCoreFiles("disable-core-files", cl::Hidden,
123 cl::desc("Disable emission of core files if possible"));
126 NoLazyCompilation("disable-lazy-compilation",
127 cl::desc("Disable JIT lazy compilation"),
130 cl::opt<Reloc::Model>
131 RelocModel("relocation-model",
132 cl::desc("Choose relocation model"),
133 cl::init(Reloc::Default),
135 clEnumValN(Reloc::Default, "default",
136 "Target default relocation model"),
137 clEnumValN(Reloc::Static, "static",
138 "Non-relocatable code"),
139 clEnumValN(Reloc::PIC_, "pic",
140 "Fully relocatable, position independent code"),
141 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
142 "Relocatable external references, non-relocatable code"),
145 cl::opt<llvm::CodeModel::Model>
146 CMModel("code-model",
147 cl::desc("Choose code model"),
148 cl::init(CodeModel::JITDefault),
149 cl::values(clEnumValN(CodeModel::JITDefault, "default",
150 "Target default JIT code model"),
151 clEnumValN(CodeModel::Small, "small",
153 clEnumValN(CodeModel::Kernel, "kernel",
154 "Kernel code model"),
155 clEnumValN(CodeModel::Medium, "medium",
156 "Medium code model"),
157 clEnumValN(CodeModel::Large, "large",
162 GenerateSoftFloatCalls("soft-float",
163 cl::desc("Generate software floating point library calls"),
166 cl::opt<llvm::FloatABI::ABIType>
167 FloatABIForCalls("float-abi",
168 cl::desc("Choose float ABI type"),
169 cl::init(FloatABI::Default),
171 clEnumValN(FloatABI::Default, "default",
172 "Target default float ABI type"),
173 clEnumValN(FloatABI::Soft, "soft",
174 "Soft float ABI (implied by -soft-float)"),
175 clEnumValN(FloatABI::Hard, "hard",
176 "Hard float ABI (uses FP registers)"),
179 // In debug builds, make this default to true.
181 #define EMIT_DEBUG false
183 #define EMIT_DEBUG true
185 EmitJitDebugInfo("jit-emit-debug",
186 cl::desc("Emit debug information to debugger"),
187 cl::init(EMIT_DEBUG));
191 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
193 cl::desc("Emit debug info objfiles to disk"),
197 static ExecutionEngine *EE = 0;
199 static void do_shutdown() {
200 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
201 #ifndef DO_NOTHING_ATEXIT
207 void layoutRemoteTargetMemory(RemoteTarget *T, RecordingMemoryManager *JMM) {
208 // Lay out our sections in order, with all the code sections first, then
209 // all the data sections.
210 uint64_t CurOffset = 0;
211 unsigned MaxAlign = T->getPageAlignment();
212 SmallVector<std::pair<const void*, uint64_t>, 16> Offsets;
213 SmallVector<unsigned, 16> Sizes;
214 for (RecordingMemoryManager::const_code_iterator I = JMM->code_begin(),
217 DEBUG(dbgs() << "code region: size " << I->first.size()
218 << ", alignment " << I->second << "\n");
219 // Align the current offset up to whatever is needed for the next
221 unsigned Align = I->second;
222 CurOffset = (CurOffset + Align - 1) / Align * Align;
223 // Save off the address of the new section and allocate its space.
224 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
225 Sizes.push_back(I->first.size());
226 CurOffset += I->first.size();
228 // Adjust to keep code and data aligned on seperate pages.
229 CurOffset = (CurOffset + MaxAlign - 1) / MaxAlign * MaxAlign;
230 unsigned FirstDataIndex = Offsets.size();
231 for (RecordingMemoryManager::const_data_iterator I = JMM->data_begin(),
234 DEBUG(dbgs() << "data region: size " << I->first.size()
235 << ", alignment " << I->second << "\n");
236 // Align the current offset up to whatever is needed for the next
238 unsigned Align = I->second;
239 CurOffset = (CurOffset + Align - 1) / Align * Align;
240 // Save off the address of the new section and allocate its space.
241 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
242 Sizes.push_back(I->first.size());
243 CurOffset += I->first.size();
246 // Allocate space in the remote target.
248 if (T->allocateSpace(CurOffset, MaxAlign, RemoteAddr))
249 report_fatal_error(T->getErrorMsg());
250 // Map the section addresses so relocations will get updated in the local
251 // copies of the sections.
252 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
253 uint64_t Addr = RemoteAddr + Offsets[i].second;
254 EE->mapSectionAddress(const_cast<void*>(Offsets[i].first), Addr);
256 DEBUG(dbgs() << " Mapping local: " << Offsets[i].first
257 << " to remote: " << format("%p", Addr) << "\n");
261 // Trigger application of relocations
262 EE->finalizeObject();
264 // Now load it all to the target.
265 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
266 uint64_t Addr = RemoteAddr + Offsets[i].second;
268 if (i < FirstDataIndex) {
269 T->loadCode(Addr, Offsets[i].first, Sizes[i]);
271 DEBUG(dbgs() << " loading code: " << Offsets[i].first
272 << " to remote: " << format("%p", Addr) << "\n");
274 T->loadData(Addr, Offsets[i].first, Sizes[i]);
276 DEBUG(dbgs() << " loading data: " << Offsets[i].first
277 << " to remote: " << format("%p", Addr) << "\n");
283 //===----------------------------------------------------------------------===//
284 // main Driver function
286 int main(int argc, char **argv, char * const *envp) {
287 sys::PrintStackTraceOnErrorSignal();
288 PrettyStackTraceProgram X(argc, argv);
290 LLVMContext &Context = getGlobalContext();
291 atexit(do_shutdown); // Call llvm_shutdown() on exit.
293 // If we have a native target, initialize it to ensure it is linked in and
294 // usable by the JIT.
295 InitializeNativeTarget();
296 InitializeNativeTargetAsmPrinter();
297 InitializeNativeTargetAsmParser();
299 cl::ParseCommandLineOptions(argc, argv,
300 "llvm interpreter & dynamic compiler\n");
302 // If the user doesn't want core files, disable them.
303 if (DisableCoreFiles)
304 sys::Process::PreventCoreFiles();
306 // Load the bitcode...
308 Module *Mod = ParseIRFile(InputFile, Err, Context);
310 Err.print(argv[0], errs());
314 // If not jitting lazily, load the whole bitcode file eagerly too.
315 std::string ErrorMsg;
316 if (NoLazyCompilation) {
317 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
318 errs() << argv[0] << ": bitcode didn't read correctly.\n";
319 errs() << "Reason: " << ErrorMsg << "\n";
324 EngineBuilder builder(Mod);
325 builder.setMArch(MArch);
326 builder.setMCPU(MCPU);
327 builder.setMAttrs(MAttrs);
328 builder.setRelocationModel(RelocModel);
329 builder.setCodeModel(CMModel);
330 builder.setErrorStr(&ErrorMsg);
331 builder.setEngineKind(ForceInterpreter
332 ? EngineKind::Interpreter
335 // If we are supposed to override the target triple, do so now.
336 if (!TargetTriple.empty())
337 Mod->setTargetTriple(Triple::normalize(TargetTriple));
339 // Enable MCJIT if desired.
340 JITMemoryManager *JMM = 0;
341 if (UseMCJIT && !ForceInterpreter) {
342 builder.setUseMCJIT(true);
344 JMM = new RecordingMemoryManager();
346 JMM = new SectionMemoryManager();
347 builder.setJITMemoryManager(JMM);
350 errs() << "error: Remote process execution requires -use-mcjit\n";
353 builder.setJITMemoryManager(ForceInterpreter ? 0 :
354 JITMemoryManager::CreateDefaultMemManager());
357 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
360 errs() << argv[0] << ": invalid optimization level.\n";
363 case '0': OLvl = CodeGenOpt::None; break;
364 case '1': OLvl = CodeGenOpt::Less; break;
365 case '2': OLvl = CodeGenOpt::Default; break;
366 case '3': OLvl = CodeGenOpt::Aggressive; break;
368 builder.setOptLevel(OLvl);
370 TargetOptions Options;
371 Options.UseSoftFloat = GenerateSoftFloatCalls;
372 if (FloatABIForCalls != FloatABI::Default)
373 Options.FloatABIType = FloatABIForCalls;
374 if (GenerateSoftFloatCalls)
375 FloatABIForCalls = FloatABI::Soft;
377 // Remote target execution doesn't handle EH or debug registration.
379 Options.JITEmitDebugInfo = EmitJitDebugInfo;
380 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
383 builder.setTargetOptions(Options);
385 EE = builder.create();
387 if (!ErrorMsg.empty())
388 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
390 errs() << argv[0] << ": unknown error creating EE!\n";
394 // The following functions have no effect if their respective profiling
395 // support wasn't enabled in the build configuration.
396 EE->RegisterJITEventListener(
397 JITEventListener::createOProfileJITEventListener());
398 EE->RegisterJITEventListener(
399 JITEventListener::createIntelJITEventListener());
401 if (!NoLazyCompilation && RemoteMCJIT) {
402 errs() << "warning: remote mcjit does not support lazy compilation\n";
403 NoLazyCompilation = true;
405 EE->DisableLazyCompilation(NoLazyCompilation);
407 // If the user specifically requested an argv[0] to pass into the program,
409 if (!FakeArgv0.empty()) {
410 InputFile = FakeArgv0;
412 // Otherwise, if there is a .bc suffix on the executable strip it off, it
413 // might confuse the program.
414 if (StringRef(InputFile).endswith(".bc"))
415 InputFile.erase(InputFile.length() - 3);
418 // Add the module's name to the start of the vector of arguments to main().
419 InputArgv.insert(InputArgv.begin(), InputFile);
421 // Call the main function from M as if its signature were:
422 // int main (int argc, char **argv, const char **envp)
423 // using the contents of Args to determine argc & argv, and the contents of
424 // EnvVars to determine envp.
426 Function *EntryFn = Mod->getFunction(EntryFunc);
428 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
432 // If the program doesn't explicitly call exit, we will need the Exit
433 // function later on to make an explicit call, so get the function now.
434 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
435 Type::getInt32Ty(Context),
438 // Reset errno to zero on entry to main.
441 // Remote target MCJIT doesn't (yet) support static constructors. No reason
442 // it couldn't. This is a limitation of the LLI implemantation, not the
443 // MCJIT itself. FIXME.
445 // Run static constructors.
447 if (UseMCJIT && !ForceInterpreter) {
448 // Give MCJIT a chance to apply relocations and set page permissions.
449 EE->finalizeObject();
451 EE->runStaticConstructorsDestructors(false);
454 if (NoLazyCompilation) {
455 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
457 if (Fn != EntryFn && !Fn->isDeclaration())
458 EE->getPointerToFunction(Fn);
464 RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(JMM);
465 // Everything is prepared now, so lay out our program for the target
466 // address space, assign the section addresses to resolve any relocations,
467 // and send it to the target.
471 // Ask for a pointer to the entry function. This triggers the actual
473 (void)EE->getPointerToFunction(EntryFn);
475 // Enough has been compiled to execute the entry function now, so
476 // layout the target memory.
477 layoutRemoteTargetMemory(&Target, MM);
479 // Since we're executing in a (at least simulated) remote address space,
480 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
481 // grab the function address directly here and tell the remote target
482 // to execute the function.
483 // FIXME: argv and envp handling.
484 uint64_t Entry = (uint64_t)EE->getPointerToFunction(EntryFn);
486 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at "
487 << format("%p", Entry) << "\n");
489 if (Target.executeCode(Entry, Result))
490 errs() << "ERROR: " << Target.getErrorMsg() << "\n";
494 // Trigger compilation separately so code regions that need to be
495 // invalidated will be known.
496 (void)EE->getPointerToFunction(EntryFn);
497 // Clear instruction cache before code will be executed.
499 static_cast<SectionMemoryManager*>(JMM)->invalidateInstructionCache();
502 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
505 // Like static constructors, the remote target MCJIT support doesn't handle
506 // this yet. It could. FIXME.
508 // Run static destructors.
509 EE->runStaticConstructorsDestructors(true);
511 // If the program didn't call exit explicitly, we should call it now.
512 // This ensures that any atexit handlers get called correctly.
513 if (Function *ExitF = dyn_cast<Function>(Exit)) {
514 std::vector<GenericValue> Args;
515 GenericValue ResultGV;
516 ResultGV.IntVal = APInt(32, Result);
517 Args.push_back(ResultGV);
518 EE->runFunction(ExitF, Args);
519 errs() << "ERROR: exit(" << Result << ") returned!\n";
522 errs() << "ERROR: exit defined with wrong prototype!\n";