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