blob: f2e210d28dd6bba7c3bfa0380e6c2f1fe5566e74 [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"
18#include "llvm/IR/LLVMContext.h"
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +000019#include "llvm/ADT/StringExtras.h"
Duncan Sands3bd97fe2010-08-28 01:30:02 +000020#include "llvm/ADT/Triple.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000021#include "llvm/Bitcode/ReaderWriter.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"
Lang Hames93de2a12015-01-23 21:25:00 +000028#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
Andrew Kaylor58365b92012-11-27 19:49:00 +000029#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Lang Hames9d7a2692016-01-11 16:35:55 +000030#include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000031#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
Andrew Kaylor1ca510e2013-10-29 01:29:56 +000034#include "llvm/IR/TypeBuilder.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000035#include "llvm/IRReader/IRReader.h"
Lang Hames173c69f2014-01-08 04:09:09 +000036#include "llvm/Object/Archive.h"
37#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000038#include "llvm/Support/CommandLine.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000039#include "llvm/Support/Debug.h"
40#include "llvm/Support/DynamicLibrary.h"
41#include "llvm/Support/Format.h"
Chris Lattner76d46322006-12-06 01:18:01 +000042#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Support/MathExtras.h"
44#include "llvm/Support/Memory.h"
Chris Lattner2785bdb2007-05-06 04:58:26 +000045#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000046#include "llvm/Support/Path.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000047#include "llvm/Support/PluginLoader.h"
Chris Lattnere3fc2d12009-03-06 05:34:10 +000048#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000049#include "llvm/Support/Process.h"
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +000050#include "llvm/Support/Program.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000051#include "llvm/Support/Signals.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000052#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000053#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000054#include "llvm/Support/raw_ostream.h"
Daniel Maleaa960c542013-06-28 19:11:40 +000055#include "llvm/Transforms/Instrumentation.h"
Chris Lattner4c522b92007-04-27 17:02:33 +000056#include <cerrno>
NAKAMURA Takumi15304872010-10-22 14:53:59 +000057
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
Brian Gaeke960707c2003-11-11 22:41:34 +000065using namespace llvm;
66
Chandler Carruthf98597a2014-04-22 03:10:36 +000067#define DEBUG_TYPE "lli"
68
Chris Lattnera0d7b082002-12-23 23:59:41 +000069namespace {
Lang Hames9528bba2015-03-25 12:11:48 +000070
71 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
72
Chris Lattnera0d7b082002-12-23 23:59:41 +000073 cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000074 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000075
Chris Lattnera0d7b082002-12-23 23:59:41 +000076 cl::list<std::string>
77 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattnerf5cad152002-07-22 02:10:13 +000078
Chris Lattnera0d7b082002-12-23 23:59:41 +000079 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukmanc2186e32003-09-25 18:10:34 +000080 cl::desc("Force interpretation: disable JIT"),
81 cl::init(false));
Evan Cheng06d988e2008-08-08 08:12:06 +000082
Lang Hames9528bba2015-03-25 12:11:48 +000083 cl::opt<JITKind> UseJITKind("jit-kind",
84 cl::desc("Choose underlying JIT kind."),
85 cl::init(JITKind::MCJIT),
86 cl::values(
87 clEnumValN(JITKind::MCJIT, "mcjit",
88 "MCJIT"),
89 clEnumValN(JITKind::OrcMCJITReplacement,
90 "orc-mcjit",
91 "Orc-based MCJIT replacement"),
92 clEnumValN(JITKind::OrcLazy,
93 "orc-lazy",
94 "Orc-based lazy JIT."),
95 clEnumValEnd));
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>
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000128 MArch("march",
129 cl::desc("Architecture to generate assembly for (see --version)"));
130
131 cl::opt<std::string>
132 MCPU("mcpu",
133 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
134 cl::value_desc("cpu-name"),
135 cl::init(""));
136
137 cl::list<std::string>
138 MAttrs("mattr",
139 cl::CommaSeparated,
140 cl::desc("Target specific attributes (-mattr=help for details)"),
141 cl::value_desc("a1,+a2,-a3,..."));
142
143 cl::opt<std::string>
Evan Cheng61582542008-11-05 23:21:52 +0000144 EntryFunc("entry-function",
145 cl::desc("Specify the entry function (default = 'main') "
146 "of the executable"),
147 cl::value_desc("function"),
148 cl::init("main"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000149
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000150 cl::list<std::string>
Andrew Kaylor4404eb42013-10-28 21:58:15 +0000151 ExtraModules("extra-module",
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000152 cl::desc("Extra modules to be loaded"),
Alp Toker0a09ebf2013-10-28 22:51:25 +0000153 cl::value_desc("input bitcode"));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000154
Lang Hames173c69f2014-01-08 04:09:09 +0000155 cl::list<std::string>
156 ExtraObjects("extra-object",
157 cl::desc("Extra object files to be loaded"),
158 cl::value_desc("input object"));
159
160 cl::list<std::string>
161 ExtraArchives("extra-archive",
162 cl::desc("Extra archive files to be loaded"),
163 cl::value_desc("input archive"));
164
165 cl::opt<bool>
166 EnableCacheManager("enable-cache-manager",
Lang Hames1ddecc02014-01-09 05:24:05 +0000167 cl::desc("Use cache manager to save/load mdoules"),
Lang Hames173c69f2014-01-08 04:09:09 +0000168 cl::init(false));
169
Chris Lattner55644062003-10-28 22:51:44 +0000170 cl::opt<std::string>
Lang Hames1ddecc02014-01-09 05:24:05 +0000171 ObjectCacheDir("object-cache-dir",
172 cl::desc("Directory to store cached object files "
173 "(must be user writable)"),
174 cl::init(""));
175
176 cl::opt<std::string>
Chris Lattner55644062003-10-28 22:51:44 +0000177 FakeArgv0("fake-argv0",
178 cl::desc("Override the 'argv[0]' value passed into the executing"
179 " program"), cl::value_desc("executable"));
Eli Bendersky4c647582012-01-16 08:56:09 +0000180
Chris Lattner3f0ffd32006-09-14 06:17:09 +0000181 cl::opt<bool>
182 DisableCoreFiles("disable-core-files", cl::Hidden,
183 cl::desc("Disable emission of core files if possible"));
Evan Cheng0422bef2008-04-22 06:51:41 +0000184
185 cl::opt<bool>
Evan Cheng16f036c2008-05-21 18:20:21 +0000186 NoLazyCompilation("disable-lazy-compilation",
Evan Cheng0422bef2008-04-22 06:51:41 +0000187 cl::desc("Disable JIT lazy compilation"),
188 cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000189
190 cl::opt<Reloc::Model>
191 RelocModel("relocation-model",
192 cl::desc("Choose relocation model"),
193 cl::init(Reloc::Default),
194 cl::values(
195 clEnumValN(Reloc::Default, "default",
196 "Target default relocation model"),
197 clEnumValN(Reloc::Static, "static",
198 "Non-relocatable code"),
199 clEnumValN(Reloc::PIC_, "pic",
200 "Fully relocatable, position independent code"),
201 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
202 "Relocatable external references, non-relocatable code"),
203 clEnumValEnd));
Evan Chengefd9b422011-07-20 07:51:56 +0000204
205 cl::opt<llvm::CodeModel::Model>
206 CMModel("code-model",
207 cl::desc("Choose code model"),
208 cl::init(CodeModel::JITDefault),
209 cl::values(clEnumValN(CodeModel::JITDefault, "default",
210 "Target default JIT code model"),
211 clEnumValN(CodeModel::Small, "small",
212 "Small code model"),
213 clEnumValN(CodeModel::Kernel, "kernel",
214 "Kernel code model"),
215 clEnumValN(CodeModel::Medium, "medium",
216 "Medium code model"),
217 clEnumValN(CodeModel::Large, "large",
218 "Large code model"),
219 clEnumValEnd));
220
Nick Lewyckyb0e97892012-04-18 08:34:12 +0000221 cl::opt<bool>
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000222 GenerateSoftFloatCalls("soft-float",
223 cl::desc("Generate software floating point library calls"),
224 cl::init(false));
225
226 cl::opt<llvm::FloatABI::ABIType>
227 FloatABIForCalls("float-abi",
228 cl::desc("Choose float ABI type"),
229 cl::init(FloatABI::Default),
230 cl::values(
231 clEnumValN(FloatABI::Default, "default",
232 "Target default float ABI type"),
233 clEnumValN(FloatABI::Soft, "soft",
234 "Soft float ABI (implied by -soft-float)"),
235 clEnumValN(FloatABI::Hard, "hard",
236 "Hard float ABI (uses FP registers)"),
237 clEnumValEnd));
Chris Lattnera0d7b082002-12-23 23:59:41 +0000238}
Chris Lattner009f8102001-10-27 08:43:52 +0000239
Lang Hames173c69f2014-01-08 04:09:09 +0000240//===----------------------------------------------------------------------===//
241// Object cache
242//
Lang Hames1ddecc02014-01-09 05:24:05 +0000243// This object cache implementation writes cached objects to disk to the
244// directory specified by CacheDir, using a filename provided in the module
245// descriptor. The cache tries to load a saved object using that path if the
246// file exists. CacheDir defaults to "", in which case objects are cached
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000247// alongside their originating bitcodes.
Lang Hames173c69f2014-01-08 04:09:09 +0000248//
249class LLIObjectCache : public ObjectCache {
250public:
Lang Hames1ddecc02014-01-09 05:24:05 +0000251 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
252 // Add trailing '/' to cache dir if necessary.
Lang Hamesf9dd8fd2014-01-09 05:29:59 +0000253 if (!this->CacheDir.empty() &&
254 this->CacheDir[this->CacheDir.size() - 1] != '/')
NAKAMURA Takumif462f9c2014-01-10 10:38:28 +0000255 this->CacheDir += '/';
Lang Hames1ddecc02014-01-09 05:24:05 +0000256 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000257 ~LLIObjectCache() override {}
Lang Hames173c69f2014-01-08 04:09:09 +0000258
Rafael Espindola48af1c22014-08-19 18:44:46 +0000259 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
Lang Hames173c69f2014-01-08 04:09:09 +0000260 const std::string ModuleID = M->getModuleIdentifier();
261 std::string CacheName;
262 if (!getCacheFilename(ModuleID, CacheName))
263 return;
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000264 if (!CacheDir.empty()) { // Create user-defined cache dir.
Rafael Espindolaf662e002015-07-15 21:24:07 +0000265 SmallString<128> dir(sys::path::parent_path(CacheName));
NAKAMURA Takumi390e0602014-01-10 10:38:34 +0000266 sys::fs::create_directories(Twine(dir));
267 }
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000268 std::error_code EC;
269 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000270 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
Lang Hames173c69f2014-01-08 04:09:09 +0000271 outfile.close();
272 }
273
Rafael Espindola5f2bb7d2014-08-13 18:49:01 +0000274 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
Lang Hames173c69f2014-01-08 04:09:09 +0000275 const std::string ModuleID = M->getModuleIdentifier();
276 std::string CacheName;
277 if (!getCacheFilename(ModuleID, CacheName))
Craig Toppere6cb63e2014-04-25 04:24:47 +0000278 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000279 // Load the object from the cache filename
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000280 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
281 MemoryBuffer::getFile(CacheName.c_str(), -1, false);
Lang Hames173c69f2014-01-08 04:09:09 +0000282 // If the file isn't there, that's OK.
283 if (!IRObjectBuffer)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000284 return nullptr;
Lang Hames173c69f2014-01-08 04:09:09 +0000285 // MCJIT will want to write into this buffer, and we don't want that
286 // because the file has probably just been mmapped. Instead we make
287 // a copy. The filed-based buffer will be released when it goes
288 // out of scope.
Rafael Espindola3560ff22014-08-27 20:03:13 +0000289 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
Lang Hames173c69f2014-01-08 04:09:09 +0000290 }
291
292private:
Lang Hames1ddecc02014-01-09 05:24:05 +0000293 std::string CacheDir;
294
Lang Hames173c69f2014-01-08 04:09:09 +0000295 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
296 std::string Prefix("file:");
297 size_t PrefixLength = Prefix.length();
298 if (ModID.substr(0, PrefixLength) != Prefix)
299 return false;
NAKAMURA Takumid7fd6d92014-01-10 10:38:40 +0000300 std::string CacheSubdir = ModID.substr(PrefixLength);
301#if defined(_WIN32)
302 // Transform "X:\foo" => "/X\foo" for convenience.
303 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
304 CacheSubdir[1] = CacheSubdir[0];
305 CacheSubdir[0] = '/';
306 }
307#endif
308 CacheName = CacheDir + CacheSubdir;
Lang Hames173c69f2014-01-08 04:09:09 +0000309 size_t pos = CacheName.rfind('.');
310 CacheName.replace(pos, CacheName.length() - pos, ".o");
311 return true;
312 }
313};
314
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000315// On Mingw and Cygwin, an external symbol named '__main' is called from the
316// generated 'main' function to allow static intialization. To avoid linking
317// problems with remote targets (because lli's remote target support does not
318// currently handle external linking) we add a secondary module which defines
319// an empty '__main' function.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000320static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000321 StringRef TargetTripleStr) {
322 IRBuilder<> Builder(Context);
323 Triple TargetTriple(TargetTripleStr);
324
325 // Create a new module.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000326 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000327 M->setTargetTriple(TargetTripleStr);
328
329 // Create an empty function named "__main".
330 Function *Result;
331 if (TargetTriple.isArch64Bit()) {
332 Result = Function::Create(
333 TypeBuilder<int64_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000334 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000335 } else {
336 Result = Function::Create(
337 TypeBuilder<int32_t(void), false>::get(Context),
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000338 GlobalValue::ExternalLinkage, "__main", M.get());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000339 }
340 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
341 Builder.SetInsertPoint(BB);
342 Value *ReturnVal;
343 if (TargetTriple.isArch64Bit())
344 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
345 else
346 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
347 Builder.CreateRet(ReturnVal);
348
349 // Add this new module to the ExecutionEngine.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000350 EE.addModule(std::move(M));
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000351}
352
Lang Hames1899d0c2015-06-09 02:43:27 +0000353CodeGenOpt::Level getOptLevel() {
354 switch (OptLevel) {
355 default:
356 errs() << "lli: Invalid optimization level.\n";
357 exit(1);
358 case '0': return CodeGenOpt::None;
359 case '1': return CodeGenOpt::Less;
360 case ' ':
361 case '2': return CodeGenOpt::Default;
362 case '3': return CodeGenOpt::Aggressive;
363 }
364 llvm_unreachable("Unrecognized opt level.");
365}
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000366
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000367//===----------------------------------------------------------------------===//
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000368// main Driver function
369//
Misha Brukman5b255e52003-10-14 21:39:53 +0000370int main(int argc, char **argv, char * const *envp) {
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000371 sys::PrintStackTraceOnErrorSignal();
372 PrettyStackTraceProgram X(argc, argv);
Eli Bendersky4c647582012-01-16 08:56:09 +0000373
Mehdi Aminia7de8202016-04-18 18:52:39 +0000374 atexit(llvm_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000375
376 // If we have a native target, initialize it to ensure it is linked in and
377 // usable by the JIT.
378 InitializeNativeTarget();
Jim Grosbach7b162492011-03-18 22:48:41 +0000379 InitializeNativeTargetAsmPrinter();
Jim Grosbach2cce3f92012-11-05 19:06:05 +0000380 InitializeNativeTargetAsmParser();
Daniel Dunbar3d92d932009-07-16 02:04:54 +0000381
Chris Lattner2785bdb2007-05-06 04:58:26 +0000382 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman2c6a8212007-10-08 15:45:12 +0000383 "llvm interpreter & dynamic compiler\n");
Reid Spencer996ec722004-12-30 05:36:08 +0000384
Chris Lattner2785bdb2007-05-06 04:58:26 +0000385 // If the user doesn't want core files, disable them.
386 if (DisableCoreFiles)
387 sys::Process::PreventCoreFiles();
Eli Bendersky4c647582012-01-16 08:56:09 +0000388
Mehdi Aminia7de8202016-04-18 18:52:39 +0000389 LLVMContext Context;
390
Gabor Greife16561c2007-07-05 17:07:56 +0000391 // Load the bitcode...
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000392 SMDiagnostic Err;
Rafael Espindolad233b062014-08-26 17:29:46 +0000393 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000394 Module *Mod = Owner.get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000395 if (!Mod) {
Chris Lattnera3a06812011-10-16 04:47:35 +0000396 Err.print(argv[0], errs());
Daniel Dunbar9589bf82010-11-13 00:28:01 +0000397 return 1;
Chris Lattner2785bdb2007-05-06 04:58:26 +0000398 }
399
Lang Hames9528bba2015-03-25 12:11:48 +0000400 if (UseJITKind == JITKind::OrcLazy)
401 return runOrcLazyJIT(std::move(Owner), argc, argv);
402
Lang Hames173c69f2014-01-08 04:09:09 +0000403 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000404 std::string CacheName("file:");
405 CacheName.append(InputFile);
406 Mod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000407 }
408
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000409 // If not jitting lazily, load the whole bitcode file eagerly too.
410 if (NoLazyCompilation) {
Rafael Espindolac4a03482015-12-18 20:13:39 +0000411 if (std::error_code EC = Mod->materializeAll()) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000412 errs() << argv[0] << ": bitcode didn't read correctly.\n";
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000413 errs() << "Reason: " << EC.message() << "\n";
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000414 exit(1);
415 }
Evan Cheng0422bef2008-04-22 06:51:41 +0000416 }
Chris Lattner2785bdb2007-05-06 04:58:26 +0000417
Rafael Espindolae9fab9b2014-01-14 23:51:27 +0000418 std::string ErrorMsg;
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000419 EngineBuilder builder(std::move(Owner));
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000420 builder.setMArch(MArch);
421 builder.setMCPU(MCPU);
422 builder.setMAttrs(MAttrs);
Evan Cheng2129f592011-07-19 06:37:02 +0000423 builder.setRelocationModel(RelocModel);
Evan Chengefd9b422011-07-20 07:51:56 +0000424 builder.setCodeModel(CMModel);
Daniel Dunbara78d8092009-07-18 08:07:13 +0000425 builder.setErrorStr(&ErrorMsg);
426 builder.setEngineKind(ForceInterpreter
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000427 ? EngineKind::Interpreter
428 : EngineKind::JIT);
Lang Hames9528bba2015-03-25 12:11:48 +0000429 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000430
Chris Lattner2785bdb2007-05-06 04:58:26 +0000431 // If we are supposed to override the target triple, do so now.
432 if (!TargetTriple.empty())
Duncan Sands3bd97fe2010-08-28 01:30:02 +0000433 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Cheng0422bef2008-04-22 06:51:41 +0000434
Eli Bendersky4c647582012-01-16 08:56:09 +0000435 // Enable MCJIT if desired.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000436 RTDyldMemoryManager *RTDyldMM = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000437 if (!ForceInterpreter) {
Jim Grosbach0f435d02012-09-05 16:50:34 +0000438 if (RemoteMCJIT)
Lang Hames9d7a2692016-01-11 16:35:55 +0000439 RTDyldMM = new ForwardingMemoryManager();
Jim Grosbach0f435d02012-09-05 16:50:34 +0000440 else
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000441 RTDyldMM = new SectionMemoryManager();
Lang Hames4a5697e2014-12-03 00:51:19 +0000442
443 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
444 // RTDyldMM: We still use it below, even though we don't own it.
445 builder.setMCJITMemoryManager(
446 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
Lang Hames0f154902014-09-23 16:56:02 +0000447 } else if (RemoteMCJIT) {
448 errs() << "error: Remote process execution does not work with the "
449 "interpreter.\n";
450 exit(1);
Eli Bendersky4c647582012-01-16 08:56:09 +0000451 }
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000452
Lang Hames1899d0c2015-06-09 02:43:27 +0000453 builder.setOptLevel(getOptLevel());
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000454
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000455 TargetOptions Options;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000456 if (FloatABIForCalls != FloatABI::Default)
457 Options.FloatABIType = FloatABIForCalls;
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000458
Tim Northoverd4a2f5b2012-10-12 09:55:13 +0000459 builder.setTargetOptions(Options);
460
Mehdi Aminia7de8202016-04-18 18:52:39 +0000461 std::unique_ptr<ExecutionEngine> EE(builder.create());
Chris Lattnerf840ed72009-07-07 18:31:09 +0000462 if (!EE) {
463 if (!ErrorMsg.empty())
Dan Gohmand8db3762009-07-15 16:35:29 +0000464 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerf840ed72009-07-07 18:31:09 +0000465 else
Dan Gohmand8db3762009-07-15 16:35:29 +0000466 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000467 exit(1);
468 }
469
Mehdi Aminia7de8202016-04-18 18:52:39 +0000470 std::unique_ptr<LLIObjectCache> CacheManager;
Lang Hames173c69f2014-01-08 04:09:09 +0000471 if (EnableCacheManager) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000472 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
473 EE->setObjectCache(CacheManager.get());
Lang Hames173c69f2014-01-08 04:09:09 +0000474 }
475
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000476 // Load any additional modules specified on the command line.
477 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
Rafael Espindolad233b062014-08-26 17:29:46 +0000478 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000479 if (!XMod) {
480 Err.print(argv[0], errs());
481 return 1;
482 }
Lang Hames173c69f2014-01-08 04:09:09 +0000483 if (EnableCacheManager) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000484 std::string CacheName("file:");
485 CacheName.append(ExtraModules[i]);
486 XMod->setModuleIdentifier(CacheName);
Lang Hames173c69f2014-01-08 04:09:09 +0000487 }
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000488 EE->addModule(std::move(XMod));
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000489 }
490
Lang Hames173c69f2014-01-08 04:09:09 +0000491 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000492 Expected<object::OwningBinary<object::ObjectFile>> Obj =
Rafael Espindola51cc3602014-01-22 00:14:49 +0000493 object::ObjectFile::createObjectFile(ExtraObjects[i]);
Lang Hames173c69f2014-01-08 04:09:09 +0000494 if (!Obj) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000495 // TODO: Actually report errors helpfully.
496 consumeError(Obj.takeError());
Lang Hames173c69f2014-01-08 04:09:09 +0000497 Err.print(argv[0], errs());
498 return 1;
499 }
Rafael Espindola061beab2014-08-20 15:19:37 +0000500 object::OwningBinary<object::ObjectFile> &O = Obj.get();
Rafael Espindola7271c192014-08-26 21:04:04 +0000501 EE->addObjectFile(std::move(O));
Lang Hames173c69f2014-01-08 04:09:09 +0000502 }
503
504 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000505 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000506 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000507 if (!ArBufOrErr) {
Lang Hames173c69f2014-01-08 04:09:09 +0000508 Err.print(argv[0], errs());
509 return 1;
510 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000511 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
Rafael Espindolae1923412014-08-01 18:31:17 +0000512
513 ErrorOr<std::unique_ptr<object::Archive>> ArOrErr =
Rafael Espindola48af1c22014-08-19 18:44:46 +0000514 object::Archive::create(ArBuf->getMemBufferRef());
Rafael Espindolae1923412014-08-01 18:31:17 +0000515 if (std::error_code EC = ArOrErr.getError()) {
516 errs() << EC.message();
Lang Hames173c69f2014-01-08 04:09:09 +0000517 return 1;
518 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000519 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
520
521 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
522
523 EE->addArchive(std::move(OB));
Lang Hames173c69f2014-01-08 04:09:09 +0000524 }
525
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000526 // If the target is Cygwin/MingW and we are generating remote code, we
527 // need an extra module to help out with linking.
528 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
Mehdi Aminia7de8202016-04-18 18:52:39 +0000529 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
Andrew Kaylor1ca510e2013-10-29 01:29:56 +0000530 }
531
Eli Bendersky5262ad22012-03-13 08:33:15 +0000532 // The following functions have no effect if their respective profiling
533 // support wasn't enabled in the build configuration.
534 EE->RegisterJITEventListener(
535 JITEventListener::createOProfileJITEventListener());
536 EE->RegisterJITEventListener(
537 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000538
Jim Grosbach0f435d02012-09-05 16:50:34 +0000539 if (!NoLazyCompilation && RemoteMCJIT) {
540 errs() << "warning: remote mcjit does not support lazy compilation\n";
541 NoLazyCompilation = true;
542 }
Jeffrey Yasskinaa8814a2009-10-27 22:39:42 +0000543 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Cheng0422bef2008-04-22 06:51:41 +0000544
Chris Lattner2785bdb2007-05-06 04:58:26 +0000545 // If the user specifically requested an argv[0] to pass into the program,
546 // do it now.
547 if (!FakeArgv0.empty()) {
Chris Bienemane71fb5c2015-01-22 01:49:59 +0000548 InputFile = static_cast<std::string>(FakeArgv0);
Chris Lattner2785bdb2007-05-06 04:58:26 +0000549 } else {
550 // Otherwise, if there is a .bc suffix on the executable strip it off, it
551 // might confuse the program.
Benjamin Kramera944a9a2010-04-15 11:33:14 +0000552 if (StringRef(InputFile).endswith(".bc"))
Chris Lattner2785bdb2007-05-06 04:58:26 +0000553 InputFile.erase(InputFile.length() - 3);
554 }
555
556 // Add the module's name to the start of the vector of arguments to main().
557 InputArgv.insert(InputArgv.begin(), InputFile);
558
559 // Call the main function from M as if its signature were:
560 // int main (int argc, char **argv, const char **envp)
561 // using the contents of Args to determine argc & argv, and the contents of
562 // EnvVars to determine envp.
563 //
Evan Cheng61582542008-11-05 23:21:52 +0000564 Function *EntryFn = Mod->getFunction(EntryFunc);
565 if (!EntryFn) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000566 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattner2785bdb2007-05-06 04:58:26 +0000567 return -1;
568 }
569
Chris Lattner2785bdb2007-05-06 04:58:26 +0000570 // Reset errno to zero on entry to main.
571 errno = 0;
Eli Bendersky4c647582012-01-16 08:56:09 +0000572
Lang Hames3fde6522016-04-18 19:55:43 +0000573 int Result = -1;
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000574
Lang Hames9d7a2692016-01-11 16:35:55 +0000575 // Sanity check use of remote-jit: LLI currently only supports use of the
576 // remote JIT on Unix platforms.
Lang Hames9d7a2692016-01-11 16:35:55 +0000577 if (RemoteMCJIT) {
578#ifndef LLVM_ON_UNIX
579 errs() << "Warning: host does not support external remote targets.\n"
Lang Hames4ce7cc02016-01-17 01:49:46 +0000580 << " Defaulting to local execution\n";
Lang Hames4b6e0212016-01-11 21:41:34 +0000581 return -1;
Lang Hames9d7a2692016-01-11 16:35:55 +0000582#else
583 if (ChildExecPath.empty()) {
584 errs() << "-remote-mcjit requires -mcjit-remote-process.\n";
585 exit(1);
586 } else if (!sys::fs::can_execute(ChildExecPath)) {
587 errs() << "Unable to find usable child executable: '" << ChildExecPath
588 << "'\n";
589 return -1;
590 }
591#endif
592 }
593
Andrew Kaylor58365b92012-11-27 19:49:00 +0000594 if (!RemoteMCJIT) {
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000595 // If the program doesn't explicitly call exit, we will need the Exit
596 // function later on to make an explicit call, so get the function now.
597 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
598 Type::getInt32Ty(Context),
David Majnemer6539ed72015-02-26 01:10:49 +0000599 nullptr);
Andrew Kaylor6587bcf2013-10-11 22:47:10 +0000600
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000601 // Run static constructors.
Eric Christopher79cc1e32014-09-02 22:28:02 +0000602 if (!ForceInterpreter) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000603 // Give MCJIT a chance to apply relocations and set page permissions.
604 EE->finalizeObject();
605 }
606 EE->runStaticConstructorsDestructors(false);
Evan Cheng0422bef2008-04-22 06:51:41 +0000607
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000608 // Trigger compilation separately so code regions that need to be
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000609 // invalidated will be known.
610 (void)EE->getPointerToFunction(EntryFn);
611 // Clear instruction cache before code will be executed.
612 if (RTDyldMM)
613 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
614
615 // Run main.
616 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
617
618 // Run static destructors.
619 EE->runStaticConstructorsDestructors(true);
620
621 // If the program didn't call exit explicitly, we should call it now.
622 // This ensures that any atexit handlers get called correctly.
623 if (Function *ExitF = dyn_cast<Function>(Exit)) {
624 std::vector<GenericValue> Args;
625 GenericValue ResultGV;
626 ResultGV.IntVal = APInt(32, Result);
627 Args.push_back(ResultGV);
628 EE->runFunction(ExitF, Args);
629 errs() << "ERROR: exit(" << Result << ") returned!\n";
630 abort();
631 } else {
632 errs() << "ERROR: exit defined with wrong prototype!\n";
633 abort();
634 }
635 } else {
636 // else == "if (RemoteMCJIT)"
637
638 // Remote target MCJIT doesn't (yet) support static constructors. No reason
639 // it couldn't. This is a limitation of the LLI implemantation, not the
640 // MCJIT itself. FIXME.
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000641
Lang Hames9d7a2692016-01-11 16:35:55 +0000642 // Lanch the remote process and get a channel to it.
643 std::unique_ptr<FDRPCChannel> C = launchRemote();
644 if (!C) {
645 errs() << "Failed to launch remote JIT.\n";
646 exit(1);
Andrew Kaylorc2ebf3f2013-10-02 17:12:36 +0000647 }
648
Lang Hames9d7a2692016-01-11 16:35:55 +0000649 // Create a remote target client running over the channel.
650 typedef orc::remote::OrcRemoteTargetClient<orc::remote::RPCChannel> MyRemote;
651 ErrorOr<MyRemote> R = MyRemote::Create(*C);
652 if (!R) {
653 errs() << "Could not create remote: " << R.getError().message() << "\n";
654 exit(1);
Renato Golin695895c2014-01-14 22:43:43 +0000655 }
Jim Grosbach748b9472012-08-28 23:22:30 +0000656
Lang Hames9d7a2692016-01-11 16:35:55 +0000657 // Create a remote memory manager.
658 std::unique_ptr<MyRemote::RCMemoryManager> RemoteMM;
659 if (auto EC = R->createRemoteMemoryManager(RemoteMM)) {
660 errs() << "Could not create remote memory manager: " << EC.message() << "\n";
661 exit(1);
662 }
663
664 // Forward MCJIT's memory manager calls to the remote memory manager.
665 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
666 std::move(RemoteMM));
667
668 // Forward MCJIT's symbol resolution calls to the remote.
669 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setResolver(
670 orc::createLambdaResolver(
671 [&](const std::string &Name) {
Lang Hames3fde6522016-04-18 19:55:43 +0000672 if (auto AddrOrErr = R->getSymbolAddress(Name))
673 return RuntimeDyld::SymbolInfo(*AddrOrErr, JITSymbolFlags::Exported);
674 else {
675 errs() << "Failure during symbol lookup: "
676 << AddrOrErr.getError().message() << "\n";
677 exit(1);
678 }
Lang Hames9d7a2692016-01-11 16:35:55 +0000679 },
680 [](const std::string &Name) { return nullptr; }
681 ));
682
683 // Grab the target address of the JIT'd main function on the remote and call
684 // it.
Jim Grosbach0f435d02012-09-05 16:50:34 +0000685 // FIXME: argv and envp handling.
Lang Hames9d7a2692016-01-11 16:35:55 +0000686 orc::TargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
687 EE->finalizeObject();
Tim Northover79ab7f72013-05-19 09:55:06 +0000688 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
689 << format("%llx", Entry) << "\n");
Lang Hames3fde6522016-04-18 19:55:43 +0000690 if (auto ResultOrErr = R->callIntVoid(Entry))
691 Result = *ResultOrErr;
692 else
693 errs() << "ERROR: " << ResultOrErr.getError().message() << "\n";
Jim Grosbach0f435d02012-09-05 16:50:34 +0000694
Andrew Kaylorc87c3472013-10-02 18:04:40 +0000695 // Like static constructors, the remote target MCJIT support doesn't handle
696 // this yet. It could. FIXME.
697
Lang Hames9d7a2692016-01-11 16:35:55 +0000698 // Delete the EE - we need to tear it down *before* we terminate the session
699 // with the remote, otherwise it'll crash when it tries to release resources
700 // on a remote that has already been disconnected.
Mehdi Aminia7de8202016-04-18 18:52:39 +0000701 EE.reset();
Lang Hames9d7a2692016-01-11 16:35:55 +0000702
703 // Signal the remote target that we're done JITing.
704 R->terminateSession();
Chris Lattner2785bdb2007-05-06 04:58:26 +0000705 }
Jim Grosbach0f435d02012-09-05 16:50:34 +0000706
Jim Grosbach0f435d02012-09-05 16:50:34 +0000707 return Result;
Chris Lattnerd7ff5782001-08-23 17:05:04 +0000708}
Lang Hames9d7a2692016-01-11 16:35:55 +0000709
710std::unique_ptr<FDRPCChannel> launchRemote() {
711#ifndef LLVM_ON_UNIX
712 llvm_unreachable("launchRemote not supported on non-Unix platforms");
713#else
714 int PipeFD[2][2];
715 pid_t ChildPID;
716
717 // Create two pipes.
718 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
719 perror("Error creating pipe: ");
720
721 ChildPID = fork();
722
723 if (ChildPID == 0) {
724 // In the child...
725
726 // Close the parent ends of the pipes
727 close(PipeFD[0][1]);
728 close(PipeFD[1][0]);
729
730
731 // Execute the child process.
732 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
733 {
734 ChildPath.reset(new char[ChildExecPath.size() + 1]);
735 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
736 ChildPath[ChildExecPath.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000737 std::string ChildInStr = utostr(PipeFD[0][0]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000738 ChildIn.reset(new char[ChildInStr.size() + 1]);
739 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
740 ChildIn[ChildInStr.size()] = '\0';
NAKAMURA Takumicef0a8212016-01-15 02:14:46 +0000741 std::string ChildOutStr = utostr(PipeFD[1][1]);
Lang Hames9d7a2692016-01-11 16:35:55 +0000742 ChildOut.reset(new char[ChildOutStr.size() + 1]);
743 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
744 ChildOut[ChildOutStr.size()] = '\0';
745 }
746
747 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
748 int rc = execv(ChildExecPath.c_str(), args);
749 if (rc != 0)
750 perror("Error executing child process: ");
751 llvm_unreachable("Error executing child process");
752 }
753 // else we're the parent...
754
755 // Close the child ends of the pipes
756 close(PipeFD[0][0]);
757 close(PipeFD[1][1]);
758
759 // Return an RPC channel connected to our end of the pipes.
760 return llvm::make_unique<FDRPCChannel>(PipeFD[1][0], PipeFD[0][1]);
761#endif
762}