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