lli.cpp revision 730e3c69952d4f26a0c51b55902ac55c88238ee8
1//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
13//
14//===----------------------------------------------------------------------===//
15
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/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/Program.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/SourceMgr.h"
47#include "llvm/Support/TargetSelect.h"
48#include "llvm/Support/raw_ostream.h"
49#include "llvm/Transforms/Instrumentation.h"
50#include <cerrno>
51
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
59using namespace llvm;
60
61namespace {
62  cl::opt<std::string>
63  InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
64
65  cl::list<std::string>
66  InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
67
68  cl::opt<bool> ForceInterpreter("force-interpreter",
69                                 cl::desc("Force interpretation: disable JIT"),
70                                 cl::init(false));
71
72  cl::opt<bool> UseMCJIT(
73    "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
74    cl::init(false));
75
76  cl::opt<bool> DebugIR(
77    "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
78    cl::init(false));
79
80  // 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
87  // 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
99  // 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(' '));
107
108  cl::opt<std::string>
109  TargetTriple("mtriple", cl::desc("Override target triple for module"));
110
111  cl::opt<std::string>
112  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>
128  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"));
133
134  cl::list<std::string>
135  ExtraModules("extra-module",
136         cl::desc("Extra modules to be loaded"),
137         cl::value_desc("input bitcode"));
138
139  cl::opt<std::string>
140  FakeArgv0("fake-argv0",
141            cl::desc("Override the 'argv[0]' value passed into the executing"
142                     " program"), cl::value_desc("executable"));
143
144  cl::opt<bool>
145  DisableCoreFiles("disable-core-files", cl::Hidden,
146                   cl::desc("Disable emission of core files if possible"));
147
148  cl::opt<bool>
149  NoLazyCompilation("disable-lazy-compilation",
150                  cl::desc("Disable JIT lazy compilation"),
151                  cl::init(false));
152
153  cl::opt<Reloc::Model>
154  RelocModel("relocation-model",
155             cl::desc("Choose relocation model"),
156             cl::init(Reloc::Default),
157             cl::values(
158            clEnumValN(Reloc::Default, "default",
159                       "Target default relocation model"),
160            clEnumValN(Reloc::Static, "static",
161                       "Non-relocatable code"),
162            clEnumValN(Reloc::PIC_, "pic",
163                       "Fully relocatable, position independent code"),
164            clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
165                       "Relocatable external references, non-relocatable code"),
166            clEnumValEnd));
167
168  cl::opt<llvm::CodeModel::Model>
169  CMModel("code-model",
170          cl::desc("Choose code model"),
171          cl::init(CodeModel::JITDefault),
172          cl::values(clEnumValN(CodeModel::JITDefault, "default",
173                                "Target default JIT code model"),
174                     clEnumValN(CodeModel::Small, "small",
175                                "Small code model"),
176                     clEnumValN(CodeModel::Kernel, "kernel",
177                                "Kernel code model"),
178                     clEnumValN(CodeModel::Medium, "medium",
179                                "Medium code model"),
180                     clEnumValN(CodeModel::Large, "large",
181                                "Large code model"),
182                     clEnumValEnd));
183
184  cl::opt<bool>
185  GenerateSoftFloatCalls("soft-float",
186    cl::desc("Generate software floating point library calls"),
187    cl::init(false));
188
189  cl::opt<llvm::FloatABI::ABIType>
190  FloatABIForCalls("float-abi",
191                   cl::desc("Choose float ABI type"),
192                   cl::init(FloatABI::Default),
193                   cl::values(
194                     clEnumValN(FloatABI::Default, "default",
195                                "Target default float ABI type"),
196                     clEnumValN(FloatABI::Soft, "soft",
197                                "Soft float ABI (implied by -soft-float)"),
198                     clEnumValN(FloatABI::Hard, "hard",
199                                "Hard float ABI (uses FP registers)"),
200                     clEnumValEnd));
201  cl::opt<bool>
202// In debug builds, make this default to true.
203#ifdef NDEBUG
204#define EMIT_DEBUG false
205#else
206#define EMIT_DEBUG true
207#endif
208  EmitJitDebugInfo("jit-emit-debug",
209    cl::desc("Emit debug information to debugger"),
210    cl::init(EMIT_DEBUG));
211#undef EMIT_DEBUG
212
213  static cl::opt<bool>
214  EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
215    cl::Hidden,
216    cl::desc("Emit debug info objfiles to disk"),
217    cl::init(false));
218}
219
220static ExecutionEngine *EE = 0;
221
222static void do_shutdown() {
223  // Cygwin-1.5 invokes DLL's dtors before atexit handler.
224#ifndef DO_NOTHING_ATEXIT
225  delete EE;
226  llvm_shutdown();
227#endif
228}
229
230//===----------------------------------------------------------------------===//
231// main Driver function
232//
233int main(int argc, char **argv, char * const *envp) {
234  sys::PrintStackTraceOnErrorSignal();
235  PrettyStackTraceProgram X(argc, argv);
236
237  LLVMContext &Context = getGlobalContext();
238  atexit(do_shutdown);  // Call llvm_shutdown() on exit.
239
240  // If we have a native target, initialize it to ensure it is linked in and
241  // usable by the JIT.
242  InitializeNativeTarget();
243  InitializeNativeTargetAsmPrinter();
244  InitializeNativeTargetAsmParser();
245
246  cl::ParseCommandLineOptions(argc, argv,
247                              "llvm interpreter & dynamic compiler\n");
248
249  // If the user doesn't want core files, disable them.
250  if (DisableCoreFiles)
251    sys::Process::PreventCoreFiles();
252
253  // Load the bitcode...
254  SMDiagnostic Err;
255  Module *Mod = ParseIRFile(InputFile, Err, Context);
256  if (!Mod) {
257    Err.print(argv[0], errs());
258    return 1;
259  }
260
261  // If not jitting lazily, load the whole bitcode file eagerly too.
262  std::string ErrorMsg;
263  if (NoLazyCompilation) {
264    if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
265      errs() << argv[0] << ": bitcode didn't read correctly.\n";
266      errs() << "Reason: " << ErrorMsg << "\n";
267      exit(1);
268    }
269  }
270
271  if (DebugIR) {
272    if (!UseMCJIT) {
273      errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
274        << " information will be emitted by the non-MC JIT engine. To see full"
275        << " source debug information, enable the flag '-use-mcjit'.\n";
276
277    }
278    ModulePass *DebugIRPass = createDebugIRPass();
279    DebugIRPass->runOnModule(*Mod);
280  }
281
282  EngineBuilder builder(Mod);
283  builder.setMArch(MArch);
284  builder.setMCPU(MCPU);
285  builder.setMAttrs(MAttrs);
286  builder.setRelocationModel(RelocModel);
287  builder.setCodeModel(CMModel);
288  builder.setErrorStr(&ErrorMsg);
289  builder.setEngineKind(ForceInterpreter
290                        ? EngineKind::Interpreter
291                        : EngineKind::JIT);
292
293  // If we are supposed to override the target triple, do so now.
294  if (!TargetTriple.empty())
295    Mod->setTargetTriple(Triple::normalize(TargetTriple));
296
297  // Enable MCJIT if desired.
298  RTDyldMemoryManager *RTDyldMM = 0;
299  if (UseMCJIT && !ForceInterpreter) {
300    builder.setUseMCJIT(true);
301    if (RemoteMCJIT)
302      RTDyldMM = new RemoteMemoryManager();
303    else
304      RTDyldMM = new SectionMemoryManager();
305    builder.setMCJITMemoryManager(RTDyldMM);
306  } else {
307    if (RemoteMCJIT) {
308      errs() << "error: Remote process execution requires -use-mcjit\n";
309      exit(1);
310    }
311    builder.setJITMemoryManager(ForceInterpreter ? 0 :
312                                JITMemoryManager::CreateDefaultMemManager());
313  }
314
315  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
316  switch (OptLevel) {
317  default:
318    errs() << argv[0] << ": invalid optimization level.\n";
319    return 1;
320  case ' ': break;
321  case '0': OLvl = CodeGenOpt::None; break;
322  case '1': OLvl = CodeGenOpt::Less; break;
323  case '2': OLvl = CodeGenOpt::Default; break;
324  case '3': OLvl = CodeGenOpt::Aggressive; break;
325  }
326  builder.setOptLevel(OLvl);
327
328  TargetOptions Options;
329  Options.UseSoftFloat = GenerateSoftFloatCalls;
330  if (FloatABIForCalls != FloatABI::Default)
331    Options.FloatABIType = FloatABIForCalls;
332  if (GenerateSoftFloatCalls)
333    FloatABIForCalls = FloatABI::Soft;
334
335  // Remote target execution doesn't handle EH or debug registration.
336  if (!RemoteMCJIT) {
337    Options.JITEmitDebugInfo = EmitJitDebugInfo;
338    Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
339  }
340
341  builder.setTargetOptions(Options);
342
343  EE = builder.create();
344  if (!EE) {
345    if (!ErrorMsg.empty())
346      errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
347    else
348      errs() << argv[0] << ": unknown error creating EE!\n";
349    exit(1);
350  }
351
352  // Load any additional modules specified on the command line.
353  for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
354    Module *XMod = ParseIRFile(ExtraModules[i], Err, Context);
355    if (!XMod) {
356      Err.print(argv[0], errs());
357      return 1;
358    }
359    EE->addModule(XMod);
360  }
361
362  // The following functions have no effect if their respective profiling
363  // support wasn't enabled in the build configuration.
364  EE->RegisterJITEventListener(
365                JITEventListener::createOProfileJITEventListener());
366  EE->RegisterJITEventListener(
367                JITEventListener::createIntelJITEventListener());
368
369  if (!NoLazyCompilation && RemoteMCJIT) {
370    errs() << "warning: remote mcjit does not support lazy compilation\n";
371    NoLazyCompilation = true;
372  }
373  EE->DisableLazyCompilation(NoLazyCompilation);
374
375  // If the user specifically requested an argv[0] to pass into the program,
376  // do it now.
377  if (!FakeArgv0.empty()) {
378    InputFile = FakeArgv0;
379  } else {
380    // Otherwise, if there is a .bc suffix on the executable strip it off, it
381    // might confuse the program.
382    if (StringRef(InputFile).endswith(".bc"))
383      InputFile.erase(InputFile.length() - 3);
384  }
385
386  // Add the module's name to the start of the vector of arguments to main().
387  InputArgv.insert(InputArgv.begin(), InputFile);
388
389  // Call the main function from M as if its signature were:
390  //   int main (int argc, char **argv, const char **envp)
391  // using the contents of Args to determine argc & argv, and the contents of
392  // EnvVars to determine envp.
393  //
394  Function *EntryFn = Mod->getFunction(EntryFunc);
395  if (!EntryFn) {
396    errs() << '\'' << EntryFunc << "\' function not found in module.\n";
397    return -1;
398  }
399
400  // Reset errno to zero on entry to main.
401  errno = 0;
402
403  int Result;
404
405  if (!RemoteMCJIT) {
406    // If the program doesn't explicitly call exit, we will need the Exit
407    // function later on to make an explicit call, so get the function now.
408    Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
409                                                      Type::getInt32Ty(Context),
410                                                      NULL);
411
412    // Run static constructors.
413    if (UseMCJIT && !ForceInterpreter) {
414      // Give MCJIT a chance to apply relocations and set page permissions.
415      EE->finalizeObject();
416    }
417    EE->runStaticConstructorsDestructors(false);
418
419    if (!UseMCJIT && NoLazyCompilation) {
420      for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
421        Function *Fn = &*I;
422        if (Fn != EntryFn && !Fn->isDeclaration())
423          EE->getPointerToFunction(Fn);
424      }
425    }
426
427    // Trigger compilation separately so code regions that need to be
428    // invalidated will be known.
429    (void)EE->getPointerToFunction(EntryFn);
430    // Clear instruction cache before code will be executed.
431    if (RTDyldMM)
432      static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
433
434    // Run main.
435    Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
436
437    // Run static destructors.
438    EE->runStaticConstructorsDestructors(true);
439
440    // If the program didn't call exit explicitly, we should call it now.
441    // This ensures that any atexit handlers get called correctly.
442    if (Function *ExitF = dyn_cast<Function>(Exit)) {
443      std::vector<GenericValue> Args;
444      GenericValue ResultGV;
445      ResultGV.IntVal = APInt(32, Result);
446      Args.push_back(ResultGV);
447      EE->runFunction(ExitF, Args);
448      errs() << "ERROR: exit(" << Result << ") returned!\n";
449      abort();
450    } else {
451      errs() << "ERROR: exit defined with wrong prototype!\n";
452      abort();
453    }
454  } else {
455    // else == "if (RemoteMCJIT)"
456
457    // Remote target MCJIT doesn't (yet) support static constructors. No reason
458    // it couldn't. This is a limitation of the LLI implemantation, not the
459    // MCJIT itself. FIXME.
460    //
461    RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
462    // Everything is prepared now, so lay out our program for the target
463    // address space, assign the section addresses to resolve any relocations,
464    // and send it to the target.
465
466    OwningPtr<RemoteTarget> Target;
467    if (!MCJITRemoteProcess.empty()) { // Remote execution on a child process
468      if (!RemoteTarget::hostSupportsExternalRemoteTarget()) {
469        errs() << "Warning: host does not support external remote targets.\n"
470               << "  Defaulting to simulated remote execution\n";
471        Target.reset(RemoteTarget::createRemoteTarget());
472      } else {
473        std::string ChildEXE = sys::FindProgramByName(MCJITRemoteProcess);
474        if (ChildEXE == "") {
475          errs() << "Unable to find child target: '\''" << MCJITRemoteProcess << "\'\n";
476          return -1;
477        }
478        Target.reset(RemoteTarget::createExternalRemoteTarget(ChildEXE));
479      }
480    } else {
481      // No child process name provided, use simulated remote execution.
482      Target.reset(RemoteTarget::createRemoteTarget());
483    }
484
485    // Give the memory manager a pointer to our remote target interface object.
486    MM->setRemoteTarget(Target.get());
487
488    // Create the remote target.
489    Target->create();
490
491    // Since we're executing in a (at least simulated) remote address space,
492    // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
493    // grab the function address directly here and tell the remote target
494    // to execute the function.
495    //
496    // Our memory manager will map generated code into the remote address
497    // space as it is loaded and copy the bits over during the finalizeMemory
498    // operation.
499    //
500    // FIXME: argv and envp handling.
501    uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
502
503    DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
504                 << format("%llx", Entry) << "\n");
505
506    if (Target->executeCode(Entry, Result))
507      errs() << "ERROR: " << Target->getErrorMsg() << "\n";
508
509    // Like static constructors, the remote target MCJIT support doesn't handle
510    // this yet. It could. FIXME.
511
512    // Stop the remote target
513    Target->stop();
514  }
515
516  return Result;
517}
518