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