Index: include/llvm/Support/Program.h =================================================================== --- include/llvm/Support/Program.h +++ include/llvm/Support/Program.h @@ -15,6 +15,7 @@ #define LLVM_SUPPORT_PROGRAM_H #include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/Optional.h" #include "llvm/Support/Path.h" #include @@ -146,6 +147,13 @@ ///< string is non-empty upon return an error occurred while invoking the ///< program. ); + + /// This function searches for an existing file in the list of directories + /// in a PATH like environment variable, and returns the first file found, + /// according to the order of the entries in the PATH like environment + /// variable. + Optional FindInEnvPath(const std::string& EnvName, + const std::string& FileName); } } Index: lib/Support/Program.cpp =================================================================== --- lib/Support/Program.cpp +++ lib/Support/Program.cpp @@ -12,7 +12,10 @@ //===----------------------------------------------------------------------===// #include "llvm/Support/Program.h" +#include "llvm/ADT/StringExtras.h" #include "llvm/Config/config.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/Process.h" #include using namespace llvm; using namespace sys; @@ -59,6 +62,33 @@ return PI; } +Optional sys::FindInEnvPath(const std::string& EnvName, + const std::string& FileName) +{ + Optional FoundPath; + Optional OptPath = Process::GetEnv(EnvName); + if (!OptPath.hasValue()) + return FoundPath; + + const char EnvPathSeparatorStr[] = {EnvPathSeparator, '\0'}; + SmallVector Dirs; + SplitString(OptPath.getValue(), Dirs, EnvPathSeparatorStr); + + for (const auto &Dir : Dirs) { + if (Dir.empty()) + continue; + + SmallString<128> FilePath(Dir); + path::append(FilePath, FileName); + if (fs::exists(Twine(FilePath))) { + FoundPath = FilePath.str(); + break; + } + } + + return FoundPath; +} + // Include the platform-specific parts of this class. #ifdef LLVM_ON_UNIX #include "Unix/Program.inc"