diff --git a/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp b/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp --- a/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp +++ b/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp @@ -57,10 +57,10 @@ TUFiles.push_back(I->path()); - ErrorOr> Out = + Expected> Out = MemoryBuffer::getFile(I->path()); - if (std::error_code BufferError = Out.getError()) { - errs() << "Error reading " << I->path() << ": " << BufferError.message() + if (Error E = Out.takeError()) { + errs() << "Error reading " << I->path() << ": " << toString(std::move(E)) << "\n"; continue; } @@ -101,10 +101,10 @@ TUFiles.push_back(I->path()); - ErrorOr> Out = + Expected> Out = MemoryBuffer::getFile(I->path()); - if (std::error_code BufferError = Out.getError()) { - errs() << "Error reading " << I->path() << ": " << BufferError.message() + if (Error E = Out.takeError()) { + errs() << "Error reading " << I->path() << ": " << toString(std::move(E)) << "\n"; continue; } diff --git a/clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp b/clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp --- a/clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp +++ b/clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp @@ -84,10 +84,10 @@ return Patterns; llvm::SmallVector Lines; - llvm::ErrorOr> File = + llvm::Expected> File = llvm::MemoryBuffer::getFile(AllowedFile); - if (!File) - return File.getError(); + if (Error E = File.takeError()) + return errorToErrorCode(std::move(E)); llvm::StringRef Content = File.get()->getBuffer(); Content.split(Lines, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false); for (auto Line : Lines) diff --git a/clang-tools-extra/clang-include-fixer/FuzzySymbolIndex.cpp b/clang-tools-extra/clang-include-fixer/FuzzySymbolIndex.cpp --- a/clang-tools-extra/clang-include-fixer/FuzzySymbolIndex.cpp +++ b/clang-tools-extra/clang-include-fixer/FuzzySymbolIndex.cpp @@ -132,8 +132,8 @@ llvm::Expected> FuzzySymbolIndex::createFromYAML(StringRef FilePath) { auto Buffer = llvm::MemoryBuffer::getFile(FilePath); - if (!Buffer) - return llvm::errorCodeToError(Buffer.getError()); + if (llvm::Error E = Buffer.takeError()) + return E; return std::make_unique( find_all_symbols::ReadSymbolInfosFromYAML(Buffer.get()->getBuffer())); } diff --git a/clang-tools-extra/clang-include-fixer/YamlSymbolIndex.cpp b/clang-tools-extra/clang-include-fixer/YamlSymbolIndex.cpp --- a/clang-tools-extra/clang-include-fixer/YamlSymbolIndex.cpp +++ b/clang-tools-extra/clang-include-fixer/YamlSymbolIndex.cpp @@ -24,8 +24,8 @@ llvm::ErrorOr> YamlSymbolIndex::createFromFile(llvm::StringRef FilePath) { auto Buffer = llvm::MemoryBuffer::getFile(FilePath); - if (!Buffer) - return Buffer.getError(); + if (llvm::Error E = Buffer.takeError()) + return errorToErrorCode(std::move(E)); return std::unique_ptr(new YamlSymbolIndex( find_all_symbols::ReadSymbolInfosFromYAML(Buffer.get()->getBuffer()))); diff --git a/clang-tools-extra/clang-include-fixer/tool/ClangIncludeFixer.cpp b/clang-tools-extra/clang-include-fixer/tool/ClangIncludeFixer.cpp --- a/clang-tools-extra/clang-include-fixer/tool/ClangIncludeFixer.cpp +++ b/clang-tools-extra/clang-include-fixer/tool/ClangIncludeFixer.cpp @@ -281,10 +281,10 @@ if (STDINMode) { assert(options.getSourcePathList().size() == 1 && "Expect exactly one file path in STDINMode."); - llvm::ErrorOr> CodeOrErr = + llvm::Expected> CodeOrErr = MemoryBuffer::getSTDIN(); - if (std::error_code EC = CodeOrErr.getError()) { - errs() << EC.message() << "\n"; + if (Error E = CodeOrErr.takeError()) { + errs() << toString(std::move(E)) << "\n"; return 1; } Code = std::move(CodeOrErr.get()); @@ -416,9 +416,9 @@ return 1; } auto Buffer = llvm::MemoryBuffer::getFile(FilePath); - if (!Buffer) { + if (Error E = Buffer.takeError()) { errs() << "Couldn't open file: " + FilePath.str() + ": " - << Buffer.getError().message() + "\n"; + << toString(std::move(E)) + "\n"; return 1; } diff --git a/clang-tools-extra/clang-query/tool/ClangQuery.cpp b/clang-tools-extra/clang-query/tool/ClangQuery.cpp --- a/clang-tools-extra/clang-query/tool/ClangQuery.cpp +++ b/clang-tools-extra/clang-query/tool/ClangQuery.cpp @@ -74,9 +74,9 @@ bool runCommandsInFile(const char *ExeName, std::string const &FileName, QuerySession &QS) { auto Buffer = llvm::MemoryBuffer::getFile(FileName); - if (!Buffer) { + if (Error E = Buffer.takeError()) { llvm::errs() << ExeName << ": cannot open " << FileName << ": " - << Buffer.getError().message() << "\n"; + << toString(std::move(E)) << "\n"; return true; } diff --git a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp --- a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp +++ b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp @@ -343,11 +343,11 @@ return nullptr; } - llvm::ErrorOr> Text = + llvm::Expected> Text = llvm::MemoryBuffer::getFile(ConfigFile); - if (std::error_code EC = Text.getError()) { + if (Error E = Text.takeError()) { llvm::errs() << "Error: can't read config-file '" << ConfigFile - << "': " << EC.message() << "\n"; + << "': " << toString(std::move(E)) << "\n"; return nullptr; } diff --git a/clang-tools-extra/clangd/CompileCommands.cpp b/clang-tools-extra/clangd/CompileCommands.cpp --- a/clang-tools-extra/clangd/CompileCommands.cpp +++ b/clang-tools-extra/clangd/CompileCommands.cpp @@ -62,8 +62,8 @@ } auto Buf = llvm::MemoryBuffer::getFile(OutFile); - if (!Buf) { - log("Can't read xcrun output: {0}", Buf.getError().message()); + if (llvm::Error E = Buf.takeError()) { + log("Can't read xcrun output: {0}", toString(std::move(E))); return llvm::None; } StringRef Path = Buf->get()->getBuffer().trim(); diff --git a/clang-tools-extra/clangd/QueryDriverDatabase.cpp b/clang-tools-extra/clangd/QueryDriverDatabase.cpp --- a/clang-tools-extra/clangd/QueryDriverDatabase.cpp +++ b/clang-tools-extra/clangd/QueryDriverDatabase.cpp @@ -220,9 +220,9 @@ } auto BufOrError = llvm::MemoryBuffer::getFile(StdErrPath); - if (!BufOrError) { + if (llvm::Error E = BufOrError.takeError()) { elog("System include extraction: failed to read {0} with error {1}", - StdErrPath, BufOrError.getError().message()); + StdErrPath, toString(std::move(E))); return llvm::None; } diff --git a/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp b/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp --- a/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp +++ b/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp @@ -56,8 +56,10 @@ const std::string ShardPath = getShardPathFromFilePath(DiskShardRoot, ShardIdentifier); auto Buffer = llvm::MemoryBuffer::getFile(ShardPath); - if (!Buffer) + if (!Buffer) { + consumeError(Buffer.takeError()); return nullptr; + } if (auto I = readIndexFile(Buffer->get()->getBuffer())) return std::make_unique(std::move(*I)); else diff --git a/clang-tools-extra/clangd/index/Serialization.cpp b/clang-tools-extra/clangd/index/Serialization.cpp --- a/clang-tools-extra/clangd/index/Serialization.cpp +++ b/clang-tools-extra/clangd/index/Serialization.cpp @@ -699,8 +699,8 @@ bool UseDex) { trace::Span OverallTracer("LoadIndex"); auto Buffer = llvm::MemoryBuffer::getFile(SymbolFilename); - if (!Buffer) { - elog("Can't open {0}: {1}", SymbolFilename, Buffer.getError().message()); + if (llvm::Error E = Buffer.takeError()) { + elog("Can't open {0}: {1}", SymbolFilename, toString(std::move(E))); return nullptr; } diff --git a/clang-tools-extra/modularize/ModularizeUtilities.cpp b/clang-tools-extra/modularize/ModularizeUtilities.cpp --- a/clang-tools-extra/modularize/ModularizeUtilities.cpp +++ b/clang-tools-extra/modularize/ModularizeUtilities.cpp @@ -12,17 +12,18 @@ // //===----------------------------------------------------------------------===// +#include "ModularizeUtilities.h" +#include "CoverageChecker.h" #include "clang/Basic/SourceManager.h" #include "clang/Driver/Options.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendActions.h" -#include "CoverageChecker.h" #include "llvm/ADT/SmallString.h" +#include "llvm/Support/Error.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" -#include "ModularizeUtilities.h" using namespace clang; using namespace llvm; @@ -144,10 +145,11 @@ HeaderDirectory = HeaderPrefix; // Read the header list file into a buffer. - ErrorOr> listBuffer = - MemoryBuffer::getFile(InputPath); - if (std::error_code EC = listBuffer.getError()) - return EC; + Expected> listBuffer = + MemoryBuffer::getFile(InputPath); + if (Error E = listBuffer.takeError()) { + return errorToErrorCode(std::move(E)); + } // Parse the header list into strings. SmallVector Strings; @@ -217,10 +219,10 @@ HeaderDirectory = HeaderPrefix; // Read the header list file into a buffer. - ErrorOr> listBuffer = - MemoryBuffer::getFile(InputPath); - if (std::error_code EC = listBuffer.getError()) - return EC; + Expected> listBuffer = + MemoryBuffer::getFile(InputPath); + if (Error E = listBuffer.takeError()) + return errorToErrorCode(std::move(E)); // Parse the header list into strings. SmallVector Strings; diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -125,7 +125,7 @@ InGroup; def err_fe_unable_to_load_basic_block_sections_file : Error< - "unable to load basic block sections function list: '%0'">; + "unable to load basic block sections function list: %0">; def warn_fe_serialized_diag_merge_failure : Warning< "unable to merge a subprocess's serialized diagnostics">, diff --git a/clang/lib/ARCMigrate/FileRemapper.cpp b/clang/lib/ARCMigrate/FileRemapper.cpp --- a/clang/lib/ARCMigrate/FileRemapper.cpp +++ b/clang/lib/ARCMigrate/FileRemapper.cpp @@ -62,10 +62,12 @@ std::vector > pairs; - llvm::ErrorOr> fileBuf = + llvm::Expected> fileBuf = llvm::MemoryBuffer::getFile(infoFile, /*IsText=*/true); - if (!fileBuf) - return report("Error opening file: " + infoFile, Diag); + if (llvm::Error E = fileBuf.takeError()) + return report("Error opening file: " + infoFile + ": " + + toString(std::move(E)), + Diag); SmallVector lines; fileBuf.get()->getBuffer().split(lines, "\n"); diff --git a/clang/lib/ARCMigrate/ObjCMT.cpp b/clang/lib/ARCMigrate/ObjCMT.cpp --- a/clang/lib/ARCMigrate/ObjCMT.cpp +++ b/clang/lib/ARCMigrate/ObjCMT.cpp @@ -2074,10 +2074,12 @@ bool parse(StringRef File, SmallVectorImpl &Entries) { using namespace llvm::yaml; - llvm::ErrorOr> FileBufOrErr = + llvm::Expected> FileBufOrErr = llvm::MemoryBuffer::getFile(File); - if (!FileBufOrErr) + if (llvm::Error E = FileBufOrErr.takeError()) { + consumeError(std::move(E)); return true; + } llvm::SourceMgr SM; Stream YAMLStream(FileBufOrErr.get()->getMemBufferRef(), SM); diff --git a/clang/lib/Basic/FileManager.cpp b/clang/lib/Basic/FileManager.cpp --- a/clang/lib/Basic/FileManager.cpp +++ b/clang/lib/Basic/FileManager.cpp @@ -359,7 +359,7 @@ if (auto ContentOrError = llvm::MemoryBuffer::getSTDIN()) Content = std::move(*ContentOrError); else - return llvm::errorCodeToError(ContentOrError.getError()); + return ContentOrError.takeError(); STDIN = getVirtualFileRef(Content->getBufferIdentifier(), Content->getBufferSize(), 0); diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp --- a/clang/lib/CodeGen/BackendUtil.cpp +++ b/clang/lib/CodeGen/BackendUtil.cpp @@ -549,11 +549,11 @@ .Default(llvm::BasicBlockSection::None); if (Options.BBSections == llvm::BasicBlockSection::List) { - ErrorOr> MBOrErr = + Expected> MBOrErr = MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5)); - if (!MBOrErr) { + if (Error E = MBOrErr.takeError()) { Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file) - << MBOrErr.getError().message(); + << toString(std::move(E)); return false; } Options.BBSectionsFuncListBuf = std::move(*MBOrErr); diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp --- a/clang/lib/CodeGen/CGCUDANV.cpp +++ b/clang/lib/CodeGen/CGCUDANV.cpp @@ -700,11 +700,11 @@ // handle so CUDA runtime can figure out what to call on the GPU side. std::unique_ptr CudaGpuBinary = nullptr; if (!CudaGpuBinaryFileName.empty()) { - llvm::ErrorOr> CudaGpuBinaryOrErr = + llvm::Expected> CudaGpuBinaryOrErr = llvm::MemoryBuffer::getFileOrSTDIN(CudaGpuBinaryFileName); - if (std::error_code EC = CudaGpuBinaryOrErr.getError()) { + if (llvm::Error E = CudaGpuBinaryOrErr.takeError()) { CGM.getDiags().Report(diag::err_cannot_open_file) - << CudaGpuBinaryFileName << EC.message(); + << CudaGpuBinaryFileName << toString(std::move(E)); return nullptr; } CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get()); diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp --- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -3327,9 +3327,9 @@ return; auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile); - if (auto EC = Buf.getError()) { + if (llvm::Error E = Buf.takeError()) { CGM.getDiags().Report(diag::err_cannot_open_file) - << CGM.getLangOpts().OMPHostIRFile << EC.message(); + << CGM.getLangOpts().OMPHostIRFile << toString(std::move(E)); return; } diff --git a/clang/lib/CrossTU/CrossTranslationUnit.cpp b/clang/lib/CrossTU/CrossTranslationUnit.cpp --- a/clang/lib/CrossTU/CrossTranslationUnit.cpp +++ b/clang/lib/CrossTU/CrossTranslationUnit.cpp @@ -674,9 +674,10 @@ if (index_error_code::success != PreviousParsingResult) return llvm::make_error(PreviousParsingResult); - llvm::ErrorOr> FileContent = + llvm::Expected> FileContent = llvm::MemoryBuffer::getFile(InvocationListFilePath); - if (!FileContent) { + if (llvm::Error E = FileContent.takeError()) { + consumeError(std::move(E)); PreviousParsingResult = index_error_code::invocation_list_file_not_found; return llvm::make_error(PreviousParsingResult); } diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -1272,10 +1272,12 @@ continue; if (fs::status(File->path(), FileStatus)) continue; - llvm::ErrorOr> CrashFile = + llvm::Expected> CrashFile = llvm::MemoryBuffer::getFile(File->path()); - if (!CrashFile) + if (llvm::Error E = CrashFile.takeError()) { + consumeError(std::move(E)); continue; + } // The first line should start with "Process:", otherwise this isn't a real // .crash file. StringRef Data = CrashFile.get()->getBuffer(); diff --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp b/clang/lib/Driver/ToolChains/AMDGPU.cpp --- a/clang/lib/Driver/ToolChains/AMDGPU.cpp +++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp @@ -768,12 +768,12 @@ Program + ": " + ErrorMessage); } - llvm::ErrorOr> OutputBuf = + llvm::Expected> OutputBuf = llvm::MemoryBuffer::getFile(OutputFile.c_str()); - if (!OutputBuf) { - return llvm::createStringError(OutputBuf.getError(), - "Failed to read stdout of " + Program + - ": " + OutputBuf.getError().message()); + if (llvm::Error E = OutputBuf.takeError()) { + return llvm::make_error( + "Failed to read stdout of " + Program + ": " + toString(std::move(E)), + llvm::inconvertibleErrorCode()); } for (llvm::line_iterator LineIt(**OutputBuf); !LineIt.is_at_end(); ++LineIt) { @@ -927,4 +927,4 @@ return RocmInstallation.getCommonBitcodeLibs( DriverArgs, LibDeviceFile, Wave64, DAZ, FiniteOnly, UnsafeMathOpt, FastRelaxedMath, CorrectSqrt); -} \ No newline at end of file +} diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp --- a/clang/lib/Frontend/CompilerInstance.cpp +++ b/clang/lib/Frontend/CompilerInstance.cpp @@ -262,10 +262,12 @@ // Collect all VFS found. SmallVector VFSEntries; for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) { - llvm::ErrorOr> Buffer = + llvm::Expected> Buffer = llvm::MemoryBuffer::getFile(VFSFile); - if (!Buffer) + if (llvm::Error E = Buffer.takeError()) { + consumeError(std::move(E)); return; + } llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()), /*DiagHandler*/ nullptr, VFSFile, VFSEntries); } diff --git a/clang/lib/Serialization/GlobalModuleIndex.cpp b/clang/lib/Serialization/GlobalModuleIndex.cpp --- a/clang/lib/Serialization/GlobalModuleIndex.cpp +++ b/clang/lib/Serialization/GlobalModuleIndex.cpp @@ -256,11 +256,10 @@ IndexPath += Path; llvm::sys::path::append(IndexPath, IndexFileName); - llvm::ErrorOr> BufferOrErr = + llvm::Expected> BufferOrErr = llvm::MemoryBuffer::getFile(IndexPath.c_str()); - if (!BufferOrErr) - return std::make_pair(nullptr, - llvm::errorCodeToError(BufferOrErr.getError())); + if (llvm::Error E = BufferOrErr.takeError()) + return std::make_pair(nullptr, std::move(E)); std::unique_ptr Buffer = std::move(BufferOrErr.get()); /// The main bitstream cursor for the main block. diff --git a/clang/lib/Serialization/ModuleManager.cpp b/clang/lib/Serialization/ModuleManager.cpp --- a/clang/lib/Serialization/ModuleManager.cpp +++ b/clang/lib/Serialization/ModuleManager.cpp @@ -28,6 +28,7 @@ #include "llvm/ADT/iterator.h" #include "llvm/Support/Chrono.h" #include "llvm/Support/DOTGraphTraits.h" +#include "llvm/Support/Error.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/GraphWriter.h" #include "llvm/Support/MemoryBuffer.h" @@ -203,23 +204,24 @@ return OutOfDate; } else { // Open the AST file. - llvm::ErrorOr> Buf((std::error_code())); - if (FileName == "-") { - Buf = llvm::MemoryBuffer::getSTDIN(); - } else { - // Get a buffer of the file and close the file descriptor when done. - // The file is volatile because in a parallel build we expect multiple - // compiler processes to use the same module file rebuilding it if needed. - // - // RequiresNullTerminator is false because module files don't need it, and - // this allows the file to still be mmapped. - Buf = FileMgr.getBufferForFile(NewModule->File, - /*IsVolatile=*/true, - /*RequiresNullTerminator=*/false); - } - - if (!Buf) { - ErrorStr = Buf.getError().message(); + llvm::Expected> Buf = + FileName == "-" + ? llvm::MemoryBuffer::getSTDIN() + : + // Get a buffer of the file and close the file descriptor when done. + // The file is volatile because in a parallel build we expect + // multiple compiler processes to use the same module file + // rebuilding it if needed. + // + // RequiresNullTerminator is false because module files don't need + // it, and this allows the file to still be mmapped. + llvm::errorOrToExpected( + FileMgr.getBufferForFile(NewModule->File, + /*IsVolatile=*/true, + /*RequiresNullTerminator=*/false)); + + if (llvm::Error E = Buf.takeError()) { + ErrorStr = toString(std::move(E)); return Missing; } diff --git a/clang/lib/Tooling/CompilationDatabase.cpp b/clang/lib/Tooling/CompilationDatabase.cpp --- a/clang/lib/Tooling/CompilationDatabase.cpp +++ b/clang/lib/Tooling/CompilationDatabase.cpp @@ -342,10 +342,10 @@ std::unique_ptr FixedCompilationDatabase::loadFromFile(StringRef Path, std::string &ErrorMsg) { ErrorMsg.clear(); - llvm::ErrorOr> File = + llvm::Expected> File = llvm::MemoryBuffer::getFile(Path); - if (std::error_code Result = File.getError()) { - ErrorMsg = "Error while opening fixed database: " + Result.message(); + if (llvm::Error E = File.takeError()) { + ErrorMsg = "Error while opening fixed database: " + toString(std::move(E)); return nullptr; } return loadFromBuffer(llvm::sys::path::parent_path(Path), diff --git a/clang/lib/Tooling/JSONCompilationDatabase.cpp b/clang/lib/Tooling/JSONCompilationDatabase.cpp --- a/clang/lib/Tooling/JSONCompilationDatabase.cpp +++ b/clang/lib/Tooling/JSONCompilationDatabase.cpp @@ -197,12 +197,13 @@ std::string &ErrorMessage, JSONCommandLineSyntax Syntax) { // Don't mmap: if we're a long-lived process, the build system may overwrite. - llvm::ErrorOr> DatabaseBuffer = + llvm::Expected> DatabaseBuffer = llvm::MemoryBuffer::getFile(FilePath, /*IsText=*/false, /*RequiresNullTerminator=*/true, /*IsVolatile=*/true); - if (std::error_code Result = DatabaseBuffer.getError()) { - ErrorMessage = "Error while opening JSON database: " + Result.message(); + if (llvm::Error E = DatabaseBuffer.takeError()) { + ErrorMessage = + "Error while opening JSON database: " + toString(std::move(E)); return nullptr; } std::unique_ptr Database( diff --git a/clang/test/CodeGen/basic-block-sections.c b/clang/test/CodeGen/basic-block-sections.c --- a/clang/test/CodeGen/basic-block-sections.c +++ b/clang/test/CodeGen/basic-block-sections.c @@ -40,4 +40,4 @@ // // UNIQUE: .section .text.world.world.__part.1, // UNIQUE: .section .text.another.another.__part.1, -// ERROR: error: unable to load basic block sections function list: '[[MSG]]' +// ERROR: error: unable to load basic block sections function list: '': [[MSG]] diff --git a/clang/tools/apinotes-test/APINotesTest.cpp b/clang/tools/apinotes-test/APINotesTest.cpp --- a/clang/tools/apinotes-test/APINotesTest.cpp +++ b/clang/tools/apinotes-test/APINotesTest.cpp @@ -40,10 +40,10 @@ } for (const std::string &Notes : APINotes) { - llvm::ErrorOr> NotesOrError = + llvm::Expected> NotesOrError = llvm::MemoryBuffer::getFileOrSTDIN(Notes); - if (std::error_code EC = NotesOrError.getError()) { - llvm::errs() << EC.message() << '\n'; + if (llvm::Error E = NotesOrError.takeError()) { + llvm::errs() << toString(std::move(E)) << '\n'; return EXIT_FAILURE; } diff --git a/clang/tools/arcmt-test/arcmt-test.cpp b/clang/tools/arcmt-test/arcmt-test.cpp --- a/clang/tools/arcmt-test/arcmt-test.cpp +++ b/clang/tools/arcmt-test/arcmt-test.cpp @@ -207,15 +207,19 @@ static bool filesCompareEqual(StringRef fname1, StringRef fname2) { using namespace llvm; - ErrorOr> file1 = + Expected> file1 = MemoryBuffer::getFile(fname1, /*IsText=*/true); - if (!file1) + if (!file1) { + consumeError(file1.takeError()); return false; + } - ErrorOr> file2 = + Expected> file2 = MemoryBuffer::getFile(fname2, /*IsText=*/true); - if (!file2) + if (!file2) { + consumeError(file2.takeError()); return false; + } return file1.get()->getBuffer() == file2.get()->getBuffer(); } @@ -238,13 +242,13 @@ resultMap[sys::path::stem(fname)] = fname; } - ErrorOr> inputBuf = std::error_code(); - if (RemappingsFile.empty()) - inputBuf = MemoryBuffer::getSTDIN(); - else - inputBuf = MemoryBuffer::getFile(RemappingsFile, /*IsText=*/true); + Expected> inputBuf = + RemappingsFile.empty() + ? MemoryBuffer::getSTDIN() + : MemoryBuffer::getFile(RemappingsFile, /*IsText=*/true); if (!inputBuf) { - errs() << "error: could not read remappings input\n"; + errs() << "error: could not read remappings input: " + + toString(inputBuf.takeError()) + "\n"; return true; } diff --git a/clang/tools/clang-format/ClangFormat.cpp b/clang/tools/clang-format/ClangFormat.cpp --- a/clang/tools/clang-format/ClangFormat.cpp +++ b/clang/tools/clang-format/ClangFormat.cpp @@ -361,11 +361,11 @@ } // On Windows, overwriting a file with an open file mapping doesn't work, // so read the whole file into memory when formatting in-place. - ErrorOr> CodeOrErr = + Expected> CodeOrErr = !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) : MemoryBuffer::getFileOrSTDIN(FileName); - if (std::error_code EC = CodeOrErr.getError()) { - errs() << EC.message() << "\n"; + if (Error E = CodeOrErr.takeError()) { + errs() << toString(std::move(E)) << "\n"; return true; } std::unique_ptr Code = std::move(CodeOrErr.get()); @@ -488,10 +488,10 @@ } else { // Read in the code in case the filename alone isn't enough to // detect the language. - ErrorOr> CodeOrErr = + Expected> CodeOrErr = MemoryBuffer::getFileOrSTDIN(FileNames[0]); - if (std::error_code EC = CodeOrErr.getError()) { - llvm::errs() << EC.message() << "\n"; + if (Error E = CodeOrErr.takeError()) { + errs() << toString(std::move(E)) << "\n"; return 1; } FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0]; diff --git a/clang/tools/clang-nvlink-wrapper/ClangNvlinkWrapper.cpp b/clang/tools/clang-nvlink-wrapper/ClangNvlinkWrapper.cpp --- a/clang/tools/clang-nvlink-wrapper/ClangNvlinkWrapper.cpp +++ b/clang/tools/clang-nvlink-wrapper/ClangNvlinkWrapper.cpp @@ -59,10 +59,10 @@ SmallVectorImpl &TmpFiles) { std::vector> ArchiveBuffers; - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFileOrSTDIN(Filename, false, false); - if (std::error_code EC = BufOrErr.getError()) - return createFileError(Filename, EC); + if (Error E = BufOrErr.takeError()) + return E; ArchiveBuffers.push_back(std::move(*BufOrErr)); Expected> LibOrErr = diff --git a/clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp b/clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp --- a/clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp +++ b/clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp @@ -870,10 +870,10 @@ SmallVector, 8u> InputBuffers; InputBuffers.reserve(InputFileNames.size()); for (auto &I : InputFileNames) { - ErrorOr> CodeOrErr = + Expected> CodeOrErr = MemoryBuffer::getFileOrSTDIN(I); - if (std::error_code EC = CodeOrErr.getError()) - return createFileError(I, EC); + if (Error E = CodeOrErr.takeError()) + return E; InputBuffers.emplace_back(std::move(*CodeOrErr)); } @@ -910,10 +910,10 @@ // List bundle IDs. Return true if an error was found. static Error ListBundleIDsInFile(StringRef InputFileName) { // Open Input file. - ErrorOr> CodeOrErr = + Expected> CodeOrErr = MemoryBuffer::getFileOrSTDIN(InputFileName); - if (std::error_code EC = CodeOrErr.getError()) - return createFileError(InputFileName, EC); + if (Error E = CodeOrErr.takeError()) + return E; MemoryBuffer &Input = **CodeOrErr; @@ -931,10 +931,10 @@ // Unbundle the files. Return true if an error was found. static Error UnbundleFiles() { // Open Input file. - ErrorOr> CodeOrErr = + Expected> CodeOrErr = MemoryBuffer::getFileOrSTDIN(InputFileNames.front()); - if (std::error_code EC = CodeOrErr.getError()) - return createFileError(InputFileNames.front(), EC); + if (Error E = CodeOrErr.takeError()) + return E; MemoryBuffer &Input = **CodeOrErr; @@ -1143,10 +1143,10 @@ } StringRef IFName = InputFileNames.front(); - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFileOrSTDIN(IFName, true, false); - if (std::error_code EC = BufOrErr.getError()) - return createFileError(InputFileNames.front(), EC); + if (Error E = BufOrErr.takeError()) + return E; ArchiveBuffers.push_back(std::move(*BufOrErr)); Expected> LibOrErr = diff --git a/clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp b/clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp --- a/clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp +++ b/clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp @@ -576,11 +576,10 @@ } // Substitute the original ELF with new one. - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFile(ELFTmpFileName); - if (!BufOrErr) { - handleErrorAsWarning( - createFileError(ELFTmpFileName, BufOrErr.getError())); + if (Error E = BufOrErr.takeError()) { + handleErrorAsWarning(std::move(E)); return Buf; } @@ -627,10 +626,10 @@ Buffers.reserve(Inputs.size()); Images.reserve(Inputs.size()); for (const std::string &File : Inputs) { - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFileOrSTDIN(File); - if (!BufOrErr) { - reportError(createFileError(File, BufOrErr.getError())); + if (Error E = BufOrErr.takeError()) { + reportError(std::move(E)); return 1; } std::unique_ptr Buffer(std::move(*BufOrErr)); diff --git a/clang/tools/clang-refactor/ClangRefactor.cpp b/clang/tools/clang-refactor/ClangRefactor.cpp --- a/clang/tools/clang-refactor/ClangRefactor.cpp +++ b/clang/tools/clang-refactor/ClangRefactor.cpp @@ -484,10 +484,11 @@ // FIXME: We should probably cleanup the result by default as well. Spec.Cleanup = false; for (const auto &File : Files) { - llvm::ErrorOr> BufferErr = + llvm::Expected> BufferErr = llvm::MemoryBuffer::getFile(File); - if (!BufferErr) { - llvm::errs() << "error: failed to open " << File << " for rewriting\n"; + if (llvm::Error E = BufferErr.takeError()) { + llvm::errs() << "error: failed to open " << File + << " for rewriting: " + toString(std::move(E)) + "\n"; return true; } auto Result = tooling::applyAtomicChanges(File, (*BufferErr)->getBuffer(), diff --git a/clang/tools/clang-refactor/TestSupport.cpp b/clang/tools/clang-refactor/TestSupport.cpp --- a/clang/tools/clang-refactor/TestSupport.cpp +++ b/clang/tools/clang-refactor/TestSupport.cpp @@ -90,10 +90,11 @@ tooling::ApplyChangesSpec Spec; Spec.Cleanup = false; for (const auto &File : Files) { - llvm::ErrorOr> BufferErr = + llvm::Expected> BufferErr = llvm::MemoryBuffer::getFile(File); - if (!BufferErr) { - llvm::errs() << "failed to open" << File << "\n"; + if (Error E = BufferErr.takeError()) { + llvm::errs() << "failed to open" << File << ": " << toString(std::move(E)) + << "\n"; return true; } auto Result = tooling::applyAtomicChanges(File, (*BufferErr)->getBuffer(), @@ -160,10 +161,12 @@ std::pair getLineColumn(StringRef Filename, unsigned Offset) { - ErrorOr> ErrOrFile = + Expected> ErrOrFile = MemoryBuffer::getFile(Filename); - if (!ErrOrFile) + if (Error E = ErrOrFile.takeError()) { + consumeError(std::move(E)); return {0, 0}; + } StringRef Source = ErrOrFile.get()->getBuffer(); Source = Source.take_front(Offset); size_t LastLine = Source.find_last_of("\r\n"); @@ -293,11 +296,12 @@ Optional findTestSelectionRanges(StringRef Filename) { - ErrorOr> ErrOrFile = + Expected> ErrOrFile = MemoryBuffer::getFile(Filename); - if (!ErrOrFile) { + if (Error E = ErrOrFile.takeError()) { llvm::errs() << "error: -selection=test:" << Filename - << " : could not open the given file"; + << " : could not open the given file: " + << toString(std::move(E)); return None; } StringRef Source = ErrOrFile.get()->getBuffer(); diff --git a/clang/tools/clang-rename/ClangRename.cpp b/clang/tools/clang-rename/ClangRename.cpp --- a/clang/tools/clang-rename/ClangRename.cpp +++ b/clang/tools/clang-rename/ClangRename.cpp @@ -108,11 +108,11 @@ if (!Input.empty()) { // Populate QualifiedNames and NewNames from a YAML file. - ErrorOr> Buffer = + Expected> Buffer = llvm::MemoryBuffer::getFile(Input); - if (!Buffer) { + if (Error E = Buffer.takeError()) { errs() << "clang-rename: failed to read " << Input << ": " - << Buffer.getError().message() << "\n"; + << toString(std::move(E)) << "\n"; return 1; } diff --git a/clang/tools/driver/cc1as_main.cpp b/clang/tools/driver/cc1as_main.cpp --- a/clang/tools/driver/cc1as_main.cpp +++ b/clang/tools/driver/cc1as_main.cpp @@ -341,11 +341,11 @@ if (!TheTarget) return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple; - ErrorOr> Buffer = + Expected> Buffer = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, /*IsText=*/true); - if (std::error_code EC = Buffer.getError()) { - Error = EC.message(); + if (llvm::Error E = Buffer.takeError()) { + Error = toString(std::move(E)); return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile; } diff --git a/clang/tools/driver/cc1gen_reproducer_main.cpp b/clang/tools/driver/cc1gen_reproducer_main.cpp --- a/clang/tools/driver/cc1gen_reproducer_main.cpp +++ b/clang/tools/driver/cc1gen_reproducer_main.cpp @@ -161,11 +161,11 @@ } // Parse the invocation descriptor. StringRef Input = Argv[0]; - llvm::ErrorOr> Buffer = + llvm::Expected> Buffer = llvm::MemoryBuffer::getFile(Input, /*IsText=*/true); - if (!Buffer) { + if (llvm::Error E = Buffer.takeError()) { llvm::errs() << "error: failed to read " << Input << ": " - << Buffer.getError().message() << "\n"; + << toString(std::move(E)) << "\n"; return 1; } llvm::yaml::Input YAML(Buffer.get()->getBuffer()); diff --git a/lld/COFF/Driver.cpp b/lld/COFF/Driver.cpp --- a/lld/COFF/Driver.cpp +++ b/lld/COFF/Driver.cpp @@ -160,8 +160,8 @@ return std::async(strategy, [=]() { auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (!mbOrErr) - return MBErrPair{nullptr, mbOrErr.getError()}; + if (Error e = mbOrErr.takeError()) + return MBErrPair{nullptr, errorToErrorCode(std::move(e))}; return MBErrPair{std::move(*mbOrErr), std::error_code()}; }); } @@ -846,9 +846,10 @@ // If the import library already exists, replace it only if the contents // have changed. - ErrorOr> oldBuf = MemoryBuffer::getFile( + Expected> oldBuf = MemoryBuffer::getFile( path, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (!oldBuf) { + if (Error e = oldBuf.takeError()) { + consumeError(std::move(e)); handleError(writeImportLibrary(libName, path, exports, config->machine, config->mingw)); return; diff --git a/lld/COFF/PDB.cpp b/lld/COFF/PDB.cpp --- a/lld/COFF/PDB.cpp +++ b/lld/COFF/PDB.cpp @@ -1297,10 +1297,10 @@ void PDBLinker::addNatvisFiles() { for (StringRef file : config->natvisFiles) { - ErrorOr> dataOrErr = + Expected> dataOrErr = MemoryBuffer::getFile(file); - if (!dataOrErr) { - warn("Cannot open input file: " + file); + if (Error e = dataOrErr.takeError()) { + warn("Cannot open input file: " + file + ": " + toString(std::move(e))); continue; } std::unique_ptr data = std::move(*dataOrErr); @@ -1317,10 +1317,10 @@ void PDBLinker::addNamedStreams() { for (const auto &streamFile : config->namedStreams) { const StringRef stream = streamFile.getKey(), file = streamFile.getValue(); - ErrorOr> dataOrErr = + Expected> dataOrErr = MemoryBuffer::getFile(file); - if (!dataOrErr) { - warn("Cannot open input file: " + file); + if (Error e = dataOrErr.takeError()) { + warn("Cannot open input file: " + file + ": " + toString(std::move(e))); continue; } std::unique_ptr data = std::move(*dataOrErr); diff --git a/lld/ELF/InputFiles.cpp b/lld/ELF/InputFiles.cpp --- a/lld/ELF/InputFiles.cpp +++ b/lld/ELF/InputFiles.cpp @@ -117,8 +117,8 @@ auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (auto ec = mbOrErr.getError()) { - error("cannot open " + path + ": " + ec.message()); + if (Error e = mbOrErr.takeError()) { + error("cannot open " + toString(std::move(e))); return None; } diff --git a/lld/ELF/LTO.cpp b/lld/ELF/LTO.cpp --- a/lld/ELF/LTO.cpp +++ b/lld/ELF/LTO.cpp @@ -100,11 +100,11 @@ } else if (config->ltoBasicBlockSections == "none") { c.Options.BBSections = BasicBlockSection::None; } else { - ErrorOr> MBOrErr = + Expected> MBOrErr = MemoryBuffer::getFile(config->ltoBasicBlockSections.str()); - if (!MBOrErr) { + if (Error E = MBOrErr.takeError()) { error("cannot open " + config->ltoBasicBlockSections + ":" + - MBOrErr.getError().message()); + toString(std::move(E))); } else { c.Options.BBSectionsFuncListBuf = std::move(*MBOrErr); } diff --git a/lld/MachO/InputFiles.cpp b/lld/MachO/InputFiles.cpp --- a/lld/MachO/InputFiles.cpp +++ b/lld/MachO/InputFiles.cpp @@ -175,9 +175,9 @@ // Open a given file path and return it as a memory-mapped file. Optional macho::readFile(StringRef path) { - ErrorOr> mbOrErr = MemoryBuffer::getFile(path); - if (std::error_code ec = mbOrErr.getError()) { - error("cannot open " + path + ": " + ec.message()); + Expected> mbOrErr = MemoryBuffer::getFile(path); + if (Error e = mbOrErr.takeError()) { + error("cannot open " + toString(std::move(e))); return None; } diff --git a/lld/lib/Driver/DarwinLdDriver.cpp b/lld/lib/Driver/DarwinLdDriver.cpp --- a/lld/lib/Driver/DarwinLdDriver.cpp +++ b/lld/lib/Driver/DarwinLdDriver.cpp @@ -168,10 +168,10 @@ static std::error_code parseExportsList(StringRef exportFilePath, MachOLinkingContext &ctx) { // Map in export list file. - ErrorOr> mb = - MemoryBuffer::getFileOrSTDIN(exportFilePath); - if (std::error_code ec = mb.getError()) - return ec; + Expected> mb = + MemoryBuffer::getFileOrSTDIN(exportFilePath); + if (Error e = mb.takeError()) + return llvm::errorToErrorCode(std::move(e)); ctx.addInputFileDependency(exportFilePath); StringRef buffer = mb->get()->getBuffer(); while (!buffer.empty()) { @@ -198,10 +198,10 @@ static std::error_code parseOrderFile(StringRef orderFilePath, MachOLinkingContext &ctx) { // Map in order file. - ErrorOr> mb = - MemoryBuffer::getFileOrSTDIN(orderFilePath); - if (std::error_code ec = mb.getError()) - return ec; + Expected> mb = + MemoryBuffer::getFileOrSTDIN(orderFilePath); + if (Error e = mb.takeError()) + return llvm::errorToErrorCode(std::move(e)); ctx.addInputFileDependency(orderFilePath); StringRef buffer = mb->get()->getBuffer(); while (!buffer.empty()) { @@ -257,10 +257,10 @@ StringRef dirName = opt.second; ctx.addInputFileDependency(filePath); // Map in file list file. - ErrorOr> mb = - MemoryBuffer::getFileOrSTDIN(filePath); - if (std::error_code ec = mb.getError()) - return llvm::errorCodeToError(ec); + Expected> mb = + MemoryBuffer::getFileOrSTDIN(filePath); + if (Error e = mb.takeError()) + return e; StringRef buffer = mb->get()->getBuffer(); while (!buffer.empty()) { // Split off each line in the file. @@ -1108,11 +1108,12 @@ const char* sect = arg->getValue(1); const char* fileName = arg->getValue(2); - ErrorOr> contentOrErr = - MemoryBuffer::getFile(fileName); + Expected> contentOrErr = + MemoryBuffer::getFile(fileName); - if (!contentOrErr) { - error("can't open -sectcreate file " + Twine(fileName)); + if (Error e = contentOrErr.takeError()) { + error("can't open -sectcreate file " + Twine(fileName) + ": " + + toString(std::move(e))); return false; } diff --git a/lld/lib/ReaderWriter/MachO/MachOLinkingContext.cpp b/lld/lib/ReaderWriter/MachO/MachOLinkingContext.cpp --- a/lld/lib/ReaderWriter/MachO/MachOLinkingContext.cpp +++ b/lld/lib/ReaderWriter/MachO/MachOLinkingContext.cpp @@ -6,7 +6,6 @@ // //===----------------------------------------------------------------------===// -#include "lld/Common/ErrorHandler.h" #include "lld/ReaderWriter/MachOLinkingContext.h" #include "ArchHandler.h" #include "File.h" @@ -15,6 +14,7 @@ #include "MachOPasses.h" #include "SectCreateFile.h" #include "lld/Common/Driver.h" +#include "lld/Common/ErrorHandler.h" #include "lld/Core/ArchiveLibraryFile.h" #include "lld/Core/PassManager.h" #include "lld/Core/Reader.h" @@ -26,6 +26,7 @@ #include "llvm/Demangle/Demangle.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Errc.h" +#include "llvm/Support/Error.h" #include "llvm/Support/Host.h" #include "llvm/Support/Path.h" #include @@ -664,10 +665,10 @@ MachOLinkingContext::getMemoryBuffer(StringRef path) { addInputFileDependency(path); - ErrorOr> mbOrErr = - MemoryBuffer::getFileOrSTDIN(path); - if (std::error_code ec = mbOrErr.getError()) - return ec; + Expected> mbOrErr = + MemoryBuffer::getFileOrSTDIN(path); + if (Error e = mbOrErr.takeError()) + return llvm::errorToErrorCode(std::move(e)); std::unique_ptr mb = std::move(mbOrErr.get()); // If buffer contains a fat file, find required arch in fat buffer @@ -675,7 +676,8 @@ uint32_t offset; uint32_t size; if (sliceFromFatFile(mb->getMemBufferRef(), offset, size)) - return MemoryBuffer::getFileSlice(path, size, offset); + return llvm::expectedToErrorOr( + MemoryBuffer::getFileSlice(path, size, offset)); return std::move(mb); } diff --git a/lld/lib/ReaderWriter/MachO/MachONormalizedFileBinaryReader.cpp b/lld/lib/ReaderWriter/MachO/MachONormalizedFileBinaryReader.cpp --- a/lld/lib/ReaderWriter/MachO/MachONormalizedFileBinaryReader.cpp +++ b/lld/lib/ReaderWriter/MachO/MachONormalizedFileBinaryReader.cpp @@ -144,9 +144,12 @@ bool isThinObjectFile(StringRef path, MachOLinkingContext::Arch &arch) { // Try opening and mapping file at path. - ErrorOr> b = MemoryBuffer::getFileOrSTDIN(path); - if (b.getError()) + Expected> b = + MemoryBuffer::getFileOrSTDIN(path); + if (Error e = b.takeError()) { + consumeError(std::move(e)); return false; + } // If file length < 32 it is too small to be mach-o object file. StringRef fileBuffer = b->get()->getBuffer(); diff --git a/lld/test/ELF/basic.s b/lld/test/ELF/basic.s --- a/lld/test/ELF/basic.s +++ b/lld/test/ELF/basic.s @@ -211,7 +211,7 @@ # RUN: echo " c:\blah\foo" > %t.responsefile # RUN: not ld.lld --rsp-quoting=windows %t @%t.responsefile 2>&1 | FileCheck \ # RUN: %s --check-prefix=WINRSP -# WINRSP: cannot open c:\blah\foo +# WINRSP: cannot open 'c:\blah\foo' # Test for the response file (invalid quoting style) # RUN: not ld.lld --rsp-quoting=patatino %t 2>&1 | FileCheck %s \ @@ -220,7 +220,7 @@ # RUN: not ld.lld %t.foo -o /dev/null 2>&1 | \ # RUN: FileCheck -DMSG=%errc_ENOENT --check-prefix=MISSING %s -# MISSING: cannot open {{.*}}.foo: [[MSG]] +# MISSING: cannot open '{{.*}}.foo': [[MSG]] # RUN: not ld.lld -o /dev/null 2>&1 | \ # RUN: FileCheck --check-prefix=NO_INPUT %s @@ -228,7 +228,7 @@ # RUN: not ld.lld %t.no.such.file -o /dev/null 2>&1 | \ # RUN: FileCheck -DMSG=%errc_ENOENT --check-prefix=CANNOT_OPEN %s -# CANNOT_OPEN: cannot open {{.*}}.no.such.file: [[MSG]] +# CANNOT_OPEN: cannot open '{{.*}}.no.such.file': [[MSG]] # RUN: not ld.lld --foo 2>&1 | FileCheck --check-prefix=UNKNOWN %s # UNKNOWN: unknown argument '--foo' diff --git a/lld/test/ELF/color-diagnostics.test b/lld/test/ELF/color-diagnostics.test --- a/lld/test/ELF/color-diagnostics.test +++ b/lld/test/ELF/color-diagnostics.test @@ -7,7 +7,7 @@ # RUN: | FileCheck -check-prefix=COLOR %s # COLOR: {{ld.lld: .\[0;31merror: .\[0munknown argument '-xyz'}} -# COLOR: {{ld.lld: .\[0;31merror: .\[0mcannot open /nosuchfile}} +# COLOR: {{ld.lld: .\[0;31merror: .\[0mcannot open '/nosuchfile'}} # RUN: not ld.lld -color-diagnostics=foobar 2>&1 | FileCheck -check-prefix=ERR %s # ERR: unknown option: --color-diagnostics=foobar @@ -18,4 +18,4 @@ # RUN: not ld.lld -color-diagnostics=always -no-color-diagnostics \ # RUN: /nosuchfile 2>&1 | FileCheck -check-prefix=NOCOLOR %s -# NOCOLOR: ld.lld: error: cannot open /nosuchfile +# NOCOLOR: ld.lld: error: cannot open '/nosuchfile' diff --git a/lld/test/ELF/driver.test b/lld/test/ELF/driver.test --- a/lld/test/ELF/driver.test +++ b/lld/test/ELF/driver.test @@ -6,7 +6,7 @@ # UNKNOWN: unknown argument '--unknown1' # UNKNOWN: unknown argument '--unkn=own2' # UNKNOWN: unknown emulation: foo -# UNKNOWN: cannot open /no/such/file +# UNKNOWN: cannot open '/no/such/file' # UNKNOWN: unable to find library -lnosuchlib # RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t diff --git a/lld/test/ELF/error-limit.test b/lld/test/ELF/error-limit.test --- a/lld/test/ELF/error-limit.test +++ b/lld/test/ELF/error-limit.test @@ -1,26 +1,26 @@ RUN: not ld.lld 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 \ RUN: 21 22 2>&1 | FileCheck -check-prefix=DEFAULT %s -DEFAULT: cannot open 01 -DEFAULT: cannot open 20 +DEFAULT: cannot open '01' +DEFAULT: cannot open '20' DEFAULT-NEXT: too many errors emitted, stopping now (use -error-limit=0 to see all errors) -DEFAULT-NOT: cannot open 21 +DEFAULT-NOT: cannot open '21' RUN: not ld.lld -error-limit=5 01 02 03 04 05 06 07 08 09 10 2>&1 \ RUN: | FileCheck -check-prefix=LIMIT5 %s RUN: not ld.lld -error-limit 5 01 02 03 04 05 06 07 08 09 10 2>&1 \ RUN: | FileCheck -check-prefix=LIMIT5 %s -LIMIT5: cannot open 01 -LIMIT5: cannot open 05 +LIMIT5: cannot open '01' +LIMIT5: cannot open '05' LIMIT5-NEXT: too many errors emitted, stopping now (use -error-limit=0 to see all errors) -LIMIT5-NOT: cannot open 06 +LIMIT5-NOT: cannot open '06' RUN: not ld.lld -error-limit=0 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 \ RUN: 16 17 18 19 20 21 22 2>&1 | FileCheck -check-prefix=UNLIMITED %s -UNLIMITED: cannot open 01 -UNLIMITED: cannot open 20 -UNLIMITED: cannot open 21 -UNLIMITED: cannot open 22 +UNLIMITED: cannot open '01' +UNLIMITED: cannot open '20' +UNLIMITED: cannot open '21' +UNLIMITED: cannot open '22' UNLIMITED-NOT: too many errors emitted, stopping now (use -error-limit=0 to see all errors) diff --git a/lld/test/ELF/invalid-linkerscript.test b/lld/test/ELF/invalid-linkerscript.test --- a/lld/test/ELF/invalid-linkerscript.test +++ b/lld/test/ELF/invalid-linkerscript.test @@ -16,45 +16,45 @@ # RUN: echo foobar > %t1 # RUN: not ld.lld %t1 no-such-file 2>&1 | FileCheck -check-prefix=ERR1 %s # ERR1: unexpected EOF -# ERR1: cannot open no-such-file: +# ERR1: cannot open 'no-such-file': # RUN: echo "foo \"bar" > %t2 # RUN: not ld.lld %t2 no-such-file 2>&1 | FileCheck -check-prefix=ERR2 %s # ERR2: unclosed quote -# ERR2: cannot open no-such-file: +# ERR2: cannot open 'no-such-file': # RUN: echo "/*" > %t3 # RUN: not ld.lld %t3 no-such-file 2>&1 | FileCheck -check-prefix=ERR3 %s # ERR3: unclosed comment -# ERR3: cannot open no-such-file: +# ERR3: cannot open 'no-such-file': # RUN: echo "EXTERN (" > %t4 # RUN: not ld.lld %t4 no-such-file 2>&1 | FileCheck -check-prefix=ERR4 %s # ERR4: unexpected EOF -# ERR4: cannot open no-such-file: +# ERR4: cannot open 'no-such-file': # RUN: echo "EXTERN (" > %t5 # RUN: not ld.lld %t5 no-such-file 2>&1 | FileCheck -check-prefix=ERR5 %s # ERR5: unexpected EOF -# ERR5: cannot open no-such-file: +# ERR5: cannot open 'no-such-file': # RUN: echo "EXTERN xyz" > %t6 # RUN: not ld.lld %t6 no-such-file 2>&1 | FileCheck -check-prefix=ERR6 %s # ERR6: ( expected, but got xyz -# ERR6: cannot open no-such-file: +# ERR6: cannot open 'no-such-file': # RUN: echo "INCLUDE /no/such/file" > %t7 # RUN: not ld.lld %t7 no-such-file 2>&1 | FileCheck -check-prefix=ERR7 %s # ERR7: cannot find linker script /no/such/file -# ERR7: cannot open no-such-file: +# ERR7: cannot open 'no-such-file': # RUN: echo "OUTPUT_FORMAT(x y z)" > %t8 # RUN: not ld.lld %t8 no-such-file 2>&1 | FileCheck -check-prefix=ERR8 %s # RUN: not ld.lld -m elf_amd64 %t8 no-such-file 2>&1 | FileCheck -check-prefix=ERR8 %s # ERR8: , expected, but got y -# ERR8: cannot open no-such-file: +# ERR8: cannot open 'no-such-file': # RUN: echo "OUTPUT_FORMAT(elf64-x86-64 y z)" > %t9 # RUN: not ld.lld %t9 no-such-file 2>&1 | FileCheck -check-prefix=ERR9 %s # ERR9: , expected, but got y -# ERR9: cannot open no-such-file: +# ERR9: cannot open 'no-such-file': diff --git a/lld/test/ELF/linkerscript/group.s b/lld/test/ELF/linkerscript/group.s --- a/lld/test/ELF/linkerscript/group.s +++ b/lld/test/ELF/linkerscript/group.s @@ -57,7 +57,7 @@ # RUN: ld.lld -o %t2 %t.script # RUN: llvm-readobj %t2 > /dev/null -# CANNOT_OPEN: error: cannot open [[FILE]]: {{.*}} +# CANNOT_OPEN: error: cannot open '[[FILE]]': {{.*}} .globl _start _start: diff --git a/lld/test/ELF/reproduce-error.s b/lld/test/ELF/reproduce-error.s --- a/lld/test/ELF/reproduce-error.s +++ b/lld/test/ELF/reproduce-error.s @@ -3,7 +3,7 @@ # RUN: cd %t.dir # RUN: not ld.lld --reproduce repro.tar abc -o t 2>&1 | FileCheck -DMSG=%errc_ENOENT %s -# CHECK: cannot open abc: [[MSG]] +# CHECK: cannot open 'abc': [[MSG]] # RUN: tar xOf repro.tar repro/response.txt | FileCheck --check-prefix=RSP %s # RSP: abc diff --git a/lld/test/ELF/symbol-ordering-file.s b/lld/test/ELF/symbol-ordering-file.s --- a/lld/test/ELF/symbol-ordering-file.s +++ b/lld/test/ELF/symbol-ordering-file.s @@ -43,7 +43,7 @@ # RUN: not ld.lld --symbol-ordering-file=%t.nonexistent %t.o -o %t3.out 2>&1 | \ # RUN: FileCheck -DMSG=%errc_ENOENT %s --check-prefix=ERR -DFILE=%t.nonexistent -# ERR: error: cannot open [[FILE]]: [[MSG]] +# ERR: error: cannot open '[[FILE]]': [[MSG]] ## Show that an empty ordering file can be handled (symbols remain in their ## normal order). diff --git a/lld/test/MachO/color-diagnostics.test b/lld/test/MachO/color-diagnostics.test --- a/lld/test/MachO/color-diagnostics.test +++ b/lld/test/MachO/color-diagnostics.test @@ -7,7 +7,7 @@ # RUN: | FileCheck -check-prefix=COLOR %s # COLOR: {{lld: .\[0;31merror: .\[0munknown argument '-xyz'}} -# COLOR: {{lld: .\[0;31merror: .\[0mcannot open /nosuchfile}} +# COLOR: {{lld: .\[0;31merror: .\[0mcannot open '/nosuchfile'}} # RUN: not %lld --color-diagnostics=foobar 2>&1 | FileCheck -check-prefix=ERR %s # ERR: unknown option: --color-diagnostics=foobar @@ -18,4 +18,4 @@ # RUN: not %lld --color-diagnostics=always --no-color-diagnostics \ # RUN: /nosuchfile 2>&1 | FileCheck -check-prefix=NOCOLOR %s -# NOCOLOR: lld: error: cannot open /nosuchfile +# NOCOLOR: lld: error: cannot open '/nosuchfile' diff --git a/lld/test/MachO/error-limit.test b/lld/test/MachO/error-limit.test --- a/lld/test/MachO/error-limit.test +++ b/lld/test/MachO/error-limit.test @@ -2,27 +2,27 @@ RUN: not %lld A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 2>&1 | \ RUN: FileCheck -check-prefix=DEFAULT %s -DEFAULT: cannot open A: -DEFAULT: cannot open T: -DEFAULT-NOT: cannot open U: +DEFAULT: cannot open 'A': +DEFAULT: cannot open 'T': +DEFAULT-NOT: cannot open 'U': DEFAULT-NEXT: too many errors emitted, stopping now (use --error-limit=0 to see all errors) ## Check that we only see 5 "cannot open" errors when --error-limit=5 RUN: not %lld --error-limit=5 A B C D E F G H I J 2>&1 \ RUN: | FileCheck -check-prefix=LIMIT5 %s -LIMIT5: cannot open A: -LIMIT5: cannot open E: -LIMIT5-NOT: cannot open F: +LIMIT5: cannot open 'A': +LIMIT5: cannot open 'E': +LIMIT5-NOT: cannot open 'F': LIMIT5-NEXT: too many errors emitted, stopping now (use --error-limit=0 to see all errors) ## Check that we see all "cannot open" errors when --error-limit=0 (unimited) RUN: not %lld --error-limit=0 A B C D E F G H I J K L M N O P Q R S T U V W 2>&1 | \ RUN: FileCheck -check-prefix=UNLIMITED %s -UNLIMITED: cannot open A: -UNLIMITED: cannot open T: -UNLIMITED: cannot open U: -UNLIMITED: cannot open V: -UNLIMITED: cannot open W: +UNLIMITED: cannot open 'A': +UNLIMITED: cannot open 'T': +UNLIMITED: cannot open 'U': +UNLIMITED: cannot open 'V': +UNLIMITED: cannot open 'W': UNLIMITED-NOT: too many errors emitted, stopping now (use --error-limit=0 to see all errors) diff --git a/lld/test/MachO/invalid/no-filelist.s b/lld/test/MachO/invalid/no-filelist.s --- a/lld/test/MachO/invalid/no-filelist.s +++ b/lld/test/MachO/invalid/no-filelist.s @@ -1,7 +1,7 @@ # REQUIRES: x86 # RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %s -o %t.o # RUN: not %lld -filelist nonexistent %t.o -o %t 2>&1 | FileCheck -DMSG=%errc_ENOENT %s -# CHECK: cannot open nonexistent: [[MSG]] +# CHECK: cannot open 'nonexistent': [[MSG]] .globl _main diff --git a/lld/test/MachO/reroot-path.s b/lld/test/MachO/reroot-path.s --- a/lld/test/MachO/reroot-path.s +++ b/lld/test/MachO/reroot-path.s @@ -52,7 +52,7 @@ # RUN: mv %t/bar.o %t/%:t/bar.o # RUN: not %lld -lSystem -syslibroot %t %t/foo.o %t/bar.o %t/test.o -o \ # RUN: /dev/null 2>&1 | FileCheck %s --check-prefix=OBJ -# OBJ: error: cannot open {{.*[\\/]}}bar.o: {{[Nn]}}o such file or directory +# OBJ: error: cannot open '{{.*[\\/]}}bar.o': {{[Nn]}}o such file or directory ## Now create a "decoy" libfoo.dylib under %t/%:t to demonstrate that the ## rerooted path takes precedence over the original path. We will get an diff --git a/lld/unittests/MachOTests/MachONormalizedFileBinaryWriterTests.cpp b/lld/unittests/MachOTests/MachONormalizedFileBinaryWriterTests.cpp --- a/lld/unittests/MachOTests/MachONormalizedFileBinaryWriterTests.cpp +++ b/lld/unittests/MachOTests/MachONormalizedFileBinaryWriterTests.cpp @@ -29,9 +29,9 @@ // Normalized file to nf parameter. static void fromBinary(StringRef path, std::unique_ptr &mb, std::unique_ptr &nf, StringRef archStr) { - ErrorOr> mbOrErr = MemoryBuffer::getFile(path); - std::error_code ec = mbOrErr.getError(); - EXPECT_FALSE(ec); + llvm::Expected> mbOrErr = + MemoryBuffer::getFile(path); + EXPECT_FALSE(!mbOrErr); mb = std::move(mbOrErr.get()); llvm::Expected> r = diff --git a/lld/wasm/InputFiles.cpp b/lld/wasm/InputFiles.cpp --- a/lld/wasm/InputFiles.cpp +++ b/lld/wasm/InputFiles.cpp @@ -58,8 +58,8 @@ log("Loading: " + path); auto mbOrErr = MemoryBuffer::getFile(path); - if (auto ec = mbOrErr.getError()) { - error("cannot open " + path + ": " + ec.message()); + if (Error e = mbOrErr.takeError()) { + error("cannot open " + path + ": " + toString(std::move(e))); return None; } std::unique_ptr &mb = *mbOrErr; diff --git a/lldb/include/lldb/Utility/ReproducerProvider.h b/lldb/include/lldb/Utility/ReproducerProvider.h --- a/lldb/include/lldb/Utility/ReproducerProvider.h +++ b/lldb/include/lldb/Utility/ReproducerProvider.h @@ -364,8 +364,10 @@ return {}; auto error_or_file = llvm::MemoryBuffer::getFile(file.GetPath()); - if (auto err = error_or_file.getError()) + if (llvm::Error e = error_or_file.takeError()) { + consumeError(std::move(e)); return {}; + } std::vector files; llvm::yaml::Input yin((*error_or_file)->getBuffer()); diff --git a/lldb/source/API/SBReproducer.cpp b/lldb/source/API/SBReproducer.cpp --- a/lldb/source/API/SBReproducer.cpp +++ b/lldb/source/API/SBReproducer.cpp @@ -175,9 +175,8 @@ if (auto *l = lldb_private::repro::Reproducer::Instance().GetLoader()) { FileSpec file = l->GetFile(); auto error_or_file = llvm::MemoryBuffer::getFile(file.GetPath()); - if (!error_or_file) { - error = - "unable to read SB API data: " + error_or_file.getError().message(); + if (llvm::Error e = error_or_file.takeError()) { + error = "unable to read SB API data: " + toString(std::move(e)); return error.c_str(); } static ReplayData r(std::move(*error_or_file)); diff --git a/lldb/source/Commands/CommandObjectReproducer.cpp b/lldb/source/Commands/CommandObjectReproducer.cpp --- a/lldb/source/Commands/CommandObjectReproducer.cpp +++ b/lldb/source/Commands/CommandObjectReproducer.cpp @@ -122,9 +122,8 @@ template llvm::Expected static ReadFromYAML(StringRef filename) { auto error_or_file = MemoryBuffer::getFile(filename); - if (auto err = error_or_file.getError()) { - return errorCodeToError(err); - } + if (Error e = error_or_file.takeError()) + return e; T t; yaml::Input yin((*error_or_file)->getBuffer()); @@ -518,8 +517,8 @@ break; auto command_buffer = llvm::MemoryBuffer::getFile(*command_file); - if (auto err = command_buffer.getError()) { - SetError(result, errorCodeToError(err)); + if (Error e = command_buffer.takeError()) { + SetError(result, std::move(e)); return false; } result.AppendMessage((*command_buffer)->getBuffer()); diff --git a/lldb/source/Commands/CommandObjectTrace.cpp b/lldb/source/Commands/CommandObjectTrace.cpp --- a/lldb/source/Commands/CommandObjectTrace.cpp +++ b/lldb/source/Commands/CommandObjectTrace.cpp @@ -10,6 +10,7 @@ #include "llvm/Support/JSON.h" #include "llvm/Support/MemoryBuffer.h" +#include #include "lldb/Core/Debugger.h" #include "lldb/Core/PluginManager.h" @@ -99,11 +100,11 @@ FileSpec json_file(command[0].ref()); auto buffer_or_error = llvm::MemoryBuffer::getFile(json_file.GetPath()); - if (!buffer_or_error) { + if (Error e = buffer_or_error.takeError()) { return end_with_failure(llvm::createStringError( - std::errc::invalid_argument, "could not open input file: %s - %s.", - json_file.GetPath().c_str(), - buffer_or_error.getError().message().c_str())); + std::make_error_code(std::errc::invalid_argument), + Twine("could not open input file: ") + json_file.GetPath() + " - " + + toString(std::move(e)) + ".")); } llvm::Expected session_file = diff --git a/lldb/source/Host/common/FileSystem.cpp b/lldb/source/Host/common/FileSystem.cpp --- a/lldb/source/Host/common/FileSystem.cpp +++ b/lldb/source/Host/common/FileSystem.cpp @@ -314,8 +314,10 @@ } else { auto buffer_or_error = llvm::WritableMemoryBuffer::getFileSlice( *external_path, size, offset, is_volatile); - if (!buffer_or_error) + if (!buffer_or_error) { + consumeError(buffer_or_error.takeError()); return nullptr; + } buffer = std::move(*buffer_or_error); } return std::shared_ptr(new DataBufferLLVM(std::move(buffer))); diff --git a/lldb/source/Host/linux/Support.cpp b/lldb/source/Host/linux/Support.cpp --- a/lldb/source/Host/linux/Support.cpp +++ b/lldb/source/Host/linux/Support.cpp @@ -16,7 +16,7 @@ std::string File = ("/proc/" + llvm::Twine(pid) + "/task/" + llvm::Twine(tid) + "/" + file) .str(); - auto Ret = llvm::MemoryBuffer::getFileAsStream(File); + auto Ret = expectedToErrorOr(llvm::MemoryBuffer::getFileAsStream(File)); if (!Ret) LLDB_LOG(log, "Failed to open {0}: {1}", File, Ret.getError().message()); return Ret; @@ -26,7 +26,7 @@ lldb_private::getProcFile(::pid_t pid, const llvm::Twine &file) { Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); std::string File = ("/proc/" + llvm::Twine(pid) + "/" + file).str(); - auto Ret = llvm::MemoryBuffer::getFileAsStream(File); + auto Ret = expectedToErrorOr(llvm::MemoryBuffer::getFileAsStream(File)); if (!Ret) LLDB_LOG(log, "Failed to open {0}: {1}", File, Ret.getError().message()); return Ret; @@ -36,7 +36,7 @@ lldb_private::getProcFile(const llvm::Twine &file) { Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); std::string File = ("/proc/" + file).str(); - auto Ret = llvm::MemoryBuffer::getFileAsStream(File); + auto Ret = expectedToErrorOr(llvm::MemoryBuffer::getFileAsStream(File)); if (!Ret) LLDB_LOG(log, "Failed to open {0}: {1}", File, Ret.getError().message()); return Ret; diff --git a/lldb/source/Plugins/ObjectFile/Minidump/MinidumpFileBuilder.cpp b/lldb/source/Plugins/ObjectFile/Minidump/MinidumpFileBuilder.cpp --- a/lldb/source/Plugins/ObjectFile/Minidump/MinidumpFileBuilder.cpp +++ b/lldb/source/Plugins/ObjectFile/Minidump/MinidumpFileBuilder.cpp @@ -652,8 +652,10 @@ std::unique_ptr getFileStreamHelper(const std::string &path) { auto maybe_stream = llvm::MemoryBuffer::getFileAsStream(path); - if (!maybe_stream) + if (!maybe_stream) { + consumeError(maybe_stream.takeError()); return nullptr; + } return std::move(maybe_stream.get()); } @@ -767,4 +769,4 @@ size_t MinidumpFileBuilder::GetCurrentDataEndOffset() const { return sizeof(llvm::minidump::Header) + m_data.GetByteSize(); -} \ No newline at end of file +} diff --git a/lldb/source/Plugins/ObjectFile/PDB/ObjectFilePDB.cpp b/lldb/source/Plugins/ObjectFile/PDB/ObjectFilePDB.cpp --- a/lldb/source/Plugins/ObjectFile/PDB/ObjectFilePDB.cpp +++ b/lldb/source/Plugins/ObjectFile/PDB/ObjectFilePDB.cpp @@ -168,15 +168,20 @@ std::unique_ptr ObjectFilePDB::loadPDBFile(std::string PdbPath, llvm::BumpPtrAllocator &Allocator) { - llvm::file_magic magic; - auto ec = llvm::identify_magic(PdbPath, magic); - if (ec || magic != llvm::file_magic::pdb) + auto magic = llvm::identify_magic_in_file(PdbPath); + if (llvm::Error e = magic.takeError()) { + consumeError(std::move(e)); return nullptr; - llvm::ErrorOr> ErrorOrBuffer = + } + if (*magic != llvm::file_magic::pdb) + return nullptr; + llvm::Expected> ErrorOrBuffer = llvm::MemoryBuffer::getFile(PdbPath, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (!ErrorOrBuffer) + if (llvm::Error e = ErrorOrBuffer.takeError()) { + consumeError(std::move(e)); return nullptr; + } std::unique_ptr Buffer = std::move(*ErrorOrBuffer); llvm::StringRef Path = Buffer->getBufferIdentifier(); diff --git a/lldb/source/Plugins/Process/Linux/IntelPTManager.cpp b/lldb/source/Plugins/Process/Linux/IntelPTManager.cpp --- a/lldb/source/Plugins/Process/Linux/IntelPTManager.cpp +++ b/lldb/source/Plugins/Process/Linux/IntelPTManager.cpp @@ -55,12 +55,11 @@ static Expected ReadIntelPTConfigFile(const char *file, IntelPTConfigFileType type) { - ErrorOr> stream = + Expected> stream = MemoryBuffer::getFileAsStream(file); - if (!stream) - return createStringError(inconvertibleErrorCode(), - "Can't open the file '%s'", file); + if (Error E = stream.takeError()) + return E; uint32_t value = 0; StringRef text_buffer = stream.get()->getBuffer(); diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.cpp b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.cpp --- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.cpp +++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationReplayServer.cpp @@ -190,8 +190,8 @@ llvm::Error GDBRemoteCommunicationReplayServer::LoadReplayHistory(const FileSpec &path) { auto error_or_file = MemoryBuffer::getFile(path.GetPath()); - if (auto err = error_or_file.getError()) - return errorCodeToError(err); + if (Error e = error_or_file.takeError()) + return e; yaml::Input yin((*error_or_file)->getBuffer()); yin >> m_packet_history; diff --git a/lldb/source/Utility/ProcessInfo.cpp b/lldb/source/Utility/ProcessInfo.cpp --- a/lldb/source/Utility/ProcessInfo.cpp +++ b/lldb/source/Utility/ProcessInfo.cpp @@ -362,8 +362,10 @@ return {}; auto error_or_file = llvm::MemoryBuffer::getFile(*nextfile); - if (std::error_code err = error_or_file.getError()) + if (llvm::Error e = error_or_file.takeError()) { + consumeError(std::move(e)); return {}; + } ProcessInstanceInfoList infos; llvm::yaml::Input yin((*error_or_file)->getBuffer()); diff --git a/lldb/source/Utility/Reproducer.cpp b/lldb/source/Utility/Reproducer.cpp --- a/lldb/source/Utility/Reproducer.cpp +++ b/lldb/source/Utility/Reproducer.cpp @@ -11,6 +11,7 @@ #include "lldb/Utility/ReproducerProvider.h" #include "lldb/Utility/Timer.h" +#include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Threading.h" #include "llvm/Support/raw_ostream.h" @@ -232,8 +233,10 @@ FileSpec index = m_root.CopyByAppendingPathComponent("index.yaml"); auto error_or_file = MemoryBuffer::getFile(index.GetPath()); - if (auto err = error_or_file.getError()) - return make_error("unable to load reproducer index", err); + if (llvm::Error e = error_or_file.takeError()) + return make_error("unable to load reproducer index: " + + toString(std::move(e)), + inconvertibleErrorCode()); yaml::Input yin((*error_or_file)->getBuffer()); yin >> m_files; @@ -349,8 +352,8 @@ static llvm::Error addPaths(StringRef path, function_ref callback) { auto buffer = llvm::MemoryBuffer::getFile(path); - if (!buffer) - return errorCodeToError(buffer.getError()); + if (Error e = buffer.takeError()) + return e; SmallVector paths; (*buffer)->getBuffer().split(paths, '\0'); diff --git a/lldb/source/Utility/ReproducerInstrumentation.cpp b/lldb/source/Utility/ReproducerInstrumentation.cpp --- a/lldb/source/Utility/ReproducerInstrumentation.cpp +++ b/lldb/source/Utility/ReproducerInstrumentation.cpp @@ -97,8 +97,10 @@ bool Registry::Replay(const FileSpec &file) { auto error_or_file = llvm::MemoryBuffer::getFile(file.GetPath()); - if (auto err = error_or_file.getError()) + if (llvm::Error e = error_or_file.takeError()) { + consumeError(std::move(e)); return false; + } return Replay((*error_or_file)->getBuffer()); } diff --git a/lldb/source/Utility/ReproducerProvider.cpp b/lldb/source/Utility/ReproducerProvider.cpp --- a/lldb/source/Utility/ReproducerProvider.cpp +++ b/lldb/source/Utility/ReproducerProvider.cpp @@ -176,8 +176,10 @@ return; auto error_or_file = llvm::MemoryBuffer::getFile(file.GetPath()); - if (auto err = error_or_file.getError()) + if (Error e = error_or_file.takeError()) { + consumeError(std::move(e)); return; + } llvm::yaml::Input yin((*error_or_file)->getBuffer()); yin >> m_symbol_files; diff --git a/lldb/source/Utility/StructuredData.cpp b/lldb/source/Utility/StructuredData.cpp --- a/lldb/source/Utility/StructuredData.cpp +++ b/lldb/source/Utility/StructuredData.cpp @@ -36,10 +36,10 @@ StructuredData::ObjectSP return_sp; auto buffer_or_error = llvm::MemoryBuffer::getFile(input_spec.GetPath()); - if (!buffer_or_error) { + if (Error e = buffer_or_error.takeError()) { error.SetErrorStringWithFormatv("could not open input file: {0} - {1}.", input_spec.GetPath(), - buffer_or_error.getError().message()); + toString(std::move(e))); return return_sp; } llvm::Expected value = diff --git a/lldb/tools/lldb-test/lldb-test.cpp b/lldb/tools/lldb-test/lldb-test.cpp --- a/lldb/tools/lldb-test/lldb-test.cpp +++ b/lldb/tools/lldb-test/lldb-test.cpp @@ -304,9 +304,9 @@ std::unique_ptr opts::openFile(const std::string &Filename) { auto MB = MemoryBuffer::getFileOrSTDIN(Filename); - if (!MB) { + if (Error E = MB.takeError()) { errs() << formatv("Could not open file '{0}: {1}\n", Filename, - MB.getError().message()); + toString(std::move(E))); exit(1); } return std::move(*MB); diff --git a/lldb/unittests/TestingSupport/TestUtilities.cpp b/lldb/unittests/TestingSupport/TestUtilities.cpp --- a/lldb/unittests/TestingSupport/TestUtilities.cpp +++ b/lldb/unittests/TestingSupport/TestUtilities.cpp @@ -40,7 +40,7 @@ auto BufferOrError = llvm::MemoryBuffer::getFile(GetInputFilePath(Name), /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (!BufferOrError) - return llvm::errorCodeToError(BufferOrError.getError()); + if (llvm::Error E = BufferOrError.takeError()) + return E; return fromYaml(BufferOrError.get()->getBuffer()); } diff --git a/llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp b/llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp --- a/llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp +++ b/llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp @@ -159,7 +159,7 @@ outs() << "About to load module: " << Path << "\n"; Expected> BitcodeBuffer = - errorOrToExpected(MemoryBuffer::getFile(Path)); + MemoryBuffer::getFile(Path); if (!BitcodeBuffer) return BitcodeBuffer.takeError(); @@ -185,7 +185,7 @@ // (1) Read the index file and parse the module summary index. std::unique_ptr SummaryBuffer = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(IndexFile))); + ExitOnErr(MemoryBuffer::getFile(IndexFile)); std::unique_ptr SummaryIndex = ExitOnErr(getModuleSummaryIndex(SummaryBuffer->getMemBufferRef())); diff --git a/llvm/include/llvm/BinaryFormat/Magic.h b/llvm/include/llvm/BinaryFormat/Magic.h --- a/llvm/include/llvm/BinaryFormat/Magic.h +++ b/llvm/include/llvm/BinaryFormat/Magic.h @@ -9,6 +9,7 @@ #ifndef LLVM_BINARYFORMAT_MAGIC_H #define LLVM_BINARYFORMAT_MAGIC_H +#include "llvm/Support/Error.h" #include namespace llvm { @@ -69,10 +70,8 @@ /// Get and identify \a path's type based on its content. /// /// @param path Input path. -/// @param result Set to the type of file, or file_magic::unknown. -/// @returns errc::success if result has been successfully set, otherwise a -/// platform-specific error_code. -std::error_code identify_magic(const Twine &path, file_magic &result); +/// @returns the type of the file, otherwise an llvm::Error +Expected identify_magic_in_file(const Twine &path); } // namespace llvm #endif diff --git a/llvm/include/llvm/Support/Error.h b/llvm/include/llvm/Support/Error.h --- a/llvm/include/llvm/Support/Error.h +++ b/llvm/include/llvm/Support/Error.h @@ -1259,13 +1259,20 @@ public: void log(raw_ostream &OS) const override { - assert(Err && !FileName.empty() && "Trying to log after takeError()."); + assert(Err && "Trying to log after takeError()."); OS << "'" << FileName << "': "; if (Line.hasValue()) OS << "line " << Line.getValue() << ": "; Err->log(OS); } + std::string messageWithoutFileInfo() const { + std::string Msg; + raw_string_ostream OS(Msg); + Err->log(OS); + return OS.str(); + } + StringRef getFileName() { return FileName; } Error takeError() { return Error(std::move(Err)); } @@ -1279,8 +1286,6 @@ FileError(const Twine &F, Optional LineNum, std::unique_ptr E) { assert(E && "Cannot create FileError from Error success value."); - assert(!F.isTriviallyEmpty() && - "The file name provided to FileError must not be empty."); FileName = F.str(); Err = std::move(E); Line = std::move(LineNum); diff --git a/llvm/include/llvm/Support/MemoryBuffer.h b/llvm/include/llvm/Support/MemoryBuffer.h --- a/llvm/include/llvm/Support/MemoryBuffer.h +++ b/llvm/include/llvm/Support/MemoryBuffer.h @@ -18,7 +18,7 @@ #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/CBindingWrapping.h" -#include "llvm/Support/ErrorOr.h" +#include "llvm/Support/Error.h" #include "llvm/Support/MemoryBufferRef.h" #include #include @@ -83,20 +83,20 @@ /// \param IsVolatile Set to true to indicate that the contents of the file /// can change outside the user's control, e.g. when libclang tries to parse /// while the user is editing/updating the file or if the file is on an NFS. - static ErrorOr> + static Expected> getFile(const Twine &Filename, bool IsText = false, bool RequiresNullTerminator = true, bool IsVolatile = false); /// Read all of the specified file into a MemoryBuffer as a stream /// (i.e. until EOF reached). This is useful for special files that /// look like a regular file but have 0 size (e.g. /proc/cpuinfo on Linux). - static ErrorOr> + static Expected> getFileAsStream(const Twine &Filename); /// Given an already-open file descriptor, map some slice of it into a /// MemoryBuffer. The slice is specified by an \p Offset and \p MapSize. /// Since this is in the middle of a file, the buffer is not null terminated. - static ErrorOr> + static Expected> getOpenFileSlice(sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize, int64_t Offset, bool IsVolatile = false); @@ -106,7 +106,7 @@ /// \param IsVolatile Set to true to indicate that the contents of the file /// can change outside the user's control, e.g. when libclang tries to parse /// while the user is editing/updating the file or if the file is on an NFS. - static ErrorOr> + static Expected> getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, bool RequiresNullTerminator = true, bool IsVolatile = false); @@ -125,16 +125,16 @@ getMemBufferCopy(StringRef InputData, const Twine &BufferName = ""); /// Read all of stdin into a file buffer, and return it. - static ErrorOr> getSTDIN(); + static Expected> getSTDIN(); /// Open the specified file as a MemoryBuffer, or open stdin if the Filename /// is "-". - static ErrorOr> + static Expected> getFileOrSTDIN(const Twine &Filename, bool IsText = false, bool RequiresNullTerminator = true); /// Map a subrange of the specified file as a MemoryBuffer. - static ErrorOr> + static Expected> getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset, bool IsVolatile = false); @@ -180,11 +180,11 @@ return {getBufferStart(), getBufferEnd()}; } - static ErrorOr> + static Expected> getFile(const Twine &Filename, bool IsVolatile = false); /// Map a subrange of the specified file as a WritableMemoryBuffer. - static ErrorOr> + static Expected> getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset, bool IsVolatile = false); @@ -238,11 +238,11 @@ return {getBufferStart(), getBufferEnd()}; } - static ErrorOr> + static Expected> getFile(const Twine &Filename, int64_t FileSize = -1); /// Map a subrange of the specified file as a ReadWriteMemoryBuffer. - static ErrorOr> + static Expected> getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset); private: diff --git a/llvm/lib/Analysis/ReplayInlineAdvisor.cpp b/llvm/lib/Analysis/ReplayInlineAdvisor.cpp --- a/llvm/lib/Analysis/ReplayInlineAdvisor.cpp +++ b/llvm/lib/Analysis/ReplayInlineAdvisor.cpp @@ -29,9 +29,8 @@ : InlineAdvisor(M, FAM), OriginalAdvisor(std::move(OriginalAdvisor)), HasReplayRemarks(false), EmitRemarks(EmitRemarks) { auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(RemarksFile); - std::error_code EC = BufferOrErr.getError(); - if (EC) { - Context.emitError("Could not open remarks file: " + EC.message()); + if (Error E = BufferOrErr.takeError()) { + Context.emitError("Could not open remarks file: " + toString(std::move(E))); return; } diff --git a/llvm/lib/AsmParser/Parser.cpp b/llvm/lib/AsmParser/Parser.cpp --- a/llvm/lib/AsmParser/Parser.cpp +++ b/llvm/lib/AsmParser/Parser.cpp @@ -61,11 +61,11 @@ SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots) { - ErrorOr> FileOrErr = + Expected> FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename); - if (std::error_code EC = FileOrErr.getError()) { + if (Error E = FileOrErr.takeError()) { Err = SMDiagnostic(Filename, SourceMgr::DK_Error, - "Could not open input file: " + EC.message()); + "Could not open input file: " + toString(std::move(E))); return nullptr; } @@ -103,11 +103,11 @@ LLVMContext &Context, SlotMapping *Slots, bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback) { - ErrorOr> FileOrErr = + Expected> FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true); - if (std::error_code EC = FileOrErr.getError()) { + if (Error E = FileOrErr.takeError()) { Err = SMDiagnostic(Filename, SourceMgr::DK_Error, - "Could not open input file: " + EC.message()); + "Could not open input file: " + toString(std::move(E))); return {nullptr, nullptr}; } @@ -168,11 +168,11 @@ std::unique_ptr llvm::parseSummaryIndexAssemblyFile(StringRef Filename, SMDiagnostic &Err) { - ErrorOr> FileOrErr = + Expected> FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename); - if (std::error_code EC = FileOrErr.getError()) { + if (Error E = FileOrErr.takeError()) { Err = SMDiagnostic(Filename, SourceMgr::DK_Error, - "Could not open input file: " + EC.message()); + "Could not open input file: " + toString(std::move(E))); return nullptr; } diff --git a/llvm/lib/BinaryFormat/Magic.cpp b/llvm/lib/BinaryFormat/Magic.cpp --- a/llvm/lib/BinaryFormat/Magic.cpp +++ b/llvm/lib/BinaryFormat/Magic.cpp @@ -227,14 +227,12 @@ return file_magic::unknown; } -std::error_code llvm::identify_magic(const Twine &Path, file_magic &Result) { +Expected llvm::identify_magic_in_file(const Twine &Path) { auto FileOrError = MemoryBuffer::getFile(Path, /*IsText=*/false, /*RequiresNullTerminator=*/false); if (!FileOrError) - return FileOrError.getError(); + return FileOrError.takeError(); std::unique_ptr FileBuffer = std::move(*FileOrError); - Result = identify_magic(FileBuffer->getBuffer()); - - return std::error_code(); + return identify_magic(FileBuffer->getBuffer()); } diff --git a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp --- a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp +++ b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp @@ -7044,10 +7044,10 @@ Expected> llvm::getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile) { - ErrorOr> FileOrErr = + Expected> FileOrErr = MemoryBuffer::getFileOrSTDIN(Path); if (!FileOrErr) - return errorCodeToError(FileOrErr.getError()); + return FileOrErr.takeError(); if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) return nullptr; return getModuleSummaryIndex(**FileOrErr); diff --git a/llvm/lib/CodeGen/CommandFlags.cpp b/llvm/lib/CodeGen/CommandFlags.cpp --- a/llvm/lib/CodeGen/CommandFlags.cpp +++ b/llvm/lib/CodeGen/CommandFlags.cpp @@ -471,11 +471,11 @@ else if (getBBSections() == "none") return BasicBlockSection::None; else { - ErrorOr> MBOrErr = + Expected> MBOrErr = MemoryBuffer::getFile(getBBSections()); - if (!MBOrErr) { + if (Error E = MBOrErr.takeError()) { errs() << "Error loading basic block sections function list file: " - << MBOrErr.getError().message() << "\n"; + << toString(std::move(E)) << "\n"; } else { Options.BBSectionsFuncListBuf = std::move(*MBOrErr); } diff --git a/llvm/lib/CodeGen/MIRParser/MIRParser.cpp b/llvm/lib/CodeGen/MIRParser/MIRParser.cpp --- a/llvm/lib/CodeGen/MIRParser/MIRParser.cpp +++ b/llvm/lib/CodeGen/MIRParser/MIRParser.cpp @@ -1018,9 +1018,10 @@ StringRef Filename, SMDiagnostic &Error, LLVMContext &Context, std::function ProcessIRFunction) { auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true); - if (std::error_code EC = FileOrErr.getError()) { - Error = SMDiagnostic(Filename, SourceMgr::DK_Error, - "Could not open input file: " + EC.message()); + if (llvm::Error E = FileOrErr.takeError()) { + Error = + SMDiagnostic(Filename, SourceMgr::DK_Error, + "Could not open input file: " + toString(std::move(E))); return nullptr; } return createMIRParser(std::move(FileOrErr.get()), Context, diff --git a/llvm/lib/DebugInfo/GSYM/GsymReader.cpp b/llvm/lib/DebugInfo/GSYM/GsymReader.cpp --- a/llvm/lib/DebugInfo/GSYM/GsymReader.cpp +++ b/llvm/lib/DebugInfo/GSYM/GsymReader.cpp @@ -33,11 +33,10 @@ llvm::Expected GsymReader::openFile(StringRef Filename) { // Open the input file and return an appropriate error if needed. - ErrorOr> BuffOrErr = + Expected> BuffOrErr = MemoryBuffer::getFileOrSTDIN(Filename); - auto Err = BuffOrErr.getError(); - if (Err) - return llvm::errorCodeToError(Err); + if (Error E = BuffOrErr.takeError()) + return E; return create(BuffOrErr.get()); } diff --git a/llvm/lib/DebugInfo/PDB/Native/NativeSession.cpp b/llvm/lib/DebugInfo/PDB/Native/NativeSession.cpp --- a/llvm/lib/DebugInfo/PDB/Native/NativeSession.cpp +++ b/llvm/lib/DebugInfo/PDB/Native/NativeSession.cpp @@ -82,18 +82,20 @@ static Expected> loadPdbFile(StringRef PdbPath, std::unique_ptr &Allocator) { - ErrorOr> ErrorOrBuffer = + Expected> ErrorOrBuffer = MemoryBuffer::getFile(PdbPath, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (!ErrorOrBuffer) - return make_error(ErrorOrBuffer.getError()); + if (Error E = ErrorOrBuffer.takeError()) + return E; std::unique_ptr Buffer = std::move(*ErrorOrBuffer); PdbPath = Buffer->getBufferIdentifier(); - file_magic Magic; - auto EC = identify_magic(PdbPath, Magic); - if (EC || Magic != file_magic::pdb) - return make_error(EC); + Expected Magic = identify_magic_in_file(PdbPath); + if (Error E = Magic.takeError()) + return E; + if (*Magic != file_magic::pdb) + return make_error("Expected a pdb file in: " + PdbPath, + inconvertibleErrorCode()); auto Stream = std::make_unique(std::move(Buffer), llvm::support::little); @@ -145,10 +147,12 @@ if (!PdbPath) return PdbPath.takeError(); - file_magic Magic; - auto EC = identify_magic(PdbPath.get(), Magic); - if (EC || Magic != file_magic::pdb) - return make_error(EC); + Expected Magic = identify_magic_in_file(*PdbPath); + if (Error E = Magic.takeError()) + return E; + if (*Magic != file_magic::pdb) + return make_error("Expected a pdb file in: " + *PdbPath, + inconvertibleErrorCode()); auto Allocator = std::make_unique(); auto File = loadPdbFile(PdbPath.get(), Allocator); diff --git a/llvm/lib/DebugInfo/Symbolize/DIPrinter.cpp b/llvm/lib/DebugInfo/Symbolize/DIPrinter.cpp --- a/llvm/lib/DebugInfo/Symbolize/DIPrinter.cpp +++ b/llvm/lib/DebugInfo/Symbolize/DIPrinter.cpp @@ -41,10 +41,12 @@ if (EmbeddedSource) return EmbeddedSource; else { - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFile(FileName); - if (!BufOrErr) + if (Error E = BufOrErr.takeError()) { + consumeError(std::move(E)); return None; + } MemBuf = std::move(*BufOrErr); return MemBuf->getBuffer(); } @@ -375,7 +377,13 @@ bool JSONPrinter::printError(const Request &Request, const ErrorInfoBase &ErrorInfo, StringRef ErrorBanner) { - json::Object Json = toJSON(Request, ErrorInfo.message()); + std::string Message; + if (ErrorInfo.isA()) + Message = + static_cast(ErrorInfo).messageWithoutFileInfo(); + else + Message = ErrorInfo.message(); + json::Object Json = toJSON(Request, Message); if (ObjectList) ObjectList->push_back(std::move(Json)); else diff --git a/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp b/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp --- a/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp +++ b/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp @@ -222,10 +222,12 @@ } bool checkFileCRC(StringRef Path, uint32_t CRCHash) { - ErrorOr> MB = + Expected> MB = MemoryBuffer::getFileOrSTDIN(Path); - if (!MB) + if (Error E = MB.takeError()) { + consumeError(std::move(E)); return false; + } return CRCHash == llvm::crc32(arrayRefFromStringRef(MB.get()->getBuffer())); } diff --git a/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp b/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp --- a/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp +++ b/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp @@ -270,7 +270,7 @@ Expected> StaticLibraryDefinitionGenerator::Load(ObjectLayer &L, const char *FileName) { - auto ArchiveBuffer = errorOrToExpected(MemoryBuffer::getFile(FileName)); + auto ArchiveBuffer = MemoryBuffer::getFile(FileName); if (!ArchiveBuffer) return ArchiveBuffer.takeError(); @@ -302,13 +302,13 @@ // slice. auto SliceBuffer = MemoryBuffer::getFileSlice(FileName, Obj.getSize(), Obj.getOffset()); - if (!SliceBuffer) + if (Error E = SliceBuffer.takeError()) return make_error( Twine("Could not create buffer for ") + TT.str() + " slice of " + FileName + ": [ " + formatv("{0:x}", Obj.getOffset()) + " .. " + formatv("{0:x}", Obj.getOffset() + Obj.getSize()) + - ": " + SliceBuffer.getError().message(), - SliceBuffer.getError()); + ": " + toString(std::move(E)), + inconvertibleErrorCode()); return Create(L, std::move(*SliceBuffer)); } } diff --git a/llvm/lib/FuzzMutate/FuzzerCLI.cpp b/llvm/lib/FuzzMutate/FuzzerCLI.cpp --- a/llvm/lib/FuzzMutate/FuzzerCLI.cpp +++ b/llvm/lib/FuzzMutate/FuzzerCLI.cpp @@ -155,8 +155,9 @@ auto BufOrErr = MemoryBuffer::getFile(Arg, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (std::error_code EC = BufOrErr.getError()) { - errs() << "Error reading file: " << Arg << ": " << EC.message() << "\n"; + if (Error E = BufOrErr.takeError()) { + errs() << "Error reading file: " << Arg << ": " << toString(std::move(E)) + << "\n"; return 1; } std::unique_ptr Buf = std::move(BufOrErr.get()); diff --git a/llvm/lib/IR/Core.cpp b/llvm/lib/IR/Core.cpp --- a/llvm/lib/IR/Core.cpp +++ b/llvm/lib/IR/Core.cpp @@ -4093,9 +4093,9 @@ LLVMMemoryBufferRef *OutMemBuf, char **OutMessage) { - ErrorOr> MBOrErr = MemoryBuffer::getFile(Path); - if (std::error_code EC = MBOrErr.getError()) { - *OutMessage = strdup(EC.message().c_str()); + Expected> MBOrErr = MemoryBuffer::getFile(Path); + if (Error E = MBOrErr.takeError()) { + *OutMessage = strdup(toString(std::move(E)).c_str()); return 1; } *OutMemBuf = wrap(MBOrErr.get().release()); @@ -4104,9 +4104,9 @@ LLVMBool LLVMCreateMemoryBufferWithSTDIN(LLVMMemoryBufferRef *OutMemBuf, char **OutMessage) { - ErrorOr> MBOrErr = MemoryBuffer::getSTDIN(); - if (std::error_code EC = MBOrErr.getError()) { - *OutMessage = strdup(EC.message().c_str()); + Expected> MBOrErr = MemoryBuffer::getSTDIN(); + if (Error E = MBOrErr.takeError()) { + *OutMessage = strdup(toString(std::move(E)).c_str()); return 1; } *OutMemBuf = wrap(MBOrErr.get().release()); diff --git a/llvm/lib/IRReader/IRReader.cpp b/llvm/lib/IRReader/IRReader.cpp --- a/llvm/lib/IRReader/IRReader.cpp +++ b/llvm/lib/IRReader/IRReader.cpp @@ -53,11 +53,11 @@ SMDiagnostic &Err, LLVMContext &Context, bool ShouldLazyLoadMetadata) { - ErrorOr> FileOrErr = + Expected> FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename); - if (std::error_code EC = FileOrErr.getError()) { + if (Error E = FileOrErr.takeError()) { Err = SMDiagnostic(Filename, SourceMgr::DK_Error, - "Could not open input file: " + EC.message()); + "Could not open input file: " + toString(std::move(E))); return nullptr; } @@ -91,11 +91,11 @@ std::unique_ptr llvm::parseIRFile(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, DataLayoutCallbackTy DataLayoutCallback) { - ErrorOr> FileOrErr = + Expected> FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true); - if (std::error_code EC = FileOrErr.getError()) { + if (Error E = FileOrErr.takeError()) { Err = SMDiagnostic(Filename, SourceMgr::DK_Error, - "Could not open input file: " + EC.message()); + "Could not open input file: " + toString(std::move(E))); return nullptr; } diff --git a/llvm/lib/InterfaceStub/ELFObjHandler.cpp b/llvm/lib/InterfaceStub/ELFObjHandler.cpp --- a/llvm/lib/InterfaceStub/ELFObjHandler.cpp +++ b/llvm/lib/InterfaceStub/ELFObjHandler.cpp @@ -603,7 +603,7 @@ Builder.write(Buf.data()); if (WriteIfChanged) { - if (ErrorOr> BufOrError = + if (Expected> BufOrError = MemoryBuffer::getFile(FilePath)) { // Compare Stub output with existing Stub file. // If Stub file unchanged, abort updating. @@ -611,7 +611,8 @@ !memcmp((*BufOrError)->getBufferStart(), Buf.data(), Builder.getSize())) return Error::success(); - } + } else + consumeError(BufOrError.takeError()); } Expected> BufOrError = diff --git a/llvm/lib/LTO/Caching.cpp b/llvm/lib/LTO/Caching.cpp --- a/llvm/lib/LTO/Caching.cpp +++ b/llvm/lib/LTO/Caching.cpp @@ -44,7 +44,7 @@ Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath); std::error_code EC; if (FDOrErr) { - ErrorOr> MBOrErr = + Expected> MBOrErr = MemoryBuffer::getOpenFile(*FDOrErr, EntryPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false); @@ -53,7 +53,7 @@ AddBuffer(Task, std::move(*MBOrErr)); return AddStreamFn(); } - EC = MBOrErr.getError(); + EC = errorToErrorCode(MBOrErr.takeError()); } else { EC = errorToErrorCode(FDOrErr.takeError()); } @@ -88,14 +88,14 @@ OS.reset(); // Open the file first to avoid racing with a cache pruner. - ErrorOr> MBOrErr = + Expected> MBOrErr = MemoryBuffer::getOpenFile( sys::fs::convertFDToNativeFile(TempFile.FD), TempFile.TmpName, /*FileSize=*/-1, /*RequiresNullTerminator=*/false); - if (!MBOrErr) + if (Error E = MBOrErr.takeError()) report_fatal_error(Twine("Failed to open new cache file ") + - TempFile.TmpName + ": " + - MBOrErr.getError().message() + "\n"); + TempFile.TmpName + ": " + toString(std::move(E)) + + "\n"); // On POSIX systems, this will atomically replace the destination if // it already exists. We try to emulate this on Windows, but this may diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp --- a/llvm/lib/LTO/LTOBackend.cpp +++ b/llvm/lib/LTO/LTOBackend.cpp @@ -629,12 +629,13 @@ /*IsImporting*/ true); } - ErrorOr> MBOrErr = + Expected> MBOrErr = llvm::MemoryBuffer::getFile(Identifier); - if (!MBOrErr) + if (Error E = MBOrErr.takeError()) return Expected>(make_error( - Twine("Error loading imported file ") + Identifier + " : ", - MBOrErr.getError())); + Twine("Error loading imported file ") + Identifier + " : " + + toString(std::move(E)), + inconvertibleErrorCode())); Expected BMOrErr = findThinLTOModule(**MBOrErr); if (!BMOrErr) diff --git a/llvm/lib/LTO/LTOCodeGenerator.cpp b/llvm/lib/LTO/LTOCodeGenerator.cpp --- a/llvm/lib/LTO/LTOCodeGenerator.cpp +++ b/llvm/lib/LTO/LTOCodeGenerator.cpp @@ -285,10 +285,10 @@ return nullptr; // read .o file into memory buffer - ErrorOr> BufferOrErr = MemoryBuffer::getFile( + Expected> BufferOrErr = MemoryBuffer::getFile( name, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (std::error_code EC = BufferOrErr.getError()) { - emitError(EC.message()); + if (Error E = BufferOrErr.takeError()) { + emitError(toString(std::move(E))); sys::fs::remove(NativeObjectPath); return nullptr; } diff --git a/llvm/lib/LTO/LTOModule.cpp b/llvm/lib/LTO/LTOModule.cpp --- a/llvm/lib/LTO/LTOModule.cpp +++ b/llvm/lib/LTO/LTOModule.cpp @@ -61,10 +61,12 @@ } bool LTOModule::isBitcodeFile(StringRef Path) { - ErrorOr> BufferOrErr = + Expected> BufferOrErr = MemoryBuffer::getFile(Path); - if (!BufferOrErr) + if (Error E = BufferOrErr.takeError()) { + consumeError(std::move(E)); return false; + } Expected BCData = IRObjectFile::findBitcodeInMemBuffer( BufferOrErr.get()->getMemBufferRef()); @@ -110,9 +112,9 @@ ErrorOr> LTOModule::createFromFile(LLVMContext &Context, StringRef path, const TargetOptions &options) { - ErrorOr> BufferOrErr = + Expected> BufferOrErr = MemoryBuffer::getFile(path); - if (std::error_code EC = BufferOrErr.getError()) { + if (std::error_code EC = errorToErrorCode(BufferOrErr.takeError())) { Context.emitError(EC.message()); return EC; } @@ -131,10 +133,10 @@ LTOModule::createFromOpenFileSlice(LLVMContext &Context, int fd, StringRef path, size_t map_size, off_t offset, const TargetOptions &options) { - ErrorOr> BufferOrErr = + Expected> BufferOrErr = MemoryBuffer::getOpenFileSlice(sys::fs::convertFDToNativeFile(fd), path, map_size, offset); - if (std::error_code EC = BufferOrErr.getError()) { + if (std::error_code EC = errorToErrorCode(BufferOrErr.takeError())) { Context.emitError(EC.message()); return EC; } diff --git a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp --- a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp +++ b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp @@ -441,10 +441,10 @@ Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath); if (!FDOrErr) return errorToErrorCode(FDOrErr.takeError()); - ErrorOr> MBOrErr = MemoryBuffer::getOpenFile( + Expected> MBOrErr = MemoryBuffer::getOpenFile( *FDOrErr, EntryPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false); sys::fs::closeFile(*FDOrErr); - return MBOrErr; + return expectedToErrorOr(std::move(MBOrErr)); } // Cache the Produced object file diff --git a/llvm/lib/Object/Archive.cpp b/llvm/lib/Object/Archive.cpp --- a/llvm/lib/Object/Archive.cpp +++ b/llvm/lib/Object/Archive.cpp @@ -454,9 +454,9 @@ if (!FullNameOrErr) return FullNameOrErr.takeError(); const std::string &FullName = *FullNameOrErr; - ErrorOr> Buf = MemoryBuffer::getFile(FullName); - if (std::error_code EC = Buf.getError()) - return errorCodeToError(EC); + Expected> Buf = MemoryBuffer::getFile(FullName); + if (Error E = Buf.takeError()) + return E; Parent->ThinBuffers.push_back(std::move(*Buf)); return Parent->ThinBuffers.back()->getBuffer(); } @@ -519,7 +519,7 @@ StringRef Name = NameOrErr.get(); Expected Buf = getBuffer(); if (!Buf) - return createFileError(Name, Buf.takeError()); + return Buf.takeError(); return MemoryBufferRef(*Buf, Name); } diff --git a/llvm/lib/Object/ArchiveWriter.cpp b/llvm/lib/Object/ArchiveWriter.cpp --- a/llvm/lib/Object/ArchiveWriter.cpp +++ b/llvm/lib/Object/ArchiveWriter.cpp @@ -85,21 +85,22 @@ assert(FD != sys::fs::kInvalidFile); if (auto EC = sys::fs::status(FD, Status)) - return errorCodeToError(EC); + return createFileError(FileName, errorCodeToError(EC)); // Opening a directory doesn't make sense. Let it fail. // Linux cannot open directories with open(2), although // cygwin and *bsd can. if (Status.type() == sys::fs::file_type::directory_file) - return errorCodeToError(make_error_code(errc::is_a_directory)); + return createFileError( + FileName, errorCodeToError(make_error_code(errc::is_a_directory))); - ErrorOr> MemberBufferOrErr = + Expected> MemberBufferOrErr = MemoryBuffer::getOpenFile(FD, FileName, Status.getSize(), false); - if (!MemberBufferOrErr) - return errorCodeToError(MemberBufferOrErr.getError()); + if (Error E = MemberBufferOrErr.takeError()) + return createFileError(FileName, std::move(E)); if (auto EC = sys::fs::closeFile(FD)) - return errorCodeToError(EC); + return createFileError(FileName, errorCodeToError(EC)); NewArchiveMember M; M.Buf = std::move(*MemberBufferOrErr); diff --git a/llvm/lib/Object/Binary.cpp b/llvm/lib/Object/Binary.cpp --- a/llvm/lib/Object/Binary.cpp +++ b/llvm/lib/Object/Binary.cpp @@ -97,17 +97,17 @@ Expected> object::createBinary(StringRef Path, LLVMContext *Context, bool InitContent) { - ErrorOr> FileOrErr = + Expected> FileOrErr = MemoryBuffer::getFileOrSTDIN(Path, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (std::error_code EC = FileOrErr.getError()) - return errorCodeToError(EC); + if (Error E = FileOrErr.takeError()) + return E; std::unique_ptr &Buffer = FileOrErr.get(); Expected> BinOrErr = createBinary(Buffer->getMemBufferRef(), Context, InitContent); - if (!BinOrErr) - return BinOrErr.takeError(); + if (Error E = BinOrErr.takeError()) + return createFileError(Path, std::move(E)); std::unique_ptr &Bin = BinOrErr.get(); return OwningBinary(std::move(Bin), std::move(Buffer)); diff --git a/llvm/lib/Object/Error.cpp b/llvm/lib/Object/Error.cpp --- a/llvm/lib/Object/Error.cpp +++ b/llvm/lib/Object/Error.cpp @@ -80,15 +80,16 @@ } llvm::Error llvm::object::isNotObjectErrorInvalidFileType(llvm::Error Err) { - return handleErrors(std::move(Err), [](std::unique_ptr M) -> Error { - // Try to handle 'M'. If successful, return a success value from - // the handler. - if (M->convertToErrorCode() == object_error::invalid_file_type) - return Error::success(); + return handleErrors( + std::move(Err), [](std::unique_ptr M) -> Error { + // Try to handle 'M'. If successful, return a success value from + // the handler. + if (M->convertToErrorCode() == object_error::invalid_file_type) + return Error::success(); - // We failed to handle 'M' - return it from the handler. - // This value will be passed back from catchErrors and - // wind up in Err2, where it will be returned from this function. - return Error(std::move(M)); - }); + // We failed to handle 'M' - return it from the handler. + // This value will be passed back from catchErrors and + // wind up in Err2, where it will be returned from this function. + return Error(std::move(M)); + }); } diff --git a/llvm/lib/Object/ObjectFile.cpp b/llvm/lib/Object/ObjectFile.cpp --- a/llvm/lib/Object/ObjectFile.cpp +++ b/llvm/lib/Object/ObjectFile.cpp @@ -183,10 +183,10 @@ Expected> ObjectFile::createObjectFile(StringRef ObjectPath) { - ErrorOr> FileOrErr = + Expected> FileOrErr = MemoryBuffer::getFile(ObjectPath); - if (std::error_code EC = FileOrErr.getError()) - return errorCodeToError(EC); + if (!FileOrErr) + return FileOrErr.takeError(); std::unique_ptr Buffer = std::move(FileOrErr.get()); Expected> ObjOrErr = diff --git a/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp b/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp --- a/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp +++ b/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp @@ -356,8 +356,8 @@ for (const auto &File : llvm::enumerate(ObjectFilenames)) { auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN( File.value(), /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (std::error_code EC = CovMappingBufOrErr.getError()) - return errorCodeToError(EC); + if (Error E = CovMappingBufOrErr.takeError()) + return E; StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()]; MemoryBufferRef CovMappingBufRef = CovMappingBufOrErr.get()->getMemBufferRef(); diff --git a/llvm/lib/ProfileData/GCOV.cpp b/llvm/lib/ProfileData/GCOV.cpp --- a/llvm/lib/ProfileData/GCOV.cpp +++ b/llvm/lib/ProfileData/GCOV.cpp @@ -576,11 +576,11 @@ LineConsumer(StringRef Filename) { // Open source files without requiring a NUL terminator. The concurrent // modification may nullify the NUL terminator condition. - ErrorOr> BufferOrErr = + Expected> BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (std::error_code EC = BufferOrErr.getError()) { - errs() << Filename << ": " << EC.message() << "\n"; + if (Error E = BufferOrErr.takeError()) { + errs() << Filename << ": " << toString(std::move(E)) << "\n"; Remaining = ""; } else { Buffer = std::move(BufferOrErr.get()); diff --git a/llvm/lib/ProfileData/InstrProfReader.cpp b/llvm/lib/ProfileData/InstrProfReader.cpp --- a/llvm/lib/ProfileData/InstrProfReader.cpp +++ b/llvm/lib/ProfileData/InstrProfReader.cpp @@ -40,11 +40,7 @@ static Expected> setupMemoryBuffer(const Twine &Path) { - ErrorOr> BufferOrErr = - MemoryBuffer::getFileOrSTDIN(Path, /*IsText=*/true); - if (std::error_code EC = BufferOrErr.getError()) - return errorCodeToError(EC); - return std::move(BufferOrErr.get()); + return MemoryBuffer::getFileOrSTDIN(Path, /*IsText=*/true); } static Error initializeReader(InstrProfReader &Reader) { diff --git a/llvm/lib/ProfileData/SampleProfReader.cpp b/llvm/lib/ProfileData/SampleProfReader.cpp --- a/llvm/lib/ProfileData/SampleProfReader.cpp +++ b/llvm/lib/ProfileData/SampleProfReader.cpp @@ -1699,8 +1699,8 @@ static ErrorOr> setupMemoryBuffer(const Twine &Filename) { auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true); - if (std::error_code EC = BufferOrErr.getError()) - return EC; + if (Error E = BufferOrErr.takeError()) + return errorToErrorCode(std::move(E)); auto Buffer = std::move(BufferOrErr.get()); // Sanity check the file. diff --git a/llvm/lib/Remarks/BitstreamRemarkParser.cpp b/llvm/lib/Remarks/BitstreamRemarkParser.cpp --- a/llvm/lib/Remarks/BitstreamRemarkParser.cpp +++ b/llvm/lib/Remarks/BitstreamRemarkParser.cpp @@ -423,10 +423,10 @@ // External file: open the external file, parse it, check if its metadata // matches the one from the separate metadata, then replace the current parser // with the one parsing the remarks. - ErrorOr> BufferOrErr = + Expected> BufferOrErr = MemoryBuffer::getFile(FullPath); - if (std::error_code EC = BufferOrErr.getError()) - return createFileError(FullPath, EC); + if (Error E = BufferOrErr.takeError()) + return E; TmpRemarkBuffer = std::move(*BufferOrErr); diff --git a/llvm/lib/Remarks/YAMLRemarkParser.cpp b/llvm/lib/Remarks/YAMLRemarkParser.cpp --- a/llvm/lib/Remarks/YAMLRemarkParser.cpp +++ b/llvm/lib/Remarks/YAMLRemarkParser.cpp @@ -146,10 +146,10 @@ sys::path::append(FullPath, ExternalFilePath); // Try to open the file and start parsing from there. - ErrorOr> BufferOrErr = + Expected> BufferOrErr = MemoryBuffer::getFile(FullPath); - if (std::error_code EC = BufferOrErr.getError()) - return createFileError(FullPath, EC); + if (Error E = BufferOrErr.takeError()) + return E; // Keep the buffer alive. SeparateBuf = std::move(*BufferOrErr); diff --git a/llvm/lib/Support/Error.cpp b/llvm/lib/Support/Error.cpp --- a/llvm/lib/Support/Error.cpp +++ b/llvm/lib/Support/Error.cpp @@ -80,8 +80,11 @@ } std::error_code FileError::convertToErrorCode() const { - return std::error_code(static_cast(ErrorErrorCode::FileError), - *ErrorErrorCat); + std::error_code NestedEC = Err->convertToErrorCode(); + if (NestedEC == inconvertibleErrorCode()) + return std::error_code(static_cast(ErrorErrorCode::FileError), + *ErrorErrorCat); + return NestedEC; } Error errorCodeToError(std::error_code EC) { diff --git a/llvm/lib/Support/FileUtilities.cpp b/llvm/lib/Support/FileUtilities.cpp --- a/llvm/lib/Support/FileUtilities.cpp +++ b/llvm/lib/Support/FileUtilities.cpp @@ -177,24 +177,25 @@ /// error occurs, allowing the caller to distinguish between a failed diff and a /// file system error. /// -int llvm::DiffFilesWithTolerance(StringRef NameA, - StringRef NameB, +int llvm::DiffFilesWithTolerance(StringRef NameA, StringRef NameB, double AbsTol, double RelTol, - std::string *Error) { + std::string *ErrString) { // Now its safe to mmap the files into memory because both files // have a non-zero size. - ErrorOr> F1OrErr = MemoryBuffer::getFile(NameA); - if (std::error_code EC = F1OrErr.getError()) { - if (Error) - *Error = EC.message(); + Expected> F1OrErr = + MemoryBuffer::getFile(NameA); + if (Error E = F1OrErr.takeError()) { + if (ErrString) + *ErrString = toString(std::move(E)); return 2; } MemoryBuffer &F1 = *F1OrErr.get(); - ErrorOr> F2OrErr = MemoryBuffer::getFile(NameB); - if (std::error_code EC = F2OrErr.getError()) { - if (Error) - *Error = EC.message(); + Expected> F2OrErr = + MemoryBuffer::getFile(NameB); + if (Error E = F1OrErr.takeError()) { + if (ErrString) + *ErrString = toString(std::move(E)); return 2; } MemoryBuffer &F2 = *F2OrErr.get(); @@ -216,8 +217,8 @@ // Otherwise, we are done a tolerances are set. if (AbsTol == 0 && RelTol == 0) { - if (Error) - *Error = "Files differ without tolerance allowance"; + if (ErrString) + *ErrString = "Files differ without tolerance allowance"; return 1; // Files different! } @@ -239,7 +240,8 @@ // Now that we are at the start of the numbers, compare them, exiting if // they don't match. - if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) { + if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, + ErrString)) { CompareFailed = true; break; } @@ -258,7 +260,7 @@ // Now that we are at the start of the numbers, compare them, exiting if // they don't match. - if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) + if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, ErrString)) CompareFailed = true; // If we found the end, we succeeded. diff --git a/llvm/lib/Support/Host.cpp b/llvm/lib/Support/Host.cpp --- a/llvm/lib/Support/Host.cpp +++ b/llvm/lib/Support/Host.cpp @@ -60,11 +60,11 @@ static std::unique_ptr LLVM_ATTRIBUTE_UNUSED getProcCpuinfoContent() { - llvm::ErrorOr> Text = + Expected> Text = llvm::MemoryBuffer::getFileAsStream("/proc/cpuinfo"); - if (std::error_code EC = Text.getError()) { + if (Error E = Text.takeError()) { llvm::errs() << "Can't read " - << "/proc/cpuinfo: " << EC.message() << "\n"; + << "/proc/cpuinfo: " << toString(std::move(E)) << "\n"; return nullptr; } return std::move(*Text); @@ -1387,11 +1387,11 @@ // Read /proc/cpuinfo as a stream (until EOF reached). It cannot be // mmapped because it appears to have 0 size. - llvm::ErrorOr> Text = + Expected> Text = llvm::MemoryBuffer::getFileAsStream("/proc/cpuinfo"); - if (std::error_code EC = Text.getError()) { + if (Error E = Text.takeError()) { llvm::errs() << "Can't read " - << "/proc/cpuinfo: " << EC.message() << "\n"; + << "/proc/cpuinfo: " << toString(std::move(E)) << "\n"; return -1; } SmallVector strs; diff --git a/llvm/lib/Support/LockFileManager.cpp b/llvm/lib/Support/LockFileManager.cpp --- a/llvm/lib/Support/LockFileManager.cpp +++ b/llvm/lib/Support/LockFileManager.cpp @@ -56,9 +56,10 @@ LockFileManager::readLockFile(StringRef LockFileName) { // Read the owning host and PID out of the lock file. If it appears that the // owning process is dead, the lock file is invalid. - ErrorOr> MBOrErr = + Expected> MBOrErr = MemoryBuffer::getFile(LockFileName); - if (!MBOrErr) { + if (Error E = MBOrErr.takeError()) { + consumeError(std::move(E)); sys::fs::remove(LockFileName); return None; } diff --git a/llvm/lib/Support/MemoryBuffer.cpp b/llvm/lib/Support/MemoryBuffer.cpp --- a/llvm/lib/Support/MemoryBuffer.cpp +++ b/llvm/lib/Support/MemoryBuffer.cpp @@ -16,6 +16,7 @@ #include "llvm/Support/AutoConvert.h" #include "llvm/Support/Errc.h" #include "llvm/Support/Errno.h" +#include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/Path.h" @@ -105,7 +106,7 @@ } // namespace template -static ErrorOr> +static Expected> getFileAux(const Twine &Filename, uint64_t MapSize, uint64_t Offset, bool IsText, bool RequiresNullTerminator, bool IsVolatile); @@ -123,11 +124,11 @@ Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator)); } -static ErrorOr> +static Expected> getMemBufferCopyImpl(StringRef InputData, const Twine &BufferName) { auto Buf = WritableMemoryBuffer::getNewUninitMemBuffer(InputData.size(), BufferName); if (!Buf) - return make_error_code(errc::not_enough_memory); + return errorCodeToError(errc::not_enough_memory); memcpy(Buf->getBufferStart(), InputData.data(), InputData.size()); return std::move(Buf); } @@ -140,7 +141,7 @@ return nullptr; } -ErrorOr> +Expected> MemoryBuffer::getFileOrSTDIN(const Twine &Filename, bool IsText, bool RequiresNullTerminator) { SmallString<256> NameBuf; @@ -152,7 +153,7 @@ /*IsVolatile=*/false); } -ErrorOr> +Expected> MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize, uint64_t Offset, bool IsVolatile) { return getFileAux(FilePath, MapSize, Offset, /*IsText=*/false, @@ -223,7 +224,7 @@ }; } // namespace -static ErrorOr> +static Expected> getMemoryBufferForStream(sys::fs::file_t FD, const Twine &BufferName) { const ssize_t ChunkSize = 4096*4; SmallString Buffer; @@ -232,8 +233,9 @@ Buffer.reserve(Buffer.size() + ChunkSize); Expected ReadBytes = sys::fs::readNativeFile( FD, makeMutableArrayRef(Buffer.end(), ChunkSize)); - if (!ReadBytes) - return errorToErrorCode(ReadBytes.takeError()); + if (Error E = ReadBytes.takeError()) + return make_error(BufferName + ": " + toString(std::move(E)), + inconvertibleErrorCode()); if (*ReadBytes == 0) break; Buffer.set_size(Buffer.size() + *ReadBytes); @@ -242,7 +244,7 @@ return getMemBufferCopyImpl(Buffer, BufferName); } -ErrorOr> +Expected> MemoryBuffer::getFile(const Twine &Filename, bool IsText, bool RequiresNullTerminator, bool IsVolatile) { return getFileAux(Filename, /*MapSize=*/-1, /*Offset=*/0, @@ -250,19 +252,19 @@ } template -static ErrorOr> +static Expected> getOpenFileImpl(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator, bool IsVolatile); template -static ErrorOr> +static Expected> getFileAux(const Twine &Filename, uint64_t MapSize, uint64_t Offset, bool IsText, bool RequiresNullTerminator, bool IsVolatile) { Expected FDOrErr = sys::fs::openNativeFileForRead( Filename, IsText ? sys::fs::OF_TextWithCRLF : sys::fs::OF_None); if (!FDOrErr) - return errorToErrorCode(FDOrErr.takeError()); + return FDOrErr.takeError(); sys::fs::file_t FD = *FDOrErr; auto Ret = getOpenFileImpl(FD, Filename, /*FileSize=*/-1, MapSize, Offset, RequiresNullTerminator, IsVolatile); @@ -270,14 +272,14 @@ return Ret; } -ErrorOr> +Expected> WritableMemoryBuffer::getFile(const Twine &Filename, bool IsVolatile) { return getFileAux( Filename, /*MapSize=*/-1, /*Offset=*/0, /*IsText=*/false, /*RequiresNullTerminator=*/false, IsVolatile); } -ErrorOr> +Expected> WritableMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset, bool IsVolatile) { return getFileAux( @@ -375,13 +377,13 @@ return true; } -static ErrorOr> +static Expected> getReadWriteFile(const Twine &Filename, uint64_t FileSize, uint64_t MapSize, uint64_t Offset) { Expected FDOrErr = sys::fs::openNativeFileForReadWrite( Filename, sys::fs::CD_OpenExisting, sys::fs::OF_None); if (!FDOrErr) - return errorToErrorCode(FDOrErr.takeError()); + return FDOrErr.takeError(); sys::fs::file_t FD = *FDOrErr; // Default is to map the full file. @@ -392,14 +394,14 @@ sys::fs::file_status Status; std::error_code EC = sys::fs::status(FD, Status); if (EC) - return EC; + return errorCodeToError(EC); // If this not a file or a block device (e.g. it's a named pipe // or character device), we can't mmap it, so error out. sys::fs::file_type Type = Status.type(); if (Type != sys::fs::file_type::regular_file && Type != sys::fs::file_type::block_file) - return make_error_code(errc::invalid_argument); + return errorCodeToError(errc::invalid_argument); FileSize = Status.getSize(); } @@ -412,24 +414,24 @@ MemoryBufferMMapFile(false, FD, MapSize, Offset, EC)); if (EC) - return EC; + return errorCodeToError(EC); return std::move(Result); } -ErrorOr> +Expected> WriteThroughMemoryBuffer::getFile(const Twine &Filename, int64_t FileSize) { return getReadWriteFile(Filename, FileSize, FileSize, 0); } /// Map a subrange of the specified file as a WritableMemoryBuffer. -ErrorOr> +Expected> WriteThroughMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset) { return getReadWriteFile(Filename, -1, MapSize, Offset); } template -static ErrorOr> +static Expected> getOpenFileImpl(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator, bool IsVolatile) { @@ -443,7 +445,7 @@ sys::fs::file_status Status; std::error_code EC = sys::fs::status(FD, Status); if (EC) - return EC; + return make_error(Filename + ": " + EC.message(), EC); // If this not a file or a block device (e.g. it's a named pipe // or character device), we can't trust the size. Create the memory @@ -478,7 +480,7 @@ if (!Buf) { // Failed to create a buffer. The only way it can fail is if // new(std::nothrow) returns 0. - return make_error_code(errc::not_enough_memory); + return errorCodeToError(errc::not_enough_memory); } // Read until EOF, zero-initialize the rest. @@ -487,7 +489,7 @@ Expected ReadBytes = sys::fs::readNativeFileSlice(FD, ToRead, Offset); if (!ReadBytes) - return errorToErrorCode(ReadBytes.takeError()); + return ReadBytes.takeError(); if (*ReadBytes == 0) { std::memset(ToRead.data(), 0, ToRead.size()); break; @@ -499,22 +501,24 @@ return std::move(Buf); } -ErrorOr> -MemoryBuffer::getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, - bool RequiresNullTerminator, bool IsVolatile) { +Expected> +MemoryBuffer::getOpenFile(sys::fs::file_t FD, const Twine &Filename, + uint64_t FileSize, bool RequiresNullTerminator, + bool IsVolatile) { return getOpenFileImpl(FD, Filename, FileSize, FileSize, 0, RequiresNullTerminator, IsVolatile); } -ErrorOr> -MemoryBuffer::getOpenFileSlice(sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize, - int64_t Offset, bool IsVolatile) { +Expected> +MemoryBuffer::getOpenFileSlice(sys::fs::file_t FD, const Twine &Filename, + uint64_t MapSize, int64_t Offset, + bool IsVolatile) { assert(MapSize != uint64_t(-1)); return getOpenFileImpl(FD, Filename, -1, MapSize, Offset, false, IsVolatile); } -ErrorOr> MemoryBuffer::getSTDIN() { +Expected> MemoryBuffer::getSTDIN() { // Read in all of the data from stdin, we cannot mmap stdin. // // FIXME: That isn't necessarily true, we should try to mmap stdin and @@ -524,14 +528,14 @@ return getMemoryBufferForStream(sys::fs::getStdinHandle(), ""); } -ErrorOr> +Expected> MemoryBuffer::getFileAsStream(const Twine &Filename) { Expected FDOrErr = sys::fs::openNativeFileForRead(Filename, sys::fs::OF_None); if (!FDOrErr) - return errorToErrorCode(FDOrErr.takeError()); + return FDOrErr.takeError(); sys::fs::file_t FD = *FDOrErr; - ErrorOr> Ret = + Expected> Ret = getMemoryBufferForStream(FD, Filename); sys::fs::closeFile(FD); return Ret; diff --git a/llvm/lib/Support/SourceMgr.cpp b/llvm/lib/Support/SourceMgr.cpp --- a/llvm/lib/Support/SourceMgr.cpp +++ b/llvm/lib/Support/SourceMgr.cpp @@ -41,19 +41,22 @@ SMLoc IncludeLoc, std::string &IncludedFile) { IncludedFile = Filename; - ErrorOr> NewBufOrErr = + Expected> NewBufOrErr = MemoryBuffer::getFile(IncludedFile); // If the file didn't exist directly, see if it's in an include path. for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBufOrErr; ++i) { + consumeError(NewBufOrErr.takeError()); IncludedFile = IncludeDirectories[i] + sys::path::get_separator().data() + Filename; NewBufOrErr = MemoryBuffer::getFile(IncludedFile); } - if (!NewBufOrErr) + if (!NewBufOrErr) { + consumeError(NewBufOrErr.takeError()); return 0; + } return AddNewSourceBuffer(std::move(*NewBufOrErr), IncludeLoc); } diff --git a/llvm/lib/Support/Unix/Path.inc b/llvm/lib/Support/Unix/Path.inc --- a/llvm/lib/Support/Unix/Path.inc +++ b/llvm/lib/Support/Unix/Path.inc @@ -1093,7 +1093,7 @@ int FD; std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode); if (EC) - return errorCodeToError(EC); + return createFileError(Name, EC); return FD; } @@ -1140,7 +1140,7 @@ file_t ResultFD; std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath); if (EC) - return errorCodeToError(EC); + return createFileError(Name, EC); return ResultFD; } diff --git a/llvm/lib/Support/VirtualFileSystem.cpp b/llvm/lib/Support/VirtualFileSystem.cpp --- a/llvm/lib/Support/VirtualFileSystem.cpp +++ b/llvm/lib/Support/VirtualFileSystem.cpp @@ -29,6 +29,7 @@ #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Errc.h" +#include "llvm/Support/Error.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/FileSystem.h" @@ -218,8 +219,8 @@ RealFile::getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, bool IsVolatile) { assert(FD != kInvalidFile && "cannot get buffer for closed file"); - return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator, - IsVolatile); + return expectedToErrorOr(MemoryBuffer::getOpenFile( + FD, Name, FileSize, RequiresNullTerminator, IsVolatile)); } std::error_code RealFile::close() { diff --git a/llvm/lib/Support/Windows/Path.inc b/llvm/lib/Support/Windows/Path.inc --- a/llvm/lib/Support/Windows/Path.inc +++ b/llvm/lib/Support/Windows/Path.inc @@ -1169,7 +1169,7 @@ std::error_code EC = openNativeFileInternal( Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit); if (EC) - return errorCodeToError(EC); + return createFileError(Name, EC); if (Flags & OF_UpdateAtime) { FILETIME FileTime; @@ -1179,14 +1179,14 @@ SetFileTime(Result, NULL, &FileTime, NULL) == 0) { DWORD LastError = ::GetLastError(); ::CloseHandle(Result); - return errorCodeToError(mapWindowsError(LastError)); + return createFileError(Name, mapWindowsError(LastError)); } } if (Flags & OF_Delete) { if ((EC = setDeleteDisposition(Result, true))) { ::CloseHandle(Result); - return errorCodeToError(EC); + return createFileError(Name, EC); } } return Result; diff --git a/llvm/lib/TableGen/Main.cpp b/llvm/lib/TableGen/Main.cpp --- a/llvm/lib/TableGen/Main.cpp +++ b/llvm/lib/TableGen/Main.cpp @@ -92,11 +92,11 @@ // Parse the input file. Records.startTimer("Parse, build records"); - ErrorOr> FileOrErr = + Expected> FileOrErr = MemoryBuffer::getFileOrSTDIN(InputFilename, /*IsText=*/true); - if (std::error_code EC = FileOrErr.getError()) + if (Error E = FileOrErr.takeError()) return reportError(argv0, "Could not open input file '" + InputFilename + - "': " + EC.message() + "\n"); + "': " + toString(std::move(E)) + "\n"); Records.saveInputFilename(InputFilename); diff --git a/llvm/lib/Target/BPF/BTFDebug.cpp b/llvm/lib/Target/BPF/BTFDebug.cpp --- a/llvm/lib/Target/BPF/BTFDebug.cpp +++ b/llvm/lib/Target/BPF/BTFDebug.cpp @@ -789,9 +789,12 @@ auto Source = File->getSource(); if (Source) Buf = MemoryBuffer::getMemBufferCopy(*Source); - else if (ErrorOr> BufOrErr = + else if (Expected> BufOrErr = MemoryBuffer::getFile(FileName)) Buf = std::move(*BufOrErr); + else { + consumeError(BufOrErr.takeError()); + } if (Buf) for (line_iterator I(*Buf, false), E; I != E; ++I) Content.push_back(std::string(*I)); diff --git a/llvm/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp b/llvm/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp --- a/llvm/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp +++ b/llvm/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp @@ -55,10 +55,12 @@ // Opens a file. Path has to be resolved already. std::unique_ptr openFile(const Twine &Path) { - ErrorOr> MB = MemoryBuffer::getFile(Path); + Expected> MB = + MemoryBuffer::getFile(Path); - if (std::error_code EC = MB.getError()) { - llvm::errs() << "cannot open file " << Path << ": " << EC.message() << "\n"; + if (Error E = MB.takeError()) { + llvm::errs() << "cannot open file " << Path << ": " + << toString(std::move(E)) << "\n"; return nullptr; } diff --git a/llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp b/llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp --- a/llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp +++ b/llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp @@ -112,9 +112,9 @@ std::unique_ptr B; for (auto *Arg : Args.filtered(OPT_INPUT)) { // Create or open the archive object. - ErrorOr> MaybeBuf = MemoryBuffer::getFile( + Expected> MaybeBuf = MemoryBuffer::getFile( Arg->getValue(), /*IsText=*/false, /*RequiresNullTerminator=*/false); - fatalOpenError(errorCodeToError(MaybeBuf.getError()), Arg->getValue()); + fatalOpenError(MaybeBuf.takeError(), Arg->getValue()); if (identify_magic(MaybeBuf.get()->getBuffer()) == file_magic::archive) { B = std::move(MaybeBuf.get()); @@ -339,9 +339,9 @@ continue; // Open a file. - ErrorOr> MOrErr = MemoryBuffer::getFile( + Expected> MOrErr = MemoryBuffer::getFile( Path, /*IsText=*/false, /*RequiresNullTerminator=*/false); - fatalOpenError(errorCodeToError(MOrErr.getError()), Path); + fatalOpenError(MOrErr.takeError(), Path); MemoryBufferRef MBRef = (*MOrErr)->getMemBufferRef(); // Append a file. diff --git a/llvm/lib/Transforms/IPO/BlockExtractor.cpp b/llvm/lib/Transforms/IPO/BlockExtractor.cpp --- a/llvm/lib/Transforms/IPO/BlockExtractor.cpp +++ b/llvm/lib/Transforms/IPO/BlockExtractor.cpp @@ -121,8 +121,9 @@ /// Gets all of the blocks specified in the input file. void BlockExtractor::loadFile() { auto ErrOrBuf = MemoryBuffer::getFile(BlockExtractorFile); - if (ErrOrBuf.getError()) - report_fatal_error("BlockExtractor couldn't load the file."); + if (Error E = ErrOrBuf.takeError()) + report_fatal_error("BlockExtractor couldn't load the file: " + + toString(std::move(E))); // Read the file. auto &Buf = *ErrOrBuf; SmallVector Lines; diff --git a/llvm/lib/Transforms/IPO/Internalize.cpp b/llvm/lib/Transforms/IPO/Internalize.cpp --- a/llvm/lib/Transforms/IPO/Internalize.cpp +++ b/llvm/lib/Transforms/IPO/Internalize.cpp @@ -75,11 +75,11 @@ void LoadFile(StringRef Filename) { // Load the APIFile... - ErrorOr> Buf = + Expected> Buf = MemoryBuffer::getFile(Filename); - if (!Buf) { - errs() << "WARNING: Internalize couldn't load file '" << Filename - << "'! Continuing as if it's empty.\n"; + if (Error E = Buf.takeError()) { + errs() << "WARNING: Internalize couldn't load file '" << Filename << "' (" + << toString(std::move(E)) << ")! Continuing as if it's empty.\n"; return; // Just continue as if the file were empty } for (line_iterator I(*Buf->get(), true), E; I != E; ++I) diff --git a/llvm/lib/Transforms/IPO/LowerTypeTests.cpp b/llvm/lib/Transforms/IPO/LowerTypeTests.cpp --- a/llvm/lib/Transforms/IPO/LowerTypeTests.cpp +++ b/llvm/lib/Transforms/IPO/LowerTypeTests.cpp @@ -1709,8 +1709,7 @@ if (!ClReadSummary.empty()) { ExitOnError ExitOnErr("-lowertypetests-read-summary: " + ClReadSummary + ": "); - auto ReadSummaryFile = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary))); + auto ReadSummaryFile = ExitOnErr(MemoryBuffer::getFile(ClReadSummary)); yaml::Input In(ReadSummaryFile->getBuffer()); In >> Summary; diff --git a/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp b/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp --- a/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp +++ b/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp @@ -891,8 +891,7 @@ if (!ClReadSummary.empty()) { ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary + ": "); - auto ReadSummaryFile = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary))); + auto ReadSummaryFile = ExitOnErr(MemoryBuffer::getFile(ClReadSummary)); if (Expected> SummaryOrErr = getModuleSummaryIndex(*ReadSummaryFile)) { Summary = std::move(*SummaryOrErr); diff --git a/llvm/lib/Transforms/Utils/SymbolRewriter.cpp b/llvm/lib/Transforms/Utils/SymbolRewriter.cpp --- a/llvm/lib/Transforms/Utils/SymbolRewriter.cpp +++ b/llvm/lib/Transforms/Utils/SymbolRewriter.cpp @@ -252,12 +252,12 @@ bool RewriteMapParser::parse(const std::string &MapFile, RewriteDescriptorList *DL) { - ErrorOr> Mapping = + Expected> Mapping = MemoryBuffer::getFile(MapFile); - if (!Mapping) - report_fatal_error("unable to read rewrite map '" + MapFile + "': " + - Mapping.getError().message()); + if (Error E = Mapping.takeError()) + report_fatal_error("unable to read rewrite map '" + MapFile + + "': " + toString(std::move(E))); if (!parse(*Mapping, DL)) report_fatal_error("unable to parse rewrite map '" + MapFile + "'"); diff --git a/llvm/test/DebugInfo/symbolize-missing-file.test b/llvm/test/DebugInfo/symbolize-missing-file.test --- a/llvm/test/DebugInfo/symbolize-missing-file.test +++ b/llvm/test/DebugInfo/symbolize-missing-file.test @@ -1,3 +1,3 @@ RUN: llvm-symbolizer --obj=unexisting-file 0x1234 2>&1 | FileCheck -DMSG=%errc_ENOENT %s -CHECK: LLVMSymbolizer: error reading file: [[MSG]] +CHECK: LLVMSymbolizer: error reading file: 'unexisting-file': [[MSG]] diff --git a/llvm/test/MC/Hexagon/not_found.s b/llvm/test/MC/Hexagon/not_found.s --- a/llvm/test/MC/Hexagon/not_found.s +++ b/llvm/test/MC/Hexagon/not_found.s @@ -1,4 +1,4 @@ # RUN: not llvm-mc -arch=hexagon -filetype=asm junk123.s 2>%t ; FileCheck -DMSG=%errc_ENOENT %s < %t # -# CHECK: junk123.s: [[MSG]] +# CHECK: 'junk123.s': [[MSG]] diff --git a/llvm/test/Object/ar-create.test b/llvm/test/Object/ar-create.test --- a/llvm/test/Object/ar-create.test +++ b/llvm/test/Object/ar-create.test @@ -13,5 +13,5 @@ RUN: llvm-ar r %t.foo.a %t 2>&1 | FileCheck --check-prefix=CREATE %s RUN: rm -f %t.foo.a -CHECK: llvm-ar{{(.exe|.EXE)?}}: error: unable to load '{{[^']+}}.foo.a': +CHECK: llvm-ar{{(.exe|.EXE)?}}: error: unable to load: '{{[^']+}}.foo.a': CREATE: creating {{.*}}.foo.a diff --git a/llvm/test/Object/ar-error.test b/llvm/test/Object/ar-error.test --- a/llvm/test/Object/ar-error.test +++ b/llvm/test/Object/ar-error.test @@ -3,4 +3,4 @@ RUN: not llvm-ar r %t.out.a sparkle.o %t 2>&1 | FileCheck %s # Don't check the message "No such file or directory". -CHECK: llvm-ar{{(.exe|.EXE)?}}: error: sparkle.o: +CHECK: llvm-ar{{(.exe|.EXE)?}}: error: 'sparkle.o': diff --git a/llvm/test/Object/archive-extract.test b/llvm/test/Object/archive-extract.test --- a/llvm/test/Object/archive-extract.test +++ b/llvm/test/Object/archive-extract.test @@ -58,4 +58,4 @@ EVENLEN: evenlen RUN: not llvm-ar p %p/Inputs/thin-path.a t/test2.o 2>&1 | FileCheck %s --DMSG=%errc_ENOENT --check-prefix=MISSING -MISSING: error: [[MSG]] +MISSING: error: '{{.*}}test2.o': [[MSG]] diff --git a/llvm/test/Object/directory.ll b/llvm/test/Object/directory.ll --- a/llvm/test/Object/directory.ll +++ b/llvm/test/Object/directory.ll @@ -1,6 +1,6 @@ ;RUN: rm -rf %t && mkdir -p %t ;RUN: not llvm-ar r %t/test.a . 2>&1 | FileCheck -DMSG=%errc_EISDIR %s -;CHECK: .: [[MSG]] +;CHECK: '.': [[MSG]] ;RUN: rm -f %t/test.a ;RUN: touch %t/a-very-long-file-name diff --git a/llvm/test/Object/invalid.test b/llvm/test/Object/invalid.test --- a/llvm/test/Object/invalid.test +++ b/llvm/test/Object/invalid.test @@ -536,7 +536,7 @@ # RUN: yaml2obj --docnum=24 %s -o %t24 # RUN: not obj2yaml 2>&1 %t24 | FileCheck %s -DFILE=%t24 --check-prefix=INVALID-SHSTRNDX -# INVALID-SHSTRNDX: Error reading file: [[FILE]]: section header string table index 255 does not exist +# INVALID-SHSTRNDX: error: '[[FILE]]': section header string table index 255 does not exist --- !ELF FileHeader: diff --git a/llvm/test/ObjectYAML/wasm/header_invalid_version.yaml b/llvm/test/ObjectYAML/wasm/header_invalid_version.yaml --- a/llvm/test/ObjectYAML/wasm/header_invalid_version.yaml +++ b/llvm/test/ObjectYAML/wasm/header_invalid_version.yaml @@ -3,4 +3,4 @@ FileHeader: Version: 0x00000002 ... -# CHECK: Error reading file: : invalid version number: 2 +# CHECK: error: '': invalid version number: 2 diff --git a/llvm/test/ObjectYAML/wasm/invalid_export.yaml b/llvm/test/ObjectYAML/wasm/invalid_export.yaml --- a/llvm/test/ObjectYAML/wasm/invalid_export.yaml +++ b/llvm/test/ObjectYAML/wasm/invalid_export.yaml @@ -10,4 +10,4 @@ Kind: FUNCTION Index: 0x00000001 -# CHECK: Error reading file: : invalid function export +# CHECK: error: '': invalid function export diff --git a/llvm/test/ObjectYAML/wasm/invalid_global_weak.yaml b/llvm/test/ObjectYAML/wasm/invalid_global_weak.yaml --- a/llvm/test/ObjectYAML/wasm/invalid_global_weak.yaml +++ b/llvm/test/ObjectYAML/wasm/invalid_global_weak.yaml @@ -22,4 +22,4 @@ Global: 0 ... -# CHECK: Error reading file: : undefined weak global symbol +# CHECK: error: '': undefined weak global symbol diff --git a/llvm/test/tools/llvm-ar/error-opening-directory.test b/llvm/test/tools/llvm-ar/error-opening-directory.test --- a/llvm/test/tools/llvm-ar/error-opening-directory.test +++ b/llvm/test/tools/llvm-ar/error-opening-directory.test @@ -9,4 +9,4 @@ # RUN: not llvm-ar p %t/tmpDir 2>&1 | \ # RUN: FileCheck %s --check-prefix=IS-DIR -DARCHIVE=%t/tmpDir -DMSG=%errc_EISDIR -# IS-DIR: error: unable to open '[[ARCHIVE]]': [[MSG]] +# IS-DIR: error: [[ARCHIVE]]: [[MSG]] diff --git a/llvm/test/tools/llvm-ar/error-opening-permission.test b/llvm/test/tools/llvm-ar/error-opening-permission.test --- a/llvm/test/tools/llvm-ar/error-opening-permission.test +++ b/llvm/test/tools/llvm-ar/error-opening-permission.test @@ -11,4 +11,4 @@ # RUN: not llvm-ar p %t/permission.b 2>&1 | \ # RUN: FileCheck %s --check-prefix=NO-PERMISSION -DARCHIVE=%t/permission.b -DMSG=%errc_EACCES -# NO-PERMISSION: error: unable to open '[[ARCHIVE]]': [[MSG]] +# NO-PERMISSION: error: '[[ARCHIVE]]': [[MSG]] diff --git a/llvm/test/tools/llvm-ar/missing-thin-archive-member.test b/llvm/test/tools/llvm-ar/missing-thin-archive-member.test --- a/llvm/test/tools/llvm-ar/missing-thin-archive-member.test +++ b/llvm/test/tools/llvm-ar/missing-thin-archive-member.test @@ -12,6 +12,6 @@ ## File has been deleted. # RUN: llvm-ar qT %t-archive.a %t-temp.txt # RUN: rm %t-temp.txt -# RUN: not llvm-ar p %t-archive.a 2>&1 | FileCheck -DMSG=%errc_ENOENT %s --check-prefix=DELETED +# RUN: not llvm-ar p %t-archive.a 2>&1 | FileCheck -DMSG=%errc_ENOENT -DFILE=%t-temp.txt %s --check-prefix=DELETED -# DELETED: error: [[MSG]] +# DELETED: error: '[[FILE]]': [[MSG]] diff --git a/llvm/test/tools/llvm-ar/move.test b/llvm/test/tools/llvm-ar/move.test --- a/llvm/test/tools/llvm-ar/move.test +++ b/llvm/test/tools/llvm-ar/move.test @@ -84,7 +84,7 @@ # RUN: not llvm-ar m %t/missing.a %t/missing.txt 2>&1 \ # RUN: | FileCheck %s --check-prefix=MISSING-FILE -DFILE=%t/missing.txt -DMSG=%errc_ENOENT -# MISSING-FILE: error: [[FILE]]: [[MSG]] +# MISSING-FILE: error: '[[FILE]]': [[MSG]] --- !ELF FileHeader: diff --git a/llvm/test/tools/llvm-ar/print.test b/llvm/test/tools/llvm-ar/print.test --- a/llvm/test/tools/llvm-ar/print.test +++ b/llvm/test/tools/llvm-ar/print.test @@ -80,7 +80,7 @@ # RUN: not llvm-ar p %t/missing.a 2>&1 \ # RUN: | FileCheck -DMSG=%errc_ENOENT %s --check-prefix=MISSING-ARCHIVE -DARCHIVE=%t/missing.a -# MISSING-ARCHIVE: error: unable to load '[[ARCHIVE]]': [[MSG]] +# MISSING-ARCHIVE: error: unable to load: '[[ARCHIVE]]': [[MSG]] ## Member does not exist: # RUN: not llvm-ar p %t/archive.a %t-missing.txt 2>&1 \ diff --git a/llvm/test/tools/llvm-ar/quick-append.test b/llvm/test/tools/llvm-ar/quick-append.test --- a/llvm/test/tools/llvm-ar/quick-append.test +++ b/llvm/test/tools/llvm-ar/quick-append.test @@ -60,7 +60,7 @@ # RUN: not llvm-ar qc %t/missing.a %t/missing.txt 2>&1 \ # RUN: | FileCheck %s --check-prefix=MISSING-FILE -DFILE=%t/missing.txt -DMSG=%errc_ENOENT -# MISSING-FILE: error: [[FILE]]: [[MSG]] +# MISSING-FILE: error: '[[FILE]]': [[MSG]] ## Create and append members to a thin archive: # RUN: llvm-ar qcT %t/thin-multiple.a %t/1.o diff --git a/llvm/test/tools/llvm-ar/replace.test b/llvm/test/tools/llvm-ar/replace.test --- a/llvm/test/tools/llvm-ar/replace.test +++ b/llvm/test/tools/llvm-ar/replace.test @@ -91,7 +91,7 @@ # RUN: not llvm-ar r %t/missing.a %t/missing.txt 2>&1 \ # RUN: | FileCheck %s --check-prefix=MISSING-FILE -DFILE=%t/missing.txt -DMSG=%errc_ENOENT -# MISSING-FILE: error: [[FILE]]: [[MSG]] +# MISSING-FILE: error: '[[FILE]]': [[MSG]] ## Create and Replace member of thin archive: # RUN: llvm-ar rcT %t/thin.a %t/1.o %t/2.o %t/3.o diff --git a/llvm/test/tools/llvm-ar/response.test b/llvm/test/tools/llvm-ar/response.test --- a/llvm/test/tools/llvm-ar/response.test +++ b/llvm/test/tools/llvm-ar/response.test @@ -34,8 +34,8 @@ # RUN: echo -e 'rc %/t.a blah\\foo' > %t-rsp.txt # RUN: not llvm-ar --rsp-quoting=windows @%t-rsp.txt 2>&1 | \ # RUN: FileCheck -DMSG=%errc_ENOENT %s --check-prefix=WIN -# WIN: error: blah\foo: [[MSG]] +# WIN: error: 'blah\foo': [[MSG]] # RUN: not llvm-ar -rsp-quoting posix @%t-rsp.txt 2>&1 | \ # RUN: FileCheck -DMSG=%errc_ENOENT %s --check-prefix=POSIX -# POSIX: error: blahfoo: [[MSG]] +# POSIX: error: 'blahfoo': [[MSG]] diff --git a/llvm/test/tools/llvm-ifs/fail-file-open.test b/llvm/test/tools/llvm-ifs/fail-file-open.test --- a/llvm/test/tools/llvm-ifs/fail-file-open.test +++ b/llvm/test/tools/llvm-ifs/fail-file-open.test @@ -1,5 +1,5 @@ -# RUN: not llvm-ifs --output-format=IFS --output=%t.tbe %s.NotAFileInTestingDir 2>&1 | FileCheck %s +# RUN: not llvm-ifs --output-format=IFS --output=%t.tbe %s.NotAFileInTestingDir 2>&1 | FileCheck -DMSG=%errc_ENOENT %s This file will not be read. An invalid file path is fed to llvm-ifs. -# CHECK: error: Could not open `{{.*}}.NotAFileInTestingDir` +# CHECK: error: '{{.*}}.NotAFileInTestingDir': [[MSG]] diff --git a/llvm/test/tools/llvm-libtool-darwin/L-and-l.test b/llvm/test/tools/llvm-libtool-darwin/L-and-l.test --- a/llvm/test/tools/llvm-libtool-darwin/L-and-l.test +++ b/llvm/test/tools/llvm-libtool-darwin/L-and-l.test @@ -1,4 +1,4 @@ -## This test checks that -l and -L options work correctly. +g# This test checks that -l and -L options work correctly. # RUN: yaml2obj %S/Inputs/input1.yaml -o %t-input1.o # RUN: yaml2obj %S/Inputs/input2.yaml -o %t-input2.o diff --git a/llvm/test/tools/llvm-libtool-darwin/archive-flattening.test b/llvm/test/tools/llvm-libtool-darwin/archive-flattening.test --- a/llvm/test/tools/llvm-libtool-darwin/archive-flattening.test +++ b/llvm/test/tools/llvm-libtool-darwin/archive-flattening.test @@ -91,7 +91,7 @@ # RUN: not llvm-libtool-darwin -static -o %t.lib %t.not-macho.ar 2>&1 | \ # RUN: FileCheck %s --check-prefix=NOT-MACHO -DARCHIVE=%t.not-macho.ar -DFILE=%basename_t.tmp.elf -# NOT-MACHO: error: '[[ARCHIVE]]': '[[FILE]]': format not supported +# NOT-MACHO: error: '[[ARCHIVE]]': [[FILE]]: format not supported --- !ELF FileHeader: diff --git a/llvm/test/tools/llvm-libtool-darwin/filelist.test b/llvm/test/tools/llvm-libtool-darwin/filelist.test --- a/llvm/test/tools/llvm-libtool-darwin/filelist.test +++ b/llvm/test/tools/llvm-libtool-darwin/filelist.test @@ -1,4 +1,4 @@ -## This test checks that the -filelist option works correctly. +g# This test checks that the -filelist option works correctly. # RUN: yaml2obj %S/Inputs/input1.yaml -o %t-input1.o # RUN: yaml2obj %S/Inputs/input2.yaml -o %t-input2.o diff --git a/llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test b/llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test --- a/llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test +++ b/llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test @@ -42,7 +42,7 @@ # RUN: not llvm-libtool-darwin -static -o %t.lib %t.elf 2>&1 | \ # RUN: FileCheck %s --check-prefix=NOT-MACHO -DFILE=%basename_t.tmp.elf -# NOT-MACHO: error: '[[FILE]]': format not supported +# NOT-MACHO: error: [[FILE]]: format not supported --- !ELF FileHeader: diff --git a/llvm/test/tools/llvm-mc/basic.test b/llvm/test/tools/llvm-mc/basic.test --- a/llvm/test/tools/llvm-mc/basic.test +++ b/llvm/test/tools/llvm-mc/basic.test @@ -1,3 +1,3 @@ # RUN: not llvm-mc %t.blah -o /dev/null 2>&1 | FileCheck -DMSG=%errc_ENOENT --check-prefix=ENOENT %s -# ENOENT: {{.*}}.blah: [[MSG]] +# ENOENT: error: '{{.*}}.blah': [[MSG]] diff --git a/llvm/test/tools/llvm-mca/invalid_input_file_name.test b/llvm/test/tools/llvm-mca/invalid_input_file_name.test --- a/llvm/test/tools/llvm-mca/invalid_input_file_name.test +++ b/llvm/test/tools/llvm-mca/invalid_input_file_name.test @@ -1,3 +1,3 @@ # RUN: not llvm-mca %t.blah -o /dev/null 2>&1 | FileCheck -DMSG=%errc_ENOENT --check-prefix=ENOENT %s -# ENOENT: {{.*}}.blah: [[MSG]] +# ENOENT: error: '{{.*}}.blah': [[MSG]] diff --git a/llvm/test/tools/llvm-ml/basic.test b/llvm/test/tools/llvm-ml/basic.test --- a/llvm/test/tools/llvm-ml/basic.test +++ b/llvm/test/tools/llvm-ml/basic.test @@ -1,3 +1,3 @@ # RUN: not llvm-ml %t.blah.asm /Fo /dev/null 2>&1 | FileCheck -DMSG=%errc_ENOENT --check-prefix=ENOENT %s -# ENOENT: {{.*}}.blah.asm: [[MSG]] +# ENOENT: error: '{{.*}}.blah.asm': [[MSG]] diff --git a/llvm/test/tools/llvm-readobj/ELF/thin-archive-paths.test b/llvm/test/tools/llvm-readobj/ELF/thin-archive-paths.test --- a/llvm/test/tools/llvm-readobj/ELF/thin-archive-paths.test +++ b/llvm/test/tools/llvm-readobj/ELF/thin-archive-paths.test @@ -16,7 +16,7 @@ # RUN: rm a/b/1.o # RUN: not llvm-readobj --file-headers a/relative.a 2>&1 | FileCheck %s --check-prefix=ERR1 -DMSG=%errc_ENOENT # RUN: not llvm-readelf --file-headers a/relative.a 2>&1 | FileCheck %s --check-prefix=ERR1 -DMSG=%errc_ENOENT -# ERR1: error: 'a/relative.a': 'b/1.o': [[MSG]] +# ERR1: error: 'a/relative.a': 'a/b/1.o': [[MSG]] # RUN: mkdir -p %t/c # RUN: yaml2obj %s -o a/b/1.o diff --git a/llvm/test/tools/llvm-sim/fail-cases.test b/llvm/test/tools/llvm-sim/fail-cases.test --- a/llvm/test/tools/llvm-sim/fail-cases.test +++ b/llvm/test/tools/llvm-sim/fail-cases.test @@ -1,8 +1,8 @@ # RUN: not llvm-sim %s 2>&1 | FileCheck %s -# RUN: not llvm-sim %s.2 2>&1 | FileCheck -DMSG=%errc_ENOENT %s --check-prefix=EXIST +# RUN: not llvm-sim %s.2 2>&1 | FileCheck -DMSG=%errc_ENOENT -DFILE=%s.2 %s --check-prefix=EXIST # File reading error messaging tests. # CHECK: error: expected top-level entity -# EXIST: error: Could not open input file: [[MSG]] +# EXIST: error: Could not open input file: '[[FILE]]': [[MSG]] diff --git a/llvm/test/tools/llvm-symbolizer/output-style-inlined.test b/llvm/test/tools/llvm-symbolizer/output-style-inlined.test --- a/llvm/test/tools/llvm-symbolizer/output-style-inlined.test +++ b/llvm/test/tools/llvm-symbolizer/output-style-inlined.test @@ -33,17 +33,17 @@ ## is specified, but a file doesn't exist. Check we report an error. RUN: llvm-symbolizer --output-style=GNU --obj=%p/Inputs/not.exist 0x1 0x2 --no-inlines 2>&1 \ -RUN: | FileCheck %s --check-prefix=NOT-EXIST-GNU -DMSG=%errc_ENOENT +RUN: | FileCheck %s --check-prefix=NOT-EXIST-GNU -DMSG=%errc_ENOENT -DFILE=%p/Inputs/not.exist RUN: llvm-symbolizer --output-style=LLVM --obj=%p/Inputs/not.exist 0x1 0x2 --no-inlines 2>&1 \ -RUN: | FileCheck %s --check-prefix=NOT-EXIST-LLVM -DMSG=%errc_ENOENT +RUN: | FileCheck %s --check-prefix=NOT-EXIST-LLVM -DMSG=%errc_ENOENT -DFILE=%p/Inputs/not.exist -# NOT-EXIST-GNU: LLVMSymbolizer: error reading file: [[MSG]] +# NOT-EXIST-GNU: LLVMSymbolizer: error reading file: '[[FILE]]': [[MSG]] # NOT-EXIST-GNU-NEXT: ?? # NOT-EXIST-GNU-NEXT: ??:0 # NOT-EXIST-GNU-NEXT: ?? # NOT-EXIST-GNU-NEXT: ??:0 -# NOT-EXIST-LLVM: LLVMSymbolizer: error reading file: [[MSG]] +# NOT-EXIST-LLVM: LLVMSymbolizer: error reading file: '[[FILE]]': [[MSG]] # NOT-EXIST-LLVM-NEXT: ?? # NOT-EXIST-LLVM-NEXT: ??:0:0 # NOT-EXIST-LLVM-EMPTY: diff --git a/llvm/test/tools/llvm-tapi-diff/tapi-diff-misspelled-tbd.test b/llvm/test/tools/llvm-tapi-diff/tapi-diff-misspelled-tbd.test --- a/llvm/test/tools/llvm-tapi-diff/tapi-diff-misspelled-tbd.test +++ b/llvm/test/tools/llvm-tapi-diff/tapi-diff-misspelled-tbd.test @@ -1,5 +1,5 @@ -; RUN: not llvm-tapi-diff %S/Inputs/v4A.tbd %S/Inputs/v4.tbd 2>&1 | FileCheck %s +; RUN: not llvm-tapi-diff %S/Inputs/v4A.tbd %S/Inputs/v4.tbd 2>&1 | FileCheck -DMSG=%errc_ENOENT %s -; CHECK: {{.*}}: error: {{.*}}v4.tbd: {{[Nn]}}o such file or directory +; CHECK: {{.*}}: error: '{{.*}}v4.tbd': [[MSG]] ; CHECK-NOT: error: ; CHECK-NOT: warning: diff --git a/llvm/test/tools/obj2yaml/Archives/regular.yaml b/llvm/test/tools/obj2yaml/Archives/regular.yaml --- a/llvm/test/tools/obj2yaml/Archives/regular.yaml +++ b/llvm/test/tools/obj2yaml/Archives/regular.yaml @@ -91,7 +91,7 @@ # RUN: not obj2yaml %t.not.regular.a 2>&1 | \ # RUN: FileCheck %s -DFILE=%t.not.regular.a --check-prefix=NOT-REGULAR-ERR -# NOT-REGULAR-ERR: Error reading file: [[FILE]]: only regular archives are supported +# NOT-REGULAR-ERR: error: '[[FILE]]': only regular archives are supported --- !Arch Magic: "!\n" @@ -104,7 +104,7 @@ # RUN: not obj2yaml %t.truncated.a 2>&1 | \ # RUN: FileCheck %s -DFILE=%t.truncated.a --check-prefix=TRUNCATED-ERR -# TRUNCATED-ERR: Error reading file: [[FILE]]: unable to read the header of a child at offset 0x8 +# TRUNCATED-ERR: error: '[[FILE]]': unable to read the header of a child at offset 0x8 --- !Arch Content: "00" @@ -115,7 +115,7 @@ # RUN: not obj2yaml %t.entdata.a 2>&1 | \ # RUN: FileCheck %s -DFILE=%t.entdata.a --check-prefix=ENTDATA-ERR -# ENTDATA-ERR: Error reading file: [[FILE]]: unable to read the data of a child at offset 0x8 of size 1: the remaining archive size is 0 +# ENTDATA-ERR: error: '[[FILE]]': unable to read the data of a child at offset 0x8 of size 1: the remaining archive size is 0 --- !Arch Members: @@ -127,7 +127,7 @@ # RUN: not obj2yaml %t.entsize.a 2>&1 | \ # RUN: FileCheck %s -DFILE=%t.entsize.a --check-prefix=ENTSIZE-ERR -# ENTSIZE-ERR: Error reading file: [[FILE]]: unable to read the size of a child at offset 0x8 as integer: "x" +# ENTSIZE-ERR: error: '[[FILE]]': unable to read the size of a child at offset 0x8 as integer: "x" ## Check we don't try to dump the padding byte when the size of the content is odd and ## the content ends at the end of a file. diff --git a/llvm/test/tools/obj2yaml/ELF/entsize.yaml b/llvm/test/tools/obj2yaml/ELF/entsize.yaml --- a/llvm/test/tools/obj2yaml/ELF/entsize.yaml +++ b/llvm/test/tools/obj2yaml/ELF/entsize.yaml @@ -40,7 +40,7 @@ # RUN: yaml2obj %s -DSYMTABES=0x19 -o %t2 # RUN: not obj2yaml %t2 2>&1 | FileCheck %s -DFILE=%t2 --check-prefix=ERR1 -# ERR1: Error reading file: [[FILE]]: section [index 2] has invalid sh_entsize: expected 24, but got 25 +# ERR1: error: '[[FILE]]': section [index 2] has invalid sh_entsize: expected 24, but got 25 ## Document that we are unable to dump a SHT_DYNSYM section when its entry size ## is not equal to sizeof(ELF_Sym). @@ -48,4 +48,4 @@ # RUN: yaml2obj %s -DDYNSYMES=0x19 -o %t3 # RUN: not obj2yaml %t3 2>&1 | FileCheck %s -DFILE=%t3 --check-prefix=ERR2 -# ERR2: Error reading file: [[FILE]]: section [index 3] has invalid sh_entsize: expected 24, but got 25 +# ERR2: error: '[[FILE]]': section [index 3] has invalid sh_entsize: expected 24, but got 25 diff --git a/llvm/test/tools/obj2yaml/ELF/section-group.yaml b/llvm/test/tools/obj2yaml/ELF/section-group.yaml --- a/llvm/test/tools/obj2yaml/ELF/section-group.yaml +++ b/llvm/test/tools/obj2yaml/ELF/section-group.yaml @@ -42,7 +42,7 @@ # RUN: not obj2yaml %t1.entsize.o 2>&1 | \ # RUN: FileCheck %s -DFILE=%t1.entsize.o --check-prefix=ENTSIZE -# ENTSIZE: Error reading file: [[FILE]]: section [index 1] has invalid sh_entsize: expected 4, but got 254 +# ENTSIZE: error: '[[FILE]]': section [index 1] has invalid sh_entsize: expected 4, but got 254 ## Check we are able to dump members of the SHT_GROUP section even when ## one of them has section index 0. @@ -56,4 +56,4 @@ # RUN: yaml2obj -DINFO=0xFF %s -o %t2.o # RUN: not obj2yaml %t2.o 2>&1 | FileCheck %s -DFILE=%t2.o --check-prefix=ERR -# ERR: Error reading file: [[FILE]]: unable to get symbol from section [index 3]: invalid symbol index (255) +# ERR: error: '[[FILE]]': unable to get symbol from section [index 3]: invalid symbol index (255) diff --git a/llvm/test/tools/obj2yaml/ELF/shlink.yaml b/llvm/test/tools/obj2yaml/ELF/shlink.yaml --- a/llvm/test/tools/obj2yaml/ELF/shlink.yaml +++ b/llvm/test/tools/obj2yaml/ELF/shlink.yaml @@ -5,7 +5,7 @@ # RUN: yaml2obj --docnum=1 %s -o %t1.o # RUN: not obj2yaml %t1.o 2>&1 | FileCheck %s -DFILE=%t1.o --check-prefix=ERR1 -## ERR1: Error reading file: [[FILE]]: unable to resolve sh_link reference in section '.test': invalid section index: 100 +## ERR1: error: '[[FILE]]': unable to resolve sh_link reference in section '.test': invalid section index: 100 --- !ELF FileHeader: diff --git a/llvm/test/tools/obj2yaml/ELF/sht-symtab-shndx.yaml b/llvm/test/tools/obj2yaml/ELF/sht-symtab-shndx.yaml --- a/llvm/test/tools/obj2yaml/ELF/sht-symtab-shndx.yaml +++ b/llvm/test/tools/obj2yaml/ELF/sht-symtab-shndx.yaml @@ -50,7 +50,7 @@ # RUN: yaml2obj --docnum=2 %s -o %t2 # RUN: not obj2yaml %t2 2>&1 | FileCheck %s -DFILE=%t2 --check-prefix=CASE2 -# CASE2: Error reading file: [[FILE]]: found an extended symbol index (1), but unable to locate the extended symbol index table +# CASE2: error: '[[FILE]]': found an extended symbol index (1), but unable to locate the extended symbol index table --- !ELF FileHeader: @@ -68,7 +68,7 @@ # RUN: yaml2obj --docnum=3 %s -o %t3 # RUN: not obj2yaml %t3 2>&1 | FileCheck %s -DFILE=%t3 --check-prefix=CASE3 -# CASE3: Error reading file: [[FILE]]: invalid section index: 254 +# CASE3: error: '[[FILE]]': invalid section index: 254 --- !ELF FileHeader: @@ -93,7 +93,7 @@ # RUN: yaml2obj --docnum=4 %s -o %t4 # RUN: not obj2yaml %t4 2>&1 | FileCheck %s -DFILE=%t4 --check-prefix=CASE4 -## CASE4: Error reading file: [[FILE]]: unable to read extended section indexes: SHT_SYMTAB_SHNDX has 3 entries, but the symbol table associated has 2 +## CASE4: error: '[[FILE]]': unable to read extended section indexes: SHT_SYMTAB_SHNDX has 3 entries, but the symbol table associated has 2 --- !ELF FileHeader: @@ -119,7 +119,7 @@ # RUN: yaml2obj --docnum=5 %s -o %t5 # RUN: not obj2yaml %t5 2>&1 | FileCheck %s -DFILE=%t5 --check-prefix=CASE5 -# CASE5: Error reading file: [[FILE]]: multiple SHT_SYMTAB_SHNDX sections are linked to the same symbol table with index 5 +# CASE5: error: '[[FILE]]': multiple SHT_SYMTAB_SHNDX sections are linked to the same symbol table with index 5 --- !ELF FileHeader: @@ -171,7 +171,7 @@ # RUN: yaml2obj --docnum=6 %s -o %t6 # RUN: not obj2yaml %t6 2>&1 | FileCheck %s -DFILE=%t6 --check-prefix=CASE6 -# CASE6: Error reading file: [[FILE]]: unable to read extended section indexes: SHT_SYMTAB_SHNDX section is linked with SHT_PROGBITS section (expected SHT_SYMTAB/SHT_DYNSYM) +# CASE6: error: '[[FILE]]': unable to read extended section indexes: SHT_SYMTAB_SHNDX section is linked with SHT_PROGBITS section (expected SHT_SYMTAB/SHT_DYNSYM) --- !ELF FileHeader: @@ -193,7 +193,7 @@ # RUN: not obj2yaml %t7.entsize.bad 2>&1 | \ # RUN: FileCheck %s -DFILE=%t7.entsize.bad --check-prefix=CASE7-BAD -# CASE7-BAD: Error reading file: [[FILE]]: unable to read extended section indexes: section [index 1] has invalid sh_entsize: expected 4, but got 255 +# CASE7-BAD: error: '[[FILE]]': unable to read extended section indexes: section [index 1] has invalid sh_entsize: expected 4, but got 255 ## Check we don't print the "EntSize" field when the "sh_entsize" field has the default value. diff --git a/llvm/test/tools/obj2yaml/ELF/verdef-section.yaml b/llvm/test/tools/obj2yaml/ELF/verdef-section.yaml --- a/llvm/test/tools/obj2yaml/ELF/verdef-section.yaml +++ b/llvm/test/tools/obj2yaml/ELF/verdef-section.yaml @@ -80,4 +80,4 @@ # RUN: not obj2yaml %t.version 2>&1 | \ # RUN: FileCheck %s -DFILE=%t.version --check-prefix=VERSION-ERR -# VERSION-ERR: Error reading file: [[FILE]]: invalid SHT_GNU_verdef section version: 2 +# VERSION-ERR: error: '[[FILE]]': invalid SHT_GNU_verdef section version: 2 diff --git a/llvm/test/tools/obj2yaml/invalid_input_file.test b/llvm/test/tools/obj2yaml/invalid_input_file.test --- a/llvm/test/tools/obj2yaml/invalid_input_file.test +++ b/llvm/test/tools/obj2yaml/invalid_input_file.test @@ -1,3 +1,3 @@ # RUN: not obj2yaml %p/path/does/not/exist 2>&1 | FileCheck -DMSG=%errc_ENOENT %s -# CHECK: Error reading file: {{.*}}/path/does/not/exist: [[MSG]] +# CHECK: error: '{{.*}}/path/does/not/exist': [[MSG]] diff --git a/llvm/tools/dsymutil/BinaryHolder.cpp b/llvm/tools/dsymutil/BinaryHolder.cpp --- a/llvm/tools/dsymutil/BinaryHolder.cpp +++ b/llvm/tools/dsymutil/BinaryHolder.cpp @@ -13,6 +13,7 @@ #include "BinaryHolder.h" #include "llvm/Object/MachO.h" +#include "llvm/Support/Error.h" #include "llvm/Support/WithColor.h" #include "llvm/Support/raw_ostream.h" @@ -49,9 +50,10 @@ // Try to load archive and force it to be memory mapped. auto ErrOrBuff = (ArchiveFilename == "-") ? MemoryBuffer::getSTDIN() - : VFS->getBufferForFile(ArchiveFilename, -1, false); - if (auto Err = ErrOrBuff.getError()) - return errorCodeToError(Err); + : errorOrToExpected( + VFS->getBufferForFile(ArchiveFilename, -1, false)); + if (Error E = ErrOrBuff.takeError()) + return E; MemBuffer = std::move(*ErrOrBuff); @@ -90,11 +92,12 @@ StringRef Filename, TimestampTy Timestamp, bool Verbose) { // Try to load regular binary and force it to be memory mapped. - auto ErrOrBuff = (Filename == "-") - ? MemoryBuffer::getSTDIN() - : VFS->getBufferForFile(Filename, -1, false); - if (auto Err = ErrOrBuff.getError()) - return errorCodeToError(Err); + auto ErrOrBuff = + (Filename == "-") + ? MemoryBuffer::getSTDIN() + : errorOrToExpected(VFS->getBufferForFile(Filename, -1, false)); + if (Error E = ErrOrBuff.takeError()) + return E; if (Filename != "-" && Timestamp != sys::TimePoint<>()) { llvm::ErrorOr Stat = VFS->status(Filename); diff --git a/llvm/tools/dsymutil/DebugMap.cpp b/llvm/tools/dsymutil/DebugMap.cpp --- a/llvm/tools/dsymutil/DebugMap.cpp +++ b/llvm/tools/dsymutil/DebugMap.cpp @@ -127,8 +127,8 @@ DebugMap::parseYAMLDebugMap(StringRef InputFile, StringRef PrependPath, bool Verbose) { auto ErrOrFile = MemoryBuffer::getFileOrSTDIN(InputFile); - if (auto Err = ErrOrFile.getError()) - return Err; + if (Error E = ErrOrFile.takeError()) + return errorToErrorCode(std::move(E)); YAMLContext Ctxt; diff --git a/llvm/tools/dsymutil/SymbolMap.cpp b/llvm/tools/dsymutil/SymbolMap.cpp --- a/llvm/tools/dsymutil/SymbolMap.cpp +++ b/llvm/tools/dsymutil/SymbolMap.cpp @@ -116,8 +116,8 @@ } auto ErrOrMemBuffer = MemoryBuffer::getFile(SymbolMapPath); - if (auto EC = ErrOrMemBuffer.getError()) { - WithColor::warning() << SymbolMapPath << ": " << EC.message() + if (Error E = ErrOrMemBuffer.takeError()) { + WithColor::warning() << SymbolMapPath << ": " << toString(std::move(E)) << ": not unobfuscating.\n"; return {}; } diff --git a/llvm/tools/lli/lli.cpp b/llvm/tools/lli/lli.cpp --- a/llvm/tools/lli/lli.cpp +++ b/llvm/tools/lli/lli.cpp @@ -325,12 +325,14 @@ if (!getCacheFilename(ModuleID, CacheName)) return nullptr; // Load the object from the cache filename - ErrorOr> IRObjectBuffer = + Expected> IRObjectBuffer = MemoryBuffer::getFile(CacheName, /*IsText=*/false, /*RequiresNullTerminator=*/false); // If the file isn't there, that's OK. - if (!IRObjectBuffer) + if (Error E = IRObjectBuffer.takeError()) { + consumeError(std::move(E)); return nullptr; + } // MCJIT will want to write into this buffer, and we don't want that // because the file has probably just been mmapped. Instead we make // a copy. The filed-based buffer will be released when it goes @@ -559,10 +561,12 @@ } for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) { - ErrorOr> ArBufOrErr = + Expected> ArBufOrErr = MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]); - if (!ArBufOrErr) + if (Error E = ArBufOrErr.takeError()) { + consumeError(std::move(E)); reportError(Err, argv[0]); + } std::unique_ptr &ArBuf = ArBufOrErr.get(); Expected> ArOrErr = @@ -1038,7 +1042,7 @@ // Add the objects. for (auto &ObjPath : ExtraObjects) { - auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath))); + auto Obj = ExitOnErr(MemoryBuffer::getFile(ObjPath)); ExitOnErr(J->addObjectFile(std::move(Obj))); } diff --git a/llvm/tools/llvm-ar/llvm-ar.cpp b/llvm/tools/llvm-ar/llvm-ar.cpp --- a/llvm/tools/llvm-ar/llvm-ar.cpp +++ b/llvm/tools/llvm-ar/llvm-ar.cpp @@ -272,7 +272,7 @@ static object::Archive &readLibrary(const Twine &Library) { auto BufOrErr = MemoryBuffer::getFile(Library, /*IsText=*/false, /*RequiresNullTerminator=*/false); - failIfError(BufOrErr.getError(), "could not open library " + Library); + failIfError(BufOrErr.takeError(), "could not open library " + Library); ArchiveBuffers.push_back(std::move(*BufOrErr)); auto LibOrErr = object::Archive::create(ArchiveBuffers.back()->getMemBufferRef()); @@ -693,7 +693,7 @@ StringRef FileName, bool FlattenArchive = false) { Expected NMOrErr = NewArchiveMember::getFile(FileName, Deterministic); - failIfError(NMOrErr.takeError(), FileName); + failIfError(NMOrErr.takeError()); StringSaver Saver(Alloc); // For regular archives, use the basename of the object path for the member // name. For thin archives, use the full relative paths so the file resolves @@ -993,16 +993,27 @@ llvm_unreachable("Unknown operation."); } +static std::pair hasErrorCode(Error E, std::error_code EC) { + bool HasErrorCode = false; + E = handleErrors(std::move(E), [&](std::unique_ptr E) { + if (EC == E->convertToErrorCode()) + HasErrorCode = true; + return Error(std::move(E)); + }); + return std::make_pair(std::move(E), HasErrorCode); +} + static int performOperation(ArchiveOperation Operation, std::vector *NewMembers) { // Create or open the archive object. - ErrorOr> Buf = MemoryBuffer::getFile( + Expected> Buf = MemoryBuffer::getFile( ArchiveName, /*IsText=*/false, /*RequiresNullTerminator=*/false); - std::error_code EC = Buf.getError(); - if (EC && EC != errc::no_such_file_or_directory) - fail("unable to open '" + ArchiveName + "': " + EC.message()); + std::pair E = + hasErrorCode(Buf.takeError(), errc::no_such_file_or_directory); + if (E.first && !E.second) + fail(toString(std::move(E.first))); - if (!EC) { + if (!E.first) { Error Err = Error::success(); object::Archive Archive(Buf.get()->getMemBufferRef(), Err); failIfError(std::move(Err), "unable to load '" + ArchiveName + "'"); @@ -1012,11 +1023,12 @@ return 0; } - assert(EC == errc::no_such_file_or_directory); + assert(E.second); if (!shouldCreateArchive(Operation)) { - failIfError(EC, Twine("unable to load '") + ArchiveName + "'"); + failIfError(std::move(E.first), "unable to load"); } else { + consumeError(std::move(E.first)); if (!Create) { // Produce a warning if we should and we're creating the archive WithColor::warning(errs(), ToolName) @@ -1031,8 +1043,8 @@ static void runMRIScript() { enum class MRICommand { AddLib, AddMod, Create, CreateThin, Delete, Save, End, Invalid }; - ErrorOr> Buf = MemoryBuffer::getSTDIN(); - failIfError(Buf.getError()); + Expected> Buf = MemoryBuffer::getSTDIN(); + failIfError(Buf.takeError()); const MemoryBuffer &Ref = *Buf.get(); bool Saved = false; std::vector NewMembers; diff --git a/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp b/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp --- a/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp +++ b/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp @@ -82,7 +82,7 @@ static Expected> openBitcodeFile(StringRef Path) { // Read the input file. Expected> MemBufOrErr = - errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Path)); + MemoryBuffer::getFileOrSTDIN(Path); if (Error E = MemBufOrErr.takeError()) return std::move(E); diff --git a/llvm/tools/llvm-cat/llvm-cat.cpp b/llvm/tools/llvm-cat/llvm-cat.cpp --- a/llvm/tools/llvm-cat/llvm-cat.cpp +++ b/llvm/tools/llvm-cat/llvm-cat.cpp @@ -58,8 +58,8 @@ BitcodeWriter Writer(Buffer); if (BinaryCat) { for (const auto &InputFilename : InputFilenames) { - std::unique_ptr MB = ExitOnErr( - errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename))); + std::unique_ptr MB = + ExitOnErr(MemoryBuffer::getFileOrSTDIN(InputFilename)); std::vector Mods = ExitOnErr(getBitcodeModuleList(*MB)); for (auto &BitcodeMod : Mods) { llvm::append_range(Buffer, BitcodeMod.getBuffer()); diff --git a/llvm/tools/llvm-cov/CodeCoverage.cpp b/llvm/tools/llvm-cov/CodeCoverage.cpp --- a/llvm/tools/llvm-cov/CodeCoverage.cpp +++ b/llvm/tools/llvm-cov/CodeCoverage.cpp @@ -282,7 +282,7 @@ if (isEquivalentFile(SourceFile, Files.first)) return *Files.second; auto Buffer = MemoryBuffer::getFile(SourceFile); - if (auto EC = Buffer.getError()) { + if (auto EC = errorToErrorCode(Buffer.takeError())) { error(EC.message(), SourceFile); return EC; } @@ -569,8 +569,8 @@ // Parse the demangler's output. auto BufOrError = MemoryBuffer::getFile(OutputPath); - if (!BufOrError) { - error(OutputPath, BufOrError.getError().message()); + if (Error E = BufOrError.takeError()) { + error(OutputPath, toString(std::move(E))); return; } diff --git a/llvm/tools/llvm-cov/gcov.cpp b/llvm/tools/llvm-cov/gcov.cpp --- a/llvm/tools/llvm-cov/gcov.cpp +++ b/llvm/tools/llvm-cov/gcov.cpp @@ -19,6 +19,14 @@ #include using namespace llvm; +static Error removeErrorCode(Error E, std::error_code EC) { + return handleErrors(std::move(E), + [&](std::unique_ptr E) -> Error { + if (EC == E->convertToErrorCode()) + return Error::success(); + return Error(std::move(E)); + }); +} static void reportCoverage(StringRef SourceFile, StringRef ObjectDir, const std::string &InputGCNO, const std::string &InputGCDA, bool DumpGCOV, @@ -45,11 +53,11 @@ // Open .gcda and .gcda without requiring a NUL terminator. The concurrent // modification may nullify the NUL terminator condition. - ErrorOr> GCNO_Buff = + Expected> GCNO_Buff = MemoryBuffer::getFileOrSTDIN(GCNO, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (std::error_code EC = GCNO_Buff.getError()) { - errs() << GCNO << ": " << EC.message() << "\n"; + if (Error E = GCNO_Buff.takeError()) { + errs() << GCNO << ": " << toString(std::move(E)) << "\n"; return; } GCOVBuffer GCNO_GB(GCNO_Buff.get().get()); @@ -58,12 +66,14 @@ return; } - ErrorOr> GCDA_Buff = + Expected> GCDA_Buff = MemoryBuffer::getFileOrSTDIN(GCDA, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (std::error_code EC = GCDA_Buff.getError()) { - if (EC != errc::no_such_file_or_directory) { - errs() << GCDA << ": " << EC.message() << "\n"; + if (Error E = GCDA_Buff.takeError()) { + if ((E = removeErrorCode( + std::move(E), + std::make_error_code(std::errc::no_such_file_or_directory)))) { + errs() << GCDA << ": " << toString(std::move(E)) << "\n"; return; } // Clear the filename to make it clear we didn't read anything. diff --git a/llvm/tools/llvm-cxxmap/llvm-cxxmap.cpp b/llvm/tools/llvm-cxxmap/llvm-cxxmap.cpp --- a/llvm/tools/llvm-cxxmap/llvm-cxxmap.cpp +++ b/llvm/tools/llvm-cxxmap/llvm-cxxmap.cpp @@ -145,16 +145,16 @@ cl::ParseCommandLineOptions(argc, argv, "LLVM C++ mangled name remapper\n"); auto OldSymbolBufOrError = MemoryBuffer::getFileOrSTDIN(OldSymbolFile); - if (!OldSymbolBufOrError) - exitWithErrorCode(OldSymbolBufOrError.getError(), OldSymbolFile); + if (Error E = OldSymbolBufOrError.takeError()) + exitWithError(std::move(E), OldSymbolFile); auto NewSymbolBufOrError = MemoryBuffer::getFileOrSTDIN(NewSymbolFile); - if (!NewSymbolBufOrError) - exitWithErrorCode(NewSymbolBufOrError.getError(), NewSymbolFile); + if (Error E = NewSymbolBufOrError.takeError()) + exitWithError(std::move(E), NewSymbolFile); auto RemappingBufOrError = MemoryBuffer::getFileOrSTDIN(RemappingFile); - if (!RemappingBufOrError) - exitWithErrorCode(RemappingBufOrError.getError(), RemappingFile); + if (Error E = RemappingBufOrError.takeError()) + exitWithError(std::move(E), RemappingFile); std::error_code EC; raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_TextWithCRLF); diff --git a/llvm/tools/llvm-dis/llvm-dis.cpp b/llvm/tools/llvm-dis/llvm-dis.cpp --- a/llvm/tools/llvm-dis/llvm-dis.cpp +++ b/llvm/tools/llvm-dis/llvm-dis.cpp @@ -174,8 +174,8 @@ } for (std::string InputFilename : InputFilenames) { - std::unique_ptr MB = ExitOnErr( - errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename))); + std::unique_ptr MB = + ExitOnErr(MemoryBuffer::getFileOrSTDIN(InputFilename)); BitcodeFileContents IF = ExitOnErr(llvm::getBitcodeFileContents(*MB)); diff --git a/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp b/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp --- a/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp +++ b/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp @@ -573,9 +573,9 @@ static bool handleFile(StringRef Filename, HandlerFn HandleObj, raw_ostream &OS) { - ErrorOr> BuffOrErr = + Expected> BuffOrErr = MemoryBuffer::getFileOrSTDIN(Filename); - error(Filename, BuffOrErr.getError()); + error(Filename, BuffOrErr.takeError()); std::unique_ptr Buffer = std::move(BuffOrErr.get()); return handleBuffer(Filename, *Buffer, HandleObj, OS); } diff --git a/llvm/tools/llvm-exegesis/lib/BenchmarkResult.cpp b/llvm/tools/llvm-exegesis/lib/BenchmarkResult.cpp --- a/llvm/tools/llvm-exegesis/lib/BenchmarkResult.cpp +++ b/llvm/tools/llvm-exegesis/lib/BenchmarkResult.cpp @@ -334,7 +334,7 @@ Expected InstructionBenchmark::readYaml(const LLVMState &State, StringRef Filename) { if (auto ExpectedMemoryBuffer = - errorOrToExpected(MemoryBuffer::getFile(Filename, /*IsText=*/true))) { + MemoryBuffer::getFile(Filename, /*IsText=*/true)) { yaml::Input Yin(*ExpectedMemoryBuffer.get()); YamlContext Context(State); InstructionBenchmark Benchmark; @@ -351,7 +351,7 @@ Expected> InstructionBenchmark::readYamls(const LLVMState &State, StringRef Filename) { if (auto ExpectedMemoryBuffer = - errorOrToExpected(MemoryBuffer::getFile(Filename, /*IsText=*/true))) { + MemoryBuffer::getFile(Filename, /*IsText=*/true)) { yaml::Input Yin(*ExpectedMemoryBuffer.get()); YamlContext Context(State); std::vector Benchmarks; diff --git a/llvm/tools/llvm-exegesis/lib/SnippetFile.cpp b/llvm/tools/llvm-exegesis/lib/SnippetFile.cpp --- a/llvm/tools/llvm-exegesis/lib/SnippetFile.cpp +++ b/llvm/tools/llvm-exegesis/lib/SnippetFile.cpp @@ -119,11 +119,11 @@ // Reads code snippets from file `Filename`. Expected> readSnippets(const LLVMState &State, StringRef Filename) { - ErrorOr> BufferPtr = + Expected> BufferPtr = MemoryBuffer::getFileOrSTDIN(Filename); - if (std::error_code EC = BufferPtr.getError()) { + if (Error E = BufferPtr.takeError()) { return make_error("cannot read snippet: " + Filename + ": " + - EC.message()); + toString(std::move(E))); } SourceMgr SM; SM.AddNewSourceBuffer(std::move(BufferPtr.get()), SMLoc()); diff --git a/llvm/tools/llvm-gsymutil/llvm-gsymutil.cpp b/llvm/tools/llvm-gsymutil/llvm-gsymutil.cpp --- a/llvm/tools/llvm-gsymutil/llvm-gsymutil.cpp +++ b/llvm/tools/llvm-gsymutil/llvm-gsymutil.cpp @@ -402,9 +402,9 @@ static llvm::Error handleFileConversionToGSYM(StringRef Filename, const std::string &OutFile) { - ErrorOr> BuffOrErr = + Expected> BuffOrErr = MemoryBuffer::getFileOrSTDIN(Filename); - error(Filename, BuffOrErr.getError()); + error(Filename, BuffOrErr.takeError()); std::unique_ptr Buffer = std::move(BuffOrErr.get()); return handleBuffer(Filename, *Buffer, OutFile); } diff --git a/llvm/tools/llvm-ifs/llvm-ifs.cpp b/llvm/tools/llvm-ifs/llvm-ifs.cpp --- a/llvm/tools/llvm-ifs/llvm-ifs.cpp +++ b/llvm/tools/llvm-ifs/llvm-ifs.cpp @@ -135,11 +135,10 @@ static Expected> readInputFile(StringRef FilePath) { // Read in file. - ErrorOr> BufOrError = + Expected> BufOrError = MemoryBuffer::getFileOrSTDIN(FilePath, /*IsText=*/true); - if (!BufOrError) - return createStringError(BufOrError.getError(), "Could not open `%s`", - FilePath.data()); + if (Error E = BufOrError.takeError()) + return E; std::unique_ptr FileReadBuffer = std::move(*BufOrError); ErrorCollector EC(/*UseFatalErrors=*/false); @@ -259,12 +258,13 @@ OutStr.flush(); if (WriteIfChanged) { - if (ErrorOr> BufOrError = + if (Expected> BufOrError = MemoryBuffer::getFile(FilePath)) { // Compare IFS output with the existing IFS file. If unchanged, avoid changing the file. if ((*BufOrError)->getBuffer() == IFSStr) return Error::success(); - } + } else + consumeError(BufOrError.takeError()); } // Open IFS file for writing. std::error_code SysErr; diff --git a/llvm/tools/llvm-jitlink/llvm-jitlink.cpp b/llvm/tools/llvm-jitlink/llvm-jitlink.cpp --- a/llvm/tools/llvm-jitlink/llvm-jitlink.cpp +++ b/llvm/tools/llvm-jitlink/llvm-jitlink.cpp @@ -949,8 +949,7 @@ for (auto &HarnessFile : TestHarnesses) { HarnessFiles.insert(HarnessFile); - auto ObjBuffer = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(HarnessFile))); + auto ObjBuffer = ExitOnErr(MemoryBuffer::getFile(HarnessFile)); auto ObjSymbolInfo = ExitOnErr(getObjectSymbolInfo(ES, ObjBuffer->getMemBufferRef())); @@ -1098,8 +1097,7 @@ static Triple FirstTT = []() { assert(!InputFiles.empty() && "InputFiles can not be empty"); for (auto InputFile : InputFiles) { - auto ObjBuffer = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(InputFile))); + auto ObjBuffer = ExitOnErr(MemoryBuffer::getFile(InputFile)); switch (identify_magic(ObjBuffer->getBuffer())) { case file_magic::elf_relocatable: case file_magic::macho_object: @@ -1203,8 +1201,7 @@ LLVM_DEBUG(dbgs() << "Adding test harness objects...\n"); for (auto HarnessFile : TestHarnesses) { LLVM_DEBUG(dbgs() << " " << HarnessFile << "\n"); - auto ObjBuffer = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(HarnessFile))); + auto ObjBuffer = ExitOnErr(MemoryBuffer::getFile(HarnessFile)); ExitOnErr(S.ObjLayer.add(*S.MainJD, std::move(ObjBuffer))); } @@ -1218,8 +1215,7 @@ auto &JD = *std::prev(IdxToJLD.lower_bound(InputFileArgIdx))->second; LLVM_DEBUG(dbgs() << " " << InputFileArgIdx << ": \"" << InputFile << "\" to " << JD.getName() << "\n";); - auto ObjBuffer = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(InputFile))); + auto ObjBuffer = ExitOnErr(MemoryBuffer::getFile(InputFile)); auto Magic = identify_magic(ObjBuffer->getBuffer()); if (Magic == file_magic::archive || @@ -1351,8 +1347,7 @@ std::string CheckLineStart = "# " + CheckName + ":"; for (auto &CheckFile : CheckFiles) { - auto CheckerFileBuf = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(CheckFile))); + auto CheckerFileBuf = ExitOnErr(MemoryBuffer::getFile(CheckFile)); if (!Checker.checkAllRulesInBuffer(CheckLineStart, &*CheckerFileBuf)) ExitOnErr(make_error( "Some checks in " + CheckFile + " failed", inconvertibleErrorCode())); diff --git a/llvm/tools/llvm-libtool-darwin/llvm-libtool-darwin.cpp b/llvm/tools/llvm-libtool-darwin/llvm-libtool-darwin.cpp --- a/llvm/tools/llvm-libtool-darwin/llvm-libtool-darwin.cpp +++ b/llvm/tools/llvm-libtool-darwin/llvm-libtool-darwin.cpp @@ -147,11 +147,11 @@ StringRef FileName, DirName; std::tie(FileName, DirName) = StringRef(FileList).rsplit(","); - ErrorOr> FileOrErr = + Expected> FileOrErr = MemoryBuffer::getFileOrSTDIN(FileName, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (std::error_code EC = FileOrErr.getError()) - return createFileError(FileName, errorCodeToError(EC)); + if (Error E = FileOrErr.takeError()) + return E; const MemoryBuffer &Ref = *FileOrErr.get(); line_iterator I(Ref, /*SkipBlanks=*/false); @@ -243,7 +243,7 @@ // Throw error if not in Mach-O format. if (!isa(**ObjOrErr)) return createStringError(std::errc::invalid_argument, - "'%s': format not supported", + "%s: format not supported", Member.MemberName.data()); auto *O = dyn_cast(ObjOrErr->get()); @@ -419,8 +419,8 @@ StringRef FileName, const Config &C) { Expected NMOrErr = NewArchiveMember::getFile(FileName, C.Deterministic); - if (!NMOrErr) - return createFileError(FileName, NMOrErr.takeError()); + if (Error E = NMOrErr.takeError()) + return E; // For regular archives, use the basename of the object path for the member // name. diff --git a/llvm/tools/llvm-link/llvm-link.cpp b/llvm/tools/llvm-link/llvm-link.cpp --- a/llvm/tools/llvm-link/llvm-link.cpp +++ b/llvm/tools/llvm-link/llvm-link.cpp @@ -306,7 +306,7 @@ auto ModuleLoader = [&DestModule](const char *argv0, const std::string &Identifier) { std::unique_ptr Buffer = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Identifier))); + ExitOnErr(MemoryBuffer::getFileOrSTDIN(Identifier)); return loadFile(argv0, std::move(Buffer), DestModule.getContext(), false); }; @@ -369,7 +369,7 @@ bool InternalizeLinkedSymbols = false; for (const auto &File : Files) { std::unique_ptr Buffer = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(File))); + ExitOnErr(MemoryBuffer::getFileOrSTDIN(File)); std::unique_ptr M = identify_magic(Buffer->getBuffer()) == file_magic::archive diff --git a/llvm/tools/llvm-lto/llvm-lto.cpp b/llvm/tools/llvm-lto/llvm-lto.cpp --- a/llvm/tools/llvm-lto/llvm-lto.cpp +++ b/llvm/tools/llvm-lto/llvm-lto.cpp @@ -333,6 +333,11 @@ exit(1); } +static void error(Error E, const Twine &Prefix) { + if (E) + error(Prefix + ": " + toString(std::move(E))); +} + static void error(std::error_code EC, const Twine &Prefix) { if (EC) error(Prefix + ": " + EC.message()); @@ -351,9 +356,10 @@ static std::unique_ptr getLocalLTOModule(StringRef Path, std::unique_ptr &Buffer, const TargetOptions &Options) { - ErrorOr> BufferOrErr = + Expected> BufferOrErr = MemoryBuffer::getFile(Path); - error(BufferOrErr, "error loading file '" + Path + "'"); + error(errorToErrorCode(BufferOrErr.takeError()), + "error loading file '" + Path + "'"); Buffer = std::move(BufferOrErr.get()); CurrentActivity = ("loading file '" + Path + "'").str(); std::unique_ptr Context = std::make_unique(); @@ -425,7 +431,7 @@ static std::unique_ptr loadFile(StringRef Filename) { ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename.str() + "': "); - return ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Filename))); + return ExitOnErr(MemoryBuffer::getFileOrSTDIN(Filename)); } static void listDependentLibraries() { @@ -484,7 +490,7 @@ for (auto &Filename : InputFilenames) { ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': "); std::unique_ptr MB = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Filename))); + ExitOnErr(MemoryBuffer::getFileOrSTDIN(Filename)); ExitOnErr(readModuleSummaryIndex(*MB, CombinedIndex, NextModuleId++)); } std::error_code EC; @@ -537,7 +543,7 @@ const auto &Filename = ModPath.first(); std::string CurrentActivity = ("loading file '" + Filename + "'").str(); auto InputOrErr = MemoryBuffer::getFile(Filename); - error(InputOrErr, "error " + CurrentActivity); + error(InputOrErr.takeError(), "error " + CurrentActivity); InputBuffers.push_back(std::move(*InputOrErr)); } return InputBuffers; @@ -644,7 +650,7 @@ auto &Filename = InputFilenames[i]; std::string CurrentActivity = "loading file '" + Filename + "'"; auto InputOrErr = MemoryBuffer::getFile(Filename); - error(InputOrErr, "error " + CurrentActivity); + error(InputOrErr.takeError(), "error " + CurrentActivity); InputBuffers.push_back(std::move(*InputOrErr)); ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer()); } @@ -857,7 +863,7 @@ for (auto &Filename : InputFilenames) { LLVMContext Ctx; auto InputOrErr = MemoryBuffer::getFile(Filename); - error(InputOrErr, "error " + CurrentActivity); + error(InputOrErr.takeError(), "error " + CurrentActivity); InputBuffers.push_back(std::move(*InputOrErr)); ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer()); } @@ -896,7 +902,7 @@ auto &Filename = InputFilenames[i]; std::string CurrentActivity = "loading file '" + Filename + "'"; auto InputOrErr = MemoryBuffer::getFile(Filename); - error(InputOrErr, "error " + CurrentActivity); + error(InputOrErr.takeError(), "error " + CurrentActivity); InputBuffers.push_back(std::move(*InputOrErr)); ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer()); } @@ -968,9 +974,8 @@ ExitOnError ExitOnErr(std::string(*argv) + ": error loading file '" + Filename + "': "); std::unique_ptr BufferOrErr = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(Filename))); - auto Buffer = std::move(BufferOrErr.get()); - if (ExitOnErr(isBitcodeContainingObjCCategory(*Buffer))) + ExitOnErr(MemoryBuffer::getFile(Filename)); + if (ExitOnErr(isBitcodeContainingObjCCategory(*BufferOrErr))) outs() << "Bitcode " << Filename << " contains ObjC\n"; else outs() << "Bitcode " << Filename << " does not contain ObjC\n"; diff --git a/llvm/tools/llvm-mc/llvm-mc.cpp b/llvm/tools/llvm-mc/llvm-mc.cpp --- a/llvm/tools/llvm-mc/llvm-mc.cpp +++ b/llvm/tools/llvm-mc/llvm-mc.cpp @@ -375,11 +375,10 @@ // construct the Triple object. Triple TheTriple(TripleName); - ErrorOr> BufferPtr = + Expected> BufferPtr = MemoryBuffer::getFileOrSTDIN(InputFilename, /*IsText=*/true); - if (std::error_code EC = BufferPtr.getError()) { - WithColor::error(errs(), ProgName) - << InputFilename << ": " << EC.message() << '\n'; + if (Error E = BufferPtr.takeError()) { + WithColor::error(errs(), ProgName) << toString(std::move(E)) << '\n'; return 1; } MemoryBuffer *Buffer = BufferPtr->get(); diff --git a/llvm/tools/llvm-mca/llvm-mca.cpp b/llvm/tools/llvm-mca/llvm-mca.cpp --- a/llvm/tools/llvm-mca/llvm-mca.cpp +++ b/llvm/tools/llvm-mca/llvm-mca.cpp @@ -331,10 +331,10 @@ // For safety, reconstruct the Triple object. Triple TheTriple(TripleName); - ErrorOr> BufferPtr = + Expected> BufferPtr = MemoryBuffer::getFileOrSTDIN(InputFilename); - if (std::error_code EC = BufferPtr.getError()) { - WithColor::error() << InputFilename << ": " << EC.message() << '\n'; + if (Error E = BufferPtr.takeError()) { + WithColor::error() << toString(std::move(E)) << '\n'; return 1; } diff --git a/llvm/tools/llvm-ml/llvm-ml.cpp b/llvm/tools/llvm-ml/llvm-ml.cpp --- a/llvm/tools/llvm-ml/llvm-ml.cpp +++ b/llvm/tools/llvm-ml/llvm-ml.cpp @@ -274,11 +274,10 @@ SafeSEH = false; } - ErrorOr> BufferPtr = + Expected> BufferPtr = MemoryBuffer::getFileOrSTDIN(InputFilename); - if (std::error_code EC = BufferPtr.getError()) { - WithColor::error(errs(), ProgName) - << InputFilename << ": " << EC.message() << '\n'; + if (llvm::Error E = BufferPtr.takeError()) { + WithColor::error(errs(), ProgName) << toString(std::move(E)) << '\n'; return 1; } diff --git a/llvm/tools/llvm-modextract/llvm-modextract.cpp b/llvm/tools/llvm-modextract/llvm-modextract.cpp --- a/llvm/tools/llvm-modextract/llvm-modextract.cpp +++ b/llvm/tools/llvm-modextract/llvm-modextract.cpp @@ -49,7 +49,7 @@ ExitOnError ExitOnErr("llvm-modextract: error: "); std::unique_ptr MB = - ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename))); + ExitOnErr(MemoryBuffer::getFileOrSTDIN(InputFilename)); std::vector Ms = ExitOnErr(getBitcodeModuleList(*MB)); LLVMContext Context; diff --git a/llvm/tools/llvm-mt/llvm-mt.cpp b/llvm/tools/llvm-mt/llvm-mt.cpp --- a/llvm/tools/llvm-mt/llvm-mt.cpp +++ b/llvm/tools/llvm-mt/llvm-mt.cpp @@ -131,10 +131,9 @@ windows_manifest::WindowsManifestMerger Merger; for (const auto &File : InputFiles) { - ErrorOr> ManifestOrErr = + Expected> ManifestOrErr = MemoryBuffer::getFile(File); - if (!ManifestOrErr) - reportError(File, ManifestOrErr.getError()); + error(ManifestOrErr.takeError()); error(Merger.merge(*ManifestOrErr.get())); } diff --git a/llvm/tools/llvm-nm/llvm-nm.cpp b/llvm/tools/llvm-nm/llvm-nm.cpp --- a/llvm/tools/llvm-nm/llvm-nm.cpp +++ b/llvm/tools/llvm-nm/llvm-nm.cpp @@ -35,6 +35,7 @@ #include "llvm/Option/ArgList.h" #include "llvm/Option/Option.h" #include "llvm/Support/CommandLine.h" +#include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/InitLLVM.h" @@ -1718,9 +1719,9 @@ } static void dumpSymbolNamesFromFile(std::string &Filename) { - ErrorOr> BufferOrErr = + Expected> BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename); - if (error(BufferOrErr.getError(), Filename)) + if (error(errorToErrorCode(BufferOrErr.takeError()), Filename)) return; LLVMContext Context; diff --git a/llvm/tools/llvm-objcopy/COFF/COFFObjcopy.cpp b/llvm/tools/llvm-objcopy/COFF/COFFObjcopy.cpp --- a/llvm/tools/llvm-objcopy/COFF/COFFObjcopy.cpp +++ b/llvm/tools/llvm-objcopy/COFF/COFFObjcopy.cpp @@ -41,10 +41,10 @@ static Expected> createGnuDebugLinkSectionContents(StringRef File) { - ErrorOr> LinkTargetOrErr = + Expected> LinkTargetOrErr = MemoryBuffer::getFile(File); - if (!LinkTargetOrErr) - return createFileError(File, LinkTargetOrErr.getError()); + if (Error E = LinkTargetOrErr.takeError()) + return E; auto LinkTarget = std::move(*LinkTargetOrErr); uint32_t CRC32 = llvm::crc32(arrayRefFromStringRef(LinkTarget->getBuffer())); @@ -234,8 +234,8 @@ std::tie(SecName, FileName) = Flag.split("="); auto BufOrErr = MemoryBuffer::getFile(FileName); - if (!BufOrErr) - return createFileError(FileName, errorCodeToError(BufOrErr.getError())); + if (Error E = BufOrErr.takeError()) + return E; auto Buf = std::move(*BufOrErr); uint32_t Characteristics; diff --git a/llvm/tools/llvm-objcopy/ConfigManager.cpp b/llvm/tools/llvm-objcopy/ConfigManager.cpp --- a/llvm/tools/llvm-objcopy/ConfigManager.cpp +++ b/llvm/tools/llvm-objcopy/ConfigManager.cpp @@ -348,8 +348,8 @@ StringSaver Saver(Alloc); SmallVector Lines; auto BufOrErr = MemoryBuffer::getFile(Filename); - if (!BufOrErr) - return createFileError(Filename, BufOrErr.getError()); + if (Error E = BufOrErr.takeError()) + return E; BufOrErr.get()->getBuffer().split(Lines, '\n'); for (StringRef Line : Lines) { @@ -406,8 +406,8 @@ StringSaver Saver(Alloc); SmallVector Lines; auto BufOrErr = MemoryBuffer::getFile(Filename); - if (!BufOrErr) - return createFileError(Filename, BufOrErr.getError()); + if (Error E = BufOrErr.takeError()) + return E; BufOrErr.get()->getBuffer().split(Lines, '\n'); size_t NumLines = Lines.size(); @@ -789,8 +789,8 @@ // here. This prevents a significant amount of I/O. if (!Config.AddGnuDebugLink.empty()) { auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink); - if (!DebugOrErr) - return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError()); + if (Error E = DebugOrErr.takeError()) + return E; auto Debug = std::move(*DebugOrErr); Config.GnuDebugLinkCRC32 = llvm::crc32(arrayRefFromStringRef(Debug->getBuffer())); diff --git a/llvm/tools/llvm-objcopy/ELF/ELFObjcopy.cpp b/llvm/tools/llvm-objcopy/ELF/ELFObjcopy.cpp --- a/llvm/tools/llvm-objcopy/ELF/ELFObjcopy.cpp +++ b/llvm/tools/llvm-objcopy/ELF/ELFObjcopy.cpp @@ -659,10 +659,10 @@ std::pair SecPair = Flag.split("="); StringRef SecName = SecPair.first; StringRef File = SecPair.second; - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFile(File); - if (!BufOrErr) - return createFileError(File, errorCodeToError(BufOrErr.getError())); + if (Error E = BufOrErr.takeError()) + return E; std::unique_ptr Buf = std::move(*BufOrErr); ArrayRef Data( reinterpret_cast(Buf->getBufferStart()), diff --git a/llvm/tools/llvm-objcopy/MachO/MachOObjcopy.cpp b/llvm/tools/llvm-objcopy/MachO/MachOObjcopy.cpp --- a/llvm/tools/llvm-objcopy/MachO/MachOObjcopy.cpp +++ b/llvm/tools/llvm-objcopy/MachO/MachOObjcopy.cpp @@ -277,10 +277,10 @@ } static Error addSection(StringRef SecName, StringRef Filename, Object &Obj) { - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFile(Filename); - if (!BufOrErr) - return createFileError(Filename, errorCodeToError(BufOrErr.getError())); + if (Error E = BufOrErr.takeError()) + return E; std::unique_ptr Buf = std::move(*BufOrErr); std::pair Pair = SecName.split(','); diff --git a/llvm/tools/llvm-objcopy/llvm-objcopy.cpp b/llvm/tools/llvm-objcopy/llvm-objcopy.cpp --- a/llvm/tools/llvm-objcopy/llvm-objcopy.cpp +++ b/llvm/tools/llvm-objcopy/llvm-objcopy.cpp @@ -329,10 +329,10 @@ if (Config.InputFormat == FileFormat::Binary || Config.InputFormat == FileFormat::IHex) { - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFileOrSTDIN(Config.InputFilename); - if (!BufOrErr) - return createFileError(Config.InputFilename, BufOrErr.getError()); + if (Error E = BufOrErr.takeError()) + return E; MemoryBufferHolder = std::move(*BufOrErr); if (Config.InputFormat == FileFormat::Binary) @@ -350,7 +350,7 @@ Expected> BinaryOrErr = createBinary(Config.InputFilename); if (!BinaryOrErr) - return createFileError(Config.InputFilename, BinaryOrErr.takeError()); + return BinaryOrErr.takeError(); BinaryHolder = std::move(*BinaryOrErr); if (Archive *Ar = dyn_cast(BinaryHolder.getBinary())) { diff --git a/llvm/tools/llvm-objcopy/wasm/WasmObjcopy.cpp b/llvm/tools/llvm-objcopy/wasm/WasmObjcopy.cpp --- a/llvm/tools/llvm-objcopy/wasm/WasmObjcopy.cpp +++ b/llvm/tools/llvm-objcopy/wasm/WasmObjcopy.cpp @@ -124,10 +124,10 @@ for (StringRef Flag : Config.AddSection) { StringRef SecName, FileName; std::tie(SecName, FileName) = Flag.split("="); - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFile(FileName); - if (!BufOrErr) - return createFileError(FileName, errorCodeToError(BufOrErr.getError())); + if (Error E = BufOrErr.takeError()) + return E; Section Sec; Sec.SectionType = llvm::wasm::WASM_SEC_CUSTOM; Sec.Name = SecName; diff --git a/llvm/tools/llvm-objdump/MachODump.cpp b/llvm/tools/llvm-objdump/MachODump.cpp --- a/llvm/tools/llvm-objdump/MachODump.cpp +++ b/llvm/tools/llvm-objdump/MachODump.cpp @@ -7359,10 +7359,10 @@ } // Load the file. - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFileOrSTDIN(DSYMPath); - if (std::error_code EC = BufOrErr.getError()) { - reportError(errorCodeToError(EC), DSYMPath); + if (Error E = BufOrErr.takeError()) { + reportError(std::move(E), DSYMPath); return; } diff --git a/llvm/tools/llvm-objdump/SourcePrinter.cpp b/llvm/tools/llvm-objdump/SourcePrinter.cpp --- a/llvm/tools/llvm-objdump/SourcePrinter.cpp +++ b/llvm/tools/llvm-objdump/SourcePrinter.cpp @@ -337,7 +337,8 @@ Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source); } else { auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName); - if (!BufferOrError) { + if (Error E = BufferOrError.takeError()) { + consumeError(std::move(E)); if (MissingSources.insert(LineInfo.FileName).second) reportWarning("failed to find source " + LineInfo.FileName, Obj->getFileName()); diff --git a/llvm/tools/llvm-opt-report/OptReport.cpp b/llvm/tools/llvm-opt-report/OptReport.cpp --- a/llvm/tools/llvm-opt-report/OptReport.cpp +++ b/llvm/tools/llvm-opt-report/OptReport.cpp @@ -146,11 +146,11 @@ } // anonymous namespace static bool readLocationInfo(LocationInfoTy &LocationInfo) { - ErrorOr> Buf = + Expected> Buf = MemoryBuffer::getFile(InputFileName.c_str()); - if (std::error_code EC = Buf.getError()) { + if (Error E = Buf.takeError()) { WithColor::error() << "Can't open file " << InputFileName << ": " - << EC.message() << "\n"; + << toString(std::move(E)) << "\n"; return false; } @@ -262,11 +262,11 @@ const auto &FileInfo = FI.second; - ErrorOr> Buf = + Expected> Buf = MemoryBuffer::getFile(FileName); - if (std::error_code EC = Buf.getError()) { + if (Error E = Buf.takeError()) { WithColor::error() << "Can't open file " << FileName << ": " - << EC.message() << "\n"; + << toString(std::move(E)) << "\n"; return false; } diff --git a/llvm/tools/llvm-pdbutil/InputFile.cpp b/llvm/tools/llvm-pdbutil/InputFile.cpp --- a/llvm/tools/llvm-pdbutil/InputFile.cpp +++ b/llvm/tools/llvm-pdbutil/InputFile.cpp @@ -257,12 +257,11 @@ return make_error(formatv("File {0} not found", Path), inconvertibleErrorCode()); - file_magic Magic; - if (auto EC = identify_magic(Path, Magic)) - return make_error( - formatv("Unable to identify file type for file {0}", Path), EC); + auto Magic = identify_magic_in_file(Path); + if (Error E = Magic.takeError()) + return E; - if (Magic == file_magic::coff_object) { + if (*Magic == file_magic::coff_object) { Expected> BinaryOrErr = createBinary(Path); if (!BinaryOrErr) return BinaryOrErr.takeError(); @@ -272,7 +271,7 @@ return std::move(IF); } - if (Magic == file_magic::pdb) { + if (*Magic == file_magic::pdb) { std::unique_ptr Session; if (auto Err = loadDataForPDB(PDB_ReaderType::Native, Path, Session)) return std::move(Err); @@ -290,9 +289,8 @@ auto Result = MemoryBuffer::getFile(Path, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (!Result) - return make_error( - formatv("File {0} could not be opened", Path), Result.getError()); + if (Error E = Result.takeError()) + return E; IF.UnknownFile = std::move(*Result); IF.PdbOrObj = IF.UnknownFile.get(); diff --git a/llvm/tools/llvm-pdbutil/llvm-pdbutil.cpp b/llvm/tools/llvm-pdbutil/llvm-pdbutil.cpp --- a/llvm/tools/llvm-pdbutil/llvm-pdbutil.cpp +++ b/llvm/tools/llvm-pdbutil/llvm-pdbutil.cpp @@ -747,12 +747,12 @@ static void yamlToPdb(StringRef Path) { BumpPtrAllocator Allocator; - ErrorOr> ErrorOrBuffer = + Expected> ErrorOrBuffer = MemoryBuffer::getFileOrSTDIN(Path, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (ErrorOrBuffer.getError()) { - ExitOnErr(createFileError(Path, errorCodeToError(ErrorOrBuffer.getError()))); + if (Error E = ErrorOrBuffer.takeError()) { + ExitOnErr(std::move(E)); } std::unique_ptr &Buffer = ErrorOrBuffer.get(); diff --git a/llvm/tools/llvm-profdata/llvm-profdata.cpp b/llvm/tools/llvm-profdata/llvm-profdata.cpp --- a/llvm/tools/llvm-profdata/llvm-profdata.cpp +++ b/llvm/tools/llvm-profdata/llvm-profdata.cpp @@ -155,7 +155,7 @@ static std::unique_ptr create(StringRef InputFile) { auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile); if (!BufOrError) - exitWithErrorCode(BufOrError.getError(), InputFile); + exitWithError(BufOrError.takeError(), InputFile); auto Remapper = std::make_unique(); Remapper->File = std::move(BufOrError.get()); @@ -630,8 +630,8 @@ return {}; auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile); - if (!BufOrError) - exitWithErrorCode(BufOrError.getError(), InputFile); + if (Error E = BufOrError.takeError()) + exitWithError(std::move(E), InputFile); return std::move(*BufOrError); } diff --git a/llvm/tools/llvm-rc/ResourceFileWriter.cpp b/llvm/tools/llvm-rc/ResourceFileWriter.cpp --- a/llvm/tools/llvm-rc/ResourceFileWriter.cpp +++ b/llvm/tools/llvm-rc/ResourceFileWriter.cpp @@ -1524,16 +1524,16 @@ // properly though, so if using that to append paths below, this early // exception case could be removed.) if (sys::path::has_root_directory(File)) - return errorOrToExpected(MemoryBuffer::getFile( - File, /*IsText=*/false, /*RequiresNullTerminator=*/false)); + return MemoryBuffer::getFile(File, /*IsText=*/false, + /*RequiresNullTerminator=*/false); // 1. The current working directory. sys::fs::current_path(Cwd); Path.assign(Cwd.begin(), Cwd.end()); sys::path::append(Path, File); if (sys::fs::exists(Path)) - return errorOrToExpected(MemoryBuffer::getFile( - Path, /*IsText=*/false, /*RequiresNullTerminator=*/false)); + return MemoryBuffer::getFile(Path, /*IsText=*/false, + /*RequiresNullTerminator=*/false); // 2. The directory of the input resource file, if it is different from the // current working directory. @@ -1541,22 +1541,22 @@ Path.assign(InputFileDir.begin(), InputFileDir.end()); sys::path::append(Path, File); if (sys::fs::exists(Path)) - return errorOrToExpected(MemoryBuffer::getFile( - Path, /*IsText=*/false, /*RequiresNullTerminator=*/false)); + return MemoryBuffer::getFile(Path, /*IsText=*/false, + /*RequiresNullTerminator=*/false); // 3. All of the include directories specified on the command line. for (StringRef ForceInclude : Params.Include) { Path.assign(ForceInclude.begin(), ForceInclude.end()); sys::path::append(Path, File); if (sys::fs::exists(Path)) - return errorOrToExpected(MemoryBuffer::getFile( - Path, /*IsText=*/false, /*RequiresNullTerminator=*/false)); + return MemoryBuffer::getFile(Path, /*IsText=*/false, + /*RequiresNullTerminator=*/false); } if (!Params.NoInclude) { if (auto Result = llvm::sys::Process::FindInEnvPath("INCLUDE", File)) - return errorOrToExpected(MemoryBuffer::getFile( - *Result, /*IsText=*/false, /*RequiresNullTerminator=*/false)); + return MemoryBuffer::getFile(*Result, /*IsText=*/false, + /*RequiresNullTerminator=*/false); } return make_error("error : file not found : " + Twine(File), diff --git a/llvm/tools/llvm-rc/llvm-rc.cpp b/llvm/tools/llvm-rc/llvm-rc.cpp --- a/llvm/tools/llvm-rc/llvm-rc.cpp +++ b/llvm/tools/llvm-rc/llvm-rc.cpp @@ -597,11 +597,11 @@ } // Read and tokenize the input file. - ErrorOr> File = + Expected> File = MemoryBuffer::getFile(PreprocessedFile); - if (!File) { + if (Error E = File.takeError()) { fatalError("Error opening file '" + Twine(PreprocessedFile) + - "': " + File.getError().message()); + "': " + toString(std::move(E))); } std::unique_ptr FileContents = std::move(*File); @@ -676,11 +676,11 @@ void doCvtres(std::string Src, std::string Dest, std::string TargetTriple) { object::WindowsResourceParser Parser; - ErrorOr> BufferOrErr = + Expected> BufferOrErr = MemoryBuffer::getFile(Src); - if (!BufferOrErr) + if (Error E = BufferOrErr.takeError()) fatalError("Error opening file '" + Twine(Src) + - "': " + BufferOrErr.getError().message()); + "': " + toString(std::move(E))); std::unique_ptr &Buffer = BufferOrErr.get(); std::unique_ptr Binary = ExitOnErr(object::WindowsResource::createWindowsResource( diff --git a/llvm/tools/llvm-readobj/llvm-readobj.cpp b/llvm/tools/llvm-readobj/llvm-readobj.cpp --- a/llvm/tools/llvm-readobj/llvm-readobj.cpp +++ b/llvm/tools/llvm-readobj/llvm-readobj.cpp @@ -502,11 +502,11 @@ /// Opens \a File and dumps it. static void dumpInput(StringRef File, ScopedPrinter &Writer) { - ErrorOr> FileOrErr = + Expected> FileOrErr = MemoryBuffer::getFileOrSTDIN(File, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (std::error_code EC = FileOrErr.getError()) - return reportError(errorCodeToError(EC), File); + if (Error E = FileOrErr.takeError()) + return reportError(std::move(E), File); std::unique_ptr &Buffer = FileOrErr.get(); file_magic Type = identify_magic(Buffer->getBuffer()); diff --git a/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp b/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp --- a/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp +++ b/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp @@ -420,10 +420,10 @@ // Load the input memory buffer. - ErrorOr> InputBuffer = + Expected> InputBuffer = MemoryBuffer::getFileOrSTDIN(File); - if (std::error_code EC = InputBuffer.getError()) - ErrorAndExit("unable to read input: '" + EC.message() + "'"); + if (Error E = InputBuffer.takeError()) + ErrorAndExit("unable to read input: '" + toString(std::move(E)) + "'"); Expected> MaybeObj( ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef())); @@ -557,10 +557,10 @@ TimeRegion TR(Timers ? &Timers->LoadObjectsTimer : nullptr); for (auto &File : InputFileList) { // Load the input memory buffer. - ErrorOr> InputBuffer = + Expected> InputBuffer = MemoryBuffer::getFileOrSTDIN(File); - if (std::error_code EC = InputBuffer.getError()) - ErrorAndExit("unable to read input: '" + EC.message() + "'"); + if (Error E = InputBuffer.takeError()) + ErrorAndExit("unable to read input: '" + toString(std::move(E)) + "'"); Expected> MaybeObj( ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef())); @@ -630,11 +630,11 @@ static int checkAllExpressions(RuntimeDyldChecker &Checker) { for (const auto& CheckerFileName : CheckFiles) { - ErrorOr> CheckerFileBuf = + Expected> CheckerFileBuf = MemoryBuffer::getFileOrSTDIN(CheckerFileName); - if (std::error_code EC = CheckerFileBuf.getError()) - ErrorAndExit("unable to read input '" + CheckerFileName + "': " + - EC.message()); + if (Error E = CheckerFileBuf.takeError()) + ErrorAndExit("unable to read input '" + CheckerFileName + + "': " + toString(std::move(E))); if (!Checker.checkAllRulesInBuffer("# rtdyld-check:", CheckerFileBuf.get().get())) @@ -952,11 +952,11 @@ InputFileList.push_back("-"); for (auto &InputFile : InputFileList) { // Load the input memory buffer. - ErrorOr> InputBuffer = + Expected> InputBuffer = MemoryBuffer::getFileOrSTDIN(InputFile); - if (std::error_code EC = InputBuffer.getError()) - ErrorAndExit("unable to read input: '" + EC.message() + "'"); + if (Error E = InputBuffer.takeError()) + ErrorAndExit("unable to read input: '" + toString(std::move(E)) + "'"); Expected> MaybeObj( ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef())); diff --git a/llvm/tools/llvm-size/llvm-size.cpp b/llvm/tools/llvm-size/llvm-size.cpp --- a/llvm/tools/llvm-size/llvm-size.cpp +++ b/llvm/tools/llvm-size/llvm-size.cpp @@ -102,6 +102,16 @@ << "'" << File << "': " << Message << '\n'; } +static void error(llvm::Error E) { + HadError = true; + WithColor::error(errs(), ToolName); + std::string Buf; + raw_string_ostream OS(Buf); + logAllUnhandledErrors(std::move(E), OS); + OS.flush(); + errs() << Buf << "\n"; +} + // This version of error() prints the archive name and member name, for example: // "libx.a(foo.o)" after the ToolName before the error message. It sets // HadError but returns allowing the code to move on to other archive members. @@ -546,7 +556,7 @@ // Attempt to open the binary. Expected> BinaryOrErr = createBinary(file); if (!BinaryOrErr) { - error(BinaryOrErr.takeError(), file); + error(BinaryOrErr.takeError()); return; } Binary &Bin = *BinaryOrErr.get().getBinary(); diff --git a/llvm/tools/llvm-strings/llvm-strings.cpp b/llvm/tools/llvm-strings/llvm-strings.cpp --- a/llvm/tools/llvm-strings/llvm-strings.cpp +++ b/llvm/tools/llvm-strings/llvm-strings.cpp @@ -172,10 +172,10 @@ InputFileNames.push_back("-"); for (const auto &File : InputFileNames) { - ErrorOr> Buffer = + Expected> Buffer = MemoryBuffer::getFileOrSTDIN(File); - if (std::error_code EC = Buffer.getError()) - errs() << File << ": " << EC.message() << '\n'; + if (Error E = Buffer.takeError()) + errs() << File << ": " << toString(std::move(E)) << '\n'; else strings(llvm::outs(), File == "-" ? "{standard input}" : File, Buffer.get()->getMemBufferRef().getBuffer()); diff --git a/llvm/tools/llvm-tapi-diff/llvm-tapi-diff.cpp b/llvm/tools/llvm-tapi-diff/llvm-tapi-diff.cpp --- a/llvm/tools/llvm-tapi-diff/llvm-tapi-diff.cpp +++ b/llvm/tools/llvm-tapi-diff/llvm-tapi-diff.cpp @@ -37,16 +37,16 @@ ExitOnError ExitOnErr; -void setErrorBanner(ExitOnError &ExitOnErr, std::string InputFile) { - ExitOnErr.setBanner(ToolName + ": error: " + InputFile + ": "); -} - -Expected> convertFileToBinary(std::string &Filename) { - ErrorOr> BufferOrErr = +Expected> convertFileToBinary(StringRef Filename) { + Expected> BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename); - if (BufferOrErr.getError()) - return errorCodeToError(BufferOrErr.getError()); - return createBinary(BufferOrErr.get()->getMemBufferRef()); + if (Error E = BufferOrErr.takeError()) + return E; + Expected> B = + createBinary(BufferOrErr.get()->getMemBufferRef()); + if (Error E = B.takeError()) + return createFileError(Filename, std::move(E)); + return B; } int main(int Argc, char **Argv) { @@ -63,24 +63,25 @@ ToolName = Argv[0]; - setErrorBanner(ExitOnErr, InputFileNameLHS); + ExitOnErr.setBanner(ToolName + ": error: "); auto BinLHS = ExitOnErr(convertFileToBinary(InputFileNameLHS)); TapiUniversal *FileLHS = dyn_cast(BinLHS.get()); if (!FileLHS) { - ExitOnErr( - createStringError(std::errc::executable_format_error, - "Error when parsing file, unsupported file format")); + ExitOnErr(createStringError( + std::errc::executable_format_error, + "%s: Error when parsing file, unsupported file format", + InputFileNameLHS.c_str())); } - setErrorBanner(ExitOnErr, InputFileNameRHS); auto BinRHS = ExitOnErr(convertFileToBinary(InputFileNameRHS)); TapiUniversal *FileRHS = dyn_cast(BinRHS.get()); if (!FileRHS) { - ExitOnErr( - createStringError(std::errc::executable_format_error, - "Error when parsing file, unsupported file format")); + ExitOnErr(createStringError( + std::errc::executable_format_error, + "%s: Error when parsing file, unsupported file format", + InputFileNameRHS.c_str())); } raw_ostream &OS = outs(); diff --git a/llvm/tools/llvm-undname/llvm-undname.cpp b/llvm/tools/llvm-undname/llvm-undname.cpp --- a/llvm/tools/llvm-undname/llvm-undname.cpp +++ b/llvm/tools/llvm-undname/llvm-undname.cpp @@ -92,11 +92,11 @@ cl::ParseCommandLineOptions(argc, argv, "llvm-undname\n"); if (!RawFile.empty()) { - ErrorOr> FileOrErr = + Expected> FileOrErr = MemoryBuffer::getFileOrSTDIN(RawFile); - if (std::error_code EC = FileOrErr.getError()) { + if (Error E = FileOrErr.takeError()) { WithColor::error() << "Could not open input file \'" << RawFile - << "\': " << EC.message() << '\n'; + << "\': " << toString(std::move(E)) << '\n'; return 1; } return msDemangle(std::string(FileOrErr->get()->getBuffer())) ? 0 : 1; diff --git a/llvm/tools/lto/lto.cpp b/llvm/tools/lto/lto.cpp --- a/llvm/tools/lto/lto.cpp +++ b/llvm/tools/lto/lto.cpp @@ -173,9 +173,11 @@ bool lto_module_is_object_file_for_target(const char* path, const char* target_triplet_prefix) { - ErrorOr> Buffer = MemoryBuffer::getFile(path); - if (!Buffer) + Expected> Buffer = MemoryBuffer::getFile(path); + if (Error E = Buffer.takeError()) { + consumeError(std::move(E)); return false; + } return LTOModule::isBitcodeForTarget(Buffer->get(), StringRef(target_triplet_prefix)); } diff --git a/llvm/tools/obj2yaml/obj2yaml.cpp b/llvm/tools/obj2yaml/obj2yaml.cpp --- a/llvm/tools/obj2yaml/obj2yaml.cpp +++ b/llvm/tools/obj2yaml/obj2yaml.cpp @@ -14,6 +14,7 @@ #include "llvm/Support/CommandLine.h" #include "llvm/Support/Errc.h" #include "llvm/Support/InitLLVM.h" +#include "llvm/Support/WithColor.h" using namespace llvm; using namespace llvm::object; @@ -34,13 +35,7 @@ llvm_unreachable("unexpected object file format"); } -static Error dumpInput(StringRef File) { - ErrorOr> FileOrErr = - MemoryBuffer::getFileOrSTDIN(File, /*IsText=*/false, - /*RequiresNullTerminator=*/false); - if (std::error_code EC = FileOrErr.getError()) - return errorCodeToError(EC); - std::unique_ptr &Buffer = FileOrErr.get(); +static Error dumpInputImpl(std::unique_ptr Buffer) { MemoryBufferRef MemBuf = Buffer->getMemBufferRef(); if (file_magic::archive == identify_magic(MemBuf.getBuffer())) return archive2yaml(outs(), MemBuf); @@ -63,15 +58,26 @@ return Error::success(); } -static void reportError(StringRef Input, Error Err) { - if (Input == "-") - Input = ""; +static Error dumpInput(StringRef File) { + Expected> FileOrErr = + MemoryBuffer::getFileOrSTDIN(File, /*IsText=*/false, + /*RequiresNullTerminator=*/false); + if (Error E = FileOrErr.takeError()) + return E; + // Get the Buffer's identifier, since it'll do the '-' -> '' mapping + // for us. + SmallString<32> Identifier = (*FileOrErr)->getBufferIdentifier(); + if (Error E = dumpInputImpl(std::move(*FileOrErr))) + return createFileError(Identifier, std::move(E)); + return Error::success(); +} + +static void reportError(const char *ProgName, Error Err) { std::string ErrMsg; raw_string_ostream OS(ErrMsg); logAllUnhandledErrors(std::move(Err), OS); OS.flush(); - errs() << "Error reading file: " << Input << ": " << ErrMsg; - errs().flush(); + WithColor::error(errs(), ProgName) << ErrMsg; } cl::opt InputFilename(cl::Positional, cl::desc(""), @@ -80,9 +86,10 @@ int main(int argc, char *argv[]) { InitLLVM X(argc, argv); cl::ParseCommandLineOptions(argc, argv); + const char *ProgName = argv[0]; if (Error Err = dumpInput(InputFilename)) { - reportError(InputFilename, std::move(Err)); + reportError(ProgName, std::move(Err)); return 1; } diff --git a/llvm/tools/sancov/sancov.cpp b/llvm/tools/sancov/sancov.cpp --- a/llvm/tools/sancov/sancov.cpp +++ b/llvm/tools/sancov/sancov.cpp @@ -227,10 +227,10 @@ ErrorOr> RawCoverage::read(const std::string &FileName) { - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFile(FileName); if (!BufOrErr) - return BufOrErr.getError(); + return errorToErrorCode(BufOrErr.takeError()); std::unique_ptr Buf = std::move(BufOrErr.get()); if (Buf->getBufferSize() < 8) { errs() << "File too small (<8): " << Buf->getBufferSize() << '\n'; @@ -365,7 +365,7 @@ std::map Points; ErrorOr> BufOrErr = - MemoryBuffer::getFile(InputFile); + expectedToErrorOr(MemoryBuffer::getFile(InputFile)); failIfError(BufOrErr); SourceMgr SM; @@ -842,7 +842,7 @@ return false; ErrorOr> BufOrErr = - MemoryBuffer::getFile(FileName); + expectedToErrorOr(MemoryBuffer::getFile(FileName)); if (!BufOrErr) { errs() << "Warning: " << BufOrErr.getError().message() << "(" << BufOrErr.getError().value() @@ -868,7 +868,7 @@ auto Coverage = std::make_unique(); ErrorOr> BufOrErr = - MemoryBuffer::getFile(ObjectFile); + expectedToErrorOr(MemoryBuffer::getFile(ObjectFile)); failIfError(BufOrErr); SHA1 Hasher; Hasher.update((*BufOrErr)->getBuffer()); diff --git a/llvm/tools/sanstats/sanstats.cpp b/llvm/tools/sanstats/sanstats.cpp --- a/llvm/tools/sanstats/sanstats.cpp +++ b/llvm/tools/sanstats/sanstats.cpp @@ -125,11 +125,11 @@ cl::ParseCommandLineOptions(argc, argv, "Sanitizer Statistics Processing Tool"); - ErrorOr> MBOrErr = MemoryBuffer::getFile( + Expected> MBOrErr = MemoryBuffer::getFile( ClInputFile, /*IsText=*/false, /*RequiresNullTerminator=*/false); - if (!MBOrErr) { - errs() << argv[0] << ": " << ClInputFile << ": " - << MBOrErr.getError().message() << '\n'; + if (Error E = MBOrErr.takeError()) { + errs() << argv[0] << ": " << ClInputFile << ": " << toString(std::move(E)) + << '\n'; return 1; } std::unique_ptr MB = std::move(MBOrErr.get()); diff --git a/llvm/tools/split-file/split-file.cpp b/llvm/tools/split-file/split-file.cpp --- a/llvm/tools/split-file/split-file.cpp +++ b/llvm/tools/split-file/split-file.cpp @@ -154,10 +154,10 @@ fatal("", "input filename is not specified"); if (output.empty()) fatal("", "output directory is not specified"); - ErrorOr> bufferOrErr = + Expected> bufferOrErr = MemoryBuffer::getFileOrSTDIN(input); - if (std::error_code ec = bufferOrErr.getError()) - fatal(input, ec.message()); + if (Error E = bufferOrErr.takeError()) + fatal(input, toString(std::move(E))); // Delete output if it is a file or an empty directory, so that we can create // a directory. diff --git a/llvm/tools/verify-uselistorder/verify-uselistorder.cpp b/llvm/tools/verify-uselistorder/verify-uselistorder.cpp --- a/llvm/tools/verify-uselistorder/verify-uselistorder.cpp +++ b/llvm/tools/verify-uselistorder/verify-uselistorder.cpp @@ -148,11 +148,10 @@ std::unique_ptr TempFile::readBitcode(LLVMContext &Context) const { LLVM_DEBUG(dbgs() << " - read bitcode\n"); - ErrorOr> BufferOr = + Expected> BufferOr = MemoryBuffer::getFile(Filename); - if (!BufferOr) { - errs() << "verify-uselistorder: error: " << BufferOr.getError().message() - << "\n"; + if (Error E = BufferOr.takeError()) { + errs() << "verify-uselistorder: error: " << toString(std::move(E)) << "\n"; return nullptr; } diff --git a/llvm/tools/yaml2obj/yaml2obj.cpp b/llvm/tools/yaml2obj/yaml2obj.cpp --- a/llvm/tools/yaml2obj/yaml2obj.cpp +++ b/llvm/tools/yaml2obj/yaml2obj.cpp @@ -123,10 +123,12 @@ return 1; } - ErrorOr> Buf = + Expected> Buf = MemoryBuffer::getFileOrSTDIN(Input); - if (!Buf) + if (Error E = Buf.takeError()) { + consumeError(std::move(E)); return 1; + } Optional Buffer = preprocess(Buf.get()->getBuffer(), ErrHandler); if (!Buffer) diff --git a/llvm/unittests/Support/MemoryBufferTest.cpp b/llvm/unittests/Support/MemoryBufferTest.cpp --- a/llvm/unittests/Support/MemoryBufferTest.cpp +++ b/llvm/unittests/Support/MemoryBufferTest.cpp @@ -112,8 +112,8 @@ ASSERT_THAT_EXPECTED(File, Succeeded()); auto OnExit = make_scope_exit([&] { ASSERT_NO_ERROR(sys::fs::closeFile(*File)); }); - ErrorOr MB = MemoryBuffer::getOpenFile(*File, TestPath, 6); - ASSERT_NO_ERROR(MB.getError()); + Expected MB = MemoryBuffer::getOpenFile(*File, TestPath, 6); + ASSERT_FALSE(!MB); EXPECT_EQ("123456", MB.get()->getBuffer()); } { @@ -122,7 +122,10 @@ ASSERT_THAT_EXPECTED(File, Succeeded()); auto OnExit = make_scope_exit([&] { ASSERT_NO_ERROR(sys::fs::closeFile(*File)); }); - ASSERT_ERROR(MemoryBuffer::getOpenFile(*File, TestPath, 6).getError()); + Expected> MB = + MemoryBuffer::getOpenFile(*File, TestPath, 6); + ASSERT_FALSE(MB); + consumeError(MB.takeError()); } } @@ -140,9 +143,8 @@ } OF.close(); - ErrorOr MB = MemoryBuffer::getFile(TestPath.c_str()); - std::error_code EC = MB.getError(); - ASSERT_FALSE(EC); + Expected MB = MemoryBuffer::getFile(TestPath.c_str()); + ASSERT_TRUE((bool)MB); const char *BufData = MB.get()->getBufferStart(); EXPECT_EQ('f', BufData[4095]); @@ -186,10 +188,10 @@ #endif } }); - ErrorOr MB = + Expected MB = MemoryBuffer::getOpenFile(pipes[0], "pipe", /*FileSize*/ -1); Writer.join(); - ASSERT_NO_ERROR(MB.getError()); + ASSERT_TRUE((bool)MB); EXPECT_EQ(MB.get()->getBuffer(), "foofoofoofoofoo"); } #endif @@ -242,14 +244,14 @@ EXPECT_FALSE(sys::fs::openFileForRead(TestPath.c_str(), TestFD)); } - ErrorOr Buf = MemoryBuffer::getOpenFileSlice( + Expected Buf = MemoryBuffer::getOpenFileSlice( sys::fs::convertFDToNativeFile(TestFD), TestPath.c_str(), 40000, // Size 80000 // Offset ); - std::error_code EC = Buf.getError(); - EXPECT_FALSE(EC); + Error E = Buf.takeError(); + EXPECT_FALSE(E); StringRef BufData = Buf.get()->getBuffer(); EXPECT_EQ(BufData.size(), 40000U); @@ -284,10 +286,9 @@ OF.close(); // Try offset of one page. - ErrorOr MB = MemoryBuffer::getFileSlice(TestPath.str(), - 0x4000, 0x1000); - std::error_code EC = MB.getError(); - ASSERT_FALSE(EC); + Expected MB = + MemoryBuffer::getFileSlice(TestPath.str(), 0x4000, 0x1000); + ASSERT_TRUE((bool)MB); EXPECT_EQ(0x4000UL, MB.get()->getBufferSize()); StringRef BufData = MB.get()->getBuffer(); @@ -299,10 +300,9 @@ EXPECT_TRUE(BufData.substr(0x3FF8,8).equals("ABCDEFGH")); // Try non-page aligned. - ErrorOr MB2 = MemoryBuffer::getFileSlice(TestPath.str(), - 0x3000, 0x0800); - EC = MB2.getError(); - ASSERT_FALSE(EC); + Expected MB2 = + MemoryBuffer::getFileSlice(TestPath.str(), 0x3000, 0x0800); + ASSERT_TRUE((bool)MB2); EXPECT_EQ(0x3000UL, MB2.get()->getBufferSize()); StringRef BufData2 = MB2.get()->getBuffer(); @@ -327,7 +327,7 @@ { auto MBOrError = WritableMemoryBuffer::getFileSlice(TestPath.str(), 0x6000, 0x2000); - ASSERT_FALSE(MBOrError.getError()); + ASSERT_TRUE((bool)MBOrError); // Write some data. It should be mapped private, so that upon completion // the original file contents are not modified. WritableMemoryBuffer &MB = **MBOrError; @@ -338,7 +338,7 @@ } auto MBOrError = MemoryBuffer::getFile(TestPath); - ASSERT_FALSE(MBOrError.getError()); + ASSERT_TRUE((bool)MBOrError); auto &MB = **MBOrError; ASSERT_EQ(0x10000u, MB.getBufferSize()); for (size_t i = 0; i < MB.getBufferSize(); i += 0x10) @@ -357,7 +357,7 @@ OF.close(); { auto MBOrError = WriteThroughMemoryBuffer::getFile(TestPath); - ASSERT_FALSE(MBOrError.getError()); + ASSERT_TRUE((bool)MBOrError); // Write some data. It should be mapped readwrite, so that upon completion // the original file contents are modified. WriteThroughMemoryBuffer &MB = **MBOrError; @@ -368,7 +368,7 @@ } auto MBOrError = MemoryBuffer::getFile(TestPath); - ASSERT_FALSE(MBOrError.getError()); + ASSERT_TRUE((bool)MBOrError); auto &MB = **MBOrError; ASSERT_EQ(16u, MB.getBufferSize()); EXPECT_EQ("xxxxxxxxxxxxxxxx", MB.getBuffer()); @@ -402,7 +402,7 @@ auto MBOrError = MemoryBuffer::getOpenFile(*File, TestPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false, /*IsVolatile=*/true); - ASSERT_NO_ERROR(MBOrError.getError()) + ASSERT_TRUE((bool)MBOrError); OwningBuffer MB = std::move(*MBOrError); EXPECT_EQ(MB->getBufferKind(), MemoryBuffer::MemoryBuffer_MMap); EXPECT_EQ(MB->getBufferSize(), std::size_t(FileWrites * 8)); diff --git a/llvm/unittests/Support/TarWriterTest.cpp b/llvm/unittests/Support/TarWriterTest.cpp --- a/llvm/unittests/Support/TarWriterTest.cpp +++ b/llvm/unittests/Support/TarWriterTest.cpp @@ -52,7 +52,7 @@ Tar.reset(); // Read the tar file. - ErrorOr> MBOrErr = + Expected> MBOrErr = MemoryBuffer::getFile(TarWriterTest.path()); EXPECT_TRUE((bool)MBOrErr); std::unique_ptr MB = std::move(*MBOrErr); diff --git a/llvm/unittests/Support/raw_ostream_test.cpp b/llvm/unittests/Support/raw_ostream_test.cpp --- a/llvm/unittests/Support/raw_ostream_test.cpp +++ b/llvm/unittests/Support/raw_ostream_test.cpp @@ -474,9 +474,9 @@ } static void checkFileData(StringRef FileName, StringRef GoldenData) { - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFileOrSTDIN(FileName); - EXPECT_FALSE(BufOrErr.getError()); + EXPECT_TRUE((bool)BufOrErr); EXPECT_EQ((*BufOrErr)->getBufferSize(), GoldenData.size()); EXPECT_EQ(memcmp((*BufOrErr)->getBufferStart(), GoldenData.data(), diff --git a/llvm/utils/FileCheck/FileCheck.cpp b/llvm/utils/FileCheck/FileCheck.cpp --- a/llvm/utils/FileCheck/FileCheck.cpp +++ b/llvm/utils/FileCheck/FileCheck.cpp @@ -821,11 +821,11 @@ SourceMgr SM; // Read the expected strings from the check file. - ErrorOr> CheckFileOrErr = + Expected> CheckFileOrErr = MemoryBuffer::getFileOrSTDIN(CheckFilename, /*IsText=*/true); - if (std::error_code EC = CheckFileOrErr.getError()) { + if (Error E = CheckFileOrErr.takeError()) { errs() << "Could not open check file '" << CheckFilename - << "': " << EC.message() << '\n'; + << "': " << toString(std::move(E)) << '\n'; return 2; } MemoryBuffer &CheckFile = *CheckFileOrErr.get(); @@ -843,13 +843,13 @@ return 2; // Open the file to check and add it to SourceMgr. - ErrorOr> InputFileOrErr = + Expected> InputFileOrErr = MemoryBuffer::getFileOrSTDIN(InputFilename, /*IsText=*/true); if (InputFilename == "-") InputFilename = ""; // Overwrite for improved diagnostic messages - if (std::error_code EC = InputFileOrErr.getError()) { + if (Error E = InputFileOrErr.takeError()) { errs() << "Could not open input file '" << InputFilename - << "': " << EC.message() << '\n'; + << "': " << toString(std::move(E)) << '\n'; return 2; } MemoryBuffer &InputFile = *InputFileOrErr.get(); diff --git a/llvm/utils/yaml-bench/YAMLBench.cpp b/llvm/utils/yaml-bench/YAMLBench.cpp --- a/llvm/utils/yaml-bench/YAMLBench.cpp +++ b/llvm/utils/yaml-bench/YAMLBench.cpp @@ -199,11 +199,13 @@ ? sys::Process::StandardOutHasColors() : UseColor == cl::BOU_TRUE; if (Input.getNumOccurrences()) { - ErrorOr> BufOrErr = + Expected> BufOrErr = MemoryBuffer::getFileOrSTDIN(Input); - if (!BufOrErr) + if (Error E = BufOrErr.takeError()) { + consumeError(std::move(E)); return 1; - MemoryBuffer &Buf = *BufOrErr.get(); + } + MemoryBuffer &Buf = **BufOrErr; llvm::SourceMgr sm; if (DumpTokens) {