Support: Convert Program APIs to std::optional

This commit is contained in:
Matt Arsenault 2022-12-01 14:47:29 -05:00
parent 75a3d9d1b3
commit e748db0f7f
20 changed files with 73 additions and 65 deletions

View File

@ -15,13 +15,13 @@
#include "clang/Driver/Util.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Option/Option.h"
#include <cassert>
#include <iterator>
#include <map>
#include <memory>
#include <optional>
#include <utility>
#include <vector>
@ -113,7 +113,7 @@ class Compilation {
ArgStringMap FailureResultFiles;
/// Optional redirection for stdin, stdout, stderr.
std::vector<Optional<StringRef>> Redirects;
std::vector<std::optional<StringRef>> Redirects;
/// Callback called after compilation job has been finished.
/// Arguments of the callback are the compilation job as an instance of
@ -332,8 +332,8 @@ public:
///
/// \param Redirects - array of optional paths. The array should have a size
/// of three. The inferior process's stdin(0), stdout(1), and stderr(2) will
/// be redirected to the corresponding paths, if provided (not llvm::None).
void Redirect(ArrayRef<Optional<StringRef>> Redirects);
/// be redirected to the corresponding paths, if provided (not std::nullopt).
void Redirect(ArrayRef<std::optional<StringRef>> Redirects);
};
} // namespace driver

View File

@ -12,13 +12,13 @@
#include "clang/Basic/LLVM.h"
#include "clang/Driver/InputInfo.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/iterator.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/Program.h"
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
@ -142,10 +142,10 @@ class Command {
std::vector<const char *> Environment;
/// Optional redirection for stdin, stdout, stderr.
std::vector<Optional<std::string>> RedirectFiles;
std::vector<std::optional<std::string>> RedirectFiles;
/// Information on executable run provided by OS.
mutable Optional<llvm::sys::ProcessStatistics> ProcStat;
mutable std::optional<llvm::sys::ProcessStatistics> ProcStat;
/// When a response file is needed, we try to put most arguments in an
/// exclusive file, while others remains as regular command line arguments.
@ -178,7 +178,7 @@ public:
virtual void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote,
CrashReportInfo *CrashInfo = nullptr) const;
virtual int Execute(ArrayRef<Optional<StringRef>> Redirects,
virtual int Execute(ArrayRef<std::optional<StringRef>> Redirects,
std::string *ErrMsg, bool *ExecutionFailed) const;
/// getSource - Return the Action which caused the creation of this job.
@ -207,7 +207,8 @@ public:
/// from the parent process will be used.
virtual void setEnvironment(llvm::ArrayRef<const char *> NewEnvironment);
void setRedirectFiles(const std::vector<Optional<std::string>> &Redirects);
void
setRedirectFiles(const std::vector<std::optional<std::string>> &Redirects);
void replaceArguments(llvm::opt::ArgStringList List) {
Arguments = std::move(List);
@ -225,7 +226,7 @@ public:
return OutputFilenames;
}
Optional<llvm::sys::ProcessStatistics> getProcessStatistics() const {
std::optional<llvm::sys::ProcessStatistics> getProcessStatistics() const {
return ProcStat;
}
@ -245,7 +246,7 @@ public:
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote,
CrashReportInfo *CrashInfo = nullptr) const override;
int Execute(ArrayRef<Optional<StringRef>> Redirects, std::string *ErrMsg,
int Execute(ArrayRef<std::optional<StringRef>> Redirects, std::string *ErrMsg,
bool *ExecutionFailed) const override;
void setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) override;
@ -264,7 +265,7 @@ public:
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote,
CrashReportInfo *CrashInfo = nullptr) const override;
int Execute(ArrayRef<Optional<StringRef>> Redirects, std::string *ErrMsg,
int Execute(ArrayRef<std::optional<StringRef>> Redirects, std::string *ErrMsg,
bool *ExecutionFailed) const override;
};

View File

