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 "RemoteMemoryManager.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/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
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 cl::opt<bool> UseMCJIT(
78 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
81 cl::opt<bool> DebugIR(
82 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
85 // The MCJIT supports building for a target address space separate from
86 // the JIT compilation process. Use a forked process and a copying
87 // memory manager with IPC to execute using this functionality.
88 cl::opt<bool> RemoteMCJIT("remote-mcjit",
89 cl::desc("Execute MCJIT'ed code in a separate process."),
92 // Manually specify the child process for remote execution. This overrides
93 // the simulated remote execution that allocates address space for child
94 // execution. The child process will be executed and will communicate with
95 // lli via stdin/stdout pipes.
97 ChildExecPath("mcjit-remote-process",
98 cl::desc("Specify the filename of the process to launch "
99 "for remote MCJIT execution. If none is specified,"
100 "\n\tremote execution will be simulated in-process."),
101 cl::value_desc("filename"), cl::init(""));
103 // Determine optimization level.
106 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
107 "(default = '-O2')"),
113 TargetTriple("mtriple", cl::desc("Override target triple for module"));
117 cl::desc("Architecture to generate assembly for (see --version)"));
121 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
122 cl::value_desc("cpu-name"),
125 cl::list<std::string>
128 cl::desc("Target specific attributes (-mattr=help for details)"),
129 cl::value_desc("a1,+a2,-a3,..."));
132 EntryFunc("entry-function",
133 cl::desc("Specify the entry function (default = 'main') "
134 "of the executable"),
135 cl::value_desc("function"),
138 cl::list<std::string>
139 ExtraModules("extra-module",
140 cl::desc("Extra modules to be loaded"),
141 cl::value_desc("input bitcode"));
143 cl::list<std::string>
144 ExtraObjects("extra-object",
145 cl::desc("Extra object files to be loaded"),
146 cl::value_desc("input object"));
148 cl::list<std::string>
149 ExtraArchives("extra-archive",
150 cl::desc("Extra archive files to be loaded"),
151 cl::value_desc("input archive"));
154 EnableCacheManager("enable-cache-manager",
155 cl::desc("Use cache manager to save/load mdoules"),
159 ObjectCacheDir("object-cache-dir",
160 cl::desc("Directory to store cached object files "
161 "(must be user writable)"),
165 FakeArgv0("fake-argv0",
166 cl::desc("Override the 'argv[0]' value passed into the executing"
167 " program"), cl::value_desc("executable"));
170 DisableCoreFiles("disable-core-files", cl::Hidden,
171 cl::desc("Disable emission of core files if possible"));
174 NoLazyCompilation("disable-lazy-compilation",
175 cl::desc("Disable JIT lazy compilation"),
178 cl::opt<Reloc::Model>
179 RelocModel("relocation-model",
180 cl::desc("Choose relocation model"),
181 cl::init(Reloc::Default),
183 clEnumValN(Reloc::Default, "default",
184 "Target default relocation model"),
185 clEnumValN(Reloc::Static, "static",
186 "Non-relocatable code"),
187 clEnumValN(Reloc::PIC_, "pic",
188 "Fully relocatable, position independent code"),
189 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
190 "Relocatable external references, non-relocatable code"),
193 cl::opt<llvm::CodeModel::Model>
194 CMModel("code-model",
195 cl::desc("Choose code model"),
196 cl::init(CodeModel::JITDefault),
197 cl::values(clEnumValN(CodeModel::JITDefault, "default",
198 "Target default JIT code model"),
199 clEnumValN(CodeModel::Small, "small",
201 clEnumValN(CodeModel::Kernel, "kernel",
202 "Kernel code model"),
203 clEnumValN(CodeModel::Medium, "medium",
204 "Medium code model"),
205 clEnumValN(CodeModel::Large, "large",
210 GenerateSoftFloatCalls("soft-float",
211 cl::desc("Generate software floating point library calls"),
214 cl::opt<llvm::FloatABI::ABIType>
215 FloatABIForCalls("float-abi",
216 cl::desc("Choose float ABI type"),
217 cl::init(FloatABI::Default),
219 clEnumValN(FloatABI::Default, "default",
220 "Target default float ABI type"),
221 clEnumValN(FloatABI::Soft, "soft",
222 "Soft float ABI (implied by -soft-float)"),
223 clEnumValN(FloatABI::Hard, "hard",
224 "Hard float ABI (uses FP registers)"),
227 // In debug builds, make this default to true.
229 #define EMIT_DEBUG false
231 #define EMIT_DEBUG true
233 EmitJitDebugInfo("jit-emit-debug",
234 cl::desc("Emit debug information to debugger"),
235 cl::init(EMIT_DEBUG));
239 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
241 cl::desc("Emit debug info objfiles to disk"),
245 //===----------------------------------------------------------------------===//
248 // This object cache implementation writes cached objects to disk to the
249 // directory specified by CacheDir, using a filename provided in the module
250 // descriptor. The cache tries to load a saved object using that path if the
251 // file exists. CacheDir defaults to "", in which case objects are cached
252 // alongside their originating bitcodes.
254 class LLIObjectCache : public ObjectCache {
256 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
257 // Add trailing '/' to cache dir if necessary.
258 if (!this->CacheDir.empty() &&
259 this->CacheDir[this->CacheDir.size() - 1] != '/')
260 this->CacheDir += '/';
262 virtual ~LLIObjectCache() {}
264 virtual void notifyObjectCompiled(const Module *M, const MemoryBuffer *Obj) {
265 const std::string ModuleID = M->getModuleIdentifier();
266 std::string CacheName;
267 if (!getCacheFilename(ModuleID, CacheName))
270 if (!CacheDir.empty()) { // Create user-defined cache dir.
271 SmallString<128> dir(CacheName);
272 sys::path::remove_filename(dir);
273 sys::fs::create_directories(Twine(dir));
275 raw_fd_ostream outfile(CacheName.c_str(), errStr, sys::fs::F_Binary);
276 outfile.write(Obj->getBufferStart(), Obj->getBufferSize());
280 virtual MemoryBuffer* getObject(const Module* M) {
281 const std::string ModuleID = M->getModuleIdentifier();
282 std::string CacheName;
283 if (!getCacheFilename(ModuleID, CacheName))
285 // Load the object from the cache filename
286 OwningPtr<MemoryBuffer> IRObjectBuffer;
287 MemoryBuffer::getFile(CacheName.c_str(), IRObjectBuffer, -1, false);
288 // If the file isn't there, that's OK.
291 // MCJIT will want to write into this buffer, and we don't want that
292 // because the file has probably just been mmapped. Instead we make
293 // a copy. The filed-based buffer will be released when it goes
295 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer->getBuffer());
299 std::string CacheDir;
301 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
302 std::string Prefix("file:");
303 size_t PrefixLength = Prefix.length();
304 if (ModID.substr(0, PrefixLength) != Prefix)
306 std::string CacheSubdir = ModID.substr(PrefixLength);
308 // Transform "X:\foo" => "/X\foo" for convenience.
309 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
310 CacheSubdir[1] = CacheSubdir[0];
311 CacheSubdir[0] = '/';
314 CacheName = CacheDir + CacheSubdir;
315 size_t pos = CacheName.rfind('.');
316 CacheName.replace(pos, CacheName.length() - pos, ".o");
321 static ExecutionEngine *EE = 0;
322 static LLIObjectCache *CacheManager = 0;
324 static void do_shutdown() {
325 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
326 #ifndef DO_NOTHING_ATEXIT
334 // On Mingw and Cygwin, an external symbol named '__main' is called from the
335 // generated 'main' function to allow static intialization. To avoid linking
336 // problems with remote targets (because lli's remote target support does not
337 // currently handle external linking) we add a secondary module which defines
338 // an empty '__main' function.
339 static void addCygMingExtraModule(ExecutionEngine *EE,
340 LLVMContext &Context,
341 StringRef TargetTripleStr) {
342 IRBuilder<> Builder(Context);
343 Triple TargetTriple(TargetTripleStr);
345 // Create a new module.
346 Module *M = new Module("CygMingHelper", Context);
347 M->setTargetTriple(TargetTripleStr);
349 // Create an empty function named "__main".
351 if (TargetTriple.isArch64Bit()) {
352 Result = Function::Create(
353 TypeBuilder<int64_t(void), false>::get(Context),
354 GlobalValue::ExternalLinkage, "__main", M);
356 Result = Function::Create(
357 TypeBuilder<int32_t(void), false>::get(Context),
358 GlobalValue::ExternalLinkage, "__main", M);
360 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
361 Builder.SetInsertPoint(BB);
363 if (TargetTriple.isArch64Bit())
364 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
366 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
367 Builder.CreateRet(ReturnVal);
369 // Add this new module to the ExecutionEngine.
374 //===----------------------------------------------------------------------===//
375 // main Driver function
377 int main(int argc, char **argv, char * const *envp) {
378 sys::PrintStackTraceOnErrorSignal();
379 PrettyStackTraceProgram X(argc, argv);
381 LLVMContext &Context = getGlobalContext();
382 atexit(do_shutdown); // Call llvm_shutdown() on exit.
384 // If we have a native target, initialize it to ensure it is linked in and
385 // usable by the JIT.
386 InitializeNativeTarget();
387 InitializeNativeTargetAsmPrinter();
388 InitializeNativeTargetAsmParser();
390 cl::ParseCommandLineOptions(argc, argv,
391 "llvm interpreter & dynamic compiler\n");
393 // If the user doesn't want core files, disable them.
394 if (DisableCoreFiles)
395 sys::Process::PreventCoreFiles();
397 // Load the bitcode...
399 Module *Mod = ParseIRFile(InputFile, Err, Context);
401 Err.print(argv[0], errs());
405 if (EnableCacheManager) {
407 std::string CacheName("file:");
408 CacheName.append(InputFile);
409 Mod->setModuleIdentifier(CacheName);
411 errs() << "warning: -enable-cache-manager can only be used with MCJIT.";
414 // If not jitting lazily, load the whole bitcode file eagerly too.
415 if (NoLazyCompilation) {
416 if (error_code EC = Mod->materializeAllPermanently()) {
417 errs() << argv[0] << ": bitcode didn't read correctly.\n";
418 errs() << "Reason: " << EC.message() << "\n";
425 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
426 << " information will be emitted by the non-MC JIT engine. To see full"
427 << " source debug information, enable the flag '-use-mcjit'.\n";
430 ModulePass *DebugIRPass = createDebugIRPass();
431 DebugIRPass->runOnModule(*Mod);
434 std::string ErrorMsg;
435 EngineBuilder builder(Mod);
436 builder.setMArch(MArch);
437 builder.setMCPU(MCPU);
438 builder.setMAttrs(MAttrs);
439 builder.setRelocationModel(RelocModel);
440 builder.setCodeModel(CMModel);
441 builder.setErrorStr(&ErrorMsg);
442 builder.setEngineKind(ForceInterpreter
443 ? EngineKind::Interpreter
446 // If we are supposed to override the target triple, do so now.
447 if (!TargetTriple.empty())
448 Mod->setTargetTriple(Triple::normalize(TargetTriple));
450 // Enable MCJIT if desired.
451 RTDyldMemoryManager *RTDyldMM = 0;
452 if (UseMCJIT && !ForceInterpreter) {
453 builder.setUseMCJIT(true);
455 RTDyldMM = new RemoteMemoryManager();
457 RTDyldMM = new SectionMemoryManager();
458 builder.setMCJITMemoryManager(RTDyldMM);
461 errs() << "error: Remote process execution requires -use-mcjit\n";
464 builder.setJITMemoryManager(ForceInterpreter ? 0 :
465 JITMemoryManager::CreateDefaultMemManager());
468 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
471 errs() << argv[0] << ": invalid optimization level.\n";
474 case '0': OLvl = CodeGenOpt::None; break;
475 case '1': OLvl = CodeGenOpt::Less; break;
476 case '2': OLvl = CodeGenOpt::Default; break;
477 case '3': OLvl = CodeGenOpt::Aggressive; break;
479 builder.setOptLevel(OLvl);
481 TargetOptions Options;
482 Options.UseSoftFloat = GenerateSoftFloatCalls;
483 if (FloatABIForCalls != FloatABI::Default)
484 Options.FloatABIType = FloatABIForCalls;
485 if (GenerateSoftFloatCalls)
486 FloatABIForCalls = FloatABI::Soft;
488 // Remote target execution doesn't handle EH or debug registration.
490 Options.JITEmitDebugInfo = EmitJitDebugInfo;
491 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
494 builder.setTargetOptions(Options);
496 EE = builder.create();
498 if (!ErrorMsg.empty())
499 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
501 errs() << argv[0] << ": unknown error creating EE!\n";
505 if (EnableCacheManager) {
506 CacheManager = new LLIObjectCache(ObjectCacheDir);
507 EE->setObjectCache(CacheManager);
510 // Load any additional modules specified on the command line.
511 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
512 Module *XMod = ParseIRFile(ExtraModules[i], Err, Context);
514 Err.print(argv[0], errs());
517 if (EnableCacheManager) {
519 std::string CacheName("file:");
520 CacheName.append(ExtraModules[i]);
521 XMod->setModuleIdentifier(CacheName);
523 // else, we already printed a warning above.
528 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
529 ErrorOr<object::ObjectFile *> Obj =
530 object::ObjectFile::createObjectFile(ExtraObjects[i]);
532 Err.print(argv[0], errs());
535 EE->addObjectFile(Obj.get());
538 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
539 OwningPtr<MemoryBuffer> ArBuf;
541 ec = MemoryBuffer::getFileOrSTDIN(ExtraArchives[i], ArBuf);
543 Err.print(argv[0], errs());
546 object::Archive *Ar = new object::Archive(ArBuf.take(), ec);
548 Err.print(argv[0], errs());
554 // If the target is Cygwin/MingW and we are generating remote code, we
555 // need an extra module to help out with linking.
556 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
557 addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
560 // The following functions have no effect if their respective profiling
561 // support wasn't enabled in the build configuration.
562 EE->RegisterJITEventListener(
563 JITEventListener::createOProfileJITEventListener());
564 EE->RegisterJITEventListener(
565 JITEventListener::createIntelJITEventListener());
567 if (!NoLazyCompilation && RemoteMCJIT) {
568 errs() << "warning: remote mcjit does not support lazy compilation\n";
569 NoLazyCompilation = true;
571 EE->DisableLazyCompilation(NoLazyCompilation);
573 // If the user specifically requested an argv[0] to pass into the program,
575 if (!FakeArgv0.empty()) {
576 InputFile = FakeArgv0;
578 // Otherwise, if there is a .bc suffix on the executable strip it off, it
579 // might confuse the program.
580 if (StringRef(InputFile).endswith(".bc"))
581 InputFile.erase(InputFile.length() - 3);
584 // Add the module's name to the start of the vector of arguments to main().
585 InputArgv.insert(InputArgv.begin(), InputFile);
587 // Call the main function from M as if its signature were:
588 // int main (int argc, char **argv, const char **envp)
589 // using the contents of Args to determine argc & argv, and the contents of
590 // EnvVars to determine envp.
592 Function *EntryFn = Mod->getFunction(EntryFunc);
594 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
598 // Reset errno to zero on entry to main.
604 // If the program doesn't explicitly call exit, we will need the Exit
605 // function later on to make an explicit call, so get the function now.
606 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
607 Type::getInt32Ty(Context),
610 // Run static constructors.
611 if (UseMCJIT && !ForceInterpreter) {
612 // Give MCJIT a chance to apply relocations and set page permissions.
613 EE->finalizeObject();
615 EE->runStaticConstructorsDestructors(false);
617 if (!UseMCJIT && NoLazyCompilation) {
618 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
620 if (Fn != EntryFn && !Fn->isDeclaration())
621 EE->getPointerToFunction(Fn);
625 // Trigger compilation separately so code regions that need to be
626 // invalidated will be known.
627 (void)EE->getPointerToFunction(EntryFn);
628 // Clear instruction cache before code will be executed.
630 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
633 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
635 // Run static destructors.
636 EE->runStaticConstructorsDestructors(true);
638 // If the program didn't call exit explicitly, we should call it now.
639 // This ensures that any atexit handlers get called correctly.
640 if (Function *ExitF = dyn_cast<Function>(Exit)) {
641 std::vector<GenericValue> Args;
642 GenericValue ResultGV;
643 ResultGV.IntVal = APInt(32, Result);
644 Args.push_back(ResultGV);
645 EE->runFunction(ExitF, Args);
646 errs() << "ERROR: exit(" << Result << ") returned!\n";
649 errs() << "ERROR: exit defined with wrong prototype!\n";
653 // else == "if (RemoteMCJIT)"
655 // Remote target MCJIT doesn't (yet) support static constructors. No reason
656 // it couldn't. This is a limitation of the LLI implemantation, not the
657 // MCJIT itself. FIXME.
659 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
660 // Everything is prepared now, so lay out our program for the target
661 // address space, assign the section addresses to resolve any relocations,
662 // and send it to the target.
664 OwningPtr<RemoteTarget> Target;
665 if (!ChildExecPath.empty()) { // Remote execution on a child process
666 if (!RemoteTarget::hostSupportsExternalRemoteTarget()) {
667 errs() << "Warning: host does not support external remote targets.\n"
668 << " Defaulting to simulated remote execution\n";
669 Target.reset(RemoteTarget::createRemoteTarget());
671 if (!sys::fs::can_execute(ChildExecPath)) {
672 errs() << "Unable to find usable child executable: '" << ChildExecPath
676 Target.reset(RemoteTarget::createExternalRemoteTarget(ChildExecPath));
679 // No child process name provided, use simulated remote execution.
680 Target.reset(RemoteTarget::createRemoteTarget());
683 // Give the memory manager a pointer to our remote target interface object.
684 MM->setRemoteTarget(Target.get());
686 // Create the remote target.
687 if (!Target->create()) {
688 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
692 // Since we're executing in a (at least simulated) remote address space,
693 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
694 // grab the function address directly here and tell the remote target
695 // to execute the function.
697 // Our memory manager will map generated code into the remote address
698 // space as it is loaded and copy the bits over during the finalizeMemory
701 // FIXME: argv and envp handling.
702 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
704 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
705 << format("%llx", Entry) << "\n");
707 if (!Target->executeCode(Entry, Result))
708 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
710 // Like static constructors, the remote target MCJIT support doesn't handle
711 // this yet. It could. FIXME.
713 // Stop the remote target