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