@ -307,6 +307,6 @@ StringRef Compilation::getSysRoot() const {
return getDriver().SysRoot;
}
void Compilation::Redirect(ArrayRef<Optional<StringRef>> Redirects) {
void Compilation::Redirect(ArrayRef<std::optional<StringRef>> Redirects) {
this->Redirects = Redirects;
}

View File

@ -4659,7 +4659,7 @@ void Driver::BuildJobs(Compilation &C) const {
if (CCPrintProcessStats) {
C.setPostCallback([=](const Command &Cmd, int Res) {
Optional<llvm::sys::ProcessStatistics> ProcStat =
std::optional<llvm::sys::ProcessStatistics> ProcStat =
Cmd.getProcessStatistics();
if (!ProcStat)
return;

View File

@ -302,7 +302,7 @@ void Command::setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) {
}
void Command::setRedirectFiles(
const std::vector<Optional<std::string>> &Redirects) {
const std::vector<std::optional<std::string>> &Redirects) {
RedirectFiles = Redirects;
}
@ -314,7 +314,7 @@ void Command::PrintFileNames() const {
}
}
int Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
int Command::Execute(ArrayRef<std::optional<StringRef>> Redirects,
std::string *ErrMsg, bool *ExecutionFailed) const {
PrintFileNames();
@ -347,7 +347,7 @@ int Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
}
}
Optional<ArrayRef<StringRef>> Env;
std::optional<ArrayRef<StringRef>> Env;
std::vector<StringRef> ArgvVectorStorage;
if (!Environment.empty()) {
assert(Environment.back() == nullptr &&
@ -360,12 +360,12 @@ int Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
// Use Job-specific redirect files if they are present.
if (!RedirectFiles.empty()) {
std::vector<Optional<StringRef>> RedirectFilesOptional;
std::vector<std::optional<StringRef>> RedirectFilesOptional;
for (const auto &Ele : RedirectFiles)
if (Ele)
RedirectFilesOptional.push_back(Optional<StringRef>(*Ele));
RedirectFilesOptional.push_back(std::optional<StringRef>(*Ele));
else
RedirectFilesOptional.push_back(None);
RedirectFilesOptional.push_back(std::nullopt);
return llvm::sys::ExecuteAndWait(Executable, Args, Env,
makeArrayRef(RedirectFilesOptional),
@ -395,7 +395,7 @@ void CC1Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
Command::Print(OS, Terminator, Quote, CrashInfo);
}
int CC1Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
int CC1Command::Execute(ArrayRef<std::optional<StringRef>> Redirects,
std::string *ErrMsg, bool *ExecutionFailed) const {
// FIXME: Currently, if there're more than one job, we disable
// -fintegrate-cc1. If we're no longer a integrated-cc1 job, fallback to
@ -452,7 +452,7 @@ void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
OS << " || (exit 0)" << Terminator;
}
int ForceSuccessCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
int ForceSuccessCommand::Execute(ArrayRef<std::optional<StringRef>> Redirects,
std::string *ErrMsg,
bool *ExecutionFailed) const {
int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);

View File

@ -778,7 +778,7 @@ AMDGPUToolChain::detectSystemGPUs(const ArgList &Args,
llvm::sys::fs::createTemporaryFile("print-system-gpus", "" /* No Suffix */,
OutputFile);
llvm::FileRemover OutputRemover(OutputFile.c_str());
llvm::Optional<llvm::StringRef> Redirects[] = {
std::optional<llvm::StringRef> Redirects[] = {
{""},
OutputFile.str(),
{""},

View File

@ -82,7 +82,7 @@ public:
"" /*no-suffix*/, ErrorFile);
llvm::FileRemover OutputRemover(OutputFile.c_str());
llvm::FileRemover ErrorRemover(ErrorFile.c_str());
llvm::Optional<StringRef> Redirects[] = {
std::optional<StringRef> Redirects[] = {
{""}, // Stdin
OutputFile.str(),
ErrorFile.str(),

View File

@ -14,12 +14,12 @@
#define LLVM_SUPPORT_PROGRAM_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include <chrono>
#include <optional>
#include <system_error>
namespace llvm {
@ -107,11 +107,12 @@ namespace sys {
ArrayRef<StringRef> Args, ///< An array of strings that are passed to the
///< program. The first element should be the name of the program.
///< The array should **not** be terminated by an empty StringRef.
Optional<ArrayRef<StringRef>> Env = None, ///< An optional vector of
std::optional<ArrayRef<StringRef>> Env =
std::nullopt, ///< An optional vector of
///< strings to use for the program's environment. If not provided, the
///< current program's environment will be used. If specified, the
///< vector should **not** be terminated by an empty StringRef.
ArrayRef<Optional<StringRef>> Redirects = {}, ///<
ArrayRef<std::optional<StringRef>> Redirects = {}, ///<
///< An array of optional paths. Should have a size of zero or three.
///< If the array is empty, no redirections are performed.
///< Otherwise, the inferior process's stdin(0), stdout(1), and stderr(2)
@ -133,7 +134,7 @@ namespace sys {
///< string is non-empty upon return an error occurred while invoking the
///< program.
bool *ExecutionFailed = nullptr,
Optional<ProcessStatistics> *ProcStat = nullptr, ///< If non-zero,
std::optional<ProcessStatistics> *ProcStat = nullptr, ///< If non-zero,
/// provides a pointer to a structure in which process execution
/// statistics will be stored.
BitVector *AffinityMask = nullptr ///< CPUs or processors the new
@ -146,8 +147,8 @@ namespace sys {
/// \see Wait until the process finished execution or win32 CloseHandle() API
/// on ProcessInfo.ProcessHandle to avoid memory leaks.
ProcessInfo ExecuteNoWait(StringRef Program, ArrayRef<StringRef> Args,
Optional<ArrayRef<StringRef>> Env,
ArrayRef<Optional<StringRef>> Redirects = {},
std::optional<ArrayRef<StringRef>> Env,
ArrayRef<std::optional<StringRef>> Redirects = {},
unsigned MemoryLimit = 0,
std::string *ErrMsg = nullptr,
bool *ExecutionFailed = nullptr,
@ -216,7 +217,8 @@ namespace sys {
///< string instance in which error messages will be returned. If the
///< string is non-empty upon return an error occurred while invoking the
///< program.
Optional<ProcessStatistics> *ProcStat = nullptr ///< If non-zero, provides
std::optional<ProcessStatistics> *ProcStat =
nullptr ///< If non-zero, provides
/// a pointer to a structure in which process execution statistics will be
/// stored.
);

View File

@ -198,8 +198,9 @@ std::string llvm::doSystemDiff(StringRef Before, StringRef After,
StringRef Args[] = {DiffBinary, "-w", "-d", OLF,
NLF, ULF, FileName[0], FileName[1]};
Optional<StringRef> Redirects[] = {None, StringRef(FileName[2]), None};
int Result = sys::ExecuteAndWait(*DiffExe, Args, None, Redirects);
std::optional<StringRef> Redirects[] = {std::nullopt, StringRef(FileName[2]),
std::nullopt};
int Result = sys::ExecuteAndWait(*DiffExe, Args, std::nullopt, Redirects);
if (Result < 0)
return "Error executing system diff.";
std::string Diff;

View File

@ -23,17 +23,18 @@ using namespace sys;
//===----------------------------------------------------------------------===//
static bool Execute(ProcessInfo &PI, StringRef Program,
ArrayRef<StringRef> Args, Optional<ArrayRef<StringRef>> Env,
ArrayRef<Optional<StringRef>> Redirects,
ArrayRef<StringRef> Args,
std::optional<ArrayRef<StringRef>> Env,
ArrayRef<std::optional<StringRef>> Redirects,
unsigned MemoryLimit, std::string *ErrMsg,
BitVector *AffinityMask);
int sys::ExecuteAndWait(StringRef Program, ArrayRef<StringRef> Args,
Optional<ArrayRef<StringRef>> Env,
ArrayRef<Optional<StringRef>> Redirects,
std::optional<ArrayRef<StringRef>> Env,
ArrayRef<std::optional<StringRef>> Redirects,
unsigned SecondsToWait, unsigned MemoryLimit,
std::string *ErrMsg, bool *ExecutionFailed,
Optional<ProcessStatistics> *ProcStat,
std::optional<ProcessStatistics> *ProcStat,
BitVector *AffinityMask) {
assert(Redirects.empty() || Redirects.size() == 3);
ProcessInfo PI;
@ -54,8 +55,8 @@ int sys::ExecuteAndWait(StringRef Program, ArrayRef<StringRef> Args,
}
ProcessInfo sys::ExecuteNoWait(StringRef Program, ArrayRef<StringRef> Args,
Optional<ArrayRef<StringRef>> Env,
ArrayRef<Optional<StringRef>> Redirects,
std::optional<ArrayRef<StringRef>> Env,
ArrayRef<std::optional<StringRef>> Redirects,
unsigned MemoryLimit, std::string *ErrMsg,
bool *ExecutionFailed, BitVector *AffinityMask) {
assert(Redirects.empty() || Redirects.size() == 3);

View File

@ -192,8 +192,8 @@ static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace,
}
}
Optional<StringRef> Redirects[] = {InputFile.str(), OutputFile.str(),
StringRef("")};
std::optional<StringRef> Redirects[] = {InputFile.str(), OutputFile.str(),
StringRef("")};
StringRef Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
#ifdef _WIN32
// Pass --relative-address on Windows so that we don't

View File

@ -95,7 +95,7 @@ ErrorOr<std::string> sys::findProgramByName(StringRef Name,
return errc::no_such_file_or_directory;
}
static bool RedirectIO(Optional<StringRef> Path, int FD, std::string *ErrMsg) {
static bool RedirectIO(std::optional<StringRef> Path, int FD, std::string *ErrMsg) {
if (!Path) // Noop
return false;
std::string File;
@ -172,8 +172,8 @@ toNullTerminatedCStringArray(ArrayRef<StringRef> Strings, StringSaver &Saver) {
}
static bool Execute(ProcessInfo &PI, StringRef Program,
ArrayRef<StringRef> Args, Optional<ArrayRef<StringRef>> Env,
ArrayRef<Optional<StringRef>> Redirects,
ArrayRef<StringRef> Args, std::optional<ArrayRef<StringRef>> Env,
ArrayRef<std::optional<StringRef>> Redirects,
unsigned MemoryLimit, std::string *ErrMsg,
BitVector *AffinityMask) {
if (!llvm::sys::fs::exists(Program)) {
@ -386,7 +386,7 @@ pid_t(llvm::sys::wait4)(pid_t pid, int *status, int options,
ProcessInfo llvm::sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
bool WaitUntilTerminates, std::string *ErrMsg,
Optional<ProcessStatistics> *ProcStat) {
std::optional<ProcessStatistics> *ProcStat) {
struct sigaction Act, Old;
assert(PI.Pid && "invalid pid to wait on, process not started?");

View File

@ -127,7 +127,7 @@ bool MakeErrMsg(std::string *ErrMsg, const std::string &prefix) {
return R != 0;
}
static HANDLE RedirectIO(Optional<StringRef> Path, int fd,
static HANDLE RedirectIO(std::optional<StringRef> Path, int fd,
std::string *ErrMsg) {
HANDLE h;
if (!Path) {
@ -172,8 +172,8 @@ static HANDLE RedirectIO(Optional<StringRef> Path, int fd,
} // namespace llvm
static bool Execute(ProcessInfo &PI, StringRef Program,
ArrayRef<StringRef> Args, Optional<ArrayRef<StringRef>> Env,
ArrayRef<Optional<StringRef>> Redirects,
ArrayRef<StringRef> Args, std::optional<ArrayRef<StringRef>> Env,
ArrayRef<std::optional<StringRef>> Redirects,
unsigned MemoryLimit, std::string *ErrMsg,
BitVector *AffinityMask) {
if (!sys::fs::can_execute(Program)) {
@ -410,7 +410,7 @@ ErrorOr<std::wstring> sys::flattenWindowsCommandLine(ArrayRef<StringRef> Args) {
ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
bool WaitUntilChildTerminates, std::string *ErrMsg,
Optional<ProcessStatistics> *ProcStat) {
std::optional<ProcessStatistics> *ProcStat) {
assert(PI.Pid && "invalid pid to wait on, process not started?");
assert((PI.Process && PI.Process != INVALID_HANDLE_VALUE) &&
"invalid process handle to wait on, process not started?");

View File

@ -232,7 +232,8 @@ bool BugDriver::runPasses(Module &Program,
<< " " << Args[i];
errs() << "\n";);
Optional<StringRef> Redirects[3] = {None, None, None};
std::optional<StringRef> Redirects[3] = {std::nullopt, std::nullopt,
std::nullopt};
// Redirect stdout and stderr to nowhere if SilencePasses is given.
if (SilencePasses) {
Redirects[1] = "";
@ -240,7 +241,7 @@ bool BugDriver::runPasses(Module &Program,
}
std::string ErrMsg;
int result = sys::ExecuteAndWait(Prog, Args, None, Redirects, Timeout,
int result = sys::ExecuteAndWait(Prog, Args, std::nullopt, Redirects, Timeout,
MemoryLimit, &ErrMsg);
// If we are supposed to delete the bitcode file or if the passes crashed,

View File

@ -58,7 +58,7 @@ static int RunProgramWithTimeout(StringRef ProgramPath,
unsigned NumSeconds = 0,
unsigned MemoryLimit = 0,
std::string *ErrMsg = nullptr) {
Optional<StringRef> Redirects[3] = {StdInFile, StdOutFile, StdErrFile};
std::optional<StringRef> Redirects[3] = {StdInFile, StdOutFile, StdErrFile};
return sys::ExecuteAndWait(ProgramPath, Args, None, Redirects, NumSeconds,
MemoryLimit, ErrMsg);
}
@ -73,7 +73,7 @@ static int RunProgramRemotelyWithTimeout(
StringRef RemoteClientPath, ArrayRef<StringRef> Args, StringRef StdInFile,
StringRef StdOutFile, StringRef StdErrFile, unsigned NumSeconds = 0,
unsigned MemoryLimit = 0) {
Optional<StringRef> Redirects[3] = {StdInFile, StdOutFile, StdErrFile};
std::optional<StringRef> Redirects[3] = {StdInFile, StdOutFile, StdErrFile};
// Run the program remotely with the remote client
int ReturnCode = sys::ExecuteAndWait(RemoteClientPath, Args, None, Redirects,

View File

@ -556,7 +556,8 @@ void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) {
std::vector<StringRef> ArgsV;
for (StringRef Arg : ViewOpts.DemanglerOpts)
ArgsV.push_back(Arg);
Optional<StringRef> Redirects[] = {InputPath.str(), OutputPath.str(), {""}};
std::optional<StringRef> Redirects[] = {
InputPath.str(), OutputPath.str(), {""}};
std::string ErrMsg;
int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV,
/*env=*/None, Redirects, /*secondsToWait=*/0,

View File

@ -364,10 +364,10 @@ PerfInputFile PerfScriptReader::convertPerfDataToTrace(
StringRef ScriptMMapArgs[] = {PerfPath, "script", "--show-mmap-events",
"-F", "comm,pid", "-i",
PerfData};
Optional<StringRef> Redirects[] = {llvm::None, // Stdin
StringRef(PerfTraceFile), // Stdout
StringRef(ErrorFile)}; // Stderr
sys::ExecuteAndWait(PerfPath, ScriptMMapArgs, llvm::None, Redirects);
std::optional<StringRef> Redirects[] = {std::nullopt, // Stdin
StringRef(PerfTraceFile), // Stdout
StringRef(ErrorFile)}; // Stderr
sys::ExecuteAndWait(PerfPath, ScriptMMapArgs, std::nullopt, Redirects);
// Collect the PIDs
TraceStream TraceIt(PerfTraceFile);

View File

@ -43,8 +43,8 @@ int TestRunner::run(StringRef Filename) const {
ProgramArgs.push_back(Filename);
std::string ErrMsg;
SmallVector<Optional<StringRef>, 3> Redirects;
Optional<StringRef> Empty = StringRef();
SmallVector<std::optional<StringRef>, 3> Redirects;
std::optional<StringRef> Empty = StringRef();
if (!Verbose) {
for (int i = 0; i < 3; ++i)
Redirects.push_back(Empty);

View File

@ -387,7 +387,7 @@ static bool runAndGetCommandOutput(
path::append(OutputFile, "out");
StringRef OutputPath = OutputFile.str();
const Optional<StringRef> Redirects[] = {
const std::optional<StringRef> Redirects[] = {
/*STDIN=*/None, /*STDOUT=*/OutputPath, /*STDERR=*/None};
int RetCode = ExecuteAndWait(ExePath, argv, /*env=*/llvm::None, Redirects);
ASSERT_EQ(0, RetCode);

View File

@ -151,7 +151,8 @@ TEST_F(ProgramEnvTest, CreateProcessLongPath) {
std::string Error;
bool ExecutionFailed;
Optional<StringRef> Redirects[] = {None, LongPath.str(), None};
std::optional<StringRef> Redirects[] = {std::nullopt, LongPath.str(),
std::nullopt};
int RC = ExecuteAndWait(MyExe, ArgV, getEnviron(), Redirects,
/*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &Error,
&ExecutionFailed);
@ -194,7 +195,7 @@ TEST_F(ProgramEnvTest, CreateProcessTrailingSlash) {
#else
StringRef nul("/dev/null");
#endif
Optional<StringRef> redirects[] = { nul, nul, None };
std::optional<StringRef> redirects[] = {nul, nul, None};
int rc = ExecuteAndWait(my_exe, argv, getEnviron(), redirects,
/*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error,
&ExecutionFailed);
@ -367,7 +368,7 @@ TEST_F(ProgramEnvTest, TestExecuteAndWaitStatistics) {
std::string Error;
bool ExecutionFailed;
Optional<ProcessStatistics> ProcStat;
std::optional<ProcessStatistics> ProcStat;
int RetCode = ExecuteAndWait(Executable, argv, getEnviron(), {}, 0, 0, &Error,
&ExecutionFailed, &ProcStat);
ASSERT_EQ(0, RetCode);