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