blob: 5167628b1a97af231e1753fad592329a75bf8b81 [file] [log] [blame]
Chris Lattnera0d7b082002-12-23 23:59:41 +00001//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner345353d2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +00009//
Chris Lattner141ea3a2003-12-26 05:07:35 +000010// 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
Torok Edwinf011f282009-07-03 12:11:32 +000012// compiler, or through an interpreter if no JIT is available for this platform.
Chris Lattnerd7ff5782001-08-23 17:05:04 +000013//
14//===----------------------------------------------------------------------===//
15
Lang Hames9528bba2015-03-25 12:11:48 +000016#include "OrcLazyJIT.h"
Lang Hames9d7a2692016-01-11 16:35:55 +000017#include "RemoteJITUtils.h"
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +000018#include "llvm/ADT/StringExtras.h"
Duncan Sands3bd97fe2010-08-28 01:30:02 +000019#include "llvm/ADT/Triple.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000020#include "llvm/Bitcode/BitcodeReader.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000021#include "llvm/CodeGen/CommandFlags.h"
Chris Lattner5af6a3f2006-08-01 22:34:35 +000022#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Brian Gaekee99ca442003-09-05 19:42:34 +000023#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000024#include "llvm/ExecutionEngine/Interpreter.h"
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +000025#include "llvm/ExecutionEngine/JITEventListener.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000026#include "llvm/ExecutionEngine/MCJIT.h"
Lang Hames173c69f2014-01-08 04:09:09 +000027#include "llvm/ExecutionEngine/ObjectCache.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000028#include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
Lang Hames93de2a12015-01-23 21:25:00 +000029#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
Andrew Kaylor58365b92012-11-27 19:49:00 +000030#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000031#include "llvm/IR/IRBuilder.h"
Rafael Espindola79e238a2017-08-03 02:16:21 +000032#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Module.h"
34#include "llvm/IR/Type.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000035#include "llvm/IR/TypeBuilder.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000036#include "llvm/IRReader/IRReader.h"
Lang Hames173c69f2014-01-08 04:09:09 +000037#include "llvm/Object/Archive.h"
38#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000039#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/DynamicLibrary.h"
42#include "llvm/Support/Format.h"
Chris Lattner76d46322006-12-06 01:18:01 +000043#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000044#include "llvm/Support/MathExtras.h"
45#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000046#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000047#include "llvm/Support/Path.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000048#include "llvm/Support/PluginLoader.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000049#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000050#include "llvm/Support/Process.h"
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000051#include "llvm/Support/Program.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000052#include "llvm/Support/Signals.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000053#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000054#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000055#include "llvm/Support/raw_ostream.h"
Daniel Maleaa960c542013-06-28 19:11:40 +000056#include "llvm/Transforms/Instrumentation.h"
Chris Lattner4c522b92007-04-27 17:02:33 +000057#include <cerrno>
NAKAMURA Takumi15304872010-10-22 14:53:59 +000058
59#ifdef __CYGWIN__
60#include <cygwin/version.h>
61#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
62#define DO_NOTHING_ATEXIT 1
63#endif
64#endif
65
Brian Gaeke960707c2003-11-11 22:41:34 +000066using namespace llvm;
67
Chandler Carruthf98597a2014-04-22 03:10:36 +000068#define DEBUG_TYPE "lli"
69
Chris Lattnera0d7b082002-12-23 23:59:41 +000070namespace {
Lang Hames9528bba2015-03-25 12:11:48 +000071
72 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
73
Chris Lattnera0d7b082002-12-23 23:59:41 +000074 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000075 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000076
Chris Lattnera0d7b082002-12-23 23:59:41 +000077 cl::list<std::string>
78 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000079
Chris Lattnera0d7b082002-12-23 23:59:41 +000080 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000081 cl::desc("Force interpretation: disable JIT"),
82 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000083
Lang Hames9528bba2015-03-25 12:11:48 +000084 cl::opt<JITKind> UseJITKind("jit-kind",
85 cl::desc("Choose underlying JIT kind."),
86 cl::init(JITKind::MCJIT),
87 cl::values(
88 clEnumValN(JITKind::MCJIT, "mcjit",
89 "MCJIT"),
90 clEnumValN(JITKind::OrcMCJITReplacement,
91 "orc-mcjit",
92 "Orc-based MCJIT replacement"),
93 clEnumValN(JITKind::OrcLazy,
94 "orc-lazy",
Mehdi Amini732afdd2016-10-08 19:41:06 +000095 "Orc-based lazy JIT.")));
Lang Hames93de2a12015-01-23 21:25:00 +000096
Jim Grosbach0f435d02012-09-05 16:50:34 +000097 // The MCJIT supports building for a target address space separate from
98 // the JIT compilation process. Use a forked process and a copying
99 // memory manager with IPC to execute using this functionality.
100 cl::opt<bool> RemoteMCJIT("remote-mcjit",
101 cl::desc("Execute MCJIT'ed code in a separate process."),
102 cl::init(false));
103
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000104 // Manually specify the child process for remote execution. This overrides
105 // the simulated remote execution that allocates address space for child
Andrew Kaylor89352582013-10-29 01:33:14 +0000106 // execution. The child process will be executed and will communicate with
107 // lli via stdin/stdout pipes.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000108 cl::opt<std::string>
Alp Tokera1186382014-01-22 21:52:35 +0000109 ChildExecPath("mcjit-remote-process",
110 cl::desc("Specify the filename of the process to launch "
111 "for remote MCJIT execution. If none is specified,"
112 "\n\tremote execution will be simulated in-process."),
113 cl::value_desc("filename"), cl::init(""));
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000114
Evan Cheng09bd0b12009-05-04 23:05:19 +0000115 // Determine optimization level.
116 cl::opt<char>
117 OptLevel("O",
118 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
119 "(default = '-O2')"),
120 cl::Prefix,
121 cl::ZeroOrMore,
122 cl::init(' '));
Evan Cheng06d988e2008-08-08 08:12:06 +0000123
Chris Lattner76766cb2005-12-16 05:00:21 +0000124 cl::opt<std::string>
Chris Lattner78e9e102005-12-16 05:19:18 +0000125 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Cheng61582542008-11-05 23:21:52 +0000126
127 cl::opt<std::string>
128 EntryFunc("entry-function",
129 cl::desc("Specify the entry function (default = 'main') "
130 "of the executable"),
131 cl::value_desc("function"),
132 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000133
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000134 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000135 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000136 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000137 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000138
Lang Hames173c69f2014-01-08 04:09:09 +0000139 cl::list<std::string>
140 ExtraObjects("extra-object",
141 cl::desc("Extra object files to be loaded"),
142 cl::value_desc("input object"));
143
144 cl::list<std::string>
145 ExtraArchives("extra-archive",
146 cl::desc("Extra archive files to be loaded"),
147 cl::value_desc("input archive"));
148
149 cl::opt<bool>
150 EnableCacheManager("enable-cache-manager",
Lang Hames1ddecc02014-01-09 05:24:05 +0000151 cl::desc("Use cache manager to save/load mdoules"),
Lang Hames173c69f2014-01-08 04:09:09 +0000152 cl::init(false));
153
Chris Lattner55644062003-10-28 22:51:44 +0000154 cl::opt<std::string>
Lang Hames1ddecc02014-01-09 05:24:05 +0000155 ObjectCacheDir("object-cache-dir",
156 cl::desc("Directory to store cached object files "
157 "(must be user writable)"),
158 cl::init(""));
159
160 cl::opt<std::string>
Chris Lattner55644062003-10-28 22:51:44 +0000161 FakeArgv0("fake-argv0",
162 cl::desc("Override the 'argv[0]' value passed into the executing"
163 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000164
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000165 cl::opt<bool>
166 DisableCoreFiles("disable-core-files", cl::Hidden,
167 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000168
169 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000170 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000171 cl::desc("Disable JIT lazy compilation"),
172 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000173
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000174 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000175 GenerateSoftFloatCalls("soft-float",
176 cl::desc("Generate software floating point library calls"),
177 cl::init(false));
178
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000179 ExitOnError ExitOnErr;
Chris Lattnera0d7b082002-12-23 23:59:41 +0000180}
Chris Lattner009f8102001-10-27 08:43:52 +0000181
Lang Hames173c69f2014-01-08 04:09:09 +0000182//===----------------------------------------------------------------------===//
183// Object cache
184//
Lang Hames1ddecc02014-01-09 05:24:05 +0000185// This object cache implementation writes cached objects to disk to the
186// directory specified by CacheDir, using a filename provided in the module
187// descriptor. The cache tries to load a saved object using that path if the
188// file exists. CacheDir defaults to "", in which case objects are cached
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000189// alongside their originating bitcodes.
Lang Hames173c69f2014-01-08 04:09:09 +0000190//
191class LLIObjectCache : public ObjectCache {
192public:
Lang Hames1ddecc02014-01-09 05:24:05 +0000193 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
194 // Add trailing '/' to cache dir if necessary.
Lang Hamesf9dd8fd2014-01-09 05:29:59 +0000195 if (!this->CacheDir.empty() &&
196 this->CacheDir[this->CacheDir.size() - 1] != '/')
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000197 this->CacheDir += '/';
Lang Hames1ddecc02014-01-09 05:24:05 +0000198 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000199 ~LLIObjectCache() override {}
Lang Hames173c69f2014-01-08 04:09:09 +0000200
Rafael Espindola48af1c22014-08-19 18:44:46 +0000201 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000202 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000203 std::string CacheName;
204 if (!getCacheFilename(ModuleID, CacheName))
205 return;
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000206 if (!CacheDir.empty()) { // Create user-defined cache dir.
Rafael Espindolaf662e002015-07-15 21:24:07 +0000207 SmallString<128> dir(sys::path::parent_path(CacheName));
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000208 sys::fs::create_directories(Twine(dir));
209 }
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000210 std::error_code EC;
211 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000212 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
Lang Hames173c69f2014-01-08 04:09:09 +0000213 outfile.close();
214 }
215
Rafael Espindola5f2bb7d2014-08-13 18:49:01 +0000216 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000217 const std::string &ModuleID = M->getModuleIdentifier();
Lang Hames173c69f2014-01-08 04:09:09 +0000218 std::string CacheName;
219 if (!getCacheFilename(ModuleID, CacheName))
Craig Toppere6cb63e2014-04-25 04:24:47 +0000220 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000221 // Load the object from the cache filename
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000222 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000223 MemoryBuffer::getFile(CacheName, -1, false);
Lang Hames173c69f2014-01-08 04:09:09 +0000224 // If the file isn't there, that's OK.
225 if (!IRObjectBuffer)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000226 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000227 // MCJIT will want to write into this buffer, and we don't want that
228 // because the file has probably just been mmapped. Instead we make
229 // a copy. The filed-based buffer will be released when it goes
230 // out of scope.
Rafael Espindola3560ff22014-08-27 20:03:13 +0000231 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
Lang Hames173c69f2014-01-08 04:09:09 +0000232 }
233
234private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000235 std::string CacheDir;
236
Lang Hames173c69f2014-01-08 04:09:09 +0000237 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
238 std::string Prefix("file:");
239 size_t PrefixLength = Prefix.length();
240 if (ModID.substr(0, PrefixLength) != Prefix)
241 return false;
NAKAMURA Takumid7fd6d92014-01-10 10:38:40 +0000242 std::string CacheSubdir = ModID.substr(PrefixLength);
243#if defined(_WIN32)
244 // Transform "X:\foo" => "/X\foo" for convenience.
245 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
246 CacheSubdir[1] = CacheSubdir[0];
247 CacheSubdir[0] = '/';
248 }
249#endif
250 CacheName = CacheDir + CacheSubdir;
Lang Hames173c69f2014-01-08 04:09:09 +0000251 size_t pos = CacheName.rfind('.');
252 CacheName.replace(pos, CacheName.length() - pos, ".o");
253 return true;
254 }
255};
256
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000257// On Mingw and Cygwin, an external symbol named '__main' is called from the
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000258// generated 'main' function to allow static initialization. To avoid linking
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000259// problems with remote targets (because lli's remote target support does not
260// currently handle external linking) we add a secondary module which defines
261// an empty '__main' function.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000262static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000263 StringRef TargetTripleStr) {
264 IRBuilder<> Builder(Context);
265 Triple TargetTriple(TargetTripleStr);
266
267 // Create a new module.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000268 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000269 M->setTargetTriple(TargetTripleStr);
270
271 // Create an empty function named "__main".
272 Function *Result;
273 if (TargetTriple.isArch64Bit()) {
274 Result = Function::Create(
275 TypeBuilder<int64_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000276 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000277 } else {
278 Result = Function::Create(
279 TypeBuilder<int32_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000280 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000281 }
282 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
283 Builder.SetInsertPoint(BB);
284 Value *ReturnVal;
285 if (TargetTriple.isArch64Bit())
286 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
287 else
288 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
289 Builder.CreateRet(ReturnVal);
290
291 // Add this new module to the ExecutionEngine.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000292 EE.addModule(std::move(M));
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000293}
294
Lang Hames1899d0c2015-06-09 02:43:27 +0000295CodeGenOpt::Level getOptLevel() {
296 switch (OptLevel) {
297 default:
298 errs() << "lli: Invalid optimization level.\n";
299 exit(1);
300 case '0': return CodeGenOpt::None;
301 case '1': return CodeGenOpt::Less;
302 case ' ':
303 case '2': return CodeGenOpt::Default;
304 case '3': return CodeGenOpt::Aggressive;
305 }
306 llvm_unreachable("Unrecognized opt level.");
307}
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000308
Davide Italianoda8e6b22016-11-17 22:58:13 +0000309LLVM_ATTRIBUTE_NORETURN
310static void reportError(SMDiagnostic Err, const char *ProgName) {
311 Err.print(ProgName, errs());
312 exit(1);
313}
314
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000315//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000316// main Driver function
317//
Misha Brukman5b255e52003-10-14 21:39:53 +0000318int main(int argc, char **argv, char * const *envp) {
Richard Smith2ad6d482016-06-09 00:53:21 +0000319 sys::PrintStackTraceOnErrorSignal(argv[0]);
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000320 PrettyStackTraceProgram X(argc, argv);
Eli Bendersky4c647582012-01-16 08:56:09 +0000321
Mehdi Aminia7de8202016-04-18 18:52:39 +0000322 atexit(llvm_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000323
Lang Hamesef5a0ee2016-04-25 19:56:45 +0000324 if (argc > 1)
325 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
326
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000327 // If we have a native target, initialize it to ensure it is linked in and
328 // usable by the JIT.
329 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000330 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000331 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000332
Chris Lattner2785bdb2007-05-06 04:58:26 +0000333 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000334 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000335
Chris Lattner2785bdb2007-05-06 04:58:26 +0000336 // If the user doesn't want core files, disable them.
337 if (DisableCoreFiles)
338 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000339
Mehdi Aminia7de8202016-04-18 18:52:39 +0000340 LLVMContext Context;
341
Gabor Greife16561c2007-07-05 17:07:56 +0000342 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000343 SMDiagnostic Err;
Rafael Espindolad233b062014-08-26 17:29:46 +0000344 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000345 Module *Mod = Owner.get();
Davide Italianoda8e6b22016-11-17 22:58:13 +0000346 if (!Mod)
347 reportError(Err, argv[0]);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000348
Lang Hames368c4222016-08-02 21:00:40 +0000349 if (UseJITKind == JITKind::OrcLazy) {
350 std::vector<std::unique_ptr<Module>> Ms;
351 Ms.push_back(std::move(Owner));
352 for (auto &ExtraMod : ExtraModules) {
353 Ms.push_back(parseIRFile(ExtraMod, Err, Context));
Davide Italianoda8e6b22016-11-17 22:58:13 +0000354 if (!Ms.back())
355 reportError(Err, argv[0]);
Lang Hames368c4222016-08-02 21:00:40 +0000356 }
Lang Hames1a2e6562016-10-28 16:52:34 +0000357 std::vector<std::string> Args;
358 Args.push_back(InputFile);
359 for (auto &Arg : InputArgv)
360 Args.push_back(Arg);
361 return runOrcLazyJIT(std::move(Ms), Args);
Lang Hames368c4222016-08-02 21:00:40 +0000362 }
Lang Hames9528bba2015-03-25 12:11:48 +0000363
Lang Hames173c69f2014-01-08 04:09:09 +0000364 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000365 std::string CacheName("file:");
366 CacheName.append(InputFile);
367 Mod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000368 }
369
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000370 // If not jitting lazily, load the whole bitcode file eagerly too.
371 if (NoLazyCompilation) {
Davide Italianob0e067b2016-11-09 21:30:33 +0000372 // Use *argv instead of argv[0] to work around a wrong GCC warning.
373 ExitOnError ExitOnErr(std::string(*argv) +
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000374 ": bitcode didn't read correctly: ");
375 ExitOnErr(Mod->materializeAll());
Evan Cheng0422bef2008-04-22 06:51:41 +0000376 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000377
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000378 std::string ErrorMsg;
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000379 EngineBuilder builder(std::move(Owner));
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000380 builder.setMArch(MArch);
381 builder.setMCPU(MCPU);
382 builder.setMAttrs(MAttrs);
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000383 if (RelocModel.getNumOccurrences())
384 builder.setRelocationModel(RelocModel);
Rafael Espindola79e238a2017-08-03 02:16:21 +0000385 if (CMModel.getNumOccurrences())
386 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000387 builder.setErrorStr(&ErrorMsg);
388 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000389 ? EngineKind::Interpreter
390 : EngineKind::JIT);
Lang Hames9528bba2015-03-25 12:11:48 +0000391 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000392
Chris Lattner2785bdb2007-05-06 04:58:26 +0000393 // If we are supposed to override the target triple, do so now.
394 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000395 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000396
Eli Bendersky4c647582012-01-16 08:56:09 +0000397 // Enable MCJIT if desired.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000398 RTDyldMemoryManager *RTDyldMM = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000399 if (!ForceInterpreter) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000400 if (RemoteMCJIT)
Lang Hames9d7a2692016-01-11 16:35:55 +0000401 RTDyldMM = new ForwardingMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000402 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000403 RTDyldMM = new SectionMemoryManager();
Lang Hames4a5697e2014-12-03 00:51:19 +0000404
405 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
406 // RTDyldMM: We still use it below, even though we don't own it.
407 builder.setMCJITMemoryManager(
408 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
Lang Hames0f154902014-09-23 16:56:02 +0000409 } else if (RemoteMCJIT) {
410 errs() << "error: Remote process execution does not work with the "
411 "interpreter.\n";
412 exit(1);
Eli Bendersky4c647582012-01-16 08:56:09 +0000413 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000414
Lang Hames1899d0c2015-06-09 02:43:27 +0000415 builder.setOptLevel(getOptLevel());
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000416
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000417 TargetOptions Options;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000418 if (FloatABIForCalls != FloatABI::Default)
419 Options.FloatABIType = FloatABIForCalls;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000420
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000421 builder.setTargetOptions(Options);
422
Mehdi Aminia7de8202016-04-18 18:52:39 +0000423 std::unique_ptr<ExecutionEngine> EE(builder.create());
Chris Lattnerf840ed72009-07-07 18:31:09 +0000424 if (!EE) {
425 if (!ErrorMsg.empty())
Dan Gohmand8db3762009-07-15 16:35:29 +0000426 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000427 else
Dan Gohmand8db3762009-07-15 16:35:29 +0000428 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000429 exit(1);
430 }
431
Mehdi Aminia7de8202016-04-18 18:52:39 +0000432 std::unique_ptr<LLIObjectCache> CacheManager;
Lang Hames173c69f2014-01-08 04:09:09 +0000433 if (EnableCacheManager) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000434 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
435 EE->setObjectCache(CacheManager.get());
Lang Hames173c69f2014-01-08 04:09:09 +0000436 }
437
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000438 // Load any additional modules specified on the command line.
439 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
Rafael Espindolad233b062014-08-26 17:29:46 +0000440 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000441 if (!XMod)
442 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000443 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000444 std::string CacheName("file:");
445 CacheName.append(ExtraModules[i]);
446 XMod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000447 }
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000448 EE->addModule(std::move(XMod));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000449 }
450
Lang Hames173c69f2014-01-08 04:09:09 +0000451 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000452 Expected<object::OwningBinary<object::ObjectFile>> Obj =
Rafael Espindola51cc3602014-01-22 00:14:49 +0000453 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames173c69f2014-01-08 04:09:09 +0000454 if (!Obj) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000455 // TODO: Actually report errors helpfully.
456 consumeError(Obj.takeError());
Davide Italianoda8e6b22016-11-17 22:58:13 +0000457 reportError(Err, argv[0]);
Lang Hames173c69f2014-01-08 04:09:09 +0000458 }
Rafael Espindola061beab2014-08-20 15:19:37 +0000459 object::OwningBinary<object::ObjectFile> &O = Obj.get();
Rafael Espindola7271c192014-08-26 21:04:04 +0000460 EE->addObjectFile(std::move(O));
Lang Hames173c69f2014-01-08 04:09:09 +0000461 }
462
463 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000464 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000465 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
Davide Italianoda8e6b22016-11-17 22:58:13 +0000466 if (!ArBufOrErr)
467 reportError(Err, argv[0]);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000468 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
Rafael Espindolae1923412014-08-01 18:31:17 +0000469
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000470 Expected<std::unique_ptr<object::Archive>> ArOrErr =
Rafael Espindola48af1c22014-08-19 18:44:46 +0000471 object::Archive::create(ArBuf->getMemBufferRef());
Kevin Enderbyc60a3212016-06-29 20:35:44 +0000472 if (!ArOrErr) {
473 std::string Buf;
474 raw_string_ostream OS(Buf);
475 logAllUnhandledErrors(ArOrErr.takeError(), OS, "");
476 OS.flush();
477 errs() << Buf;
Davide Italiano86511442016-11-17 22:59:13 +0000478 exit(1);
Lang Hames173c69f2014-01-08 04:09:09 +0000479 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000480 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
481
482 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
483
484 EE->addArchive(std::move(OB));
Lang Hames173c69f2014-01-08 04:09:09 +0000485 }
486
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000487 // If the target is Cygwin/MingW and we are generating remote code, we
488 // need an extra module to help out with linking.
489 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000490 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000491 }
492
Eli Bendersky5262ad22012-03-13 08:33:15 +0000493 // The following functions have no effect if their respective profiling
494 // support wasn't enabled in the build configuration.
495 EE->RegisterJITEventListener(
496 JITEventListener::createOProfileJITEventListener());
497 EE->RegisterJITEventListener(
498 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000499
Jim Grosbach0f435d02012-09-05 16:50:34 +0000500 if (!NoLazyCompilation && RemoteMCJIT) {
501 errs() << "warning: remote mcjit does not support lazy compilation\n";
502 NoLazyCompilation = true;
503 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000504 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000505
Chris Lattner2785bdb2007-05-06 04:58:26 +0000506 // If the user specifically requested an argv[0] to pass into the program,
507 // do it now.
508 if (!FakeArgv0.empty()) {
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000509 InputFile = static_cast<std::string>(FakeArgv0);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000510 } else {
511 // Otherwise, if there is a .bc suffix on the executable strip it off, it
512 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000513 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000514 InputFile.erase(InputFile.length() - 3);
515 }
516
517 // Add the module's name to the start of the vector of arguments to main().
518 InputArgv.insert(InputArgv.begin(), InputFile);
519
520 // Call the main function from M as if its signature were:
521 // int main (int argc, char **argv, const char **envp)
522 // using the contents of Args to determine argc & argv, and the contents of
523 // EnvVars to determine envp.
524 //
Evan Cheng61582542008-11-05 23:21:52 +0000525 Function *EntryFn = Mod->getFunction(EntryFunc);
526 if (!EntryFn) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000527 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000528 return -1;
529 }
530
Chris Lattner2785bdb2007-05-06 04:58:26 +0000531 // Reset errno to zero on entry to main.
532 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000533
Lang Hames3fde6522016-04-18 19:55:43 +0000534 int Result = -1;
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000535
Lang Hames9d7a2692016-01-11 16:35:55 +0000536 // Sanity check use of remote-jit: LLI currently only supports use of the
537 // remote JIT on Unix platforms.
Lang Hames9d7a2692016-01-11 16:35:55 +0000538 if (RemoteMCJIT) {
539#ifndef LLVM_ON_UNIX
540 errs() << "Warning: host does not support external remote targets.\n"
Lang Hames4ce7cc02016-01-17 01:49:46 +0000541 << " Defaulting to local execution\n";
Lang Hames4b6e0212016-01-11 21:41:34 +0000542 return -1;
Lang Hames9d7a2692016-01-11 16:35:55 +0000543#else
544 if (ChildExecPath.empty()) {
545 errs() << "-remote-mcjit requires -mcjit-remote-process.\n";
546 exit(1);
547 } else if (!sys::fs::can_execute(ChildExecPath)) {
548 errs() << "Unable to find usable child executable: '" << ChildExecPath
549 << "'\n";
550 return -1;
551 }
552#endif
553 }
554
Andrew Kaylor58365b92012-11-27 19:49:00 +0000555 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000556 // If the program doesn't explicitly call exit, we will need the Exit
557 // function later on to make an explicit call, so get the function now.
558 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000559 Type::getInt32Ty(Context));
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000560
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000561 // Run static constructors.
Eric Christopher79cc1e32014-09-02 22:28:02 +0000562 if (!ForceInterpreter) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000563 // Give MCJIT a chance to apply relocations and set page permissions.
564 EE->finalizeObject();
565 }
566 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000567
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000568 // Trigger compilation separately so code regions that need to be
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000569 // invalidated will be known.
570 (void)EE->getPointerToFunction(EntryFn);
571 // Clear instruction cache before code will be executed.
572 if (RTDyldMM)
573 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
574
575 // Run main.
576 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
577
578 // Run static destructors.
579 EE->runStaticConstructorsDestructors(true);
580
581 // If the program didn't call exit explicitly, we should call it now.
582 // This ensures that any atexit handlers get called correctly.
583 if (Function *ExitF = dyn_cast<Function>(Exit)) {
584 std::vector<GenericValue> Args;
585 GenericValue ResultGV;
586 ResultGV.IntVal = APInt(32, Result);
587 Args.push_back(ResultGV);
588 EE->runFunction(ExitF, Args);
589 errs() << "ERROR: exit(" << Result << ") returned!\n";
590 abort();
591 } else {
592 errs() << "ERROR: exit defined with wrong prototype!\n";
593 abort();
594 }
595 } else {
596 // else == "if (RemoteMCJIT)"
597
598 // Remote target MCJIT doesn't (yet) support static constructors. No reason
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000599 // it couldn't. This is a limitation of the LLI implementation, not the
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000600 // MCJIT itself. FIXME.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000601
Lang Hames9d7a2692016-01-11 16:35:55 +0000602 // Lanch the remote process and get a channel to it.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000603 std::unique_ptr<FDRawChannel> C = launchRemote();
Lang Hames9d7a2692016-01-11 16:35:55 +0000604 if (!C) {
605 errs() << "Failed to launch remote JIT.\n";
606 exit(1);
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000607 }
608
Lang Hames9d7a2692016-01-11 16:35:55 +0000609 // Create a remote target client running over the channel.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000610 typedef orc::remote::OrcRemoteTargetClient<orc::rpc::RawByteChannel>
Lang Hamese98bc7af2016-09-11 18:41:05 +0000611 MyRemote;
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000612 auto R = ExitOnErr(MyRemote::Create(*C));
Jim Grosbach748b9472012-08-28 23:22:30 +0000613
Lang Hames9d7a2692016-01-11 16:35:55 +0000614 // Create a remote memory manager.
615 std::unique_ptr<MyRemote::RCMemoryManager> RemoteMM;
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000616 ExitOnErr(R->createRemoteMemoryManager(RemoteMM));
Lang Hames9d7a2692016-01-11 16:35:55 +0000617
618 // Forward MCJIT's memory manager calls to the remote memory manager.
619 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
620 std::move(RemoteMM));
621
622 // Forward MCJIT's symbol resolution calls to the remote.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000623 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
624 orc::createLambdaResolver(
625 [](const std::string &Name) { return nullptr; },
626 [&](const std::string &Name) {
627 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
628 return JITSymbol(Addr, JITSymbolFlags::Exported);
629 return JITSymbol(nullptr);
630 }));
Lang Hames9d7a2692016-01-11 16:35:55 +0000631
632 // Grab the target address of the JIT'd main function on the remote and call
633 // it.
Jim Grosbach0f435d02012-09-05 16:50:34 +0000634 // FIXME: argv and envp handling.
Lang Hamesad4a9112016-08-01 20:49:11 +0000635 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
Lang Hames9d7a2692016-01-11 16:35:55 +0000636 EE->finalizeObject();
Tim Northover79ab7f72013-05-19 09:55:06 +0000637 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
638 << format("%llx", Entry) << "\n");
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000639 Result = ExitOnErr(R->callIntVoid(Entry));
Jim Grosbach0f435d02012-09-05 16:50:34 +0000640
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000641 // Like static constructors, the remote target MCJIT support doesn't handle
642 // this yet. It could. FIXME.
643
Lang Hames9d7a2692016-01-11 16:35:55 +0000644 // Delete the EE - we need to tear it down *before* we terminate the session
645 // with the remote, otherwise it'll crash when it tries to release resources
646 // on a remote that has already been disconnected.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000647 EE.reset();
Lang Hames9d7a2692016-01-11 16:35:55 +0000648
649 // Signal the remote target that we're done JITing.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000650 ExitOnErr(R->terminateSession());
Chris Lattner2785bdb2007-05-06 04:58:26 +0000651 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000652
Jim Grosbach0f435d02012-09-05 16:50:34 +0000653 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000654}
Lang Hames9d7a2692016-01-11 16:35:55 +0000655
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000656std::unique_ptr<FDRawChannel> launchRemote() {
Lang Hames9d7a2692016-01-11 16:35:55 +0000657#ifndef LLVM_ON_UNIX
658 llvm_unreachable("launchRemote not supported on non-Unix platforms");
659#else
660 int PipeFD[2][2];
661 pid_t ChildPID;
662
663 // Create two pipes.
664 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
665 perror("Error creating pipe: ");
666
667 ChildPID = fork();
668
669 if (ChildPID == 0) {
670 // In the child...
671
672 // Close the parent ends of the pipes
673 close(PipeFD[0][1]);
674 close(PipeFD[1][0]);
675
676
677 // Execute the child process.
678 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
679 {
680 ChildPath.reset(new char[ChildExecPath.size() + 1]);
681 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
682 ChildPath[ChildExecPath.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000683 std::string ChildInStr = utostr(PipeFD[0][0]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000684 ChildIn.reset(new char[ChildInStr.size() + 1]);
685 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
686 ChildIn[ChildInStr.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000687 std::string ChildOutStr = utostr(PipeFD[1][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000688 ChildOut.reset(new char[ChildOutStr.size() + 1]);
689 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
690 ChildOut[ChildOutStr.size()] = '\0';
691 }
692
693 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
694 int rc = execv(ChildExecPath.c_str(), args);
695 if (rc != 0)
696 perror("Error executing child process: ");
697 llvm_unreachable("Error executing child process");
698 }
699 // else we're the parent...
700
701 // Close the child ends of the pipes
702 close(PipeFD[0][0]);
703 close(PipeFD[1][1]);
704
705 // Return an RPC channel connected to our end of the pipes.
Lang Hames1f2bf2d2016-11-11 21:42:09 +0000706 return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000707#endif
708}