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 #include "llvm/IR/LLVMContext.h"
17 #include "RemoteMemoryManager.h"
18 #include "RemoteTarget.h"
19 #include "RemoteTargetExternal.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/ObjectCache.h"
30 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/TypeBuilder.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/Object/Archive.h"
37 #include "llvm/Object/ObjectFile.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/DynamicLibrary.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/ManagedStatic.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/Memory.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/PluginLoader.h"
47 #include "llvm/Support/PrettyStackTrace.h"
48 #include "llvm/Support/Process.h"
49 #include "llvm/Support/Program.h"
50 #include "llvm/Support/Signals.h"
51 #include "llvm/Support/SourceMgr.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Transforms/Instrumentation.h"
58 #include <cygwin/version.h>
59 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
60 #define DO_NOTHING_ATEXIT 1
65 using std::error_code;
67 #define DEBUG_TYPE "lli"
71 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
74 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
76 cl::opt<bool> ForceInterpreter("force-interpreter",
77 cl::desc("Force interpretation: disable JIT"),
80 cl::opt<bool> UseMCJIT(
81 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
84 cl::opt<bool> DebugIR(
85 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
88 // The MCJIT supports building for a target address space separate from
89 // the JIT compilation process. Use a forked process and a copying
90 // memory manager with IPC to execute using this functionality.
91 cl::opt<bool> RemoteMCJIT("remote-mcjit",
92 cl::desc("Execute MCJIT'ed code in a separate process."),
95 // Manually specify the child process for remote execution. This overrides
96 // the simulated remote execution that allocates address space for child
97 // execution. The child process will be executed and will communicate with
98 // lli via stdin/stdout pipes.
100 ChildExecPath("mcjit-remote-process",
101 cl::desc("Specify the filename of the process to launch "
102 "for remote MCJIT execution. If none is specified,"
103 "\n\tremote execution will be simulated in-process."),
104 cl::value_desc("filename"), cl::init(""));
106 // Determine optimization level.
109 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
110 "(default = '-O2')"),
116 TargetTriple("mtriple", cl::desc("Override target triple for module"));
120 cl::desc("Architecture to generate assembly for (see --version)"));
124 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
125 cl::value_desc("cpu-name"),
128 cl::list<std::string>
131 cl::desc("Target specific attributes (-mattr=help for details)"),
132 cl::value_desc("a1,+a2,-a3,..."));
135 EntryFunc("entry-function",
136 cl::desc("Specify the entry function (default = 'main') "
137 "of the executable"),
138 cl::value_desc("function"),
141 cl::list<std::string>
142 ExtraModules("extra-module",
143 cl::desc("Extra modules to be loaded"),
144 cl::value_desc("input bitcode"));
146 cl::list<std::string>
147 ExtraObjects("extra-object",
148 cl::desc("Extra object files to be loaded"),
149 cl::value_desc("input object"));
151 cl::list<std::string>
152 ExtraArchives("extra-archive",
153 cl::desc("Extra archive files to be loaded"),
154 cl::value_desc("input archive"));
157 EnableCacheManager("enable-cache-manager",
158 cl::desc("Use cache manager to save/load mdoules"),
162 ObjectCacheDir("object-cache-dir",
163 cl::desc("Directory to store cached object files "
164 "(must be user writable)"),
168 FakeArgv0("fake-argv0",
169 cl::desc("Override the 'argv[0]' value passed into the executing"
170 " program"), cl::value_desc("executable"));
173 DisableCoreFiles("disable-core-files", cl::Hidden,
174 cl::desc("Disable emission of core files if possible"));
177 NoLazyCompilation("disable-lazy-compilation",
178 cl::desc("Disable JIT lazy compilation"),
181 cl::opt<Reloc::Model>
182 RelocModel("relocation-model",
183 cl::desc("Choose relocation model"),
184 cl::init(Reloc::Default),
186 clEnumValN(Reloc::Default, "default",
187 "Target default relocation model"),
188 clEnumValN(Reloc::Static, "static",
189 "Non-relocatable code"),
190 clEnumValN(Reloc::PIC_, "pic",
191 "Fully relocatable, position independent code"),
192 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
193 "Relocatable external references, non-relocatable code"),
196 cl::opt<llvm::CodeModel::Model>
197 CMModel("code-model",
198 cl::desc("Choose code model"),
199 cl::init(CodeModel::JITDefault),
200 cl::values(clEnumValN(CodeModel::JITDefault, "default",
201 "Target default JIT code model"),
202 clEnumValN(CodeModel::Small, "small",
204 clEnumValN(CodeModel::Kernel, "kernel",
205 "Kernel code model"),
206 clEnumValN(CodeModel::Medium, "medium",
207 "Medium code model"),
208 clEnumValN(CodeModel::Large, "large",
213 GenerateSoftFloatCalls("soft-float",
214 cl::desc("Generate software floating point library calls"),
217 cl::opt<llvm::FloatABI::ABIType>
218 FloatABIForCalls("float-abi",
219 cl::desc("Choose float ABI type"),
220 cl::init(FloatABI::Default),
222 clEnumValN(FloatABI::Default, "default",
223 "Target default float ABI type"),
224 clEnumValN(FloatABI::Soft, "soft",
225 "Soft float ABI (implied by -soft-float)"),
226 clEnumValN(FloatABI::Hard, "hard",
227 "Hard float ABI (uses FP registers)"),
230 // In debug builds, make this default to true.
232 #define EMIT_DEBUG false
234 #define EMIT_DEBUG true
236 EmitJitDebugInfo("jit-emit-debug",
237 cl::desc("Emit debug information to debugger"),
238 cl::init(EMIT_DEBUG));
242 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
244 cl::desc("Emit debug info objfiles to disk"),
248 //===----------------------------------------------------------------------===//
251 // This object cache implementation writes cached objects to disk to the
252 // directory specified by CacheDir, using a filename provided in the module
253 // descriptor. The cache tries to load a saved object using that path if the
254 // file exists. CacheDir defaults to "", in which case objects are cached
255 // alongside their originating bitcodes.
257 class LLIObjectCache : public ObjectCache {
259 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
260 // Add trailing '/' to cache dir if necessary.
261 if (!this->CacheDir.empty() &&
262 this->CacheDir[this->CacheDir.size() - 1] != '/')
263 this->CacheDir += '/';
265 virtual ~LLIObjectCache() {}
267 void notifyObjectCompiled(const Module *M, const MemoryBuffer *Obj) override {
268 const std::string ModuleID = M->getModuleIdentifier();
269 std::string CacheName;
270 if (!getCacheFilename(ModuleID, CacheName))
273 if (!CacheDir.empty()) { // Create user-defined cache dir.
274 SmallString<128> dir(CacheName);
275 sys::path::remove_filename(dir);
276 sys::fs::create_directories(Twine(dir));
278 raw_fd_ostream outfile(CacheName.c_str(), errStr, sys::fs::F_None);
279 outfile.write(Obj->getBufferStart(), Obj->getBufferSize());
283 MemoryBuffer* getObject(const Module* M) override {
284 const std::string ModuleID = M->getModuleIdentifier();
285 std::string CacheName;
286 if (!getCacheFilename(ModuleID, CacheName))
288 // Load the object from the cache filename
289 std::unique_ptr<MemoryBuffer> IRObjectBuffer;
290 MemoryBuffer::getFile(CacheName.c_str(), IRObjectBuffer, -1, false);
291 // If the file isn't there, that's OK.
294 // MCJIT will want to write into this buffer, and we don't want that
295 // because the file has probably just been mmapped. Instead we make
296 // a copy. The filed-based buffer will be released when it goes
298 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer->getBuffer());
302 std::string CacheDir;
304 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
305 std::string Prefix("file:");
306 size_t PrefixLength = Prefix.length();
307 if (ModID.substr(0, PrefixLength) != Prefix)
309 std::string CacheSubdir = ModID.substr(PrefixLength);
311 // Transform "X:\foo" => "/X\foo" for convenience.
312 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
313 CacheSubdir[1] = CacheSubdir[0];
314 CacheSubdir[0] = '/';
317 CacheName = CacheDir + CacheSubdir;
318 size_t pos = CacheName.rfind('.');
319 CacheName.replace(pos, CacheName.length() - pos, ".o");
324 static ExecutionEngine *EE = nullptr;
325 static LLIObjectCache *CacheManager = nullptr;
327 static void do_shutdown() {
328 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
329 #ifndef DO_NOTHING_ATEXIT
337 // On Mingw and Cygwin, an external symbol named '__main' is called from the
338 // generated 'main' function to allow static intialization. To avoid linking
339 // problems with remote targets (because lli's remote target support does not
340 // currently handle external linking) we add a secondary module which defines
341 // an empty '__main' function.
342 static void addCygMingExtraModule(ExecutionEngine *EE,
343 LLVMContext &Context,
344 StringRef TargetTripleStr) {
345 IRBuilder<> Builder(Context);
346 Triple TargetTriple(TargetTripleStr);
348 // Create a new module.
349 Module *M = new Module("CygMingHelper", Context);
350 M->setTargetTriple(TargetTripleStr);
352 // Create an empty function named "__main".
354 if (TargetTriple.isArch64Bit()) {
355 Result = Function::Create(
356 TypeBuilder<int64_t(void), false>::get(Context),
357 GlobalValue::ExternalLinkage, "__main", M);
359 Result = Function::Create(
360 TypeBuilder<int32_t(void), false>::get(Context),
361 GlobalValue::ExternalLinkage, "__main", M);
363 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
364 Builder.SetInsertPoint(BB);
366 if (TargetTriple.isArch64Bit())
367 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
369 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
370 Builder.CreateRet(ReturnVal);
372 // Add this new module to the ExecutionEngine.
377 //===----------------------------------------------------------------------===//
378 // main Driver function
380 int main(int argc, char **argv, char * const *envp) {
381 sys::PrintStackTraceOnErrorSignal();
382 PrettyStackTraceProgram X(argc, argv);
384 LLVMContext &Context = getGlobalContext();
385 atexit(do_shutdown); // Call llvm_shutdown() on exit.
387 // If we have a native target, initialize it to ensure it is linked in and
388 // usable by the JIT.
389 InitializeNativeTarget();
390 InitializeNativeTargetAsmPrinter();
391 InitializeNativeTargetAsmParser();
393 cl::ParseCommandLineOptions(argc, argv,
394 "llvm interpreter & dynamic compiler\n");
396 // If the user doesn't want core files, disable them.
397 if (DisableCoreFiles)
398 sys::Process::PreventCoreFiles();
400 // Load the bitcode...
402 Module *Mod = ParseIRFile(InputFile, Err, Context);
404 Err.print(argv[0], errs());
408 if (EnableCacheManager) {
410 std::string CacheName("file:");
411 CacheName.append(InputFile);
412 Mod->setModuleIdentifier(CacheName);
414 errs() << "warning: -enable-cache-manager can only be used with MCJIT.";
417 // If not jitting lazily, load the whole bitcode file eagerly too.
418 if (NoLazyCompilation) {
419 if (error_code EC = Mod->materializeAllPermanently()) {
420 errs() << argv[0] << ": bitcode didn't read correctly.\n";
421 errs() << "Reason: " << EC.message() << "\n";
428 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
429 << " information will be emitted by the non-MC JIT engine. To see full"
430 << " source debug information, enable the flag '-use-mcjit'.\n";
433 ModulePass *DebugIRPass = createDebugIRPass();
434 DebugIRPass->runOnModule(*Mod);
437 std::string ErrorMsg;
438 EngineBuilder builder(Mod);
439 builder.setMArch(MArch);
440 builder.setMCPU(MCPU);
441 builder.setMAttrs(MAttrs);
442 builder.setRelocationModel(RelocModel);
443 builder.setCodeModel(CMModel);
444 builder.setErrorStr(&ErrorMsg);
445 builder.setEngineKind(ForceInterpreter
446 ? EngineKind::Interpreter
449 // If we are supposed to override the target triple, do so now.
450 if (!TargetTriple.empty())
451 Mod->setTargetTriple(Triple::normalize(TargetTriple));
453 // Enable MCJIT if desired.
454 RTDyldMemoryManager *RTDyldMM = nullptr;
455 if (UseMCJIT && !ForceInterpreter) {
456 builder.setUseMCJIT(true);
458 RTDyldMM = new RemoteMemoryManager();
460 RTDyldMM = new SectionMemoryManager();
461 builder.setMCJITMemoryManager(RTDyldMM);
464 errs() << "error: Remote process execution requires -use-mcjit\n";
467 builder.setJITMemoryManager(ForceInterpreter ? nullptr :
468 JITMemoryManager::CreateDefaultMemManager());
471 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
474 errs() << argv[0] << ": invalid optimization level.\n";
477 case '0': OLvl = CodeGenOpt::None; break;
478 case '1': OLvl = CodeGenOpt::Less; break;
479 case '2': OLvl = CodeGenOpt::Default; break;
480 case '3': OLvl = CodeGenOpt::Aggressive; break;
482 builder.setOptLevel(OLvl);
484 TargetOptions Options;
485 Options.UseSoftFloat = GenerateSoftFloatCalls;
486 if (FloatABIForCalls != FloatABI::Default)
487 Options.FloatABIType = FloatABIForCalls;
488 if (GenerateSoftFloatCalls)
489 FloatABIForCalls = FloatABI::Soft;
491 // Remote target execution doesn't handle EH or debug registration.
493 Options.JITEmitDebugInfo = EmitJitDebugInfo;
494 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
497 builder.setTargetOptions(Options);
499 EE = builder.create();
501 if (!ErrorMsg.empty())
502 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
504 errs() << argv[0] << ": unknown error creating EE!\n";
508 if (EnableCacheManager) {
509 CacheManager = new LLIObjectCache(ObjectCacheDir);
510 EE->setObjectCache(CacheManager);
513 // Load any additional modules specified on the command line.
514 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
515 Module *XMod = ParseIRFile(ExtraModules[i], Err, Context);
517 Err.print(argv[0], errs());
520 if (EnableCacheManager) {
522 std::string CacheName("file:");
523 CacheName.append(ExtraModules[i]);
524 XMod->setModuleIdentifier(CacheName);
526 // else, we already printed a warning above.
531 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
532 ErrorOr<object::ObjectFile *> Obj =
533 object::ObjectFile::createObjectFile(ExtraObjects[i]);
535 Err.print(argv[0], errs());
538 EE->addObjectFile(std::unique_ptr<object::ObjectFile>(Obj.get()));
541 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
542 std::unique_ptr<MemoryBuffer> ArBuf;
544 ec = MemoryBuffer::getFileOrSTDIN(ExtraArchives[i], ArBuf);
546 Err.print(argv[0], errs());
549 object::Archive *Ar = new object::Archive(ArBuf.release(), ec);
551 Err.print(argv[0], errs());
557 // If the target is Cygwin/MingW and we are generating remote code, we
558 // need an extra module to help out with linking.
559 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
560 addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
563 // The following functions have no effect if their respective profiling
564 // support wasn't enabled in the build configuration.
565 EE->RegisterJITEventListener(
566 JITEventListener::createOProfileJITEventListener());
567 EE->RegisterJITEventListener(
568 JITEventListener::createIntelJITEventListener());
570 if (!NoLazyCompilation && RemoteMCJIT) {
571 errs() << "warning: remote mcjit does not support lazy compilation\n";
572 NoLazyCompilation = true;
574 EE->DisableLazyCompilation(NoLazyCompilation);
576 // If the user specifically requested an argv[0] to pass into the program,
578 if (!FakeArgv0.empty()) {
579 InputFile = FakeArgv0;
581 // Otherwise, if there is a .bc suffix on the executable strip it off, it
582 // might confuse the program.
583 if (StringRef(InputFile).endswith(".bc"))
584 InputFile.erase(InputFile.length() - 3);
587 // Add the module's name to the start of the vector of arguments to main().
588 InputArgv.insert(InputArgv.begin(), InputFile);
590 // Call the main function from M as if its signature were:
591 // int main (int argc, char **argv, const char **envp)
592 // using the contents of Args to determine argc & argv, and the contents of
593 // EnvVars to determine envp.
595 Function *EntryFn = Mod->getFunction(EntryFunc);
597 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
601 // Reset errno to zero on entry to main.
607 // If the program doesn't explicitly call exit, we will need the Exit
608 // function later on to make an explicit call, so get the function now.
609 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
610 Type::getInt32Ty(Context),
613 // Run static constructors.
614 if (UseMCJIT && !ForceInterpreter) {
615 // Give MCJIT a chance to apply relocations and set page permissions.
616 EE->finalizeObject();
618 EE->runStaticConstructorsDestructors(false);
620 if (!UseMCJIT && NoLazyCompilation) {
621 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
623 if (Fn != EntryFn && !Fn->isDeclaration())
624 EE->getPointerToFunction(Fn);
628 // Trigger compilation separately so code regions that need to be
629 // invalidated will be known.
630 (void)EE->getPointerToFunction(EntryFn);
631 // Clear instruction cache before code will be executed.
633 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
636 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
638 // Run static destructors.
639 EE->runStaticConstructorsDestructors(true);
641 // If the program didn't call exit explicitly, we should call it now.
642 // This ensures that any atexit handlers get called correctly.
643 if (Function *ExitF = dyn_cast<Function>(Exit)) {
644 std::vector<GenericValue> Args;
645 GenericValue ResultGV;
646 ResultGV.IntVal = APInt(32, Result);
647 Args.push_back(ResultGV);
648 EE->runFunction(ExitF, Args);
649 errs() << "ERROR: exit(" << Result << ") returned!\n";
652 errs() << "ERROR: exit defined with wrong prototype!\n";
656 // else == "if (RemoteMCJIT)"
658 // Remote target MCJIT doesn't (yet) support static constructors. No reason
659 // it couldn't. This is a limitation of the LLI implemantation, not the
660 // MCJIT itself. FIXME.
662 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
663 // Everything is prepared now, so lay out our program for the target
664 // address space, assign the section addresses to resolve any relocations,
665 // and send it to the target.
667 std::unique_ptr<RemoteTarget> Target;
668 if (!ChildExecPath.empty()) { // Remote execution on a child process
670 // FIXME: Remove this pointless fallback mode which causes tests to "pass"
671 // on platforms where they should XFAIL.
672 errs() << "Warning: host does not support external remote targets.\n"
673 << " Defaulting to simulated remote execution\n";
674 Target.reset(new RemoteTarget);
676 if (!sys::fs::can_execute(ChildExecPath)) {
677 errs() << "Unable to find usable child executable: '" << ChildExecPath
681 Target.reset(new RemoteTargetExternal(ChildExecPath));
684 // No child process name provided, use simulated remote execution.
685 Target.reset(new RemoteTarget);
688 // Give the memory manager a pointer to our remote target interface object.
689 MM->setRemoteTarget(Target.get());
691 // Create the remote target.
692 if (!Target->create()) {
693 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
697 // Since we're executing in a (at least simulated) remote address space,
698 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
699 // grab the function address directly here and tell the remote target
700 // to execute the function.
702 // Our memory manager will map generated code into the remote address
703 // space as it is loaded and copy the bits over during the finalizeMemory
706 // FIXME: argv and envp handling.
707 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
709 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
710 << format("%llx", Entry) << "\n");
712 if (!Target->executeCode(Entry, Result))
713 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
715 // Like static constructors, the remote target MCJIT support doesn't handle
716 // this yet. It could. FIXME.
718 // Stop the remote target