1 //===-- ToolRunner.cpp ----------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the interfaces described in the ToolRunner.h file.
12 //===----------------------------------------------------------------------===//
14 #include "ToolRunner.h"
15 #include "llvm/Config/config.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/Program.h"
21 #include "llvm/Support/raw_ostream.h"
27 #define DEBUG_TYPE "toolrunner"
30 cl::opt<bool> SaveTemps("save-temps", cl::init(false),
31 cl::desc("Save temporary files"));
36 RemoteClient("remote-client",
37 cl::desc("Remote execution client (rsh/ssh)"));
39 cl::opt<std::string> RemoteHost("remote-host",
40 cl::desc("Remote execution (rsh/ssh) host"));
42 cl::opt<std::string> RemotePort("remote-port",
43 cl::desc("Remote execution (rsh/ssh) port"));
45 cl::opt<std::string> RemoteUser("remote-user",
46 cl::desc("Remote execution (rsh/ssh) user id"));
49 RemoteExtra("remote-extra-options",
50 cl::desc("Remote execution (rsh/ssh) extra options"));
53 /// RunProgramWithTimeout - This function provides an alternate interface
54 /// to the sys::Program::ExecuteAndWait interface.
55 /// @see sys::Program::ExecuteAndWait
56 static int RunProgramWithTimeout(StringRef ProgramPath, const char **Args,
57 StringRef StdInFile, StringRef StdOutFile,
58 StringRef StdErrFile, unsigned NumSeconds = 0,
59 unsigned MemoryLimit = 0,
60 std::string *ErrMsg = nullptr) {
61 const StringRef *Redirects[3] = {&StdInFile, &StdOutFile, &StdErrFile};
62 return sys::ExecuteAndWait(ProgramPath, Args, nullptr, Redirects, NumSeconds,
66 /// RunProgramRemotelyWithTimeout - This function runs the given program
67 /// remotely using the given remote client and the sys::Program::ExecuteAndWait.
68 /// Returns the remote program exit code or reports a remote client error if it
69 /// fails. Remote client is required to return 255 if it failed or program exit
71 /// @see sys::Program::ExecuteAndWait
72 static int RunProgramRemotelyWithTimeout(StringRef RemoteClientPath,
73 const char **Args, StringRef StdInFile,
76 unsigned NumSeconds = 0,
77 unsigned MemoryLimit = 0) {
78 const StringRef *Redirects[3] = {&StdInFile, &StdOutFile, &StdErrFile};
80 // Run the program remotely with the remote client
81 int ReturnCode = sys::ExecuteAndWait(RemoteClientPath, Args, nullptr,
82 Redirects, NumSeconds, MemoryLimit);
84 // Has the remote client fail?
85 if (255 == ReturnCode) {
86 std::ostringstream OS;
87 OS << "\nError running remote client:\n ";
88 for (const char **Arg = Args; *Arg; ++Arg)
92 // The error message is in the output file, let's print it out from there.
93 std::string StdOutFileName = StdOutFile.str();
94 std::ifstream ErrorFile(StdOutFileName.c_str());
96 std::copy(std::istreambuf_iterator<char>(ErrorFile),
97 std::istreambuf_iterator<char>(),
98 std::ostreambuf_iterator<char>(OS));
108 static Error ProcessFailure(StringRef ProgPath, const char **Args,
109 unsigned Timeout = 0, unsigned MemoryLimit = 0) {
110 std::ostringstream OS;
111 OS << "\nError running tool:\n ";
112 for (const char **Arg = Args; *Arg; ++Arg)
116 // Rerun the compiler, capturing any error messages to print them.
117 SmallString<128> ErrorFilename;
118 std::error_code EC = sys::fs::createTemporaryFile(
119 "bugpoint.program_error_messages", "", ErrorFilename);
121 errs() << "Error making unique filename: " << EC.message() << "\n";
125 RunProgramWithTimeout(ProgPath, Args, "", ErrorFilename.str(),
126 ErrorFilename.str(), Timeout, MemoryLimit);
127 // FIXME: check return code ?
129 // Print out the error messages generated by CC if possible...
130 std::ifstream ErrorFile(ErrorFilename.c_str());
132 std::copy(std::istreambuf_iterator<char>(ErrorFile),
133 std::istreambuf_iterator<char>(),
134 std::ostreambuf_iterator<char>(OS));
138 sys::fs::remove(ErrorFilename.c_str());
139 return make_error<StringError>(OS.str(), inconvertibleErrorCode());
142 //===---------------------------------------------------------------------===//
143 // LLI Implementation of AbstractIntepreter interface
146 class LLI : public AbstractInterpreter {
147 std::string LLIPath; // The path to the LLI executable
148 std::vector<std::string> ToolArgs; // Args to pass to LLI
150 LLI(const std::string &Path, const std::vector<std::string> *Args)
158 Expected<int> ExecuteProgram(
159 const std::string &Bitcode, const std::vector<std::string> &Args,
160 const std::string &InputFile, const std::string &OutputFile,
161 const std::vector<std::string> &CCArgs,
162 const std::vector<std::string> &SharedLibs = std::vector<std::string>(),
163 unsigned Timeout = 0, unsigned MemoryLimit = 0) override;
167 Expected<int> LLI::ExecuteProgram(const std::string &Bitcode,
168 const std::vector<std::string> &Args,
169 const std::string &InputFile,
170 const std::string &OutputFile,
171 const std::vector<std::string> &CCArgs,
172 const std::vector<std::string> &SharedLibs,
173 unsigned Timeout, unsigned MemoryLimit) {
174 std::vector<const char *> LLIArgs;
175 LLIArgs.push_back(LLIPath.c_str());
176 LLIArgs.push_back("-force-interpreter=true");
178 for (std::vector<std::string>::const_iterator i = SharedLibs.begin(),
179 e = SharedLibs.end();
181 LLIArgs.push_back("-load");
182 LLIArgs.push_back((*i).c_str());
185 // Add any extra LLI args.
186 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
187 LLIArgs.push_back(ToolArgs[i].c_str());
189 LLIArgs.push_back(Bitcode.c_str());
190 // Add optional parameters to the running program from Argv
191 for (unsigned i = 0, e = Args.size(); i != e; ++i)
192 LLIArgs.push_back(Args[i].c_str());
193 LLIArgs.push_back(nullptr);
197 DEBUG(errs() << "\nAbout to run:\t";
198 for (unsigned i = 0, e = LLIArgs.size() - 1; i != e; ++i) errs()
199 << " " << LLIArgs[i];
201 return RunProgramWithTimeout(LLIPath, &LLIArgs[0], InputFile, OutputFile,
202 OutputFile, Timeout, MemoryLimit);
205 void AbstractInterpreter::anchor() {}
207 #if defined(LLVM_ON_UNIX)
208 const char EXESuffix[] = "";
209 #elif defined(LLVM_ON_WIN32)
210 const char EXESuffix[] = "exe";
213 /// Prepend the path to the program being executed
214 /// to \p ExeName, given the value of argv[0] and the address of main()
215 /// itself. This allows us to find another LLVM tool if it is built in the same
216 /// directory. An empty string is returned on error; note that this function
217 /// just mainpulates the path and doesn't check for executability.
218 /// @brief Find a named executable.
219 static std::string PrependMainExecutablePath(const std::string &ExeName,
222 // Check the directory that the calling program is in. We can do
223 // this if ProgramPath contains at least one / character, indicating that it
224 // is a relative path to the executable itself.
225 std::string Main = sys::fs::getMainExecutable(Argv0, MainAddr);
226 StringRef Result = sys::path::parent_path(Main);
228 if (!Result.empty()) {
229 SmallString<128> Storage = Result;
230 sys::path::append(Storage, ExeName);
231 sys::path::replace_extension(Storage, EXESuffix);
232 return Storage.str();
238 // LLI create method - Try to find the LLI executable
239 AbstractInterpreter *
240 AbstractInterpreter::createLLI(const char *Argv0, std::string &Message,
241 const std::vector<std::string> *ToolArgs) {
242 std::string LLIPath =
243 PrependMainExecutablePath("lli", Argv0, (void *)(intptr_t)&createLLI);
244 if (!LLIPath.empty()) {
245 Message = "Found lli: " + LLIPath + "\n";
246 return new LLI(LLIPath, ToolArgs);
249 Message = "Cannot find `lli' in executable directory!\n";
253 //===---------------------------------------------------------------------===//
254 // Custom compiler command implementation of AbstractIntepreter interface
256 // Allows using a custom command for compiling the bitcode, thus allows, for
257 // example, to compile a bitcode fragment without linking or executing, then
258 // using a custom wrapper script to check for compiler errors.
260 class CustomCompiler : public AbstractInterpreter {
261 std::string CompilerCommand;
262 std::vector<std::string> CompilerArgs;
265 CustomCompiler(const std::string &CompilerCmd,
266 std::vector<std::string> CompArgs)
267 : CompilerCommand(CompilerCmd), CompilerArgs(std::move(CompArgs)) {}
269 Error compileProgram(const std::string &Bitcode, unsigned Timeout = 0,
270 unsigned MemoryLimit = 0) override;
272 Expected<int> ExecuteProgram(
273 const std::string &Bitcode, const std::vector<std::string> &Args,
274 const std::string &InputFile, const std::string &OutputFile,
275 const std::vector<std::string> &CCArgs = std::vector<std::string>(),
276 const std::vector<std::string> &SharedLibs = std::vector<std::string>(),
277 unsigned Timeout = 0, unsigned MemoryLimit = 0) override {
278 return make_error<StringError>(
279 "Execution not supported with -compile-custom",
280 inconvertibleErrorCode());
285 Error CustomCompiler::compileProgram(const std::string &Bitcode,
286 unsigned Timeout, unsigned MemoryLimit) {
288 std::vector<const char *> ProgramArgs;
289 ProgramArgs.push_back(CompilerCommand.c_str());
291 for (std::size_t i = 0; i < CompilerArgs.size(); ++i)
292 ProgramArgs.push_back(CompilerArgs.at(i).c_str());
293 ProgramArgs.push_back(Bitcode.c_str());
294 ProgramArgs.push_back(nullptr);
296 // Add optional parameters to the running program from Argv
297 for (unsigned i = 0, e = CompilerArgs.size(); i != e; ++i)
298 ProgramArgs.push_back(CompilerArgs[i].c_str());
300 if (RunProgramWithTimeout(CompilerCommand, &ProgramArgs[0], "", "", "",
301 Timeout, MemoryLimit))
302 return ProcessFailure(CompilerCommand, &ProgramArgs[0], Timeout,
304 return Error::success();
307 //===---------------------------------------------------------------------===//
308 // Custom execution command implementation of AbstractIntepreter interface
310 // Allows using a custom command for executing the bitcode, thus allows,
311 // for example, to invoke a cross compiler for code generation followed by
312 // a simulator that executes the generated binary.
314 class CustomExecutor : public AbstractInterpreter {
315 std::string ExecutionCommand;
316 std::vector<std::string> ExecutorArgs;
319 CustomExecutor(const std::string &ExecutionCmd,
320 std::vector<std::string> ExecArgs)
321 : ExecutionCommand(ExecutionCmd), ExecutorArgs(std::move(ExecArgs)) {}
323 Expected<int> ExecuteProgram(
324 const std::string &Bitcode, const std::vector<std::string> &Args,
325 const std::string &InputFile, const std::string &OutputFile,
326 const std::vector<std::string> &CCArgs,
327 const std::vector<std::string> &SharedLibs = std::vector<std::string>(),
328 unsigned Timeout = 0, unsigned MemoryLimit = 0) override;
332 Expected<int> CustomExecutor::ExecuteProgram(
333 const std::string &Bitcode, const std::vector<std::string> &Args,
334 const std::string &InputFile, const std::string &OutputFile,
335 const std::vector<std::string> &CCArgs,
336 const std::vector<std::string> &SharedLibs, unsigned Timeout,
337 unsigned MemoryLimit) {
339 std::vector<const char *> ProgramArgs;
340 ProgramArgs.push_back(ExecutionCommand.c_str());
342 for (std::size_t i = 0; i < ExecutorArgs.size(); ++i)
343 ProgramArgs.push_back(ExecutorArgs.at(i).c_str());
344 ProgramArgs.push_back(Bitcode.c_str());
345 ProgramArgs.push_back(nullptr);
347 // Add optional parameters to the running program from Argv
348 for (unsigned i = 0, e = Args.size(); i != e; ++i)
349 ProgramArgs.push_back(Args[i].c_str());
351 return RunProgramWithTimeout(ExecutionCommand, &ProgramArgs[0], InputFile,
352 OutputFile, OutputFile, Timeout, MemoryLimit);
355 // Tokenize the CommandLine to the command and the args to allow
356 // defining a full command line as the command instead of just the
357 // executed program. We cannot just pass the whole string after the command
358 // as a single argument because then the program sees only a single
359 // command line argument (with spaces in it: "foo bar" instead
360 // of "foo" and "bar").
362 // Spaces are used as a delimiter; however repeated, leading, and trailing
363 // whitespace are ignored. Simple escaping is allowed via the '\'
364 // character, as seen below:
366 // Two consecutive '\' evaluate to a single '\'.
367 // A space after a '\' evaluates to a space that is not interpreted as a
369 // Any other instances of the '\' character are removed.
374 // 'exa\mple' -> 'example'
376 static void lexCommand(std::string &Message, const std::string &CommandLine,
377 std::string &CmdPath, std::vector<std::string> &Args) {
381 bool FoundPath = false;
383 // first argument is the PATH.
384 // Skip repeated whitespace, leading whitespace and trailing whitespace.
385 for (std::size_t Pos = 0u; Pos <= CommandLine.size(); ++Pos) {
386 if ('\\' == CommandLine[Pos]) {
387 if (Pos + 1 < CommandLine.size())
388 Token.push_back(CommandLine[++Pos]);
392 if (' ' == CommandLine[Pos] || CommandLine.size() == Pos) {
403 Args.push_back(Token);
407 Token.push_back(CommandLine[Pos]);
410 auto Path = sys::findProgramByName(Command);
412 Message = std::string("Cannot find '") + Command +
413 "' in PATH: " + Path.getError().message() + "\n";
418 Message = "Found command in: " + CmdPath + "\n";
421 // Custom execution environment create method, takes the execution command
423 AbstractInterpreter *AbstractInterpreter::createCustomCompiler(
424 std::string &Message, const std::string &CompileCommandLine) {
427 std::vector<std::string> Args;
428 lexCommand(Message, CompileCommandLine, CmdPath, Args);
432 return new CustomCompiler(CmdPath, Args);
435 // Custom execution environment create method, takes the execution command
437 AbstractInterpreter *
438 AbstractInterpreter::createCustomExecutor(std::string &Message,
439 const std::string &ExecCommandLine) {
442 std::vector<std::string> Args;
443 lexCommand(Message, ExecCommandLine, CmdPath, Args);
447 return new CustomExecutor(CmdPath, Args);
450 //===----------------------------------------------------------------------===//
451 // LLC Implementation of AbstractIntepreter interface
453 Expected<CC::FileType> LLC::OutputCode(const std::string &Bitcode,
454 std::string &OutputAsmFile,
455 unsigned Timeout, unsigned MemoryLimit) {
456 const char *Suffix = (UseIntegratedAssembler ? ".llc.o" : ".llc.s");
458 SmallString<128> UniqueFile;
460 sys::fs::createUniqueFile(Bitcode + "-%%%%%%%" + Suffix, UniqueFile);
462 errs() << "Error making unique filename: " << EC.message() << "\n";
465 OutputAsmFile = UniqueFile.str();
466 std::vector<const char *> LLCArgs;
467 LLCArgs.push_back(LLCPath.c_str());
469 // Add any extra LLC args.
470 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
471 LLCArgs.push_back(ToolArgs[i].c_str());
473 LLCArgs.push_back("-o");
474 LLCArgs.push_back(OutputAsmFile.c_str()); // Output to the Asm file
475 LLCArgs.push_back(Bitcode.c_str()); // This is the input bitcode
477 if (UseIntegratedAssembler)
478 LLCArgs.push_back("-filetype=obj");
480 LLCArgs.push_back(nullptr);
482 outs() << (UseIntegratedAssembler ? "<llc-ia>" : "<llc>");
484 DEBUG(errs() << "\nAbout to run:\t";
485 for (unsigned i = 0, e = LLCArgs.size() - 1; i != e; ++i) errs()
486 << " " << LLCArgs[i];
488 if (RunProgramWithTimeout(LLCPath, &LLCArgs[0], "", "", "", Timeout,
490 return ProcessFailure(LLCPath, &LLCArgs[0], Timeout, MemoryLimit);
491 return UseIntegratedAssembler ? CC::ObjectFile : CC::AsmFile;
494 Error LLC::compileProgram(const std::string &Bitcode, unsigned Timeout,
495 unsigned MemoryLimit) {
496 std::string OutputAsmFile;
497 Expected<CC::FileType> Result =
498 OutputCode(Bitcode, OutputAsmFile, Timeout, MemoryLimit);
499 sys::fs::remove(OutputAsmFile);
500 if (Error E = Result.takeError())
502 return Error::success();
505 Expected<int> LLC::ExecuteProgram(const std::string &Bitcode,
506 const std::vector<std::string> &Args,
507 const std::string &InputFile,
508 const std::string &OutputFile,
509 const std::vector<std::string> &ArgsForCC,
510 const std::vector<std::string> &SharedLibs,
511 unsigned Timeout, unsigned MemoryLimit) {
513 std::string OutputAsmFile;
514 Expected<CC::FileType> FileKind =
515 OutputCode(Bitcode, OutputAsmFile, Timeout, MemoryLimit);
516 FileRemover OutFileRemover(OutputAsmFile, !SaveTemps);
517 if (Error E = FileKind.takeError())
520 std::vector<std::string> CCArgs(ArgsForCC);
521 CCArgs.insert(CCArgs.end(), SharedLibs.begin(), SharedLibs.end());
523 // Assuming LLC worked, compile the result with CC and run it.
524 return cc->ExecuteProgram(OutputAsmFile, Args, *FileKind, InputFile,
525 OutputFile, CCArgs, Timeout, MemoryLimit);
528 /// createLLC - Try to find the LLC executable
530 LLC *AbstractInterpreter::createLLC(const char *Argv0, std::string &Message,
531 const std::string &CCBinary,
532 const std::vector<std::string> *Args,
533 const std::vector<std::string> *CCArgs,
534 bool UseIntegratedAssembler) {
535 std::string LLCPath =
536 PrependMainExecutablePath("llc", Argv0, (void *)(intptr_t)&createLLC);
537 if (LLCPath.empty()) {
538 Message = "Cannot find `llc' in executable directory!\n";
542 CC *cc = CC::create(Message, CCBinary, CCArgs);
544 errs() << Message << "\n";
547 Message = "Found llc: " + LLCPath + "\n";
548 return new LLC(LLCPath, cc, Args, UseIntegratedAssembler);
551 //===---------------------------------------------------------------------===//
552 // JIT Implementation of AbstractIntepreter interface
555 class JIT : public AbstractInterpreter {
556 std::string LLIPath; // The path to the LLI executable
557 std::vector<std::string> ToolArgs; // Args to pass to LLI
559 JIT(const std::string &Path, const std::vector<std::string> *Args)
567 Expected<int> ExecuteProgram(
568 const std::string &Bitcode, const std::vector<std::string> &Args,
569 const std::string &InputFile, const std::string &OutputFile,
570 const std::vector<std::string> &CCArgs = std::vector<std::string>(),
571 const std::vector<std::string> &SharedLibs = std::vector<std::string>(),
572 unsigned Timeout = 0, unsigned MemoryLimit = 0) override;
576 Expected<int> JIT::ExecuteProgram(const std::string &Bitcode,
577 const std::vector<std::string> &Args,
578 const std::string &InputFile,
579 const std::string &OutputFile,
580 const std::vector<std::string> &CCArgs,
581 const std::vector<std::string> &SharedLibs,
582 unsigned Timeout, unsigned MemoryLimit) {
583 // Construct a vector of parameters, incorporating those from the command-line
584 std::vector<const char *> JITArgs;
585 JITArgs.push_back(LLIPath.c_str());
586 JITArgs.push_back("-force-interpreter=false");
588 // Add any extra LLI args.
589 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
590 JITArgs.push_back(ToolArgs[i].c_str());
592 for (unsigned i = 0, e = SharedLibs.size(); i != e; ++i) {
593 JITArgs.push_back("-load");
594 JITArgs.push_back(SharedLibs[i].c_str());
596 JITArgs.push_back(Bitcode.c_str());
597 // Add optional parameters to the running program from Argv
598 for (unsigned i = 0, e = Args.size(); i != e; ++i)
599 JITArgs.push_back(Args[i].c_str());
600 JITArgs.push_back(nullptr);
604 DEBUG(errs() << "\nAbout to run:\t";
605 for (unsigned i = 0, e = JITArgs.size() - 1; i != e; ++i) errs()
606 << " " << JITArgs[i];
608 DEBUG(errs() << "\nSending output to " << OutputFile << "\n");
609 return RunProgramWithTimeout(LLIPath, &JITArgs[0], InputFile, OutputFile,
610 OutputFile, Timeout, MemoryLimit);
613 /// createJIT - Try to find the LLI executable
615 AbstractInterpreter *
616 AbstractInterpreter::createJIT(const char *Argv0, std::string &Message,
617 const std::vector<std::string> *Args) {
618 std::string LLIPath =
619 PrependMainExecutablePath("lli", Argv0, (void *)(intptr_t)&createJIT);
620 if (!LLIPath.empty()) {
621 Message = "Found lli: " + LLIPath + "\n";
622 return new JIT(LLIPath, Args);
625 Message = "Cannot find `lli' in executable directory!\n";
629 //===---------------------------------------------------------------------===//
633 static bool IsARMArchitecture(std::vector<const char *> Args) {
634 for (std::vector<const char *>::const_iterator I = Args.begin(),
637 if (StringRef(*I).equals_lower("-arch")) {
639 if (I != E && StringRef(*I).startswith_lower("arm"))
647 Expected<int> CC::ExecuteProgram(const std::string &ProgramFile,
648 const std::vector<std::string> &Args,
650 const std::string &InputFile,
651 const std::string &OutputFile,
652 const std::vector<std::string> &ArgsForCC,
653 unsigned Timeout, unsigned MemoryLimit) {
654 std::vector<const char *> CCArgs;
656 CCArgs.push_back(CCPath.c_str());
658 if (TargetTriple.getArch() == Triple::x86)
659 CCArgs.push_back("-m32");
661 for (std::vector<std::string>::const_iterator I = ccArgs.begin(),
664 CCArgs.push_back(I->c_str());
666 // Specify -x explicitly in case the extension is wonky
667 if (fileType != ObjectFile) {
668 CCArgs.push_back("-x");
669 if (fileType == CFile) {
670 CCArgs.push_back("c");
671 CCArgs.push_back("-fno-strict-aliasing");
673 CCArgs.push_back("assembler");
675 // For ARM architectures we don't want this flag. bugpoint isn't
676 // explicitly told what architecture it is working on, so we get
678 if (TargetTriple.isOSDarwin() && !IsARMArchitecture(CCArgs))
679 CCArgs.push_back("-force_cpusubtype_ALL");
683 CCArgs.push_back(ProgramFile.c_str()); // Specify the input filename.
685 CCArgs.push_back("-x");
686 CCArgs.push_back("none");
687 CCArgs.push_back("-o");
689 SmallString<128> OutputBinary;
691 sys::fs::createUniqueFile(ProgramFile + "-%%%%%%%.cc.exe", OutputBinary);
693 errs() << "Error making unique filename: " << EC.message() << "\n";
696 CCArgs.push_back(OutputBinary.c_str()); // Output to the right file...
698 // Add any arguments intended for CC. We locate them here because this is
699 // most likely -L and -l options that need to come before other libraries but
700 // after the source. Other options won't be sensitive to placement on the
701 // command line, so this should be safe.
702 for (unsigned i = 0, e = ArgsForCC.size(); i != e; ++i)
703 CCArgs.push_back(ArgsForCC[i].c_str());
705 CCArgs.push_back("-lm"); // Hard-code the math library...
706 CCArgs.push_back("-O2"); // Optimize the program a bit...
707 if (TargetTriple.getArch() == Triple::sparc)
708 CCArgs.push_back("-mcpu=v9");
709 CCArgs.push_back(nullptr); // NULL terminator
713 DEBUG(errs() << "\nAbout to run:\t";
714 for (unsigned i = 0, e = CCArgs.size() - 1; i != e; ++i) errs()
717 if (RunProgramWithTimeout(CCPath, &CCArgs[0], "", "", ""))
718 return ProcessFailure(CCPath, &CCArgs[0]);
720 std::vector<const char *> ProgramArgs;
722 // Declared here so that the destructor only runs after
723 // ProgramArgs is used.
726 if (RemoteClientPath.empty())
727 ProgramArgs.push_back(OutputBinary.c_str());
729 ProgramArgs.push_back(RemoteClientPath.c_str());
730 ProgramArgs.push_back(RemoteHost.c_str());
731 if (!RemoteUser.empty()) {
732 ProgramArgs.push_back("-l");
733 ProgramArgs.push_back(RemoteUser.c_str());
735 if (!RemotePort.empty()) {
736 ProgramArgs.push_back("-p");
737 ProgramArgs.push_back(RemotePort.c_str());
739 if (!RemoteExtra.empty()) {
740 ProgramArgs.push_back(RemoteExtra.c_str());
743 // Full path to the binary. We need to cd to the exec directory because
744 // there is a dylib there that the exec expects to find in the CWD
745 char *env_pwd = getenv("PWD");
749 Exec += OutputBinary.c_str();
750 ProgramArgs.push_back(Exec.c_str());
753 // Add optional parameters to the running program from Argv
754 for (unsigned i = 0, e = Args.size(); i != e; ++i)
755 ProgramArgs.push_back(Args[i].c_str());
756 ProgramArgs.push_back(nullptr); // NULL terminator
758 // Now that we have a binary, run it!
759 outs() << "<program>";
761 DEBUG(errs() << "\nAbout to run:\t";
762 for (unsigned i = 0, e = ProgramArgs.size() - 1; i != e; ++i) errs()
763 << " " << ProgramArgs[i];
766 FileRemover OutputBinaryRemover(OutputBinary.str(), !SaveTemps);
768 if (RemoteClientPath.empty()) {
769 DEBUG(errs() << "<run locally>");
771 int ExitCode = RunProgramWithTimeout(OutputBinary.str(), &ProgramArgs[0],
772 InputFile, OutputFile, OutputFile,
773 Timeout, MemoryLimit, &Error);
774 // Treat a signal (usually SIGSEGV) or timeout as part of the program output
775 // so that crash-causing miscompilation is handled seamlessly.
777 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
778 outFile << Error << '\n';
783 outs() << "<run remotely>";
785 return RunProgramRemotelyWithTimeout(RemoteClientPath, &ProgramArgs[0],
786 InputFile, OutputFile, OutputFile,
787 Timeout, MemoryLimit);
791 Error CC::MakeSharedObject(const std::string &InputFile, FileType fileType,
792 std::string &OutputFile,
793 const std::vector<std::string> &ArgsForCC) {
794 SmallString<128> UniqueFilename;
795 std::error_code EC = sys::fs::createUniqueFile(
796 InputFile + "-%%%%%%%" + LTDL_SHLIB_EXT, UniqueFilename);
798 errs() << "Error making unique filename: " << EC.message() << "\n";
801 OutputFile = UniqueFilename.str();
803 std::vector<const char *> CCArgs;
805 CCArgs.push_back(CCPath.c_str());
807 if (TargetTriple.getArch() == Triple::x86)
808 CCArgs.push_back("-m32");
810 for (std::vector<std::string>::const_iterator I = ccArgs.begin(),
813 CCArgs.push_back(I->c_str());
815 // Compile the C/asm file into a shared object
816 if (fileType != ObjectFile) {
817 CCArgs.push_back("-x");
818 CCArgs.push_back(fileType == AsmFile ? "assembler" : "c");
820 CCArgs.push_back("-fno-strict-aliasing");
821 CCArgs.push_back(InputFile.c_str()); // Specify the input filename.
822 CCArgs.push_back("-x");
823 CCArgs.push_back("none");
824 if (TargetTriple.getArch() == Triple::sparc)
825 CCArgs.push_back("-G"); // Compile a shared library, `-G' for Sparc
826 else if (TargetTriple.isOSDarwin()) {
827 // link all source files into a single module in data segment, rather than
828 // generating blocks. dynamic_lookup requires that you set
829 // MACOSX_DEPLOYMENT_TARGET=10.3 in your env. FIXME: it would be better for
830 // bugpoint to just pass that in the environment of CC.
831 CCArgs.push_back("-single_module");
832 CCArgs.push_back("-dynamiclib"); // `-dynamiclib' for MacOS X/PowerPC
833 CCArgs.push_back("-undefined");
834 CCArgs.push_back("dynamic_lookup");
836 CCArgs.push_back("-shared"); // `-shared' for Linux/X86, maybe others
838 if (TargetTriple.getArch() == Triple::x86_64)
839 CCArgs.push_back("-fPIC"); // Requires shared objs to contain PIC
841 if (TargetTriple.getArch() == Triple::sparc)
842 CCArgs.push_back("-mcpu=v9");
844 CCArgs.push_back("-o");
845 CCArgs.push_back(OutputFile.c_str()); // Output to the right filename.
846 CCArgs.push_back("-O2"); // Optimize the program a bit.
848 // Add any arguments intended for CC. We locate them here because this is
849 // most likely -L and -l options that need to come before other libraries but
850 // after the source. Other options won't be sensitive to placement on the
851 // command line, so this should be safe.
852 for (unsigned i = 0, e = ArgsForCC.size(); i != e; ++i)
853 CCArgs.push_back(ArgsForCC[i].c_str());
854 CCArgs.push_back(nullptr); // NULL terminator
858 DEBUG(errs() << "\nAbout to run:\t";
859 for (unsigned i = 0, e = CCArgs.size() - 1; i != e; ++i) errs()
862 if (RunProgramWithTimeout(CCPath, &CCArgs[0], "", "", ""))
863 return ProcessFailure(CCPath, &CCArgs[0]);
864 return Error::success();
867 /// create - Try to find the CC executable
869 CC *CC::create(std::string &Message, const std::string &CCBinary,
870 const std::vector<std::string> *Args) {
871 auto CCPath = sys::findProgramByName(CCBinary);
873 Message = "Cannot find `" + CCBinary + "' in PATH: " +
874 CCPath.getError().message() + "\n";
878 std::string RemoteClientPath;
879 if (!RemoteClient.empty()) {
880 auto Path = sys::findProgramByName(RemoteClient);
882 Message = "Cannot find `" + RemoteClient + "' in PATH: " +
883 Path.getError().message() + "\n";
886 RemoteClientPath = *Path;
889 Message = "Found CC: " + *CCPath + "\n";
890 return new CC(*CCPath, RemoteClientPath, Args);