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