[Orc] New JIT APIs.
[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 #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/OrcMCJITReplacement.h"
29 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/TypeBuilder.h"
34 #include "llvm/IRReader/IRReader.h"
35 #include "llvm/Object/Archive.h"
36 #include "llvm/Object/ObjectFile.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/DynamicLibrary.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Memory.h"
44 #include "llvm/Support/MemoryBuffer.h"
45 #include "llvm/Support/PluginLoader.h"
46 #include "llvm/Support/PrettyStackTrace.h"
47 #include "llvm/Support/Process.h"
48 #include "llvm/Support/Program.h"
49 #include "llvm/Support/Signals.h"
50 #include "llvm/Support/SourceMgr.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Transforms/Instrumentation.h"
54 #include <cerrno>
55
56 #ifdef __CYGWIN__
57 #include <cygwin/version.h>
58 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
59 #define DO_NOTHING_ATEXIT 1
60 #endif
61 #endif
62
63 using namespace llvm;
64
65 #define DEBUG_TYPE "lli"
66
67 namespace {
68   cl::opt<std::string>
69   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
70
71   cl::list<std::string>
72   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
73
74   cl::opt<bool> ForceInterpreter("force-interpreter",
75                                  cl::desc("Force interpretation: disable JIT"),
76                                  cl::init(false));
77
78   cl::opt<bool> UseOrcMCJITReplacement("use-orcmcjit",
79                                        cl::desc("Use the experimental "
80                                                 "OrcMCJITReplacement as a "
81                                                 "drop-in replacement for "
82                                                 "MCJIT."),
83                                        cl::init(false));
84
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."),
90     cl::init(false));
91
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.
96   cl::opt<std::string>
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(""));
102
103   // Determine optimization level.
104   cl::opt<char>
105   OptLevel("O",
106            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
107                     "(default = '-O2')"),
108            cl::Prefix,
109            cl::ZeroOrMore,
110            cl::init(' '));
111
112   cl::opt<std::string>
113   TargetTriple("mtriple", cl::desc("Override target triple for module"));
114
115   cl::opt<std::string>
116   MArch("march",
117         cl::desc("Architecture to generate assembly for (see --version)"));
118
119   cl::opt<std::string>
120   MCPU("mcpu",
121        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
122        cl::value_desc("cpu-name"),
123        cl::init(""));
124
125   cl::list<std::string>
126   MAttrs("mattr",
127          cl::CommaSeparated,
128          cl::desc("Target specific attributes (-mattr=help for details)"),
129          cl::value_desc("a1,+a2,-a3,..."));
130
131   cl::opt<std::string>
132   EntryFunc("entry-function",
133             cl::desc("Specify the entry function (default = 'main') "
134                      "of the executable"),
135             cl::value_desc("function"),
136             cl::init("main"));
137
138   cl::list<std::string>
139   ExtraModules("extra-module",
140          cl::desc("Extra modules to be loaded"),
141          cl::value_desc("input bitcode"));
142
143   cl::list<std::string>
144   ExtraObjects("extra-object",
145          cl::desc("Extra object files to be loaded"),
146          cl::value_desc("input object"));
147
148   cl::list<std::string>
149   ExtraArchives("extra-archive",
150          cl::desc("Extra archive files to be loaded"),
151          cl::value_desc("input archive"));
152
153   cl::opt<bool>
154   EnableCacheManager("enable-cache-manager",
155         cl::desc("Use cache manager to save/load mdoules"),
156         cl::init(false));
157
158   cl::opt<std::string>
159   ObjectCacheDir("object-cache-dir",
160                   cl::desc("Directory to store cached object files "
161                            "(must be user writable)"),
162                   cl::init(""));
163
164   cl::opt<std::string>
165   FakeArgv0("fake-argv0",
166             cl::desc("Override the 'argv[0]' value passed into the executing"
167                      " program"), cl::value_desc("executable"));
168
169   cl::opt<bool>
170   DisableCoreFiles("disable-core-files", cl::Hidden,
171                    cl::desc("Disable emission of core files if possible"));
172
173   cl::opt<bool>
174   NoLazyCompilation("disable-lazy-compilation",
175                   cl::desc("Disable JIT lazy compilation"),
176                   cl::init(false));
177
178   cl::opt<Reloc::Model>
179   RelocModel("relocation-model",
180              cl::desc("Choose relocation model"),
181              cl::init(Reloc::Default),
182              cl::values(
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"),
191             clEnumValEnd));
192
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",
200                                 "Small code model"),
201                      clEnumValN(CodeModel::Kernel, "kernel",
202                                 "Kernel code model"),
203                      clEnumValN(CodeModel::Medium, "medium",
204                                 "Medium code model"),
205                      clEnumValN(CodeModel::Large, "large",
206                                 "Large code model"),
207                      clEnumValEnd));
208
209   cl::opt<bool>
210   GenerateSoftFloatCalls("soft-float",
211     cl::desc("Generate software floating point library calls"),
212     cl::init(false));
213
214   cl::opt<llvm::FloatABI::ABIType>
215   FloatABIForCalls("float-abi",
216                    cl::desc("Choose float ABI type"),
217                    cl::init(FloatABI::Default),
218                    cl::values(
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)"),
225                      clEnumValEnd));
226   cl::opt<bool>
227 // In debug builds, make this default to true.
228 #ifdef NDEBUG
229 #define EMIT_DEBUG false
230 #else
231 #define EMIT_DEBUG true
232 #endif
233   EmitJitDebugInfo("jit-emit-debug",
234     cl::desc("Emit debug information to debugger"),
235     cl::init(EMIT_DEBUG));
236 #undef EMIT_DEBUG
237
238   static cl::opt<bool>
239   EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
240     cl::Hidden,
241     cl::desc("Emit debug info objfiles to disk"),
242     cl::init(false));
243 }
244
245 //===----------------------------------------------------------------------===//
246 // Object cache
247 //
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.
253 //
254 class LLIObjectCache : public ObjectCache {
255 public:
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 += '/';
261   }
262   virtual ~LLIObjectCache() {}
263
264   void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
265     const std::string ModuleID = M->getModuleIdentifier();
266     std::string CacheName;
267     if (!getCacheFilename(ModuleID, CacheName))
268       return;
269     if (!CacheDir.empty()) { // Create user-defined cache dir.
270       SmallString<128> dir(CacheName);
271       sys::path::remove_filename(dir);
272       sys::fs::create_directories(Twine(dir));
273     }
274     std::error_code EC;
275     raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
276     outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
277     outfile.close();
278   }
279
280   std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
281     const std::string ModuleID = M->getModuleIdentifier();
282     std::string CacheName;
283     if (!getCacheFilename(ModuleID, CacheName))
284       return nullptr;
285     // Load the object from the cache filename
286     ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
287         MemoryBuffer::getFile(CacheName.c_str(), -1, false);
288     // If the file isn't there, that's OK.
289     if (!IRObjectBuffer)
290       return nullptr;
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
294     // out of scope.
295     return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
296   }
297
298 private:
299   std::string CacheDir;
300
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)
305       return false;
306         std::string CacheSubdir = ModID.substr(PrefixLength);
307 #if defined(_WIN32)
308         // Transform "X:\foo" => "/X\foo" for convenience.
309         if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
310           CacheSubdir[1] = CacheSubdir[0];
311           CacheSubdir[0] = '/';
312         }
313 #endif
314     CacheName = CacheDir + CacheSubdir;
315     size_t pos = CacheName.rfind('.');
316     CacheName.replace(pos, CacheName.length() - pos, ".o");
317     return true;
318   }
319 };
320
321 static ExecutionEngine *EE = nullptr;
322 static LLIObjectCache *CacheManager = nullptr;
323
324 static void do_shutdown() {
325   // Cygwin-1.5 invokes DLL's dtors before atexit handler.
326 #ifndef DO_NOTHING_ATEXIT
327   delete EE;
328   if (CacheManager)
329     delete CacheManager;
330   llvm_shutdown();
331 #endif
332 }
333
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);
344
345   // Create a new module.
346   std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
347   M->setTargetTriple(TargetTripleStr);
348
349   // Create an empty function named "__main".
350   Function *Result;
351   if (TargetTriple.isArch64Bit()) {
352     Result = Function::Create(
353       TypeBuilder<int64_t(void), false>::get(Context),
354       GlobalValue::ExternalLinkage, "__main", M.get());
355   } else {
356     Result = Function::Create(
357       TypeBuilder<int32_t(void), false>::get(Context),
358       GlobalValue::ExternalLinkage, "__main", M.get());
359   }
360   BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
361   Builder.SetInsertPoint(BB);
362   Value *ReturnVal;
363   if (TargetTriple.isArch64Bit())
364     ReturnVal = ConstantInt::get(Context, APInt(64, 0));
365   else
366     ReturnVal = ConstantInt::get(Context, APInt(32, 0));
367   Builder.CreateRet(ReturnVal);
368
369   // Add this new module to the ExecutionEngine.
370   EE->addModule(std::move(M));
371 }
372
373
374 //===----------------------------------------------------------------------===//
375 // main Driver function
376 //
377 int main(int argc, char **argv, char * const *envp) {
378   sys::PrintStackTraceOnErrorSignal();
379   PrettyStackTraceProgram X(argc, argv);
380
381   LLVMContext &Context = getGlobalContext();
382   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
383
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();
389
390   cl::ParseCommandLineOptions(argc, argv,
391                               "llvm interpreter & dynamic compiler\n");
392
393   // If the user doesn't want core files, disable them.
394   if (DisableCoreFiles)
395     sys::Process::PreventCoreFiles();
396
397   // Load the bitcode...
398   SMDiagnostic Err;
399   std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
400   Module *Mod = Owner.get();
401   if (!Mod) {
402     Err.print(argv[0], errs());
403     return 1;
404   }
405
406   if (EnableCacheManager) {
407     std::string CacheName("file:");
408     CacheName.append(InputFile);
409     Mod->setModuleIdentifier(CacheName);
410   }
411
412   // If not jitting lazily, load the whole bitcode file eagerly too.
413   if (NoLazyCompilation) {
414     if (std::error_code EC = Mod->materializeAllPermanently()) {
415       errs() << argv[0] << ": bitcode didn't read correctly.\n";
416       errs() << "Reason: " << EC.message() << "\n";
417       exit(1);
418     }
419   }
420
421   std::string ErrorMsg;
422   EngineBuilder builder(std::move(Owner));
423   builder.setMArch(MArch);
424   builder.setMCPU(MCPU);
425   builder.setMAttrs(MAttrs);
426   builder.setRelocationModel(RelocModel);
427   builder.setCodeModel(CMModel);
428   builder.setErrorStr(&ErrorMsg);
429   builder.setEngineKind(ForceInterpreter
430                         ? EngineKind::Interpreter
431                         : EngineKind::JIT);
432   builder.setUseOrcMCJITReplacement(UseOrcMCJITReplacement);
433
434   // If we are supposed to override the target triple, do so now.
435   if (!TargetTriple.empty())
436     Mod->setTargetTriple(Triple::normalize(TargetTriple));
437
438   // Enable MCJIT if desired.
439   RTDyldMemoryManager *RTDyldMM = nullptr;
440   if (!ForceInterpreter) {
441     if (RemoteMCJIT)
442       RTDyldMM = new RemoteMemoryManager();
443     else
444       RTDyldMM = new SectionMemoryManager();
445
446     // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
447     // RTDyldMM: We still use it below, even though we don't own it.
448     builder.setMCJITMemoryManager(
449       std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
450   } else if (RemoteMCJIT) {
451     errs() << "error: Remote process execution does not work with the "
452               "interpreter.\n";
453     exit(1);
454   }
455
456   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
457   switch (OptLevel) {
458   default:
459     errs() << argv[0] << ": invalid optimization level.\n";
460     return 1;
461   case ' ': break;
462   case '0': OLvl = CodeGenOpt::None; break;
463   case '1': OLvl = CodeGenOpt::Less; break;
464   case '2': OLvl = CodeGenOpt::Default; break;
465   case '3': OLvl = CodeGenOpt::Aggressive; break;
466   }
467   builder.setOptLevel(OLvl);
468
469   TargetOptions Options;
470   Options.UseSoftFloat = GenerateSoftFloatCalls;
471   if (FloatABIForCalls != FloatABI::Default)
472     Options.FloatABIType = FloatABIForCalls;
473   if (GenerateSoftFloatCalls)
474     FloatABIForCalls = FloatABI::Soft;
475
476   // Remote target execution doesn't handle EH or debug registration.
477   if (!RemoteMCJIT) {
478     Options.JITEmitDebugInfo = EmitJitDebugInfo;
479     Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
480   }
481
482   builder.setTargetOptions(Options);
483
484   EE = builder.create();
485   if (!EE) {
486     if (!ErrorMsg.empty())
487       errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
488     else
489       errs() << argv[0] << ": unknown error creating EE!\n";
490     exit(1);
491   }
492
493   if (EnableCacheManager) {
494     CacheManager = new LLIObjectCache(ObjectCacheDir);
495     EE->setObjectCache(CacheManager);
496   }
497
498   // Load any additional modules specified on the command line.
499   for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
500     std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
501     if (!XMod) {
502       Err.print(argv[0], errs());
503       return 1;
504     }
505     if (EnableCacheManager) {
506       std::string CacheName("file:");
507       CacheName.append(ExtraModules[i]);
508       XMod->setModuleIdentifier(CacheName);
509     }
510     EE->addModule(std::move(XMod));
511   }
512
513   for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
514     ErrorOr<object::OwningBinary<object::ObjectFile>> Obj =
515         object::ObjectFile::createObjectFile(ExtraObjects[i]);
516     if (!Obj) {
517       Err.print(argv[0], errs());
518       return 1;
519     }
520     object::OwningBinary<object::ObjectFile> &O = Obj.get();
521     EE->addObjectFile(std::move(O));
522   }
523
524   for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
525     ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
526         MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
527     if (!ArBufOrErr) {
528       Err.print(argv[0], errs());
529       return 1;
530     }
531     std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
532
533     ErrorOr<std::unique_ptr<object::Archive>> ArOrErr =
534         object::Archive::create(ArBuf->getMemBufferRef());
535     if (std::error_code EC = ArOrErr.getError()) {
536       errs() << EC.message();
537       return 1;
538     }
539     std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
540
541     object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
542
543     EE->addArchive(std::move(OB));
544   }
545
546   // If the target is Cygwin/MingW and we are generating remote code, we
547   // need an extra module to help out with linking.
548   if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
549     addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
550   }
551
552   // The following functions have no effect if their respective profiling
553   // support wasn't enabled in the build configuration.
554   EE->RegisterJITEventListener(
555                 JITEventListener::createOProfileJITEventListener());
556   EE->RegisterJITEventListener(
557                 JITEventListener::createIntelJITEventListener());
558
559   if (!NoLazyCompilation && RemoteMCJIT) {
560     errs() << "warning: remote mcjit does not support lazy compilation\n";
561     NoLazyCompilation = true;
562   }
563   EE->DisableLazyCompilation(NoLazyCompilation);
564
565   // If the user specifically requested an argv[0] to pass into the program,
566   // do it now.
567   if (!FakeArgv0.empty()) {
568     InputFile = static_cast<std::string>(FakeArgv0);
569   } else {
570     // Otherwise, if there is a .bc suffix on the executable strip it off, it
571     // might confuse the program.
572     if (StringRef(InputFile).endswith(".bc"))
573       InputFile.erase(InputFile.length() - 3);
574   }
575
576   // Add the module's name to the start of the vector of arguments to main().
577   InputArgv.insert(InputArgv.begin(), InputFile);
578
579   // Call the main function from M as if its signature were:
580   //   int main (int argc, char **argv, const char **envp)
581   // using the contents of Args to determine argc & argv, and the contents of
582   // EnvVars to determine envp.
583   //
584   Function *EntryFn = Mod->getFunction(EntryFunc);
585   if (!EntryFn) {
586     errs() << '\'' << EntryFunc << "\' function not found in module.\n";
587     return -1;
588   }
589
590   // Reset errno to zero on entry to main.
591   errno = 0;
592
593   int Result;
594
595   if (!RemoteMCJIT) {
596     // If the program doesn't explicitly call exit, we will need the Exit
597     // function later on to make an explicit call, so get the function now.
598     Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
599                                                       Type::getInt32Ty(Context),
600                                                       NULL);
601
602     // Run static constructors.
603     if (!ForceInterpreter) {
604       // Give MCJIT a chance to apply relocations and set page permissions.
605       EE->finalizeObject();
606     }
607     EE->runStaticConstructorsDestructors(false);
608
609     // Trigger compilation separately so code regions that need to be
610     // invalidated will be known.
611     (void)EE->getPointerToFunction(EntryFn);
612     // Clear instruction cache before code will be executed.
613     if (RTDyldMM)
614       static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
615
616     // Run main.
617     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
618
619     // Run static destructors.
620     EE->runStaticConstructorsDestructors(true);
621
622     // If the program didn't call exit explicitly, we should call it now.
623     // This ensures that any atexit handlers get called correctly.
624     if (Function *ExitF = dyn_cast<Function>(Exit)) {
625       std::vector<GenericValue> Args;
626       GenericValue ResultGV;
627       ResultGV.IntVal = APInt(32, Result);
628       Args.push_back(ResultGV);
629       EE->runFunction(ExitF, Args);
630       errs() << "ERROR: exit(" << Result << ") returned!\n";
631       abort();
632     } else {
633       errs() << "ERROR: exit defined with wrong prototype!\n";
634       abort();
635     }
636   } else {
637     // else == "if (RemoteMCJIT)"
638
639     // Remote target MCJIT doesn't (yet) support static constructors. No reason
640     // it couldn't. This is a limitation of the LLI implemantation, not the
641     // MCJIT itself. FIXME.
642     //
643     RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
644     // Everything is prepared now, so lay out our program for the target
645     // address space, assign the section addresses to resolve any relocations,
646     // and send it to the target.
647
648     std::unique_ptr<RemoteTarget> Target;
649     if (!ChildExecPath.empty()) { // Remote execution on a child process
650 #ifndef LLVM_ON_UNIX
651       // FIXME: Remove this pointless fallback mode which causes tests to "pass"
652       // on platforms where they should XFAIL.
653       errs() << "Warning: host does not support external remote targets.\n"
654              << "  Defaulting to simulated remote execution\n";
655       Target.reset(new RemoteTarget);
656 #else
657       if (!sys::fs::can_execute(ChildExecPath)) {
658         errs() << "Unable to find usable child executable: '" << ChildExecPath
659                << "'\n";
660         return -1;
661       }
662       Target.reset(new RemoteTargetExternal(ChildExecPath));
663 #endif
664     } else {
665       // No child process name provided, use simulated remote execution.
666       Target.reset(new RemoteTarget);
667     }
668
669     // Give the memory manager a pointer to our remote target interface object.
670     MM->setRemoteTarget(Target.get());
671
672     // Create the remote target.
673     if (!Target->create()) {
674       errs() << "ERROR: " << Target->getErrorMsg() << "\n";
675       return EXIT_FAILURE;
676     }
677
678     // Since we're executing in a (at least simulated) remote address space,
679     // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
680     // grab the function address directly here and tell the remote target
681     // to execute the function.
682     //
683     // Our memory manager will map generated code into the remote address
684     // space as it is loaded and copy the bits over during the finalizeMemory
685     // operation.
686     //
687     // FIXME: argv and envp handling.
688     uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
689
690     DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
691                  << format("%llx", Entry) << "\n");
692
693     if (!Target->executeCode(Entry, Result))
694       errs() << "ERROR: " << Target->getErrorMsg() << "\n";
695
696     // Like static constructors, the remote target MCJIT support doesn't handle
697     // this yet. It could. FIXME.
698
699     // Stop the remote target
700     Target->stop();
701   }
702
703   return Result;
704 }