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/JITEventListener.h"
26 #include "llvm/ExecutionEngine/MCJIT.h"
27 #include "llvm/ExecutionEngine/ObjectCache.h"
28 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/TypeBuilder.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/Object/Archive.h"
35 #include "llvm/Object/ObjectFile.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/DynamicLibrary.h"
39 #include "llvm/Support/Format.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/Memory.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/PluginLoader.h"
45 #include "llvm/Support/PrettyStackTrace.h"
46 #include "llvm/Support/Process.h"
47 #include "llvm/Support/Program.h"
48 #include "llvm/Support/Signals.h"
49 #include "llvm/Support/SourceMgr.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Transforms/Instrumentation.h"
56 #include <cygwin/version.h>
57 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
58 #define DO_NOTHING_ATEXIT 1
64 #define DEBUG_TYPE "lli"
68 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
71 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
73 cl::opt<bool> ForceInterpreter("force-interpreter",
74 cl::desc("Force interpretation: disable JIT"),
77 // The MCJIT supports building for a target address space separate from
78 // the JIT compilation process. Use a forked process and a copying
79 // memory manager with IPC to execute using this functionality.
80 cl::opt<bool> RemoteMCJIT("remote-mcjit",
81 cl::desc("Execute MCJIT'ed code in a separate process."),
84 // Manually specify the child process for remote execution. This overrides
85 // the simulated remote execution that allocates address space for child
86 // execution. The child process will be executed and will communicate with
87 // lli via stdin/stdout pipes.
89 ChildExecPath("mcjit-remote-process",
90 cl::desc("Specify the filename of the process to launch "
91 "for remote MCJIT execution. If none is specified,"
92 "\n\tremote execution will be simulated in-process."),
93 cl::value_desc("filename"), cl::init(""));
95 // Determine optimization level.
98 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
105 TargetTriple("mtriple", cl::desc("Override target triple for module"));
109 cl::desc("Architecture to generate assembly for (see --version)"));
113 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
114 cl::value_desc("cpu-name"),
117 cl::list<std::string>
120 cl::desc("Target specific attributes (-mattr=help for details)"),
121 cl::value_desc("a1,+a2,-a3,..."));
124 EntryFunc("entry-function",
125 cl::desc("Specify the entry function (default = 'main') "
126 "of the executable"),
127 cl::value_desc("function"),
130 cl::list<std::string>
131 ExtraModules("extra-module",
132 cl::desc("Extra modules to be loaded"),
133 cl::value_desc("input bitcode"));
135 cl::list<std::string>
136 ExtraObjects("extra-object",
137 cl::desc("Extra object files to be loaded"),
138 cl::value_desc("input object"));
140 cl::list<std::string>
141 ExtraArchives("extra-archive",
142 cl::desc("Extra archive files to be loaded"),
143 cl::value_desc("input archive"));
146 EnableCacheManager("enable-cache-manager",
147 cl::desc("Use cache manager to save/load mdoules"),
151 ObjectCacheDir("object-cache-dir",
152 cl::desc("Directory to store cached object files "
153 "(must be user writable)"),
157 FakeArgv0("fake-argv0",
158 cl::desc("Override the 'argv[0]' value passed into the executing"
159 " program"), cl::value_desc("executable"));
162 DisableCoreFiles("disable-core-files", cl::Hidden,
163 cl::desc("Disable emission of core files if possible"));
166 NoLazyCompilation("disable-lazy-compilation",
167 cl::desc("Disable JIT lazy compilation"),
170 cl::opt<Reloc::Model>
171 RelocModel("relocation-model",
172 cl::desc("Choose relocation model"),
173 cl::init(Reloc::Default),
175 clEnumValN(Reloc::Default, "default",
176 "Target default relocation model"),
177 clEnumValN(Reloc::Static, "static",
178 "Non-relocatable code"),
179 clEnumValN(Reloc::PIC_, "pic",
180 "Fully relocatable, position independent code"),
181 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
182 "Relocatable external references, non-relocatable code"),
185 cl::opt<llvm::CodeModel::Model>
186 CMModel("code-model",
187 cl::desc("Choose code model"),
188 cl::init(CodeModel::JITDefault),
189 cl::values(clEnumValN(CodeModel::JITDefault, "default",
190 "Target default JIT code model"),
191 clEnumValN(CodeModel::Small, "small",
193 clEnumValN(CodeModel::Kernel, "kernel",
194 "Kernel code model"),
195 clEnumValN(CodeModel::Medium, "medium",
196 "Medium code model"),
197 clEnumValN(CodeModel::Large, "large",
202 GenerateSoftFloatCalls("soft-float",
203 cl::desc("Generate software floating point library calls"),
206 cl::opt<llvm::FloatABI::ABIType>
207 FloatABIForCalls("float-abi",
208 cl::desc("Choose float ABI type"),
209 cl::init(FloatABI::Default),
211 clEnumValN(FloatABI::Default, "default",
212 "Target default float ABI type"),
213 clEnumValN(FloatABI::Soft, "soft",
214 "Soft float ABI (implied by -soft-float)"),
215 clEnumValN(FloatABI::Hard, "hard",
216 "Hard float ABI (uses FP registers)"),
219 // In debug builds, make this default to true.
221 #define EMIT_DEBUG false
223 #define EMIT_DEBUG true
225 EmitJitDebugInfo("jit-emit-debug",
226 cl::desc("Emit debug information to debugger"),
227 cl::init(EMIT_DEBUG));
231 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
233 cl::desc("Emit debug info objfiles to disk"),
237 //===----------------------------------------------------------------------===//
240 // This object cache implementation writes cached objects to disk to the
241 // directory specified by CacheDir, using a filename provided in the module
242 // descriptor. The cache tries to load a saved object using that path if the
243 // file exists. CacheDir defaults to "", in which case objects are cached
244 // alongside their originating bitcodes.
246 class LLIObjectCache : public ObjectCache {
248 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
249 // Add trailing '/' to cache dir if necessary.
250 if (!this->CacheDir.empty() &&
251 this->CacheDir[this->CacheDir.size() - 1] != '/')
252 this->CacheDir += '/';
254 virtual ~LLIObjectCache() {}
256 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
257 const std::string ModuleID = M->getModuleIdentifier();
258 std::string CacheName;
259 if (!getCacheFilename(ModuleID, CacheName))
261 if (!CacheDir.empty()) { // Create user-defined cache dir.
262 SmallString<128> dir(CacheName);
263 sys::path::remove_filename(dir);
264 sys::fs::create_directories(Twine(dir));
267 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
268 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
272 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
273 const std::string ModuleID = M->getModuleIdentifier();
274 std::string CacheName;
275 if (!getCacheFilename(ModuleID, CacheName))
277 // Load the object from the cache filename
278 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
279 MemoryBuffer::getFile(CacheName.c_str(), -1, false);
280 // If the file isn't there, that's OK.
283 // MCJIT will want to write into this buffer, and we don't want that
284 // because the file has probably just been mmapped. Instead we make
285 // a copy. The filed-based buffer will be released when it goes
287 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
291 std::string CacheDir;
293 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
294 std::string Prefix("file:");
295 size_t PrefixLength = Prefix.length();
296 if (ModID.substr(0, PrefixLength) != Prefix)
298 std::string CacheSubdir = ModID.substr(PrefixLength);
300 // Transform "X:\foo" => "/X\foo" for convenience.
301 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
302 CacheSubdir[1] = CacheSubdir[0];
303 CacheSubdir[0] = '/';
306 CacheName = CacheDir + CacheSubdir;
307 size_t pos = CacheName.rfind('.');
308 CacheName.replace(pos, CacheName.length() - pos, ".o");
313 static ExecutionEngine *EE = nullptr;
314 static LLIObjectCache *CacheManager = nullptr;
316 static void do_shutdown() {
317 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
318 #ifndef DO_NOTHING_ATEXIT
326 // On Mingw and Cygwin, an external symbol named '__main' is called from the
327 // generated 'main' function to allow static intialization. To avoid linking
328 // problems with remote targets (because lli's remote target support does not
329 // currently handle external linking) we add a secondary module which defines
330 // an empty '__main' function.
331 static void addCygMingExtraModule(ExecutionEngine *EE,
332 LLVMContext &Context,
333 StringRef TargetTripleStr) {
334 IRBuilder<> Builder(Context);
335 Triple TargetTriple(TargetTripleStr);
337 // Create a new module.
338 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
339 M->setTargetTriple(TargetTripleStr);
341 // Create an empty function named "__main".
343 if (TargetTriple.isArch64Bit()) {
344 Result = Function::Create(
345 TypeBuilder<int64_t(void), false>::get(Context),
346 GlobalValue::ExternalLinkage, "__main", M.get());
348 Result = Function::Create(
349 TypeBuilder<int32_t(void), false>::get(Context),
350 GlobalValue::ExternalLinkage, "__main", M.get());
352 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
353 Builder.SetInsertPoint(BB);
355 if (TargetTriple.isArch64Bit())
356 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
358 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
359 Builder.CreateRet(ReturnVal);
361 // Add this new module to the ExecutionEngine.
362 EE->addModule(std::move(M));
366 //===----------------------------------------------------------------------===//
367 // main Driver function
369 int main(int argc, char **argv, char * const *envp) {
370 sys::PrintStackTraceOnErrorSignal();
371 PrettyStackTraceProgram X(argc, argv);
373 LLVMContext &Context = getGlobalContext();
374 atexit(do_shutdown); // Call llvm_shutdown() on exit.
376 // If we have a native target, initialize it to ensure it is linked in and
377 // usable by the JIT.
378 InitializeNativeTarget();
379 InitializeNativeTargetAsmPrinter();
380 InitializeNativeTargetAsmParser();
382 cl::ParseCommandLineOptions(argc, argv,
383 "llvm interpreter & dynamic compiler\n");
385 // If the user doesn't want core files, disable them.
386 if (DisableCoreFiles)
387 sys::Process::PreventCoreFiles();
389 // Load the bitcode...
391 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
392 Module *Mod = Owner.get();
394 Err.print(argv[0], errs());
398 if (EnableCacheManager) {
399 std::string CacheName("file:");
400 CacheName.append(InputFile);
401 Mod->setModuleIdentifier(CacheName);
404 // If not jitting lazily, load the whole bitcode file eagerly too.
405 if (NoLazyCompilation) {
406 if (std::error_code EC = Mod->materializeAllPermanently()) {
407 errs() << argv[0] << ": bitcode didn't read correctly.\n";
408 errs() << "Reason: " << EC.message() << "\n";
413 std::string ErrorMsg;
414 EngineBuilder builder(std::move(Owner));
415 builder.setMArch(MArch);
416 builder.setMCPU(MCPU);
417 builder.setMAttrs(MAttrs);
418 builder.setRelocationModel(RelocModel);
419 builder.setCodeModel(CMModel);
420 builder.setErrorStr(&ErrorMsg);
421 builder.setEngineKind(ForceInterpreter
422 ? EngineKind::Interpreter
425 // If we are supposed to override the target triple, do so now.
426 if (!TargetTriple.empty())
427 Mod->setTargetTriple(Triple::normalize(TargetTriple));
429 // Enable MCJIT if desired.
430 RTDyldMemoryManager *RTDyldMM = nullptr;
431 if (!ForceInterpreter) {
433 RTDyldMM = new RemoteMemoryManager();
435 RTDyldMM = new SectionMemoryManager();
437 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
438 // RTDyldMM: We still use it below, even though we don't own it.
439 builder.setMCJITMemoryManager(
440 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
441 } else if (RemoteMCJIT) {
442 errs() << "error: Remote process execution does not work with the "
447 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
450 errs() << argv[0] << ": invalid optimization level.\n";
453 case '0': OLvl = CodeGenOpt::None; break;
454 case '1': OLvl = CodeGenOpt::Less; break;
455 case '2': OLvl = CodeGenOpt::Default; break;
456 case '3': OLvl = CodeGenOpt::Aggressive; break;
458 builder.setOptLevel(OLvl);
460 TargetOptions Options;
461 Options.UseSoftFloat = GenerateSoftFloatCalls;
462 if (FloatABIForCalls != FloatABI::Default)
463 Options.FloatABIType = FloatABIForCalls;
464 if (GenerateSoftFloatCalls)
465 FloatABIForCalls = FloatABI::Soft;
467 // Remote target execution doesn't handle EH or debug registration.
469 Options.JITEmitDebugInfo = EmitJitDebugInfo;
470 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
473 builder.setTargetOptions(Options);
475 EE = builder.create();
477 if (!ErrorMsg.empty())
478 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
480 errs() << argv[0] << ": unknown error creating EE!\n";
484 if (EnableCacheManager) {
485 CacheManager = new LLIObjectCache(ObjectCacheDir);
486 EE->setObjectCache(CacheManager);
489 // Load any additional modules specified on the command line.
490 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
491 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
493 Err.print(argv[0], errs());
496 if (EnableCacheManager) {
497 std::string CacheName("file:");
498 CacheName.append(ExtraModules[i]);
499 XMod->setModuleIdentifier(CacheName);
501 EE->addModule(std::move(XMod));
504 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
505 ErrorOr<object::OwningBinary<object::ObjectFile>> Obj =
506 object::ObjectFile::createObjectFile(ExtraObjects[i]);
508 Err.print(argv[0], errs());
511 object::OwningBinary<object::ObjectFile> &O = Obj.get();
512 EE->addObjectFile(std::move(O));
515 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
516 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
517 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
519 Err.print(argv[0], errs());
522 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
524 ErrorOr<std::unique_ptr<object::Archive>> ArOrErr =
525 object::Archive::create(ArBuf->getMemBufferRef());
526 if (std::error_code EC = ArOrErr.getError()) {
527 errs() << EC.message();
530 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
532 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
534 EE->addArchive(std::move(OB));
537 // If the target is Cygwin/MingW and we are generating remote code, we
538 // need an extra module to help out with linking.
539 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
540 addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
543 // The following functions have no effect if their respective profiling
544 // support wasn't enabled in the build configuration.
545 EE->RegisterJITEventListener(
546 JITEventListener::createOProfileJITEventListener());
547 EE->RegisterJITEventListener(
548 JITEventListener::createIntelJITEventListener());
550 if (!NoLazyCompilation && RemoteMCJIT) {
551 errs() << "warning: remote mcjit does not support lazy compilation\n";
552 NoLazyCompilation = true;
554 EE->DisableLazyCompilation(NoLazyCompilation);
556 // If the user specifically requested an argv[0] to pass into the program,
558 if (!FakeArgv0.empty()) {
559 InputFile = FakeArgv0;
561 // Otherwise, if there is a .bc suffix on the executable strip it off, it
562 // might confuse the program.
563 if (StringRef(InputFile).endswith(".bc"))
564 InputFile.erase(InputFile.length() - 3);
567 // Add the module's name to the start of the vector of arguments to main().
568 InputArgv.insert(InputArgv.begin(), InputFile);
570 // Call the main function from M as if its signature were:
571 // int main (int argc, char **argv, const char **envp)
572 // using the contents of Args to determine argc & argv, and the contents of
573 // EnvVars to determine envp.
575 Function *EntryFn = Mod->getFunction(EntryFunc);
577 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
581 // Reset errno to zero on entry to main.
587 // If the program doesn't explicitly call exit, we will need the Exit
588 // function later on to make an explicit call, so get the function now.
589 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
590 Type::getInt32Ty(Context),
593 // Run static constructors.
594 if (!ForceInterpreter) {
595 // Give MCJIT a chance to apply relocations and set page permissions.
596 EE->finalizeObject();
598 EE->runStaticConstructorsDestructors(false);
600 // Trigger compilation separately so code regions that need to be
601 // invalidated will be known.
602 (void)EE->getPointerToFunction(EntryFn);
603 // Clear instruction cache before code will be executed.
605 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
608 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
610 // Run static destructors.
611 EE->runStaticConstructorsDestructors(true);
613 // If the program didn't call exit explicitly, we should call it now.
614 // This ensures that any atexit handlers get called correctly.
615 if (Function *ExitF = dyn_cast<Function>(Exit)) {
616 std::vector<GenericValue> Args;
617 GenericValue ResultGV;
618 ResultGV.IntVal = APInt(32, Result);
619 Args.push_back(ResultGV);
620 EE->runFunction(ExitF, Args);
621 errs() << "ERROR: exit(" << Result << ") returned!\n";
624 errs() << "ERROR: exit defined with wrong prototype!\n";
628 // else == "if (RemoteMCJIT)"
630 // Remote target MCJIT doesn't (yet) support static constructors. No reason
631 // it couldn't. This is a limitation of the LLI implemantation, not the
632 // MCJIT itself. FIXME.
634 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
635 // Everything is prepared now, so lay out our program for the target
636 // address space, assign the section addresses to resolve any relocations,
637 // and send it to the target.
639 std::unique_ptr<RemoteTarget> Target;
640 if (!ChildExecPath.empty()) { // Remote execution on a child process
642 // FIXME: Remove this pointless fallback mode which causes tests to "pass"
643 // on platforms where they should XFAIL.
644 errs() << "Warning: host does not support external remote targets.\n"
645 << " Defaulting to simulated remote execution\n";
646 Target.reset(new RemoteTarget);
648 if (!sys::fs::can_execute(ChildExecPath)) {
649 errs() << "Unable to find usable child executable: '" << ChildExecPath
653 Target.reset(new RemoteTargetExternal(ChildExecPath));
656 // No child process name provided, use simulated remote execution.
657 Target.reset(new RemoteTarget);
660 // Give the memory manager a pointer to our remote target interface object.
661 MM->setRemoteTarget(Target.get());
663 // Create the remote target.
664 if (!Target->create()) {
665 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
669 // Since we're executing in a (at least simulated) remote address space,
670 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
671 // grab the function address directly here and tell the remote target
672 // to execute the function.
674 // Our memory manager will map generated code into the remote address
675 // space as it is loaded and copy the bits over during the finalizeMemory
678 // FIXME: argv and envp handling.
679 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
681 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
682 << format("%llx", Entry) << "\n");
684 if (!Target->executeCode(Entry, Result))
685 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
687 // Like static constructors, the remote target MCJIT support doesn't handle
688 // this yet. It could. FIXME.
690 // Stop the remote target