[lld-macho] Change most Optional to std::optional

This commit is contained in:
Fangrui Song 2022-11-27 16:54:07 -08:00
parent 9da7aee7c9
commit 026e797367
11 changed files with 40 additions and 39 deletions

View File

@ -175,7 +175,7 @@ struct Configuration {
// they can't easily fix them. // they can't easily fix them.
llvm::StringSet<> ignoreAutoLinkOptions; llvm::StringSet<> ignoreAutoLinkOptions;
PlatformInfo platformInfo; PlatformInfo platformInfo;
llvm::Optional<PlatformInfo> secondaryPlatformInfo; std::optional<PlatformInfo> secondaryPlatformInfo;
NamespaceKind namespaceKind = NamespaceKind::twolevel; NamespaceKind namespaceKind = NamespaceKind::twolevel;
UndefinedSymbolTreatment undefinedSymbolTreatment = UndefinedSymbolTreatment undefinedSymbolTreatment =
UndefinedSymbolTreatment::error; UndefinedSymbolTreatment::error;

View File

@ -82,7 +82,7 @@ static HeaderFileType getOutputType(const InputArgList &args) {
} }
static DenseMap<CachedHashStringRef, StringRef> resolvedLibraries; static DenseMap<CachedHashStringRef, StringRef> resolvedLibraries;
static Optional<StringRef> findLibrary(StringRef name) { static std::optional<StringRef> findLibrary(StringRef name) {
CachedHashStringRef key(name); CachedHashStringRef key(name);
auto entry = resolvedLibraries.find(key); auto entry = resolvedLibraries.find(key);
if (entry != resolvedLibraries.end()) if (entry != resolvedLibraries.end())
@ -90,7 +90,7 @@ static Optional<StringRef> findLibrary(StringRef name) {
auto doFind = [&] { auto doFind = [&] {
if (config->searchDylibsFirst) { if (config->searchDylibsFirst) {
if (Optional<StringRef> path = findPathCombination( if (std::optional<StringRef> path = findPathCombination(
"lib" + name, config->librarySearchPaths, {".tbd", ".dylib"})) "lib" + name, config->librarySearchPaths, {".tbd", ".dylib"}))
return path; return path;
return findPathCombination("lib" + name, config->librarySearchPaths, return findPathCombination("lib" + name, config->librarySearchPaths,
@ -100,7 +100,7 @@ static Optional<StringRef> findLibrary(StringRef name) {
{".tbd", ".dylib", ".a"}); {".tbd", ".dylib", ".a"});
}; };
Optional<StringRef> path = doFind(); std::optional<StringRef> path = doFind();
if (path) if (path)
resolvedLibraries[key] = *path; resolvedLibraries[key] = *path;
@ -108,7 +108,7 @@ static Optional<StringRef> findLibrary(StringRef name) {
} }
static DenseMap<CachedHashStringRef, StringRef> resolvedFrameworks; static DenseMap<CachedHashStringRef, StringRef> resolvedFrameworks;
static Optional<StringRef> findFramework(StringRef name) { static std::optional<StringRef> findFramework(StringRef name) {
CachedHashStringRef key(name); CachedHashStringRef key(name);
auto entry = resolvedFrameworks.find(key); auto entry = resolvedFrameworks.find(key);
if (entry != resolvedFrameworks.end()) if (entry != resolvedFrameworks.end())
@ -134,7 +134,7 @@ static Optional<StringRef> findFramework(StringRef name) {
// Suffix lookup failed, fall through to the no-suffix case. // Suffix lookup failed, fall through to the no-suffix case.
} }
if (Optional<StringRef> path = resolveDylibPath(symlink.str())) if (std::optional<StringRef> path = resolveDylibPath(symlink.str()))
return resolvedFrameworks[key] = *path; return resolvedFrameworks[key] = *path;
} }
return {}; return {};
@ -268,7 +268,7 @@ static InputFile *addFile(StringRef path, LoadType loadType,
bool isLazy = false, bool isExplicit = true, bool isLazy = false, bool isExplicit = true,
bool isBundleLoader = false, bool isBundleLoader = false,
bool isForceHidden = false) { bool isForceHidden = false) {
Optional<MemoryBufferRef> buffer = readFile(path); std::optional<MemoryBufferRef> buffer = readFile(path);
if (!buffer) if (!buffer)
return nullptr; return nullptr;
MemoryBufferRef mbref = *buffer; MemoryBufferRef mbref = *buffer;
@ -309,7 +309,7 @@ static InputFile *addFile(StringRef path, LoadType loadType,
path::filename(path).startswith("libswift"); path::filename(path).startswith("libswift");
if ((isCommandLineLoad && config->allLoad) || if ((isCommandLineLoad && config->allLoad) ||
loadType == LoadType::CommandLineForce || isLCLinkerForceLoad) { loadType == LoadType::CommandLineForce || isLCLinkerForceLoad) {
if (Optional<MemoryBufferRef> buffer = readFile(path)) { if (std::optional<MemoryBufferRef> buffer = readFile(path)) {
Error e = Error::success(); Error e = Error::success();
for (const object::Archive::Child &c : file->getArchive().children(e)) { for (const object::Archive::Child &c : file->getArchive().children(e)) {
StringRef reason; StringRef reason;
@ -339,7 +339,7 @@ static InputFile *addFile(StringRef path, LoadType loadType,
// TODO: no need to look for ObjC sections for a given archive member if // TODO: no need to look for ObjC sections for a given archive member if
// we already found that it contains an ObjC symbol. // we already found that it contains an ObjC symbol.
if (Optional<MemoryBufferRef> buffer = readFile(path)) { if (std::optional<MemoryBufferRef> buffer = readFile(path)) {
Error e = Error::success(); Error e = Error::success();
for (const object::Archive::Child &c : file->getArchive().children(e)) { for (const object::Archive::Child &c : file->getArchive().children(e)) {
Expected<MemoryBufferRef> mb = c.getMemoryBufferRef(); Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
@ -409,7 +409,7 @@ static InputFile *addFile(StringRef path, LoadType loadType,
static void addLibrary(StringRef name, bool isNeeded, bool isWeak, static void addLibrary(StringRef name, bool isNeeded, bool isWeak,
bool isReexport, bool isHidden, bool isExplicit, bool isReexport, bool isHidden, bool isExplicit,
LoadType loadType) { LoadType loadType) {
if (Optional<StringRef> path = findLibrary(name)) { if (std::optional<StringRef> path = findLibrary(name)) {
if (auto *dylibFile = dyn_cast_or_null<DylibFile>( if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
addFile(*path, loadType, /*isLazy=*/false, isExplicit, addFile(*path, loadType, /*isLazy=*/false, isExplicit,
/*isBundleLoader=*/false, isHidden))) { /*isBundleLoader=*/false, isHidden))) {
@ -430,7 +430,7 @@ static void addLibrary(StringRef name, bool isNeeded, bool isWeak,
static DenseSet<StringRef> loadedObjectFrameworks; static DenseSet<StringRef> loadedObjectFrameworks;
static void addFramework(StringRef name, bool isNeeded, bool isWeak, static void addFramework(StringRef name, bool isNeeded, bool isWeak,
bool isReexport, bool isExplicit, LoadType loadType) { bool isReexport, bool isExplicit, LoadType loadType) {
if (Optional<StringRef> path = findFramework(name)) { if (std::optional<StringRef> path = findFramework(name)) {
if (loadedObjectFrameworks.contains(*path)) if (loadedObjectFrameworks.contains(*path))
return; return;
@ -496,7 +496,7 @@ void macho::parseLCLinkerOption(InputFile *f, unsigned argc, StringRef data) {
} }
static void addFileList(StringRef path, bool isLazy) { static void addFileList(StringRef path, bool isLazy) {
Optional<MemoryBufferRef> buffer = readFile(path); std::optional<MemoryBufferRef> buffer = readFile(path);
if (!buffer) if (!buffer)
return; return;
MemoryBufferRef mbref = *buffer; MemoryBufferRef mbref = *buffer;
@ -1037,7 +1037,7 @@ bool SymbolPatterns::match(StringRef symbolName) const {
static void parseSymbolPatternsFile(const Arg *arg, static void parseSymbolPatternsFile(const Arg *arg,
SymbolPatterns &symbolPatterns) { SymbolPatterns &symbolPatterns) {
StringRef path = arg->getValue(); StringRef path = arg->getValue();
Optional<MemoryBufferRef> buffer = readFile(path); std::optional<MemoryBufferRef> buffer = readFile(path);
if (!buffer) { if (!buffer) {
error("Could not read symbol file: " + path); error("Could not read symbol file: " + path);
return; return;
@ -1820,7 +1820,7 @@ bool macho::link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
StringRef segName = arg->getValue(0); StringRef segName = arg->getValue(0);
StringRef sectName = arg->getValue(1); StringRef sectName = arg->getValue(1);
StringRef fileName = arg->getValue(2); StringRef fileName = arg->getValue(2);
Optional<MemoryBufferRef> buffer = readFile(fileName); std::optional<MemoryBufferRef> buffer = readFile(fileName);
if (buffer) if (buffer)
inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName)); inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName));
} }

View File

@ -10,12 +10,12 @@
#define LLD_MACHO_DRIVER_H #define LLD_MACHO_DRIVER_H
#include "lld/Common/LLVM.h" #include "lld/Common/LLVM.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SetVector.h" #include "llvm/ADT/SetVector.h"
#include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/MachO.h" #include "llvm/BinaryFormat/MachO.h"
#include "llvm/Option/OptTable.h" #include "llvm/Option/OptTable.h"
#include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/MemoryBuffer.h"
#include <optional>
#include <set> #include <set>
#include <type_traits> #include <type_traits>
@ -45,7 +45,7 @@ void parseLCLinkerOption(InputFile *, unsigned argc, StringRef data);
std::string createResponseFile(const llvm::opt::InputArgList &args); std::string createResponseFile(const llvm::opt::InputArgList &args);
// Check for both libfoo.dylib and libfoo.tbd (in that order). // Check for both libfoo.dylib and libfoo.tbd (in that order).
llvm::Optional<StringRef> resolveDylibPath(llvm::StringRef path); std::optional<StringRef> resolveDylibPath(llvm::StringRef path);
DylibFile *loadDylib(llvm::MemoryBufferRef mbref, DylibFile *umbrella = nullptr, DylibFile *loadDylib(llvm::MemoryBufferRef mbref, DylibFile *umbrella = nullptr,
bool isBundleLoader = false, bool isBundleLoader = false,
@ -54,7 +54,7 @@ void resetLoadedDylibs();
// Search for all possible combinations of `{root}/{name}.{extension}`. // Search for all possible combinations of `{root}/{name}.{extension}`.
// If \p extensions are not specified, then just search for `{root}/{name}`. // If \p extensions are not specified, then just search for `{root}/{name}`.
llvm::Optional<llvm::StringRef> std::optional<llvm::StringRef>
findPathCombination(const llvm::Twine &name, findPathCombination(const llvm::Twine &name,
const std::vector<llvm::StringRef> &roots, const std::vector<llvm::StringRef> &roots,
ArrayRef<llvm::StringRef> extensions = {""}); ArrayRef<llvm::StringRef> extensions = {""});

View File

@ -144,7 +144,7 @@ std::string macho::createResponseFile(const InputArgList &args) {
os << "-o " << quote(path::filename(arg->getValue())) << "\n"; os << "-o " << quote(path::filename(arg->getValue())) << "\n";
break; break;
case OPT_filelist: case OPT_filelist:
if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
for (StringRef path : args::getLines(*buffer)) for (StringRef path : args::getLines(*buffer))
os << quote(rewriteInputPath(path)) << "\n"; os << quote(rewriteInputPath(path)) << "\n";
break; break;
@ -184,7 +184,7 @@ static void searchedDylib(const Twine &path, bool found) {
depTracker->logFileNotFound(path); depTracker->logFileNotFound(path);
} }
Optional<StringRef> macho::resolveDylibPath(StringRef dylibPath) { std::optional<StringRef> macho::resolveDylibPath(StringRef dylibPath) {
// TODO: if a tbd and dylib are both present, we should check to make sure // TODO: if a tbd and dylib are both present, we should check to make sure
// they are consistent. // they are consistent.
SmallString<261> tbdPath = dylibPath; SmallString<261> tbdPath = dylibPath;
@ -253,7 +253,7 @@ DylibFile *macho::loadDylib(MemoryBufferRef mbref, DylibFile *umbrella,
void macho::resetLoadedDylibs() { loadedDylibs.clear(); } void macho::resetLoadedDylibs() { loadedDylibs.clear(); }
Optional<StringRef> std::optional<StringRef>
macho::findPathCombination(const Twine &name, macho::findPathCombination(const Twine &name,
const std::vector<StringRef> &roots, const std::vector<StringRef> &roots,
ArrayRef<StringRef> extensions) { ArrayRef<StringRef> extensions) {
@ -276,7 +276,7 @@ StringRef macho::rerootPath(StringRef path) {
if (!path::is_absolute(path, path::Style::posix) || path.endswith(".o")) if (!path::is_absolute(path, path::Style::posix) || path.endswith(".o"))
return path; return path;
if (Optional<StringRef> rerootedPath = if (std::optional<StringRef> rerootedPath =
findPathCombination(path, config->systemLibraryRoots)) findPathCombination(path, config->systemLibraryRoots))
return *rerootedPath; return *rerootedPath;

View File

@ -46,8 +46,8 @@
* 1. Length of the entry (4 or 12 bytes) * 1. Length of the entry (4 or 12 bytes)
* 2. CIE offset (4 bytes pcrel offset that points backwards to this FDE's CIE) * 2. CIE offset (4 bytes pcrel offset that points backwards to this FDE's CIE)
* 3. Function address (pointer-sized pcrel offset) * 3. Function address (pointer-sized pcrel offset)
* 4. (Optional) Augmentation data length * 4. (std::optional) Augmentation data length
* 5. (Optional) LSDA address (pointer-sized pcrel offset) * 5. (std::optional) LSDA address (pointer-sized pcrel offset)
* 6. DWARF instructions (ignored by LLD) * 6. DWARF instructions (ignored by LLD)
*/ */
namespace lld::macho { namespace lld::macho {

View File

@ -39,7 +39,6 @@
#include "lld/Common/ErrorHandler.h" #include "lld/Common/ErrorHandler.h"
#include "lld/Common/Memory.h" #include "lld/Common/Memory.h"
#include "llvm/ADT/Optional.h"
#include "llvm/BinaryFormat/MachO.h" #include "llvm/BinaryFormat/MachO.h"
#include "llvm/Support/LEB128.h" #include "llvm/Support/LEB128.h"
#include <optional> #include <optional>

View File

@ -191,7 +191,7 @@ static bool checkCompatibility(const InputFile *input) {
// would require altering many callers to track the state. // would require altering many callers to track the state.
DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads; DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;
// Open a given file path and return it as a memory-mapped file. // Open a given file path and return it as a memory-mapped file.
Optional<MemoryBufferRef> macho::readFile(StringRef path) { std::optional<MemoryBufferRef> macho::readFile(StringRef path) {
CachedHashStringRef key(path); CachedHashStringRef key(path);
auto entry = cachedReads.find(key); auto entry = cachedReads.find(key);
if (entry != cachedReads.end()) if (entry != cachedReads.end())
@ -1498,7 +1498,7 @@ lld::DWARFCache *ObjFile::getDwarf() {
} }
// The path can point to either a dylib or a .tbd file. // The path can point to either a dylib or a .tbd file.
static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) { static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
Optional<MemoryBufferRef> mbref = readFile(path); std::optional<MemoryBufferRef> mbref = readFile(path);
if (!mbref) { if (!mbref) {
error("could not read dylib file at " + path); error("could not read dylib file at " + path);
return nullptr; return nullptr;
@ -1528,10 +1528,11 @@ static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
for (StringRef dir : config->frameworkSearchPaths) { for (StringRef dir : config->frameworkSearchPaths) {
SmallString<128> candidate = dir; SmallString<128> candidate = dir;
path::append(candidate, frameworkName); path::append(candidate, frameworkName);
if (Optional<StringRef> dylibPath = resolveDylibPath(candidate.str())) if (std::optional<StringRef> dylibPath =
resolveDylibPath(candidate.str()))
return loadDylib(*dylibPath, umbrella); return loadDylib(*dylibPath, umbrella);
} }
} else if (Optional<StringRef> dylibPath = findPathCombination( } else if (std::optional<StringRef> dylibPath = findPathCombination(
stem, config->librarySearchPaths, {".tbd", ".dylib"})) stem, config->librarySearchPaths, {".tbd", ".dylib"}))
return loadDylib(*dylibPath, umbrella); return loadDylib(*dylibPath, umbrella);
} }
@ -1539,7 +1540,8 @@ static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
// 2. As absolute path. // 2. As absolute path.
if (path::is_absolute(path, path::Style::posix)) if (path::is_absolute(path, path::Style::posix))
for (StringRef root : config->systemLibraryRoots) for (StringRef root : config->systemLibraryRoots)
if (Optional<StringRef> dylibPath = resolveDylibPath((root + path).str())) if (std::optional<StringRef> dylibPath =
resolveDylibPath((root + path).str()))
return loadDylib(*dylibPath, umbrella); return loadDylib(*dylibPath, umbrella);
// 3. As relative path. // 3. As relative path.
@ -1568,7 +1570,7 @@ static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
path::remove_filename(newPath); path::remove_filename(newPath);
} }
path::append(newPath, rpath, path.drop_front(strlen("@rpath/"))); path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
if (Optional<StringRef> dylibPath = resolveDylibPath(newPath.str())) if (std::optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))
return loadDylib(*dylibPath, umbrella); return loadDylib(*dylibPath, umbrella);
} }
} }
@ -1587,7 +1589,7 @@ static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
} }
} }
if (Optional<StringRef> dylibPath = resolveDylibPath(path)) if (std::optional<StringRef> dylibPath = resolveDylibPath(path))
return loadDylib(*dylibPath, umbrella); return loadDylib(*dylibPath, umbrella);
return nullptr; return nullptr;

View File

@ -313,7 +313,7 @@ private:
extern llvm::SetVector<InputFile *> inputFiles; extern llvm::SetVector<InputFile *> inputFiles;
extern llvm::DenseMap<llvm::CachedHashStringRef, MemoryBufferRef> cachedReads; extern llvm::DenseMap<llvm::CachedHashStringRef, MemoryBufferRef> cachedReads;
llvm::Optional<MemoryBufferRef> readFile(StringRef path); std::optional<MemoryBufferRef> readFile(StringRef path);
void extract(InputFile &file, StringRef reason); void extract(InputFile &file, StringRef reason);

View File

@ -57,7 +57,7 @@ static lto::Config createConfig() {
// If `originalPath` exists, hardlinks `path` to `originalPath`. If that fails, // If `originalPath` exists, hardlinks `path` to `originalPath`. If that fails,
// or `originalPath` is not set, saves `buffer` to `path`. // or `originalPath` is not set, saves `buffer` to `path`.
static void saveOrHardlinkBuffer(StringRef buffer, const Twine &path, static void saveOrHardlinkBuffer(StringRef buffer, const Twine &path,
Optional<StringRef> originalPath) { std::optional<StringRef> originalPath) {
if (originalPath) { if (originalPath) {
auto err = fs::create_hard_link(*originalPath, path); auto err = fs::create_hard_link(*originalPath, path);
if (!err) if (!err)
@ -168,7 +168,7 @@ std::vector<ObjFile *> BitcodeCompiler::compile() {
// not use the cached MemoryBuffer directly to ensure dsymutil does not // not use the cached MemoryBuffer directly to ensure dsymutil does not
// race with the cache pruner. // race with the cache pruner.
StringRef objBuf; StringRef objBuf;
Optional<StringRef> cachePath = llvm::None; std::optional<StringRef> cachePath = llvm::None;
if (files[i]) { if (files[i]) {
objBuf = files[i]->getBuffer(); objBuf = files[i]->getBuffer();
cachePath = files[i]->getBufferIdentifier(); cachePath = files[i]->getBufferIdentifier();

View File

@ -22,7 +22,6 @@
#include "lld/Common/ErrorHandler.h" #include "lld/Common/ErrorHandler.h"
#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/MapVector.h" #include "llvm/ADT/MapVector.h"
#include "llvm/ADT/Optional.h"
#include "llvm/Support/Path.h" #include "llvm/Support/Path.h"
#include "llvm/Support/TimeProfiler.h" #include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
@ -250,7 +249,8 @@ DenseMap<const InputSection *, size_t> CallGraphSort::run() {
return orderMap; return orderMap;
} }
Optional<size_t> macho::PriorityBuilder::getSymbolPriority(const Defined *sym) { std::optional<size_t>
macho::PriorityBuilder::getSymbolPriority(const Defined *sym) {
if (sym->isAbsolute()) if (sym->isAbsolute())
return None; return None;
@ -295,7 +295,7 @@ void macho::PriorityBuilder::extractCallGraphProfile() {
void macho::PriorityBuilder::parseOrderFile(StringRef path) { void macho::PriorityBuilder::parseOrderFile(StringRef path) {
assert(callGraphProfile.empty() && assert(callGraphProfile.empty() &&
"Order file must be parsed before call graph profile is processed"); "Order file must be parsed before call graph profile is processed");
Optional<MemoryBufferRef> buffer = readFile(path); std::optional<MemoryBufferRef> buffer = readFile(path);
if (!buffer) { if (!buffer) {
error("Could not read order file at " + path); error("Could not read order file at " + path);
return; return;
@ -367,7 +367,7 @@ macho::PriorityBuilder::buildInputSectionPriorities() {
return sectionPriorities; return sectionPriorities;
auto addSym = [&](const Defined *sym) { auto addSym = [&](const Defined *sym) {
Optional<size_t> symbolPriority = getSymbolPriority(sym); std::optional<size_t> symbolPriority = getSymbolPriority(sym);
if (!symbolPriority) if (!symbolPriority)
return; return;
size_t &priority = sectionPriorities[sym->isec]; size_t &priority = sectionPriorities[sym->isec];

View File

@ -69,7 +69,7 @@ private:
llvm::DenseMap<llvm::StringRef, size_t> objectFiles; llvm::DenseMap<llvm::StringRef, size_t> objectFiles;
}; };
llvm::Optional<size_t> getSymbolPriority(const Defined *sym); std::optional<size_t> getSymbolPriority(const Defined *sym);
llvm::DenseMap<llvm::StringRef, SymbolPriorityEntry> priorities; llvm::DenseMap<llvm::StringRef, SymbolPriorityEntry> priorities;
llvm::MapVector<SectionPair, uint64_t> callGraphProfile; llvm::MapVector<SectionPair, uint64_t> callGraphProfile;
}; };