From bf9eab8aa038619548d9ac90d6156e3b8f90fff4 Mon Sep 17 00:00:00 2001 From: Jan Svoboda Date: Tue, 21 Oct 2025 15:48:10 -0700 Subject: [PATCH] Revert "[clang] Cherry-pick FS sandboxing (pt. 1)" --- .../lib/Tooling/ApplyReplacements.cpp | 2 +- .../clang-include-fixer/IncludeFixer.cpp | 5 +- clang-tools-extra/clang-move/Move.cpp | 2 +- clang-tools-extra/clangd/Compiler.cpp | 10 +- clang-tools-extra/clangd/ConfigCompile.cpp | 2 +- .../clangd/SystemIncludeExtractor.cpp | 2 +- .../clangd/index/SymbolCollector.cpp | 2 +- clang-tools-extra/clangd/tool/ClangdMain.cpp | 6 +- .../include-cleaner/tool/IncludeCleaner.cpp | 2 +- .../include-cleaner/unittests/RecordTest.cpp | 10 +- .../clang/Basic/DiagnosticDriverKinds.td | 6 +- .../clang/Basic/DiagnosticFrontendKinds.td | 3 - clang/include/clang/CodeGen/BackendUtil.h | 2 +- clang/include/clang/Driver/Options.td | 11 +- clang/include/clang/Frontend/ASTUnit.h | 7 +- .../include/clang/Frontend/CompilerInstance.h | 51 ++--- .../clang/Frontend/CompilerInvocation.h | 3 +- clang/include/clang/Frontend/Utils.h | 5 +- clang/include/clang/Lex/HeaderSearch.h | 3 - .../include/clang/Serialization/ModuleCache.h | 9 +- clang/lib/CodeGen/BackendUtil.cpp | 57 +++-- clang/lib/CodeGen/CGOpenMPRuntime.cpp | 10 +- clang/lib/CodeGen/CodeGenAction.cpp | 3 +- clang/lib/CodeGen/CodeGenModule.cpp | 35 +--- clang/lib/CrossTU/CrossTranslationUnit.cpp | 16 +- clang/lib/Driver/ToolChains/Clang.cpp | 43 +--- clang/lib/ExtractAPI/ExtractAPIConsumer.cpp | 3 +- clang/lib/Frontend/ASTMerge.cpp | 3 +- clang/lib/Frontend/ASTUnit.cpp | 15 +- clang/lib/Frontend/ChainedIncludesSource.cpp | 3 +- clang/lib/Frontend/CompileJobCache.cpp | 6 +- clang/lib/Frontend/CompilerInstance.cpp | 198 ++++++++++++------ clang/lib/Frontend/CompilerInvocation.cpp | 96 +++++++-- clang/lib/Frontend/FrontendAction.cpp | 26 ++- .../Frontend/ModuleDependencyCollector.cpp | 11 +- clang/lib/Frontend/PrecompiledPreamble.cpp | 5 +- .../lib/Frontend/Rewrite/FrontendActions.cpp | 2 +- .../ExecuteCompilerInvocation.cpp | 13 +- clang/lib/Interpreter/Interpreter.cpp | 7 +- clang/lib/Lex/HeaderSearch.cpp | 14 +- clang/lib/Serialization/ASTWriter.cpp | 7 +- clang/lib/Serialization/ModuleCache.cpp | 86 -------- clang/lib/StaticAnalyzer/Checkers/Yaml.h | 8 +- .../StaticAnalyzer/Frontend/ModelInjector.cpp | 15 +- clang/lib/Testing/TestAST.cpp | 12 +- .../DependencyScanningWorker.cpp | 108 ++++++---- .../InProcessModuleCache.cpp | 7 - .../IncludeTreeActionController.cpp | 3 +- clang/lib/Tooling/Tooling.cpp | 5 +- .../Inputs/taint-generic-config-vfs.json | 17 -- clang/test/Analysis/model-file-missing.cpp | 3 - clang/test/Analysis/taint-generic.c | 6 +- clang/test/CAS/output-path-error.c | 2 +- clang/test/CAS/pgo-profile-with-pch.c | 6 +- clang/test/CAS/pgo-profile.c | 16 +- clang/test/CodeGen/cspgo-instrumentation.c | 6 +- .../test/CodeGen/cspgo-instrumentation_lto.c | 6 +- .../CodeGen/cspgo-instrumentation_thinlto.c | 8 +- clang/test/CodeGen/opt-record.c | 2 +- clang/test/CodeGen/pgo-instrumentation.c | 4 +- .../thinlto-clang-diagnostic-handler-in-be.c | 2 +- .../CodeGenCXX/fdebug-info-for-profiling.cpp | 2 +- clang/test/CodeGenCXX/profile-remap.cpp | 4 +- clang/test/Driver/Inputs/a.proftext | 2 - clang/test/Driver/cl-options.c | 17 +- clang/test/Driver/clang_f_opts.c | 18 +- clang/test/Driver/fcs-profile-generate.c | 12 +- clang/test/Driver/fsplit-machine-functions.c | 12 +- .../optimization-remark-with-hotness-new-pm.c | 11 +- ...dules-cache-path-canonicalization-output.c | 18 -- clang/test/OpenMP/amdgcn_save_temps.c | 23 -- clang/test/OpenMP/host-ir-file-vfs.c | 33 --- clang/test/Profile/c-captured.c | 2 +- clang/test/Profile/c-counter-overflows.c | 2 +- clang/test/Profile/c-general.c | 8 +- clang/test/Profile/c-outdated-data.c | 4 +- clang/test/Profile/c-unprofiled-blocks.c | 2 +- clang/test/Profile/c-unprofiled.c | 2 +- clang/test/Profile/cxx-class.cpp | 2 +- clang/test/Profile/cxx-hash-v2.cpp | 4 +- clang/test/Profile/cxx-lambda.cpp | 2 +- clang/test/Profile/cxx-missing-bodies.cpp | 2 +- .../Profile/cxx-never-executed-branch.cpp | 2 +- clang/test/Profile/cxx-rangefor.cpp | 2 +- clang/test/Profile/cxx-templates.cpp | 2 +- clang/test/Profile/cxx-throws.cpp | 4 +- clang/test/Profile/func-entry.c | 2 +- clang/test/Profile/misexpect-branch-cold.c | 2 +- .../misexpect-branch-nonconst-expected-val.c | 2 +- .../Profile/misexpect-branch-unpredictable.c | 2 +- clang/test/Profile/misexpect-branch.c | 8 +- clang/test/Profile/misexpect-switch-default.c | 2 +- .../test/Profile/misexpect-switch-nonconst.c | 2 +- .../misexpect-switch-only-default-case.c | 2 +- clang/test/Profile/misexpect-switch.c | 2 +- clang/test/Profile/objc-general.m | 2 +- .../test/Profile/profile-does-not-exist-ir.c | 10 +- clang/test/Profile/profile-does-not-exist.c | 6 +- clang/test/Profile/profile-summary.c | 2 +- clang/test/VFS/broken-vfs-module-dep.c | 1 + clang/tools/c-index-test/core_main.cpp | 7 +- .../ClangExtDefMapGen.cpp | 4 +- .../clang-import-test/clang-import-test.cpp | 6 +- .../clang-installapi/ClangInstallAPI.cpp | 2 +- clang/tools/driver/cc1_main.cpp | 8 +- clang/tools/driver/cc1as_main.cpp | 16 +- clang/tools/driver/driver.cpp | 21 +- clang/tools/libclang/CDependencies.cpp | 5 +- clang/tools/libclang/CIndex.cpp | 7 +- clang/unittests/AST/ExternalASTSourceTest.cpp | 3 +- clang/unittests/CodeGen/TestCompiler.h | 5 +- clang/unittests/Driver/ToolChainTest.cpp | 3 +- clang/unittests/Frontend/ASTUnitTest.cpp | 3 +- .../unittests/Frontend/CodeGenActionTest.cpp | 6 +- .../Frontend/CompilerInstanceTest.cpp | 6 +- .../unittests/Frontend/FrontendActionTest.cpp | 19 +- clang/unittests/Frontend/OutputStreamTest.cpp | 9 +- .../Serialization/ForceCheckFileInputTest.cpp | 11 +- .../Serialization/ModuleCacheTest.cpp | 4 - .../Serialization/NoCommentsTest.cpp | 1 - .../PreambleInNamedModulesTest.cpp | 8 +- clang/unittests/Support/TimeProfilerTest.cpp | 7 +- .../DependencyScannerTest.cpp | 5 +- flang/lib/Frontend/CompilerInvocation.cpp | 3 +- flang/lib/Frontend/FrontendActions.cpp | 6 +- lldb/source/Commands/CommandObjectTarget.cpp | 4 +- .../Clang/ClangExpressionParser.cpp | 8 +- .../Clang/ClangModulesDeclVendor.cpp | 3 +- .../Clang/ModuleDependencyCollector.h | 4 +- llvm/include/llvm/CodeGen/AsmPrinter.h | 8 - .../llvm/Frontend/OpenMP/OMPIRBuilder.h | 9 +- llvm/include/llvm/Passes/PassBuilder.h | 19 +- llvm/include/llvm/Support/CommandLine.h | 4 +- llvm/include/llvm/Support/FileCollector.h | 11 +- llvm/include/llvm/Support/FileSystem.h | 12 ++ llvm/include/llvm/Support/PGOOptions.h | 11 +- llvm/include/llvm/Support/Path.h | 12 -- llvm/include/llvm/Support/SourceMgr.h | 11 +- llvm/include/llvm/Support/VirtualFileSystem.h | 10 +- .../Instrumentation/DataFlowSanitizer.h | 7 +- .../Transforms/Instrumentation/GCOVProfiler.h | 7 +- llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp | 2 - .../AsmPrinter/AsmPrinterInlineAsm.cpp | 2 - llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp | 20 +- llvm/lib/LTO/LTOBackend.cpp | 17 +- llvm/lib/Passes/PassBuilder.cpp | 5 +- llvm/lib/Passes/PassBuilderPipelines.cpp | 43 ++-- llvm/lib/Support/CommandLine.cpp | 24 +-- llvm/lib/Support/FileCollector.cpp | 16 +- llvm/lib/Support/PGOOptions.cpp | 9 +- llvm/lib/Support/Path.cpp | 100 ++++----- llvm/lib/Support/SourceMgr.cpp | 18 +- llvm/lib/Support/VirtualFileSystem.cpp | 31 +-- llvm/lib/TableGen/Main.cpp | 2 - llvm/lib/TableGen/Parser.cpp | 2 - llvm/lib/Target/ARM/ARMExpandPseudoInsts.cpp | 2 - llvm/lib/Target/X86/X86InstrInfo.cpp | 1 - .../Instrumentation/DataFlowSanitizer.cpp | 12 +- .../Instrumentation/GCOVProfiling.cpp | 30 ++- llvm/tools/dsymutil/Reproducer.cpp | 5 +- llvm/tools/llvm-config/llvm-config.cpp | 6 +- llvm/tools/llvm-dwp/llvm-dwp.cpp | 2 +- .../llvm-mc-assemble-fuzzer.cpp | 2 - llvm/tools/llvm-mc/llvm-mc.cpp | 2 - llvm/tools/llvm-ml/llvm-ml.cpp | 2 - llvm/tools/llvm-opt-report/OptReport.cpp | 2 +- llvm/tools/obj2yaml/obj2yaml.cpp | 2 +- llvm/tools/opt/NewPMDriver.cpp | 14 +- llvm/tools/yaml2obj/yaml2obj.cpp | 2 +- llvm/unittests/Support/CommandLineTest.cpp | 12 +- llvm/unittests/Support/FileCollectorTest.cpp | 21 +- llvm/unittests/Support/Path.cpp | 4 +- llvm/unittests/Support/SourceMgrTest.cpp | 10 - .../Support/VirtualFileSystemTest.cpp | 55 +---- llvm/utils/FileCheck/FileCheck.cpp | 2 +- llvm/utils/split-file/split-file.cpp | 1 - mlir/lib/IR/Diagnostics.cpp | 6 +- .../OpenMP/OpenMPToLLVMIRTranslation.cpp | 21 +- mlir/lib/Tools/PDLL/Parser/Parser.cpp | 2 - .../Tools/mlir-pdll-lsp-server/PDLLServer.cpp | 2 - .../tblgen-lsp-server/TableGenServer.cpp | 2 - mlir/tools/mlir-pdll/mlir-pdll.cpp | 2 - 182 files changed, 865 insertions(+), 1240 deletions(-) delete mode 100644 clang/test/Analysis/Inputs/taint-generic-config-vfs.json delete mode 100644 clang/test/Analysis/model-file-missing.cpp delete mode 100644 clang/test/Driver/Inputs/a.proftext delete mode 100644 clang/test/Modules/modules-cache-path-canonicalization-output.c delete mode 100644 clang/test/OpenMP/amdgcn_save_temps.c delete mode 100644 clang/test/OpenMP/host-ir-file-vfs.c diff --git a/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp b/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp index 0ac8f712e112f..b895075e4f31c 100644 --- a/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp +++ b/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp @@ -142,7 +142,7 @@ groupReplacements(const TUReplacements &TUs, const TUDiagnostics &TUDs, // build directories, make them absolute immediately. SmallString<128> Path = R.getFilePath(); if (BuildDir) - llvm::sys::path::make_absolute(*BuildDir, Path); + llvm::sys::fs::make_absolute(*BuildDir, Path); else SM.getFileManager().makeAbsolutePath(Path); diff --git a/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp b/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp index fa3ec4a975d65..7b0e4ecda8214 100644 --- a/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp +++ b/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp @@ -94,9 +94,10 @@ bool IncludeFixerActionFactory::runInvocation( // Create the compiler's actual diagnostics engine. We want to drop all // diagnostics here. - Compiler.createDiagnostics(new clang::IgnoringDiagConsumer, + Compiler.createDiagnostics(Files->getVirtualFileSystem(), + new clang::IgnoringDiagConsumer, /*ShouldOwnClient=*/true); - Compiler.createSourceManager(); + Compiler.createSourceManager(*Files); // We abort on fatal errors so don't let a large number of errors become // fatal. A missing #include can cause thousands of errors. diff --git a/clang-tools-extra/clang-move/Move.cpp b/clang-tools-extra/clang-move/Move.cpp index 519d359991cdb..17f597170f9f6 100644 --- a/clang-tools-extra/clang-move/Move.cpp +++ b/clang-tools-extra/clang-move/Move.cpp @@ -75,7 +75,7 @@ std::string MakeAbsolutePath(StringRef CurrentDir, StringRef Path) { return ""; llvm::SmallString<128> InitialDirectory(CurrentDir); llvm::SmallString<128> AbsolutePath(Path); - llvm::sys::path::make_absolute(InitialDirectory, AbsolutePath); + llvm::sys::fs::make_absolute(InitialDirectory, AbsolutePath); return CleanPath(std::move(AbsolutePath)); } diff --git a/clang-tools-extra/clangd/Compiler.cpp b/clang-tools-extra/clangd/Compiler.cpp index 6ebc2eac25745..8b3865c8a8e5c 100644 --- a/clang-tools-extra/clangd/Compiler.cpp +++ b/clang-tools-extra/clangd/Compiler.cpp @@ -147,9 +147,13 @@ prepareCompilerInstance(std::unique_ptr CI, } auto Clang = std::make_unique(std::move(CI)); - Clang->createVirtualFileSystem(VFS, &DiagsClient); - Clang->createDiagnostics(&DiagsClient, false); - Clang->createFileManager(); + Clang->createDiagnostics(*VFS, &DiagsClient, false); + + if (auto VFSWithRemapping = createVFSFromCompilerInvocation( + Clang->getInvocation(), Clang->getDiagnostics(), VFS)) + VFS = VFSWithRemapping; + Clang->createFileManager(VFS); + if (!Clang->createTarget()) return nullptr; diff --git a/clang-tools-extra/clangd/ConfigCompile.cpp b/clang-tools-extra/clangd/ConfigCompile.cpp index 6a5206df9a261..35d35f747a868 100644 --- a/clang-tools-extra/clangd/ConfigCompile.cpp +++ b/clang-tools-extra/clangd/ConfigCompile.cpp @@ -131,7 +131,7 @@ struct FragmentCompiler { return std::nullopt; } llvm::SmallString<256> AbsPath = llvm::StringRef(*Path); - llvm::sys::path::make_absolute(FragmentDirectory, AbsPath); + llvm::sys::fs::make_absolute(FragmentDirectory, AbsPath); llvm::sys::path::native(AbsPath, Style); return AbsPath.str().str(); } diff --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp index b4f0c4f765c2f..0b067e8b0b2b2 100644 --- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp +++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp @@ -106,7 +106,7 @@ struct DriverArgs { // relative or absolute). if (llvm::any_of(Driver, [](char C) { return llvm::sys::path::is_separator(C); })) { - llvm::sys::path::make_absolute(Cmd.Directory, Driver); + llvm::sys::fs::make_absolute(Cmd.Directory, Driver); } this->Driver = Driver.str().str(); for (size_t I = 0, E = Cmd.CommandLine.size(); I < E; ++I) { diff --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp b/clang-tools-extra/clangd/index/SymbolCollector.cpp index 39c479b5f4d5b..6bdb1080fb294 100644 --- a/clang-tools-extra/clangd/index/SymbolCollector.cpp +++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp @@ -325,7 +325,7 @@ class SymbolCollector::HeaderFileURICache { if (R.second) { llvm::SmallString<256> AbsPath = Path; if (!llvm::sys::path::is_absolute(AbsPath) && !FallbackDir.empty()) - llvm::sys::path::make_absolute(FallbackDir, AbsPath); + llvm::sys::fs::make_absolute(FallbackDir, AbsPath); assert(llvm::sys::path::is_absolute(AbsPath) && "If the VFS can't make paths absolute, a FallbackDir must be " "provided"); diff --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp b/clang-tools-extra/clangd/tool/ClangdMain.cpp index 91b2422d412c8..f287439f10cab 100644 --- a/clang-tools-extra/clangd/tool/ClangdMain.cpp +++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp @@ -577,7 +577,7 @@ class TestScheme : public URIScheme { Body = Body.ltrim('/'); llvm::SmallString<16> Path(Body); path::native(Path); - path::make_absolute(TestScheme::TestDir, Path); + fs::make_absolute(TestScheme::TestDir, Path); return std::string(Path); } @@ -775,8 +775,8 @@ It should be used via an editor plugin rather than invoked directly. For more in clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment variable. )"; llvm::cl::HideUnrelatedOptions(ClangdCategories); - llvm::cl::ParseCommandLineOptions(argc, argv, Overview, /*Errs=*/nullptr, - /*VFS=*/nullptr, FlagsEnvVar); + llvm::cl::ParseCommandLineOptions(argc, argv, Overview, + /*Errs=*/nullptr, FlagsEnvVar); if (Test) { if (!Sync.getNumOccurrences()) Sync = true; diff --git a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp index fefbfc3a9614d..372ab5fa2706e 100644 --- a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp +++ b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp @@ -344,7 +344,7 @@ mapInputsToAbsPaths(clang::tooling::CompilationDatabase &CDB, } for (const auto &Cmd : Cmds) { llvm::SmallString<256> CDBPath(Cmd.Filename); - llvm::sys::path::make_absolute(Cmd.Directory, CDBPath); + llvm::sys::fs::make_absolute(Cmd.Directory, CDBPath); CDBToAbsPaths[std::string(CDBPath)] = std::string(AbsPath); } } diff --git a/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp b/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp index fc8b23ffcb17c..91d2697712b6e 100644 --- a/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp +++ b/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp @@ -625,15 +625,13 @@ TEST_F(PragmaIncludeTest, ExportInUnnamedBuffer) { *Diags, "clang")); auto Clang = std::make_unique(std::move(Invocation)); - Clang->createVirtualFileSystem(VFS); - Clang->createDiagnostics(); + Clang->createDiagnostics(*VFS); - Clang->createFileManager(); - FileManager &FM = Clang->getFileManager(); + auto *FM = Clang->createFileManager(VFS); ASSERT_TRUE(Clang->ExecuteAction(*Inputs.MakeAction())); EXPECT_THAT( - PI.getExporters(llvm::cantFail(FM.getFileRef("foo.h")), FM), - testing::ElementsAre(llvm::cantFail(FM.getFileRef("exporter.h")))); + PI.getExporters(llvm::cantFail(FM->getFileRef("foo.h")), *FM), + testing::ElementsAre(llvm::cantFail(FM->getFileRef("exporter.h")))); } TEST_F(PragmaIncludeTest, OutlivesFMAndSM) { diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td b/clang/include/clang/Basic/DiagnosticDriverKinds.td index 0141205adafd5..ab66191a3fc0f 100644 --- a/clang/include/clang/Basic/DiagnosticDriverKinds.td +++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td @@ -367,6 +367,9 @@ def err_drv_optimization_remark_format : Error< def err_drv_no_neon_modifier : Error<"[no]neon is not accepted as modifier, please use [no]simd instead">; def err_drv_invalid_omp_target : Error<"OpenMP target is invalid: '%0'">; def err_drv_incompatible_omp_arch : Error<"OpenMP target architecture '%0' pointer size is incompatible with host '%1'">; +def err_drv_omp_host_ir_file_not_found : Error< + "provided host compiler IR file '%0' is required to generate code for OpenMP " + "target regions but cannot be found">; def err_drv_omp_host_target_not_supported : Error< "target '%0' is not a supported OpenMP host target">; def err_drv_ptrauth_not_supported : Error< @@ -683,9 +686,6 @@ def warn_drv_fine_grained_bitfield_accesses_ignored : Warning< "option '-ffine-grained-bitfield-accesses' cannot be enabled together with a sanitizer; flag ignored">, InGroup; -def err_drv_profile_instrument_use_path_with_no_kind : Error< - "option '-fprofile-instrument-use-path=' requires -fprofile-instrument-use=">; - def note_drv_verify_prefix_spelling : Note< "-verify prefixes must start with a letter and contain only alphanumeric" " characters, hyphens, and underscores">; diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index fac9d81ee542a..a45500887588a 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -327,9 +327,6 @@ def err_target_unsupported_type_for_abi : Error<"%0 requires %1 type support, but ABI '%2' does not support it">; } -def err_omp_host_ir_file_not_found : Error< - "provided host compiler IR file '%0' is required to generate code for OpenMP " - "target regions but cannot be found">; def err_alias_to_undefined : Error< "%select{alias|ifunc}0 must point to a defined " "%select{variable or |}1function">; diff --git a/clang/include/clang/CodeGen/BackendUtil.h b/clang/include/clang/CodeGen/BackendUtil.h index 9a2b31393735b..bae2798b09f66 100644 --- a/clang/include/clang/CodeGen/BackendUtil.h +++ b/clang/include/clang/CodeGen/BackendUtil.h @@ -52,7 +52,7 @@ void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf); void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, - llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags); + DiagnosticsEngine &Diags); } // namespace clang #endif diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 8962a035a4e2a..ab36095da58d4 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -3399,8 +3399,7 @@ defm declspec : BoolOption<"f", "declspec", def fmodules_cache_path : Joined<["-"], "fmodules-cache-path=">, Group, Flags<[]>, Visibility<[ClangOption, CC1Option]>, MetaVarName<"">, - HelpText<"Specify the module cache path">, - MarshallingInfoString>; + HelpText<"Specify the module cache path">; def fmodules_user_build_path : Separate<["-"], "fmodules-user-build-path">, Group, Flags<[]>, Visibility<[ClangOption, CC1Option]>, MetaVarName<"">, @@ -8084,11 +8083,6 @@ def fprofile_instrument_path_EQ : Joined<["-"], "fprofile-instrument-path=">, HelpText<"Generate instrumented code to collect execution counts into " " (overridden by LLVM_PROFILE_FILE env var)">, MarshallingInfoString>; -def fprofile_instrument_use_EQ : Joined<["-"], "fprofile-instrument-use=">, - HelpText<"Enable PGO use instrumentation">, Values<"none,clang,llvm,csllvm,sample-coldcov">, - NormalizedValuesScope<"llvm::driver::ProfileInstrKind">, - NormalizedValues<["ProfileNone", "ProfileClangInstr", "ProfileIRInstr", "ProfileCSIRInstr", "ProfileIRSampleColdCov"]>, - MarshallingInfoEnum, "ProfileNone">; def fprofile_instrument_use_path_EQ : Joined<["-"], "fprofile-instrument-use-path=">, HelpText<"Specify the profile path in PGO use compilation">, @@ -8892,8 +8886,7 @@ def fopenmp_is_target_device : Flag<["-"], "fopenmp-is-target-device">, HelpText<"Generate code only for an OpenMP target device.">; def : Flag<["-"], "fopenmp-is-device">, Alias; def fopenmp_host_ir_file_path : Separate<["-"], "fopenmp-host-ir-file-path">, - HelpText<"Path to the IR file produced by the frontend for the host.">, - MarshallingInfoString>; + HelpText<"Path to the IR file produced by the frontend for the host.">; } // let Visibility = [CC1Option, FC1Option] diff --git a/clang/include/clang/Frontend/ASTUnit.h b/clang/include/clang/Frontend/ASTUnit.h index b7ba65a8d85bc..1485192e8f1e3 100644 --- a/clang/include/clang/Frontend/ASTUnit.h +++ b/clang/include/clang/Frontend/ASTUnit.h @@ -706,15 +706,16 @@ class ASTUnit { /// \returns - The initialized ASTUnit or null if the AST failed to load. static std::unique_ptr LoadFromASTFile( StringRef Filename, const PCHContainerReader &PCHContainerRdr, - WhatToLoad ToLoad, IntrusiveRefCntPtr VFS, - std::shared_ptr DiagOpts, + WhatToLoad ToLoad, std::shared_ptr DiagOpts, IntrusiveRefCntPtr Diags, const FileSystemOptions &FileSystemOpts, const HeaderSearchOptions &HSOpts, const LangOptions *LangOpts = nullptr, bool OnlyLocalDecls = false, CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::None, bool AllowASTWithCompilerErrors = false, - bool UserFilesAreVolatile = false); + bool UserFilesAreVolatile = false, + IntrusiveRefCntPtr VFS = + llvm::vfs::getRealFileSystem()); private: /// Helper function for \c LoadFromCompilerInvocation() and diff --git a/clang/include/clang/Frontend/CompilerInstance.h b/clang/include/clang/Frontend/CompilerInstance.h index 91782a2694886..72861e573ea34 100644 --- a/clang/include/clang/Frontend/CompilerInstance.h +++ b/clang/include/clang/Frontend/CompilerInstance.h @@ -87,9 +87,6 @@ class CompilerInstance : public ModuleLoader { /// The options used in this compiler instance. std::shared_ptr Invocation; - /// The virtual file system instance. - IntrusiveRefCntPtr VFS; - /// The diagnostics engine instance. IntrusiveRefCntPtr Diagnostics; @@ -456,31 +453,7 @@ class CompilerInstance : public ModuleLoader { /// @name Virtual File System /// @{ - bool hasVirtualFileSystem() const { return VFS != nullptr; } - - /// Create a virtual file system instance based on the invocation. - /// - /// @param BaseFS The file system that may be used when configuring the final - /// file system, and act as the underlying file system. Must not - /// be NULL. - /// @param DC If non-NULL, the diagnostic consumer to be used in case - /// configuring the file system emits diagnostics. Note that the - /// DiagnosticsEngine using the consumer won't obey the - /// --warning-suppression-mappings= flag. - void createVirtualFileSystem(IntrusiveRefCntPtr - BaseFS = llvm::vfs::getRealFileSystem(), - DiagnosticConsumer *DC = nullptr); - - /// Use the given file system. - void setVirtualFileSystem(IntrusiveRefCntPtr FS) { - VFS = std::move(FS); - } - - llvm::vfs::FileSystem &getVirtualFileSystem() const { return *VFS; } - - IntrusiveRefCntPtr getVirtualFileSystemPtr() const { - return VFS; - } + llvm::vfs::FileSystem &getVirtualFileSystem() const; /// @} /// @name File Manager @@ -718,31 +691,32 @@ class CompilerInstance : public ModuleLoader { /// Note that this routine also replaces the diagnostic client, /// allocating one if one is not provided. /// + /// \param VFS is used for any IO needed when creating DiagnosticsEngine. It + /// doesn't replace VFS in the CompilerInstance (if any). + /// /// \param Client If non-NULL, a diagnostic client that will be /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST /// unit. /// /// \param ShouldOwnClient If Client is non-NULL, specifies whether /// the diagnostic object should take ownership of the client. - void createDiagnostics(DiagnosticConsumer *Client = nullptr, + void createDiagnostics(llvm::vfs::FileSystem &VFS, + DiagnosticConsumer *Client = nullptr, bool ShouldOwnClient = true); - /// Create a DiagnosticsEngine object. + /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter. /// /// If no diagnostic client is provided, this creates a /// DiagnosticConsumer that is owned by the returned diagnostic /// object, if using directly the caller is responsible for /// releasing the returned DiagnosticsEngine's client eventually. /// - /// \param VFS The file system used to load the suppression mappings file. - /// /// \param Opts - The diagnostic options; note that the created text /// diagnostic object contains a reference to these options. /// /// \param Client If non-NULL, a diagnostic client that will be /// attached to (and, then, owned by) the returned DiagnosticsEngine - /// object. If NULL, the returned DiagnosticsEngine will own a newly-created - /// client. + /// object. /// /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be /// used by some diagnostics printers (for logging purposes only). @@ -755,10 +729,13 @@ class CompilerInstance : public ModuleLoader { const CodeGenOptions *CodeGenOpts = nullptr); /// Create the file manager and replace any existing one with it. - void createFileManager(); + /// + /// \return The new file manager on success, or null on failure. + FileManager * + createFileManager(IntrusiveRefCntPtr VFS = nullptr); /// Create the source manager and replace any existing one with it. - void createSourceManager(); + void createSourceManager(FileManager &FileMgr); /// Create the preprocessor, using the invocation, file, and source managers, /// and replace any existing one with it. @@ -1028,7 +1005,7 @@ class CompilerInstance : public ModuleLoader { std::pair, std::shared_ptr> - getOrCreateCASDatabases(); + createCASDatabases(); }; } // end namespace clang diff --git a/clang/include/clang/Frontend/CompilerInvocation.h b/clang/include/clang/Frontend/CompilerInvocation.h index d3455d240d916..4bf5f8ec15b86 100644 --- a/clang/include/clang/Frontend/CompilerInvocation.h +++ b/clang/include/clang/Frontend/CompilerInvocation.h @@ -434,8 +434,7 @@ IntrusiveRefCntPtr createVFSFromCompilerInvocation( IntrusiveRefCntPtr createVFSFromCompilerInvocation( const CompilerInvocation &CI, DiagnosticsEngine &Diags, - IntrusiveRefCntPtr BaseFS, - std::shared_ptr OverrideCAS = nullptr); + IntrusiveRefCntPtr BaseFS); IntrusiveRefCntPtr createVFSFromOverlayFiles(ArrayRef VFSOverlayFiles, diff --git a/clang/include/clang/Frontend/Utils.h b/clang/include/clang/Frontend/Utils.h index 18bf21c147bde..4e76006905f5a 100644 --- a/clang/include/clang/Frontend/Utils.h +++ b/clang/include/clang/Frontend/Utils.h @@ -152,9 +152,8 @@ class ModuleDependencyCollector : public DependencyCollector { std::error_code copyToRoot(StringRef Src, StringRef Dst = {}); public: - ModuleDependencyCollector(std::string DestDir, - IntrusiveRefCntPtr VFS) - : DestDir(std::move(DestDir)), Canonicalizer(std::move(VFS)) {} + ModuleDependencyCollector(std::string DestDir) + : DestDir(std::move(DestDir)) {} ~ModuleDependencyCollector() override { writeFileMap(); } StringRef getDest() { return DestDir; } diff --git a/clang/include/clang/Lex/HeaderSearch.h b/clang/include/clang/Lex/HeaderSearch.h index fb95c6187ca74..bccec4dd951d6 100644 --- a/clang/include/clang/Lex/HeaderSearch.h +++ b/clang/include/clang/Lex/HeaderSearch.h @@ -966,9 +966,6 @@ void ApplyHeaderSearchOptions(HeaderSearch &HS, const LangOptions &Lang, const llvm::Triple &triple); -void normalizeModuleCachePath(FileManager &FileMgr, StringRef Path, - SmallVectorImpl &NormalizedPath); - } // namespace clang #endif // LLVM_CLANG_LEX_HEADERSEARCH_H diff --git a/clang/include/clang/Serialization/ModuleCache.h b/clang/include/clang/Serialization/ModuleCache.h index ec052c5c18e0a..3117d954a09cc 100644 --- a/clang/include/clang/Serialization/ModuleCache.h +++ b/clang/include/clang/Serialization/ModuleCache.h @@ -45,15 +45,11 @@ class ModuleCache : public RefCountedBase { /// were validated. virtual void updateModuleTimestamp(StringRef ModuleFilename) = 0; - /// Prune module files that haven't been accessed in a long time. - virtual void maybePrune(StringRef Path, time_t PruneInterval, - time_t PruneAfter) = 0; - /// Returns this process's view of the module cache. virtual InMemoryModuleCache &getInMemoryModuleCache() = 0; virtual const InMemoryModuleCache &getInMemoryModuleCache() const = 0; - // TODO: Virtualize writing/reading PCM files, etc. + // TODO: Virtualize writing/reading PCM files, pruning, etc. virtual ~ModuleCache() = default; }; @@ -63,9 +59,6 @@ class ModuleCache : public RefCountedBase { /// \c CompilerInstance instances participating in building modules for single /// translation unit in order to share the same \c InMemoryModuleCache. IntrusiveRefCntPtr createCrossProcessModuleCache(); - -/// Shared implementation of `ModuleCache::maybePrune()`. -void maybePruneImpl(StringRef Path, time_t PruneInterval, time_t PruneAfter); } // namespace clang #endif diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp index 0f9129d1575a4..32afc66f4b742 100644 --- a/clang/lib/CodeGen/BackendUtil.cpp +++ b/clang/lib/CodeGen/BackendUtil.cpp @@ -447,8 +447,7 @@ static bool initTargetOptions(const CompilerInstance &CI, if (Options.BBSections == llvm::BasicBlockSection::List) { ErrorOr> MBOrErr = - CI.getVirtualFileSystem().getBufferForFile( - CodeGenOpts.BBSections.substr(5)); + MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5)); if (!MBOrErr) { Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file) << MBOrErr.getError().message(); @@ -580,8 +579,7 @@ getInstrProfOptions(const CodeGenOptions &CodeGenOpts, return Options; } -static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts, - vfs::FileSystem &VFS) { +static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) { SmallVector BackendArgs; BackendArgs.push_back("clang"); // Fake program name. if (!CodeGenOpts.DebugPass.empty()) { @@ -601,9 +599,8 @@ static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts, // FIXME: The command line parser below is not thread-safe and shares a global // state, so this call might crash or overwrite the options of another Clang // instance in the same process. - llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(), - /*Overview=*/"", /*Errs=*/nullptr, - /*VFS=*/&VFS); + llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, + BackendArgs.data()); } void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { @@ -804,8 +801,7 @@ static void addSanitizers(const Triple &TargetTriple, HWASanPass(SanitizerKind::KernelHWAddress, true); if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { - MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles, - PB.getVirtualFileSystemPtr())); + MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles)); } }; if (ClSanitizeOnOptimizerEarlyEP) { @@ -857,9 +853,9 @@ void EmitAssemblyHelper::RunOptimizationPipeline( if (CodeGenOpts.hasProfileIRInstr()) // -fprofile-generate. PGOOpt = PGOOptions(getProfileGenName(CodeGenOpts), "", "", - CodeGenOpts.MemoryProfileUsePath, PGOOptions::IRInstr, - PGOOptions::NoCSAction, ClPGOColdFuncAttr, - CodeGenOpts.DebugInfoForProfiling, + CodeGenOpts.MemoryProfileUsePath, nullptr, + PGOOptions::IRInstr, PGOOptions::NoCSAction, + ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling, /*PseudoProbeForProfiling=*/false, CodeGenOpts.AtomicProfileUpdate); else if (CodeGenOpts.hasProfileIRUse()) { @@ -868,30 +864,32 @@ void EmitAssemblyHelper::RunOptimizationPipeline( : PGOOptions::NoCSAction; PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "", CodeGenOpts.ProfileRemappingFile, - CodeGenOpts.MemoryProfileUsePath, PGOOptions::IRUse, - CSAction, ClPGOColdFuncAttr, + CodeGenOpts.MemoryProfileUsePath, VFS, + PGOOptions::IRUse, CSAction, ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling); } else if (!CodeGenOpts.SampleProfileFile.empty()) // -fprofile-sample-use PGOOpt = PGOOptions( CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile, - CodeGenOpts.MemoryProfileUsePath, PGOOptions::SampleUse, + CodeGenOpts.MemoryProfileUsePath, VFS, PGOOptions::SampleUse, PGOOptions::NoCSAction, ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling); else if (!CodeGenOpts.MemoryProfileUsePath.empty()) // -fmemory-profile-use (without any of the above options) - PGOOpt = PGOOptions("", "", "", CodeGenOpts.MemoryProfileUsePath, + PGOOpt = PGOOptions("", "", "", CodeGenOpts.MemoryProfileUsePath, VFS, PGOOptions::NoAction, PGOOptions::NoCSAction, ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling); else if (CodeGenOpts.PseudoProbeForProfiling) // -fpseudo-probe-for-profiling - PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", PGOOptions::NoAction, - PGOOptions::NoCSAction, ClPGOColdFuncAttr, - CodeGenOpts.DebugInfoForProfiling, true); + PGOOpt = + PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr, + PGOOptions::NoAction, PGOOptions::NoCSAction, + ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling, true); else if (CodeGenOpts.DebugInfoForProfiling) // -fdebug-info-for-profiling - PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", PGOOptions::NoAction, - PGOOptions::NoCSAction, ClPGOColdFuncAttr, true); + PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr, + PGOOptions::NoAction, PGOOptions::NoCSAction, + ClPGOColdFuncAttr, true); // Check to see if we want to generate a CS profile. if (CodeGenOpts.hasProfileCSIRInstr()) { @@ -907,7 +905,7 @@ void EmitAssemblyHelper::RunOptimizationPipeline( PGOOpt->CSAction = PGOOptions::CSIRInstr; } else PGOOpt = PGOOptions("", getProfileGenName(CodeGenOpts), "", - /*MemoryProfile=*/"", PGOOptions::NoAction, + /*MemoryProfile=*/"", nullptr, PGOOptions::NoAction, PGOOptions::CSIRInstr, ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling); } @@ -943,7 +941,7 @@ void EmitAssemblyHelper::RunOptimizationPipeline( (CodeGenOpts.DebugPassManager || DebugPassStructure), CodeGenOpts.VerifyEach, PrintPassOpts); SI.registerCallbacks(PIC, &MAM); - PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC, CI.getVirtualFileSystemPtr()); + PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC); // Handle the assignment tracking feature options. switch (CodeGenOpts.getAssignmentTrackingMode()) { @@ -1121,9 +1119,8 @@ void EmitAssemblyHelper::RunOptimizationPipeline( if (std::optional Options = getGCOVOptions(CodeGenOpts, LangOpts)) PB.registerPipelineStartEPCallback( - [this, Options](ModulePassManager &MPM, OptimizationLevel Level) { - MPM.addPass( - GCOVProfilerPass(*Options, CI.getVirtualFileSystemPtr())); + [Options](ModulePassManager &MPM, OptimizationLevel Level) { + MPM.addPass(GCOVProfilerPass(*Options)); }); if (std::optional Options = getInstrProfOptions(CodeGenOpts, LangOpts)) @@ -1297,7 +1294,7 @@ void EmitAssemblyHelper::emitAssembly(BackendAction Action, std::unique_ptr OS, std::unique_ptr CasIDOS, BackendConsumer *BC) { - setCommandLineOpts(CodeGenOpts, CI.getVirtualFileSystem()); + setCommandLineOpts(CodeGenOpts); bool RequiresCodeGen = actionRequiresCodeGen(Action); CreateTargetMachine(RequiresCodeGen); @@ -1334,7 +1331,7 @@ runThinLTOBackend(CompilerInstance &CI, ModuleSummaryIndex *CombinedIndex, ModuleToDefinedGVSummaries; CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); - setCommandLineOpts(CGOpts, CI.getVirtualFileSystem()); + setCommandLineOpts(CGOpts); // We can simply import the values mentioned in the combined index, since // we should only invoke this using the individual indexes written out @@ -1510,13 +1507,13 @@ void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, } void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, - llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags) { + DiagnosticsEngine &Diags) { if (CGOpts.OffloadObjects.empty()) return; for (StringRef OffloadObject : CGOpts.OffloadObjects) { llvm::ErrorOr> ObjectOrErr = - VFS.getBufferForFile(OffloadObject); + llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject); if (ObjectOrErr.getError()) { auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "could not open '%0' for embedding"); diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp index df9201f26aa18..a5f2f0efa2c3b 100644 --- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -1038,8 +1038,7 @@ CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM) /*HasRequiresReverseOffload*/ false, /*HasRequiresUnifiedAddress*/ false, hasRequiresUnifiedSharedMemory(), /*HasRequiresDynamicAllocators*/ false); OMPBuilder.initialize(); - OMPBuilder.loadOffloadInfoMetadata(*CGM.getFileSystem(), - CGM.getLangOpts().OpenMPIsTargetDevice + OMPBuilder.loadOffloadInfoMetadata(CGM.getLangOpts().OpenMPIsTargetDevice ? CGM.getLangOpts().OMPHostIRFile : StringRef{}); OMPBuilder.setConfig(Config); @@ -1539,14 +1538,15 @@ static llvm::TargetRegionEntryInfo getEntryInfoFromPresumedLoc( SourceManager &SM = CGM.getContext().getSourceManager(); PresumedLoc PLoc = SM.getPresumedLoc(BeginLoc); - if (!CGM.getFileSystem()->exists(PLoc.getFilename())) + llvm::sys::fs::UniqueID ID; + if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { PLoc = SM.getPresumedLoc(BeginLoc, /*UseLineDirectives=*/false); + } return std::pair(PLoc.getFilename(), PLoc.getLine()); }; - return OMPBuilder.getTargetEntryUniqueInfo(FileInfoCallBack, - *CGM.getFileSystem(), ParentName); + return OMPBuilder.getTargetEntryUniqueInfo(FileInfoCallBack, ParentName); } ConstantAddress CGOpenMPRuntime::getAddrOfDeclareTargetVar(const VarDecl *VD) { diff --git a/clang/lib/CodeGen/CodeGenAction.cpp b/clang/lib/CodeGen/CodeGenAction.cpp index 61ae1cdcb1395..892db0014fe83 100644 --- a/clang/lib/CodeGen/CodeGenAction.cpp +++ b/clang/lib/CodeGen/CodeGenAction.cpp @@ -1160,8 +1160,7 @@ void CodeGenAction::ExecuteAction() { TheModule->setTargetTriple(Triple(TargetOpts.Triple)); } - EmbedObject(TheModule.get(), CodeGenOpts, CI.getVirtualFileSystem(), - Diagnostics); + EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics); EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile); LLVMContext &Ctx = TheModule->getContext(); diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 138c007c2834f..c54c5fe19b974 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -496,15 +496,10 @@ CodeGenModule::CodeGenModule(ASTContext &C, auto ReaderOrErr = llvm::IndexedInstrProfReader::create( CodeGenOpts.ProfileInstrumentUsePath, *FS, CodeGenOpts.ProfileRemappingFile); - if (auto E = ReaderOrErr.takeError()) { - unsigned DiagID = Diags.getCustomDiagID( - DiagnosticsEngine::Error, "Error in reading profile %0: %1"); - llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { - Diags.Report(DiagID) - << CodeGenOpts.ProfileInstrumentUsePath << EI.message(); - }); - return; - } + // We're checking for profile read errors in CompilerInvocation, so if + // there was an error it should've already been caught. If it hasn't been + // somehow, trip an assertion. + assert(ReaderOrErr); PGOReader = std::move(ReaderOrErr.get()); } @@ -536,7 +531,8 @@ CodeGenModule::CodeGenModule(ASTContext &C, if (!CGO.MSSecureHotPatchFunctionsFile.empty() || !CGO.MSSecureHotPatchFunctionsList.empty()) { if (!CGO.MSSecureHotPatchFunctionsFile.empty()) { - auto BufOrErr = FS->getBufferForFile(CGO.MSSecureHotPatchFunctionsFile); + auto BufOrErr = + llvm::MemoryBuffer::getFile(CGO.MSSecureHotPatchFunctionsFile); if (BufOrErr) { const llvm::MemoryBuffer &FileBuffer = **BufOrErr; for (llvm::line_iterator I(FileBuffer.getMemBufferRef(), true), E; @@ -592,10 +588,6 @@ void CodeGenModule::createOpenCLRuntime() { } void CodeGenModule::createOpenMPRuntime() { - if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile)) - Diags.Report(diag::err_omp_host_ir_file_not_found) - << LangOpts.OMPHostIRFile; - // Select a specialized code generation class based on the target, if any. // If it does not exist use the default implementation. switch (getTriple().getArch()) { @@ -1571,7 +1563,7 @@ void CodeGenModule::Release() { EmitBackendOptionsMetadata(getCodeGenOpts()); // If there is device offloading code embed it in the host now. - EmbedObject(&getModule(), CodeGenOpts, *getFileSystem(), getDiags()); + EmbedObject(&getModule(), CodeGenOpts, getDiags()); // Set visibility from DLL storage class // We do this at the end of LLVM IR generation; after any operation @@ -8121,17 +8113,12 @@ void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, // Get the UniqueID for the file containing the decl. llvm::sys::fs::UniqueID ID; - auto Status = FS->status(PLoc.getFilename()); - if (!Status) { + if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false); assert(PLoc.isValid() && "Source location is expected to be valid."); - Status = FS->status(PLoc.getFilename()); - } - if (!Status) { - SM.getDiagnostics().Report(diag::err_cannot_open_file) - << PLoc.getFilename() << Status.getError().message(); - } else { - ID = Status->getUniqueID(); + if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) + SM.getDiagnostics().Report(diag::err_cannot_open_file) + << PLoc.getFilename() << EC.message(); } OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice()) << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8); diff --git a/clang/lib/CrossTU/CrossTranslationUnit.cpp b/clang/lib/CrossTU/CrossTranslationUnit.cpp index a3fe2f4325e9c..6d0f042d5accd 100644 --- a/clang/lib/CrossTU/CrossTranslationUnit.cpp +++ b/clang/lib/CrossTU/CrossTranslationUnit.cpp @@ -13,7 +13,6 @@ #include "clang/AST/ASTImporter.h" #include "clang/AST/Decl.h" #include "clang/AST/ParentMapContext.h" -#include "clang/Basic/DiagnosticDriver.h" #include "clang/Basic/TargetInfo.h" #include "clang/CrossTU/CrossTUDiagnostic.h" #include "clang/Frontend/ASTUnit.h" @@ -238,16 +237,7 @@ template static bool hasBodyOrInit(const T *D) { } CrossTranslationUnitContext::CrossTranslationUnitContext(CompilerInstance &CI) - : Context(CI.getASTContext()), ASTStorage(CI) { - if (CI.getAnalyzerOpts().ShouldEmitErrorsOnInvalidConfigValue && - !CI.getAnalyzerOpts().CTUDir.empty()) { - auto S = CI.getVirtualFileSystem().status(CI.getAnalyzerOpts().CTUDir); - if (!S || S->getType() != llvm::sys::fs::file_type::directory_file) - CI.getDiagnostics().Report(diag::err_analyzer_config_invalid_input) - << "ctu-dir" - << "a filename"; - } -} + : Context(CI.getASTContext()), ASTStorage(CI) {} CrossTranslationUnitContext::~CrossTranslationUnitContext() {} @@ -578,8 +568,8 @@ CrossTranslationUnitContext::ASTLoader::loadFromDump(StringRef ASTDumpPath) { new DiagnosticsEngine(DiagID, *DiagOpts, DiagClient)); return ASTUnit::LoadFromASTFile( ASTDumpPath, CI.getPCHContainerOperations()->getRawReader(), - ASTUnit::LoadEverything, CI.getVirtualFileSystemPtr(), DiagOpts, Diags, - CI.getFileSystemOpts(), CI.getHeaderSearchOpts()); + ASTUnit::LoadEverything, DiagOpts, Diags, CI.getFileSystemOpts(), + CI.getHeaderSearchOpts()); } /// Load the AST from a source-file, which is supposed to be located inside the diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 33ebc7cd25f62..1c2d82ff10c2f 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -41,7 +41,6 @@ #include "llvm/Frontend/Debug/Options.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Option/ArgList.h" -#include "llvm/ProfileData/InstrProfReader.h" #include "llvm/Support/CodeGen.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Compression.h" @@ -503,47 +502,19 @@ static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, } if (ProfileUseArg) { - SmallString<128> UsePathBuf; - StringRef UsePath; if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ)) - UsePath = ProfileUseArg->getValue(); + CmdArgs.push_back(Args.MakeArgString( + Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue())); else if ((ProfileUseArg->getOption().matches( options::OPT_fprofile_use_EQ) || ProfileUseArg->getOption().matches( options::OPT_fprofile_instr_use))) { - UsePathBuf = - ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue(); - if (UsePathBuf.empty() || llvm::sys::fs::is_directory(UsePathBuf)) - llvm::sys::path::append(UsePathBuf, "default.profdata"); - UsePath = UsePathBuf; - } - auto ReaderOrErr = - llvm::IndexedInstrProfReader::create(UsePath, D.getVFS()); - if (auto E = ReaderOrErr.takeError()) { - auto DiagID = D.getDiags().getCustomDiagID( - DiagnosticsEngine::Error, "Error in reading profile %0: %1"); - llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { - D.Diag(DiagID) << UsePath.str() << EI.message(); - }); - } else { - std::unique_ptr PGOReader = - std::move(ReaderOrErr.get()); - StringRef UseKind; - // Currently memprof profiles are only added at the IR level. Mark the - // profile type as IR in that case as well and the subsequent matching - // needs to detect which is available (might be one or both). - if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) { - if (PGOReader->hasCSIRLevelProfile()) - UseKind = "csllvm"; - else - UseKind = "llvm"; - } else - UseKind = "clang"; - - CmdArgs.push_back( - Args.MakeArgString("-fprofile-instrument-use=" + UseKind)); + SmallString<128> Path( + ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue()); + if (Path.empty() || llvm::sys::fs::is_directory(Path)) + llvm::sys::path::append(Path, "default.profdata"); CmdArgs.push_back( - Args.MakeArgString("-fprofile-instrument-use-path=" + UsePath)); + Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path)); } } diff --git a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp index 6966d4097d64a..1087eb3001856 100644 --- a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp +++ b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp @@ -444,7 +444,8 @@ bool ExtractAPIAction::PrepareToExecuteAction(CompilerInstance &CI) { return true; if (!CI.hasFileManager()) - CI.createFileManager(); + if (!CI.createFileManager()) + return false; auto Kind = Inputs[0].getKind(); diff --git a/clang/lib/Frontend/ASTMerge.cpp b/clang/lib/Frontend/ASTMerge.cpp index 51925ec85e7b6..a4ce88351e28e 100644 --- a/clang/lib/Frontend/ASTMerge.cpp +++ b/clang/lib/Frontend/ASTMerge.cpp @@ -47,8 +47,7 @@ void ASTMergeAction::ExecuteAction() { /*ShouldOwnClient=*/true)); std::unique_ptr Unit = ASTUnit::LoadFromASTFile( ASTFiles[I], CI.getPCHContainerReader(), ASTUnit::LoadEverything, - CI.getVirtualFileSystemPtr(), nullptr, Diags, CI.getFileSystemOpts(), - CI.getHeaderSearchOpts()); + nullptr, Diags, CI.getFileSystemOpts(), CI.getHeaderSearchOpts()); if (!Unit) continue; diff --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp index e4390b9f6f9d6..a99e176291582 100644 --- a/clang/lib/Frontend/ASTUnit.cpp +++ b/clang/lib/Frontend/ASTUnit.cpp @@ -799,13 +799,12 @@ void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr Diags, std::unique_ptr ASTUnit::LoadFromASTFile( StringRef Filename, const PCHContainerReader &PCHContainerRdr, - WhatToLoad ToLoad, IntrusiveRefCntPtr VFS, - std::shared_ptr DiagOpts, + WhatToLoad ToLoad, std::shared_ptr DiagOpts, IntrusiveRefCntPtr Diags, const FileSystemOptions &FileSystemOpts, const HeaderSearchOptions &HSOpts, const LangOptions *LangOpts, bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics, bool AllowASTWithCompilerErrors, - bool UserFilesAreVolatile) { + bool UserFilesAreVolatile, IntrusiveRefCntPtr VFS) { std::unique_ptr AST(new ASTUnit(true)); // Recover resources if we crash before exiting this method. @@ -1180,14 +1179,10 @@ bool ASTUnit::Parse(std::shared_ptr PCHContainerOps, // Ensure that Clang has a FileManager with the right VFS, which may have // changed above in AddImplicitPreamble. If VFS is nullptr, rely on // createFileManager to create one. - if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS) { - Clang->setVirtualFileSystem(std::move(VFS)); + if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS) Clang->setFileManager(&*FileMgr); - } else { - Clang->setVirtualFileSystem(std::move(VFS)); - Clang->createFileManager(); - FileMgr = Clang->getFileManagerPtr().get(); - } + else + FileMgr = Clang->createFileManager(std::move(VFS)); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar diff --git a/clang/lib/Frontend/ChainedIncludesSource.cpp b/clang/lib/Frontend/ChainedIncludesSource.cpp index 990fb3c32a3d0..f9a398dbfb90f 100644 --- a/clang/lib/Frontend/ChainedIncludesSource.cpp +++ b/clang/lib/Frontend/ChainedIncludesSource.cpp @@ -124,12 +124,11 @@ IntrusiveRefCntPtr clang::createChainedIncludesSource( auto Clang = std::make_unique( std::move(CInvok), CI.getPCHContainerOperations()); - Clang->createVirtualFileSystem(); Clang->setDiagnostics(Diags.get()); Clang->setTarget(TargetInfo::CreateTargetInfo( Clang->getDiagnostics(), Clang->getInvocation().getTargetOpts())); Clang->createFileManager(); - Clang->createSourceManager(); + Clang->createSourceManager(Clang->getFileManager()); Clang->createPreprocessor(TU_Prefix); Clang->getDiagnosticClient().BeginSourceFile(Clang->getLangOpts(), &Clang->getPreprocessor()); diff --git a/clang/lib/Frontend/CompileJobCache.cpp b/clang/lib/Frontend/CompileJobCache.cpp index c210d075d26b1..6e32eb80edb87 100644 --- a/clang/lib/Frontend/CompileJobCache.cpp +++ b/clang/lib/Frontend/CompileJobCache.cpp @@ -271,7 +271,7 @@ static std::string fixupRelativePath(const std::string &Path, FileManager &FM, // Apply "normal" working directory. if (!WorkingDir.empty()) { SmallString<128> Tmp(Path); - llvm::sys::path::make_absolute(WorkingDir, Tmp); + llvm::sys::fs::make_absolute(WorkingDir, Tmp); return std::string(Tmp); } return Path; @@ -296,7 +296,7 @@ std::optional CompileJobCache::initialize(CompilerInstance &Clang) { if (!CacheCompileJob) return std::nullopt; - std::tie(CAS, Cache) = Clang.getOrCreateCASDatabases(); + std::tie(CAS, Cache) = Clang.createCASDatabases(); if (!CAS || !Cache) return 1; // Exit with error! @@ -613,8 +613,8 @@ Expected> CompileJobCache::replayCachedResult( std::optional *OutMCOutputID) { CompilerInstance Clang(std::move(Invok)); llvm::raw_svector_ostream DiagOS(DiagText); - Clang.createVirtualFileSystem(llvm::vfs::getRealFileSystem()); Clang.createDiagnostics( + *llvm::vfs::getRealFileSystem(), new TextDiagnosticPrinter(DiagOS, Clang.getDiagnosticOpts())); Clang.setVerboseOutputStream(DiagOS); diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp index b73095f076fe1..2f25e3f9e8643 100644 --- a/clang/lib/Frontend/CompilerInstance.cpp +++ b/clang/lib/Frontend/CompilerInstance.cpp @@ -172,14 +172,11 @@ bool CompilerInstance::createTarget() { return true; } +llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const { + return getFileManager().getVirtualFileSystem(); +} + void CompilerInstance::setFileManager(FileManager *Value) { - if (Value == nullptr) { - FileMgr = nullptr; - return; - } - if (VFS == nullptr) - VFS = Value->getVirtualFileSystemPtr(); - assert(VFS == Value->getVirtualFileSystemPtr()); FileMgr = Value; } @@ -279,35 +276,24 @@ static void collectIncludePCH(CompilerInstance &CI, static void collectVFSEntries(CompilerInstance &CI, std::shared_ptr MDC) { + if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) + return; + // Collect all VFS found. SmallVector VFSEntries; - CI.getVirtualFileSystem().visit([&](llvm::vfs::FileSystem &VFS) { - if (auto *RedirectingVFS = dyn_cast(&VFS)) - llvm::vfs::collectVFSEntries(*RedirectingVFS, VFSEntries); - }); + for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) { + llvm::ErrorOr> Buffer = + llvm::MemoryBuffer::getFile(VFSFile); + if (!Buffer) + return; + llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()), + /*DiagHandler*/ nullptr, VFSFile, VFSEntries); + } for (auto &E : VFSEntries) MDC->addFile(E.VPath, E.RPath); } -void CompilerInstance::createVirtualFileSystem( - IntrusiveRefCntPtr BaseFS, DiagnosticConsumer *DC) { - DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(new DiagnosticIDs, DiagOpts, DC, - /*ShouldOwnClient=*/false); - - std::tie(CAS, ActionCache) = - getInvocation().getCASOpts().getOrCreateDatabases( - Diags, /*CreateEmptyCASOnFailure=*/false); - - VFS = createVFSFromCompilerInvocation(getInvocation(), Diags, - std::move(BaseFS), CAS); - // FIXME: Should this go into createVFSFromCompilerInvocation? - if (getFrontendOpts().ShowStats) - VFS = - llvm::makeIntrusiveRefCnt(std::move(VFS)); -} - // Diagnostics static void SetUpDiagnosticLog(DiagnosticOptions &DiagOpts, const CodeGenOptions *CodeGenOpts, @@ -359,10 +345,11 @@ static void SetupSerializedDiagnostics(DiagnosticOptions &DiagOpts, } } -void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client, +void CompilerInstance::createDiagnostics(llvm::vfs::FileSystem &VFS, + DiagnosticConsumer *Client, bool ShouldOwnClient) { - Diagnostics = createDiagnostics(getVirtualFileSystem(), getDiagnosticOpts(), - Client, ShouldOwnClient, &getCodeGenOpts()); + Diagnostics = createDiagnostics(VFS, getDiagnosticOpts(), Client, + ShouldOwnClient, &getCodeGenOpts()); } IntrusiveRefCntPtr CompilerInstance::createDiagnostics( @@ -401,18 +388,24 @@ IntrusiveRefCntPtr CompilerInstance::createDiagnostics( // File Manager -void CompilerInstance::createFileManager() { - assert(VFS && "CompilerInstance needs a VFS for creating FileManager"); - FileMgr = llvm::makeIntrusiveRefCnt(getFileSystemOpts(), VFS); +FileManager *CompilerInstance::createFileManager( + IntrusiveRefCntPtr VFS) { + if (!VFS) + VFS = FileMgr ? &FileMgr->getVirtualFileSystem() + : createVFSFromCompilerInvocation(getInvocation(), + getDiagnostics(), CAS); + assert(VFS && "FileManager has no VFS?"); + if (getFrontendOpts().ShowStats) + VFS = + llvm::makeIntrusiveRefCnt(std::move(VFS)); + FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS)); + return FileMgr.get(); } // Source Manager -void CompilerInstance::createSourceManager() { - assert(Diagnostics && "DiagnosticsEngine needed for creating SourceManager"); - assert(FileMgr && "FileManager needed for creating SourceManager"); - SourceMgr = new SourceManager(getDiagnostics(), - getFileManager()); +void CompilerInstance::createSourceManager(FileManager &FileMgr) { + SourceMgr = new SourceManager(getDiagnostics(), FileMgr); } // Initialize the remapping of files to alternative contents, e.g., @@ -524,7 +517,7 @@ void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { // then we're the top level compiler instance and need to create one. if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) { ModuleDepCollector = std::make_shared( - DepOpts.ModuleDependencyOutputDir, getVirtualFileSystemPtr()); + DepOpts.ModuleDependencyOutputDir); } // If there is a module dep collector, register with other dep collectors @@ -566,16 +559,9 @@ void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { } std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) { - assert(FileMgr && "Specific module cache path requires a FileManager"); - - if (getHeaderSearchOpts().ModuleCachePath.empty()) - return ""; - // Set up the module path, including the hash for the module-creation options. - SmallString<256> SpecificModuleCache; - normalizeModuleCachePath(*FileMgr, getHeaderSearchOpts().ModuleCachePath, - SpecificModuleCache); - if (!getHeaderSearchOpts().DisableModuleHash) + SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath); + if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash) llvm::sys::path::append(SpecificModuleCache, ModuleHash); return std::string(SpecificModuleCache); } @@ -973,7 +959,7 @@ llvm::vfs::OutputBackend &CompilerInstance::getOrCreateOutputBackend() { std::pair, std::shared_ptr> -CompilerInstance::getOrCreateCASDatabases() { +CompilerInstance::createCASDatabases() { // Create a new CAS databases from the CompilerInvocation. Future calls to // createFileManager() will use the same CAS. std::tie(CAS, ActionCache) = @@ -985,13 +971,13 @@ CompilerInstance::getOrCreateCASDatabases() { llvm::cas::ObjectStore &CompilerInstance::getOrCreateObjectStore() { if (!CAS) - getOrCreateCASDatabases(); + createCASDatabases(); return *CAS; } llvm::cas::ActionCache &CompilerInstance::getOrCreateActionCache() { if (!ActionCache) - getOrCreateCASDatabases(); + createCASDatabases(); return *ActionCache; } @@ -1402,28 +1388,27 @@ std::unique_ptr CompilerInstance::cloneForModuleCompileImpl( auto &Inv = Instance.getInvocation(); if (ThreadSafeConfig) { - Instance.setVirtualFileSystem(ThreadSafeConfig->getVFS()); - Instance.createFileManager(); + Instance.createFileManager(ThreadSafeConfig->getVFS()); } else if (FrontendOpts.ModulesShareFileManager) { - Instance.setVirtualFileSystem(getVirtualFileSystemPtr()); Instance.setFileManager(&getFileManager()); } else { - Instance.setVirtualFileSystem(&getVirtualFileSystem()); - Instance.createFileManager(); + Instance.createFileManager(&getVirtualFileSystem()); } if (ThreadSafeConfig) { - Instance.createDiagnostics(&ThreadSafeConfig->getDiagConsumer(), + Instance.createDiagnostics(Instance.getVirtualFileSystem(), + &ThreadSafeConfig->getDiagConsumer(), /*ShouldOwnClient=*/false); } else { Instance.createDiagnostics( + Instance.getVirtualFileSystem(), new ForwardingDiagnosticConsumer(getDiagnosticClient()), /*ShouldOwnClient=*/true); } if (llvm::is_contained(DiagOpts.SystemHeaderWarningsModules, ModuleName)) Instance.getDiagnostics().setSuppressSystemWarnings(false); - Instance.createSourceManager(); + Instance.createSourceManager(Instance.getFileManager()); SourceManager &SourceMgr = Instance.getSourceManager(); if (ThreadSafeConfig) { @@ -1853,6 +1838,90 @@ static void checkConfigMacros(Preprocessor &PP, Module *M, } } +/// Write a new timestamp file with the given path. +static void writeTimestampFile(StringRef TimestampFile) { + std::error_code EC; + llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None); +} + +/// Prune the module cache of modules that haven't been accessed in +/// a long time. +static void pruneModuleCache(const HeaderSearchOptions &HSOpts) { + llvm::sys::fs::file_status StatBuf; + llvm::SmallString<128> TimestampFile; + TimestampFile = HSOpts.ModuleCachePath; + assert(!TimestampFile.empty()); + llvm::sys::path::append(TimestampFile, "modules.timestamp"); + + // Try to stat() the timestamp file. + if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) { + // If the timestamp file wasn't there, create one now. + if (EC == std::errc::no_such_file_or_directory) { + writeTimestampFile(TimestampFile); + } + return; + } + + // Check whether the time stamp is older than our pruning interval. + // If not, do nothing. + time_t TimeStampModTime = + llvm::sys::toTimeT(StatBuf.getLastModificationTime()); + time_t CurrentTime = time(nullptr); + if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval)) + return; + + // Write a new timestamp file so that nobody else attempts to prune. + // There is a benign race condition here, if two Clang instances happen to + // notice at the same time that the timestamp is out-of-date. + writeTimestampFile(TimestampFile); + + // Walk the entire module cache, looking for unused module files and module + // indices. + std::error_code EC; + for (llvm::sys::fs::directory_iterator Dir(HSOpts.ModuleCachePath, EC), + DirEnd; + Dir != DirEnd && !EC; Dir.increment(EC)) { + // If we don't have a directory, there's nothing to look into. + if (!llvm::sys::fs::is_directory(Dir->path())) + continue; + + // Walk all of the files within this directory. + for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd; + File != FileEnd && !EC; File.increment(EC)) { + // We only care about module and global module index files. + StringRef Extension = llvm::sys::path::extension(File->path()); + if (Extension != ".pcm" && Extension != ".timestamp" && + llvm::sys::path::filename(File->path()) != "modules.idx") + continue; + + // Look at this file. If we can't stat it, there's nothing interesting + // there. + if (llvm::sys::fs::status(File->path(), StatBuf)) + continue; + + // If the file has been used recently enough, leave it there. + time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime()); + if (CurrentTime - FileAccessTime <= + time_t(HSOpts.ModuleCachePruneAfter)) { + continue; + } + + // Remove the file. + llvm::sys::fs::remove(File->path()); + + // Remove the timestamp file. + std::string TimpestampFilename = File->path() + ".timestamp"; + llvm::sys::fs::remove(TimpestampFilename); + } + + // If we removed all of the files in the directory, remove the directory + // itself. + if (llvm::sys::fs::directory_iterator(Dir->path(), EC) == + llvm::sys::fs::directory_iterator() && !EC) + llvm::sys::fs::remove(Dir->path()); + } +} + void CompilerInstance::createASTReader() { if (TheASTReader) return; @@ -1863,10 +1932,11 @@ void CompilerInstance::createASTReader() { // If we're implicitly building modules but not currently recursively // building a module, check whether we need to prune the module cache. if (getSourceManager().getModuleBuildStack().empty() && - !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty()) - ModCache->maybePrune(getHeaderSearchOpts().ModuleCachePath, - getHeaderSearchOpts().ModuleCachePruneInterval, - getHeaderSearchOpts().ModuleCachePruneAfter); + !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() && + getHeaderSearchOpts().ModuleCachePruneInterval > 0 && + getHeaderSearchOpts().ModuleCachePruneAfter > 0) { + pruneModuleCache(getHeaderSearchOpts()); + } HeaderSearchOptions &HSOpts = getHeaderSearchOpts(); std::string Sysroot = HSOpts.Sysroot; diff --git a/clang/lib/Frontend/CompilerInvocation.cpp b/clang/lib/Frontend/CompilerInvocation.cpp index c4c738ef3604c..8602b16c2f526 100644 --- a/clang/lib/Frontend/CompilerInvocation.cpp +++ b/clang/lib/Frontend/CompilerInvocation.cpp @@ -1373,6 +1373,15 @@ static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions) Diags->Report(diag::err_analyzer_config_invalid_input) << "track-conditions-debug" << "'track-conditions' to also be enabled"; + + if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir)) + Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir" + << "a filename"; + + if (!AnOpts.ModelPath.empty() && + !llvm::sys::fs::is_directory(AnOpts.ModelPath)) + Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path" + << "a filename"; } /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`. @@ -1527,10 +1536,9 @@ static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) { static IntrusiveRefCntPtr createBaseFS(const FileSystemOptions &FSOpts, const FrontendOptions &FEOpts, const CASOptions &CASOpts, DiagnosticsEngine &Diags, - IntrusiveRefCntPtr BaseFS, std::shared_ptr OverrideCAS) { if (FSOpts.CASFileSystemRootID.empty() && FEOpts.CASIncludeTreeID.empty()) - return BaseFS; + return llvm::vfs::getRealFileSystem(); // If no CAS was provided, create one with CASOptions. std::shared_ptr CAS = std::move(OverrideCAS); @@ -1621,6 +1629,34 @@ createBaseFS(const FileSystemOptions &FSOpts, const FrontendOptions &FEOpts, return FS; } +// Set the profile kind using fprofile-instrument-use-path. +static void setPGOUseInstrumentor(CodeGenOptions &Opts, + const Twine &ProfileName, + llvm::vfs::FileSystem &FS, + DiagnosticsEngine &Diags) { + auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName, FS); + if (auto E = ReaderOrErr.takeError()) { + unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, + "Error in reading profile %0: %1"); + llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { + Diags.Report(DiagID) << ProfileName.str() << EI.message(); + }); + return; + } + std::unique_ptr PGOReader = + std::move(ReaderOrErr.get()); + // Currently memprof profiles are only added at the IR level. Mark the profile + // type as IR in that case as well and the subsequent matching needs to detect + // which is available (might be one or both). + if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) { + if (PGOReader->hasCSIRLevelProfile()) + Opts.setProfileUse(llvm::driver::ProfileInstrKind::ProfileCSIRInstr); + else + Opts.setProfileUse(llvm::driver::ProfileInstrKind::ProfileIRInstr); + } else + Opts.setProfileUse(llvm::driver::ProfileInstrKind::ProfileClangInstr); +} + void CompilerInvocation::setDefaultPointerAuthOptions( PointerAuthOptions &Opts, const LangOptions &LangOpts, const llvm::Triple &Triple) { @@ -2186,6 +2222,11 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, : llvm::codegenoptions::DebugTemplateNamesKind::Mangled); } + if (!Opts.ProfileInstrumentUsePath.empty()) { + auto FS = createBaseFS(FSOpts, FEOpts, CASOpts, Diags, nullptr); + setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath, *FS, Diags); + } + if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ, OPT_ftime_report_json)) { Opts.TimePasses = true; @@ -3545,6 +3586,9 @@ static void GenerateHeaderSearchArgs(const HeaderSearchOptions &Opts, if (Opts.UseLibcxx) GenerateArg(Consumer, OPT_stdlib_EQ, "libc++"); + if (!Opts.ModuleCachePath.empty()) + GenerateArg(Consumer, OPT_fmodules_cache_path, Opts.ModuleCachePath); + for (const auto &File : Opts.PrebuiltModuleFiles) GenerateArg(Consumer, OPT_fmodule_file, File.first + "=" + File.second); @@ -3647,7 +3691,8 @@ static void GenerateHeaderSearchArgs(const HeaderSearchOptions &Opts, } static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, - DiagnosticsEngine &Diags) { + DiagnosticsEngine &Diags, + const std::string &WorkingDir) { unsigned NumErrorsBefore = Diags.getNumErrors(); HeaderSearchOptions *HeaderSearchOpts = &Opts; @@ -3660,6 +3705,17 @@ static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ)) Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0); + // Canonicalize -fmodules-cache-path before storing it. + SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path)); + if (!(P.empty() || llvm::sys::path::is_absolute(P))) { + if (WorkingDir.empty()) + llvm::sys::fs::make_absolute(P); + else + llvm::sys::fs::make_absolute(WorkingDir, P); + } + llvm::sys::path::remove_dots(P); + Opts.ModuleCachePath = std::string(P); + // Only the -fmodule-file== form. for (const auto *A : Args.filtered(OPT_fmodule_file)) { StringRef Val = A->getValue(); @@ -4217,6 +4273,9 @@ void CompilerInvocationBase::GenerateLangArgs(const LangOptions &Opts, GenerateArg(Consumer, OPT_offload_targets_EQ, Targets); } + if (!Opts.OMPHostIRFile.empty()) + GenerateArg(Consumer, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile); + if (Opts.OpenMPCUDAMode) GenerateArg(Consumer, OPT_fopenmp_cuda_mode); @@ -4842,6 +4901,15 @@ bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args, } } + // Get OpenMP host file path if any and report if a non existent file is + // found + if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) { + Opts.OMPHostIRFile = A->getValue(); + if (!llvm::sys::fs::exists(Opts.OMPHostIRFile)) + Diags.Report(diag::err_drv_omp_host_ir_file_not_found) + << Opts.OMPHostIRFile; + } + // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options Opts.OpenMPCUDAMode = Opts.OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN()) && @@ -5514,7 +5582,8 @@ bool CompilerInvocation::CreateFromArgsImpl( InputKind DashX = Res.getFrontendOpts().DashX; ParseTargetArgs(Res.getTargetOpts(), Args, Diags); llvm::Triple T(Res.getTargetOpts().Triple); - ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags); + ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags, + Res.getFileSystemOpts().WorkingDir); if (Res.getFrontendOpts().GenReducedBMI || Res.getFrontendOpts().ProgramAction == frontend::GenerateReducedModuleInterface || @@ -5610,11 +5679,6 @@ bool CompilerInvocation::CreateFromArgsImpl( append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs); } - if (!Res.getCodeGenOpts().ProfileInstrumentUsePath.empty() && - Res.getCodeGenOpts().getProfileUse() == - llvm::driver::ProfileInstrKind::ProfileNone) - Diags.Report(diag::err_drv_profile_instrument_use_path_with_no_kind); - FixupInvocation(Res, Diags, Args, DashX); return Diags.getNumErrors() == NumErrorsBefore; @@ -5853,19 +5917,17 @@ clang::createVFSFromCompilerInvocation( const CompilerInvocation &CI, DiagnosticsEngine &Diags, std::shared_ptr OverrideCAS) { return createVFSFromCompilerInvocation( - CI, Diags, llvm::vfs::getRealFileSystem(), std::move(OverrideCAS)); + CI, Diags, + createBaseFS(CI.getFileSystemOpts(), CI.getFrontendOpts(), + CI.getCASOpts(), Diags, std::move(OverrideCAS))); } IntrusiveRefCntPtr clang::createVFSFromCompilerInvocation( const CompilerInvocation &CI, DiagnosticsEngine &Diags, - IntrusiveRefCntPtr BaseFS, - std::shared_ptr OverrideCAS) { - return createVFSFromOverlayFiles( - CI.getHeaderSearchOpts().VFSOverlayFiles, Diags, - createBaseFS(CI.getFileSystemOpts(), CI.getFrontendOpts(), - CI.getCASOpts(), Diags, std::move(BaseFS), - std::move(OverrideCAS))); + IntrusiveRefCntPtr BaseFS) { + return createVFSFromOverlayFiles(CI.getHeaderSearchOpts().VFSOverlayFiles, + Diags, std::move(BaseFS)); } IntrusiveRefCntPtr clang::createVFSFromOverlayFiles( diff --git a/clang/lib/Frontend/FrontendAction.cpp b/clang/lib/Frontend/FrontendAction.cpp index ca54599b41613..269dba1745d73 100644 --- a/clang/lib/Frontend/FrontendAction.cpp +++ b/clang/lib/Frontend/FrontendAction.cpp @@ -904,8 +904,7 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, std::unique_ptr AST = ASTUnit::LoadFromASTFile( InputFile, CI.getPCHContainerReader(), ASTUnit::LoadPreprocessorOnly, - CI.getVirtualFileSystemPtr(), nullptr, ASTDiags, CI.getFileSystemOpts(), - CI.getHeaderSearchOpts()); + nullptr, ASTDiags, CI.getFileSystemOpts(), CI.getHeaderSearchOpts()); if (!AST) return false; @@ -917,9 +916,8 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // Set the shared objects, these are reset when we finish processing the // file, otherwise the CompilerInstance will happily destroy them. - CI.setVirtualFileSystem(AST->getFileManager().getVirtualFileSystemPtr()); CI.setFileManager(&AST->getFileManager()); - CI.createSourceManager(); + CI.createSourceManager(CI.getFileManager()); CI.getSourceManager().initializeForReplay(AST->getSourceManager()); // Preload all the module files loaded transitively by the AST unit. Also @@ -972,9 +970,9 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, StringRef InputFile = Input.getFile(); std::unique_ptr AST = ASTUnit::LoadFromASTFile( - InputFile, CI.getPCHContainerReader(), ASTUnit::LoadEverything, - CI.getVirtualFileSystemPtr(), nullptr, Diags, CI.getFileSystemOpts(), - CI.getHeaderSearchOpts(), &CI.getLangOpts()); + InputFile, CI.getPCHContainerReader(), ASTUnit::LoadEverything, nullptr, + Diags, CI.getFileSystemOpts(), CI.getHeaderSearchOpts(), + &CI.getLangOpts()); if (!AST) return false; @@ -985,7 +983,6 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // Set the shared objects, these are reset when we finish processing the // file, otherwise the CompilerInstance will happily destroy them. - CI.setVirtualFileSystem(AST->getFileManager().getVirtualFileSystemPtr()); CI.setFileManager(&AST->getFileManager()); CI.setSourceManager(&AST->getSourceManager()); CI.setPreprocessor(AST->getPreprocessorPtr()); @@ -1009,13 +1006,14 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, return true; } - // Set up the file system, file and source managers, if needed. - if (!CI.hasVirtualFileSystem()) - CI.createVirtualFileSystem(); - if (!CI.hasFileManager()) - CI.createFileManager(); + // Set up the file and source managers, if needed. + if (!CI.hasFileManager()) { + if (!CI.createFileManager()) { + return false; + } + } if (!CI.hasSourceManager()) { - CI.createSourceManager(); + CI.createSourceManager(CI.getFileManager()); if (CI.getDiagnosticOpts().getFormat() == DiagnosticOptions::SARIF) { static_cast(&CI.getDiagnosticClient()) ->setSarifWriter( diff --git a/clang/lib/Frontend/ModuleDependencyCollector.cpp b/clang/lib/Frontend/ModuleDependencyCollector.cpp index ff37065885289..3b363f948a3a8 100644 --- a/clang/lib/Frontend/ModuleDependencyCollector.cpp +++ b/clang/lib/Frontend/ModuleDependencyCollector.cpp @@ -91,10 +91,10 @@ void ModuleDependencyCollector::attachToPreprocessor(Preprocessor &PP) { std::make_unique(*this)); } -static bool isCaseSensitivePath(llvm::vfs::FileSystem &VFS, StringRef Path) { +static bool isCaseSensitivePath(StringRef Path) { SmallString<256> TmpDest = Path, UpperDest, RealDest; // Remove component traversals, links, etc. - if (VFS.getRealPath(Path, TmpDest)) + if (llvm::sys::fs::real_path(Path, TmpDest)) return true; // Current default value in vfs.yaml Path = TmpDest; @@ -104,7 +104,7 @@ static bool isCaseSensitivePath(llvm::vfs::FileSystem &VFS, StringRef Path) { // already expects when sensitivity isn't setup. for (auto &C : Path) UpperDest.push_back(toUppercase(C)); - if (!VFS.getRealPath(UpperDest, RealDest) && Path == RealDest) + if (!llvm::sys::fs::real_path(UpperDest, RealDest) && Path == RealDest) return false; return true; } @@ -121,8 +121,7 @@ void ModuleDependencyCollector::writeFileMap() { // Explicitly set case sensitivity for the YAML writer. For that, find out // the sensitivity at the path where the headers all collected to. - VFSWriter.setCaseSensitivity( - isCaseSensitivePath(Canonicalizer.getFileSystem(), VFSDir)); + VFSWriter.setCaseSensitivity(isCaseSensitivePath(VFSDir)); // Do not rely on real path names when executing the crash reproducer scripts // since we only want to actually use the files we have on the VFS cache. @@ -154,7 +153,7 @@ std::error_code ModuleDependencyCollector::copyToRoot(StringRef Src, } else { // When collecting entries from input vfsoverlays, copy the external // contents into the cache but still map from the source. - if (!Canonicalizer.getFileSystem().exists(Dst)) + if (!fs::exists(Dst)) return std::error_code(); path::append(CacheDst, Dst); Paths.CopyFrom = Dst; diff --git a/clang/lib/Frontend/PrecompiledPreamble.cpp b/clang/lib/Frontend/PrecompiledPreamble.cpp index efa6d11a6f1d2..3f3fe3c9937e4 100644 --- a/clang/lib/Frontend/PrecompiledPreamble.cpp +++ b/clang/lib/Frontend/PrecompiledPreamble.cpp @@ -479,10 +479,11 @@ llvm::ErrorOr PrecompiledPreamble::Build( Diagnostics.Reset(); ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts(), *VFS); - Clang->createVirtualFileSystem(VFS, Diagnostics.getClient()); + VFS = + createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS); // Create a file manager object to provide access to and cache the filesystem. - Clang->createFileManager(); + Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS)); // Create the source manager. Clang->setSourceManager( diff --git a/clang/lib/Frontend/Rewrite/FrontendActions.cpp b/clang/lib/Frontend/Rewrite/FrontendActions.cpp index e47aa4eba4f0e..9d82af8ac7f91 100644 --- a/clang/lib/Frontend/Rewrite/FrontendActions.cpp +++ b/clang/lib/Frontend/Rewrite/FrontendActions.cpp @@ -250,8 +250,8 @@ class RewriteIncludesAction::RewriteImportsListener : public ASTReaderListener { CompilerInstance Instance( std::make_shared(CI.getInvocation()), CI.getPCHContainerOperations(), &CI.getModuleCache()); - Instance.setVirtualFileSystem(CI.getVirtualFileSystemPtr()); Instance.createDiagnostics( + CI.getVirtualFileSystem(), new ForwardingDiagnosticConsumer(CI.getDiagnosticClient()), /*ShouldOwnClient=*/true); Instance.getFrontendOpts().DisableFree = false; diff --git a/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp b/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp index b17f5860a8682..a084b883e1b6a 100644 --- a/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp +++ b/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp @@ -214,8 +214,6 @@ CreateFrontendAction(CompilerInstance &CI) { } bool ExecuteCompilerInvocation(CompilerInstance *Clang) { - unsigned NumErrorsBefore = Clang->getDiagnostics().getNumErrors(); - // Honor -help. if (Clang->getFrontendOpts().ShowHelp) { driver::getDriverOptTable().printHelp( @@ -260,9 +258,7 @@ bool ExecuteCompilerInvocation(CompilerInstance *Clang) { for (unsigned i = 0; i != NumArgs; ++i) Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str(); Args[NumArgs + 1] = nullptr; - llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get(), /*Overview=*/"", - /*Errs=*/nullptr, - /*VFS=*/&Clang->getVirtualFileSystem()); + llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get()); } #if CLANG_ENABLE_STATIC_ANALYZER @@ -313,12 +309,9 @@ bool ExecuteCompilerInvocation(CompilerInstance *Clang) { } #endif - // If there were errors in the above, don't do anything else. - // This intentionally ignores errors emitted before this function to - // accommodate lenient callers that decided to make progress despite errors. - if (Clang->getDiagnostics().getNumErrors() != NumErrorsBefore) + // If there were errors in processing arguments, don't do anything else. + if (Clang->getDiagnostics().hasErrorOccurred()) return false; - // Create and execute the frontend action. std::unique_ptr Act(CreateFrontendAction(*Clang)); if (!Act) diff --git a/clang/lib/Interpreter/Interpreter.cpp b/clang/lib/Interpreter/Interpreter.cpp index 030a7ace92c31..ed3bae59a144c 100644 --- a/clang/lib/Interpreter/Interpreter.cpp +++ b/clang/lib/Interpreter/Interpreter.cpp @@ -108,10 +108,8 @@ CreateCI(const llvm::opt::ArgStringList &Argv) { Clang->getHeaderSearchOpts().ResourceDir = CompilerInvocation::GetResourcesPath(Argv[0], nullptr); - Clang->createVirtualFileSystem(); - // Create the actual diagnostics engine. - Clang->createDiagnostics(); + Clang->createDiagnostics(*llvm::vfs::getRealFileSystem()); if (!Clang->hasDiagnostics()) return llvm::createStringError(llvm::errc::not_supported, "Initialization failed. " @@ -491,8 +489,7 @@ Interpreter::createWithCUDA(std::unique_ptr CI, std::make_unique( llvm::vfs::getRealFileSystem()); OverlayVFS->pushOverlay(IMVFS); - CI->createVirtualFileSystem(OverlayVFS); - CI->createFileManager(); + CI->createFileManager(OverlayVFS); llvm::Expected> InterpOrErr = Interpreter::create(std::move(CI)); diff --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp index a703fbd00488c..2665580e5afce 100644 --- a/clang/lib/Lex/HeaderSearch.cpp +++ b/clang/lib/Lex/HeaderSearch.cpp @@ -672,8 +672,9 @@ OptionalFileEntryRef DirectoryLookup::DoFrameworkLookup( if (getDirCharacteristic() == SrcMgr::C_User) { SmallString<1024> SystemFrameworkMarker(FrameworkName); SystemFrameworkMarker += ".system_framework"; - if (FileMgr.getOptionalFileRef(SystemFrameworkMarker)) + if (llvm::sys::fs::exists(SystemFrameworkMarker)) { CacheEntry.IsUserSpecifiedSystemFramework = true; + } } } @@ -1989,7 +1990,7 @@ std::string HeaderSearch::suggestPathToFileForDiagnostics( llvm::SmallString<32> FilePath = File; if (!WorkingDir.empty() && !path::is_absolute(FilePath)) - path::make_absolute(WorkingDir, FilePath); + fs::make_absolute(WorkingDir, FilePath); // remove_dots switches to backslashes on windows as a side-effect! // We always want to suggest forward slashes for includes. // (not remove_dots(..., posix) as that misparses windows paths). @@ -2003,7 +2004,7 @@ std::string HeaderSearch::suggestPathToFileForDiagnostics( // `BestPrefixLength` accordingly. auto CheckDir = [&](llvm::SmallString<32> Dir) -> bool { if (!WorkingDir.empty() && !path::is_absolute(Dir)) - path::make_absolute(WorkingDir, Dir); + fs::make_absolute(WorkingDir, Dir); path::remove_dots(Dir, /*remove_dot_dot=*/true); for (auto NI = path::begin(File), NE = path::end(File), DI = path::begin(Dir), DE = path::end(Dir); @@ -2094,10 +2095,3 @@ std::string HeaderSearch::suggestPathToFileForDiagnostics( } return path::convert_to_slash(Filename); } - -void clang::normalizeModuleCachePath(FileManager &FileMgr, StringRef Path, - SmallVectorImpl &NormalizedPath) { - NormalizedPath.assign(Path.begin(), Path.end()); - FileMgr.makeAbsolutePath(NormalizedPath); - llvm::sys::path::remove_dots(NormalizedPath); -} diff --git a/clang/lib/Serialization/ASTWriter.cpp b/clang/lib/Serialization/ASTWriter.cpp index c4108dc5c8e68..ca1053a44e4d5 100644 --- a/clang/lib/Serialization/ASTWriter.cpp +++ b/clang/lib/Serialization/ASTWriter.cpp @@ -57,7 +57,6 @@ #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" #include "clang/Basic/Version.h" -#include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/MacroInfo.h" @@ -1732,13 +1731,9 @@ void ASTWriter::WriteControlBlock(Preprocessor &PP, StringRef isysroot) { const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); - SmallString<256> HSOpts_ModuleCachePath; - normalizeModuleCachePath(PP.getFileManager(), HSOpts.ModuleCachePath, - HSOpts_ModuleCachePath); - AddString(HSOpts.Sysroot, Record); AddString(HSOpts.ResourceDir, Record); - AddString(HSOpts_ModuleCachePath, Record); + AddString(HSOpts.ModuleCachePath, Record); AddString(HSOpts.ModuleUserBuildPath, Record); Record.push_back(HSOpts.DisableModuleHash); Record.push_back(HSOpts.ImplicitModuleMaps); diff --git a/clang/lib/Serialization/ModuleCache.cpp b/clang/lib/Serialization/ModuleCache.cpp index 9850956380423..88ad8dd6495dd 100644 --- a/clang/lib/Serialization/ModuleCache.cpp +++ b/clang/lib/Serialization/ModuleCache.cpp @@ -16,87 +16,6 @@ using namespace clang; -/// Write a new timestamp file with the given path. -static void writeTimestampFile(StringRef TimestampFile) { - std::error_code EC; - llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None); -} - -void clang::maybePruneImpl(StringRef Path, time_t PruneInterval, - time_t PruneAfter) { - if (PruneInterval <= 0 || PruneAfter <= 0) - return; - - llvm::SmallString<128> TimestampFile(Path); - llvm::sys::path::append(TimestampFile, "modules.timestamp"); - - // Try to stat() the timestamp file. - llvm::sys::fs::file_status StatBuf; - if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) { - // If the timestamp file wasn't there, create one now. - if (EC == std::errc::no_such_file_or_directory) - writeTimestampFile(TimestampFile); - return; - } - - // Check whether the time stamp is older than our pruning interval. - // If not, do nothing. - time_t TimestampModTime = - llvm::sys::toTimeT(StatBuf.getLastModificationTime()); - time_t CurrentTime = time(nullptr); - if (CurrentTime - TimestampModTime <= PruneInterval) - return; - - // Write a new timestamp file so that nobody else attempts to prune. - // There is a benign race condition here, if two Clang instances happen to - // notice at the same time that the timestamp is out-of-date. - writeTimestampFile(TimestampFile); - - // Walk the entire module cache, looking for unused module files and module - // indices. - std::error_code EC; - for (llvm::sys::fs::directory_iterator Dir(Path, EC), DirEnd; - Dir != DirEnd && !EC; Dir.increment(EC)) { - // If we don't have a directory, there's nothing to look into. - if (!llvm::sys::fs::is_directory(Dir->path())) - continue; - - // Walk all the files within this directory. - for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd; - File != FileEnd && !EC; File.increment(EC)) { - // We only care about module and global module index files. - StringRef Extension = llvm::sys::path::extension(File->path()); - if (Extension != ".pcm" && Extension != ".timestamp" && - llvm::sys::path::filename(File->path()) != "modules.idx") - continue; - - // Look at this file. If we can't stat it, there's nothing interesting - // there. - if (llvm::sys::fs::status(File->path(), StatBuf)) - continue; - - // If the file has been used recently enough, leave it there. - time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime()); - if (CurrentTime - FileAccessTime <= PruneAfter) - continue; - - // Remove the file. - llvm::sys::fs::remove(File->path()); - - // Remove the timestamp file. - std::string TimpestampFilename = File->path() + ".timestamp"; - llvm::sys::fs::remove(TimpestampFilename); - } - - // If we removed all the files in the directory, remove the directory - // itself. - if (llvm::sys::fs::directory_iterator(Dir->path(), EC) == - llvm::sys::fs::directory_iterator() && - !EC) - llvm::sys::fs::remove(Dir->path()); - } -} - namespace { class CrossProcessModuleCache : public ModuleCache { InMemoryModuleCache InMemory; @@ -136,11 +55,6 @@ class CrossProcessModuleCache : public ModuleCache { OS.clear_error(); // Avoid triggering a fatal error. } - void maybePrune(StringRef Path, time_t PruneInterval, - time_t PruneAfter) override { - maybePruneImpl(Path, PruneInterval, PruneAfter); - } - InMemoryModuleCache &getInMemoryModuleCache() override { return InMemory; } const InMemoryModuleCache &getInMemoryModuleCache() const override { return InMemory; diff --git a/clang/lib/StaticAnalyzer/Checkers/Yaml.h b/clang/lib/StaticAnalyzer/Checkers/Yaml.h index ec521cbfcdc8e..b2d17420686ee 100644 --- a/clang/lib/StaticAnalyzer/Checkers/Yaml.h +++ b/clang/lib/StaticAnalyzer/Checkers/Yaml.h @@ -14,7 +14,6 @@ #ifndef LLVM_CLANG_LIB_STATICANALYZER_CHECKER_YAML_H #define LLVM_CLANG_LIB_STATICANALYZER_CHECKER_YAML_H -#include "clang/Basic/SourceManager.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/YAMLTraits.h" @@ -32,12 +31,9 @@ std::optional getConfiguration(CheckerManager &Mgr, Checker *Chk, if (ConfigFile.trim().empty()) return std::nullopt; - auto &VFS = Mgr.getASTContext() - .getSourceManager() - .getFileManager() - .getVirtualFileSystem(); + llvm::vfs::FileSystem *FS = llvm::vfs::getRealFileSystem().get(); llvm::ErrorOr> Buffer = - VFS.getBufferForFile(ConfigFile.str()); + FS->getBufferForFile(ConfigFile.str()); if (Buffer.getError()) { Mgr.reportInvalidCheckerOptionValue(Chk, Option, diff --git a/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp b/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp index f2a05f835396d..5d392afcb9825 100644 --- a/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp +++ b/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp @@ -9,7 +9,6 @@ #include "ModelInjector.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclObjC.h" -#include "clang/Basic/DiagnosticDriver.h" #include "clang/Basic/LangStandard.h" #include "clang/Basic/Stack.h" #include "clang/Frontend/ASTUnit.h" @@ -25,15 +24,7 @@ using namespace clang; using namespace ento; -ModelInjector::ModelInjector(CompilerInstance &CI) : CI(CI) { - if (CI.getAnalyzerOpts().ShouldEmitErrorsOnInvalidConfigValue && - !CI.getAnalyzerOpts().ModelPath.empty()) { - auto S = CI.getVirtualFileSystem().status(CI.getAnalyzerOpts().ModelPath); - if (!S || S->getType() != llvm::sys::fs::file_type::directory_file) - CI.getDiagnostics().Report(diag::err_analyzer_config_invalid_input) - << "model-path" << "a filename"; - } -} +ModelInjector::ModelInjector(CompilerInstance &CI) : CI(CI) {} Stmt *ModelInjector::getBody(const FunctionDecl *D) { onBodySynthesis(D); @@ -65,7 +56,7 @@ void ModelInjector::onBodySynthesis(const NamedDecl *D) { else fileName = llvm::StringRef(D->getName().str() + ".model"); - if (!CI.getVirtualFileSystem().exists(fileName)) { + if (!llvm::sys::fs::exists(fileName.str())) { Bodies[D->getName()] = nullptr; return; } @@ -84,8 +75,8 @@ void ModelInjector::onBodySynthesis(const NamedDecl *D) { // behavior for models CompilerInstance Instance(std::move(Invocation), CI.getPCHContainerOperations()); - Instance.setVirtualFileSystem(CI.getVirtualFileSystemPtr()); Instance.createDiagnostics( + CI.getVirtualFileSystem(), new ForwardingDiagnosticConsumer(CI.getDiagnosticClient()), /*ShouldOwnClient=*/true); diff --git a/clang/lib/Testing/TestAST.cpp b/clang/lib/Testing/TestAST.cpp index d3338956f3043..b59a8d55129de 100644 --- a/clang/lib/Testing/TestAST.cpp +++ b/clang/lib/Testing/TestAST.cpp @@ -54,14 +54,12 @@ class StoreDiagnostics : public DiagnosticConsumer { // Fills in the bits of a CompilerInstance that weren't initialized yet. // Provides "empty" ASTContext etc if we fail before parsing gets started. void createMissingComponents(CompilerInstance &Clang) { - if (!Clang.hasVirtualFileSystem()) - Clang.createVirtualFileSystem(); if (!Clang.hasDiagnostics()) - Clang.createDiagnostics(); + Clang.createDiagnostics(*llvm::vfs::getRealFileSystem()); if (!Clang.hasFileManager()) Clang.createFileManager(); if (!Clang.hasSourceManager()) - Clang.createSourceManager(); + Clang.createSourceManager(Clang.getFileManager()); if (!Clang.hasTarget()) Clang.createTarget(); if (!Clang.hasPreprocessor()) @@ -100,9 +98,7 @@ TestAST::TestAST(const TestInputs &In) { // Extra error conditions are reported through diagnostics, set that up first. bool ErrorOK = In.ErrorOK || llvm::StringRef(In.Code).contains("error-ok"); - auto DiagConsumer = new StoreDiagnostics(Diagnostics, !ErrorOK); - Clang->createVirtualFileSystem(std::move(VFS), DiagConsumer); - Clang->createDiagnostics(DiagConsumer); + Clang->createDiagnostics(*VFS, new StoreDiagnostics(Diagnostics, !ErrorOK)); // Parse cc1 argv, (typically [-std=c++20 input.cc]) into CompilerInvocation. std::vector Argv; @@ -119,7 +115,7 @@ TestAST::TestAST(const TestInputs &In) { } assert(!Clang->getInvocation().getFrontendOpts().DisableFree); - Clang->createFileManager(); + Clang->createFileManager(VFS); // Running the FrontendAction creates the other components: SourceManager, // Preprocessor, ASTContext, Sema. Preprocessor needs TargetInfo to be set. diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp index 487d43dc4ec52..0420a83191922 100644 --- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp +++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp @@ -28,6 +28,7 @@ #include "clang/Tooling/DependencyScanning/InProcessModuleCache.h" #include "clang/Tooling/DependencyScanning/ModuleDepCollector.h" #include "clang/Tooling/DependencyScanning/ScanAndUpdateArgs.h" +#include "clang/Tooling/Tooling.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/CAS/CASProvidingFileSystem.h" #include "llvm/CAS/CachingOnDiskFileSystem.h" @@ -61,7 +62,7 @@ class DependencyConsumerForwarder : public DependencyFileGenerator { for (const auto &File : getDependencies()) { CanonPath = File; llvm::sys::path::remove_dots(CanonPath, /*remove_dot_dot=*/true); - llvm::sys::path::make_absolute(WorkingDirectory, CanonPath); + llvm::sys::fs::make_absolute(WorkingDirectory, CanonPath); C.handleFileDependency(CanonPath); } if (EmitDependencyFile) @@ -505,7 +506,7 @@ class CASDependencyDirectivesGetter : public DependencyDirectivesGetter { /// A clang tool that runs the preprocessor in a mode that's optimized for /// dependency scanning for the given compiler invocation. -class DependencyScanningAction { +class DependencyScanningAction : public tooling::ToolAction { public: DependencyScanningAction( DependencyScanningService &Service, StringRef WorkingDirectory, @@ -513,23 +514,26 @@ class DependencyScanningAction { llvm::IntrusiveRefCntPtr DepFS, llvm::IntrusiveRefCntPtr DepCASFS, llvm::IntrusiveRefCntPtr CacheFS, - bool EmitDependencyFile, + bool DisableFree, bool EmitDependencyFile, bool DiagGenerationAsCompilation, const CASOptions &CASOpts, std::optional ModuleName = std::nullopt, raw_ostream *VerboseOS = nullptr) : Service(Service), WorkingDirectory(WorkingDirectory), Consumer(Consumer), Controller(Controller), DepFS(std::move(DepFS)), DepCASFS(std::move(DepCASFS)), CacheFS(std::move(CacheFS)), + DisableFree(DisableFree), CASOpts(CASOpts), EmitDependencyFile(EmitDependencyFile), DiagGenerationAsCompilation(DiagGenerationAsCompilation), ModuleName(ModuleName), VerboseOS(VerboseOS) {} bool runInvocation(std::shared_ptr Invocation, - IntrusiveRefCntPtr FS, + FileManager *DriverFileMgr, std::shared_ptr PCHContainerOps, - DiagnosticConsumer *DiagConsumer) { + DiagnosticConsumer *DiagConsumer) override { // Make a deep copy of the original Clang invocation. CompilerInvocation OriginalInvocation(*Invocation); + // Restore the value of DisableFree, which may be modified by Tooling. + OriginalInvocation.getFrontendOpts().DisableFree = DisableFree; if (any(Service.getOptimizeArgs() & ScanningOptimizations::Macros)) canonicalizeDefines(OriginalInvocation.getPreprocessorOpts()); @@ -566,13 +570,12 @@ class DependencyScanningAction { ScanInstance.getInvocation().getCASOpts() = CASOpts; ScanInstance.setBuildingModule(false); - ScanInstance.createVirtualFileSystem(FS, DiagConsumer); - // Create the compiler's actual diagnostics engine. if (!DiagGenerationAsCompilation) sanitizeDiagOpts(ScanInstance.getDiagnosticOpts()); assert(!DiagConsumerFinished && "attempt to reuse finished consumer"); - ScanInstance.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false); + ScanInstance.createDiagnostics(DriverFileMgr->getVirtualFileSystem(), + DiagConsumer, /*ShouldOwnClient=*/false); if (!ScanInstance.hasDiagnostics()) return false; if (VerboseOS) @@ -585,7 +588,6 @@ class DependencyScanningAction { ScanInstance.getHeaderSearchOpts().BuildSessionTimestamp = Service.getBuildSessionTimestamp(); - ScanInstance.getFrontendOpts().DisableFree = false; ScanInstance.getFrontendOpts().GenerateGlobalModuleIndex = false; ScanInstance.getFrontendOpts().UseGlobalModuleIndex = false; // This will prevent us compiling individual modules asynchronously since @@ -597,24 +599,25 @@ class DependencyScanningAction { ScanInstance.getHeaderSearchOpts().ModulesIncludeVFSUsage = any(Service.getOptimizeArgs() & ScanningOptimizations::VFS); + // Support for virtual file system overlays. + auto FS = createVFSFromCompilerInvocation( + ScanInstance.getInvocation(), ScanInstance.getDiagnostics(), + DriverFileMgr->getVirtualFileSystemPtr()); + // Create a new FileManager to match the invocation's FileSystemOptions. - ScanInstance.createFileManager(); + auto *FileMgr = ScanInstance.createFileManager(FS); // Use the dependency scanning optimized file system if requested to do so. if (DepFS) { + StringRef ModulesCachePath = + ScanInstance.getHeaderSearchOpts().ModuleCachePath; + DepFS->resetBypassedPathPrefix(); - if (!ScanInstance.getHeaderSearchOpts().ModuleCachePath.empty()) { - SmallString<256> ModulesCachePath; - normalizeModuleCachePath( - ScanInstance.getFileManager(), - ScanInstance.getHeaderSearchOpts().ModuleCachePath, - ModulesCachePath); + if (!ModulesCachePath.empty()) DepFS->setBypassedPathPrefix(ModulesCachePath); - } ScanInstance.setDependencyDirectivesGetter( - std::make_unique( - ScanInstance.getFileManager())); + std::make_unique(*FileMgr)); } // CAS Implementation. @@ -622,7 +625,7 @@ class DependencyScanningAction { ScanInstance.setDependencyDirectivesGetter( std::make_unique(DepCASFS.get())); - ScanInstance.createSourceManager(); + ScanInstance.createSourceManager(*FileMgr); // Create a collection of stable directories derived from the ScanInstance // for determining whether module dependencies would fully resolve from @@ -773,6 +776,9 @@ class DependencyScanningAction { LastCC1Arguments = OriginalInvocation.getCC1CommandLine(); LastCC1CacheKey = Controller.getCacheKey(OriginalInvocation); + // Propagate the statistics to the parent FileManager. + DriverFileMgr->AddStats(ScanInstance.getFileManager()); + return true; } @@ -813,6 +819,7 @@ class DependencyScanningAction { llvm::IntrusiveRefCntPtr DepFS; llvm::IntrusiveRefCntPtr DepCASFS; llvm::IntrusiveRefCntPtr CacheFS; + bool DisableFree; const CASOptions &CASOpts; bool EmitDependencyFile = false; bool DiagGenerationAsCompilation; @@ -915,14 +922,15 @@ llvm::Error DependencyScanningWorker::computeDependencies( } static bool forEachDriverJob( - ArrayRef ArgStrs, DiagnosticsEngine &Diags, - IntrusiveRefCntPtr FS, + ArrayRef ArgStrs, DiagnosticsEngine &Diags, FileManager &FM, llvm::function_ref Callback) { SmallVector Argv; Argv.reserve(ArgStrs.size()); for (const std::string &Arg : ArgStrs) Argv.push_back(Arg.c_str()); + llvm::vfs::FileSystem *FS = &FM.getVirtualFileSystem(); + std::unique_ptr Driver = std::make_unique( Argv[0], llvm::sys::getDefaultTargetTriple(), Diags, "clang LLVM compiler", FS); @@ -932,8 +940,7 @@ static bool forEachDriverJob( bool CLMode = driver::IsClangCL( driver::getDriverMode(Argv[0], ArrayRef(Argv).slice(1))); - if (llvm::Error E = - driver::expandResponseFiles(Argv, CLMode, Alloc, FS.get())) { + if (llvm::Error E = driver::expandResponseFiles(Argv, CLMode, Alloc, FS)) { Diags.Report(diag::err_drv_expand_response_file) << llvm::toString(std::move(E)); return false; @@ -956,25 +963,17 @@ static bool forEachDriverJob( static bool createAndRunToolInvocation( std::vector CommandLine, DependencyScanningAction &Action, - IntrusiveRefCntPtr FS, + FileManager &FM, std::shared_ptr &PCHContainerOps, DiagnosticsEngine &Diags, DependencyConsumer &Consumer) { // Save executable path before providing CommandLine to ToolInvocation std::string Executable = CommandLine[0]; - - llvm::opt::ArgStringList Argv; - for (const std::string &Str : ArrayRef(CommandLine).drop_front()) - Argv.push_back(Str.c_str()); - - auto Invocation = std::make_shared(); - if (!CompilerInvocation::CreateFromArgs(*Invocation, Argv, Diags)) { - // FIXME: Should we just go on like cc1_main does? - return false; - } - - if (!Action.runInvocation(std::move(Invocation), std::move(FS), - PCHContainerOps, Diags.getClient())) + ToolInvocation Invocation(std::move(CommandLine), &Action, &FM, + PCHContainerOps); + Invocation.setDiagnosticConsumer(Diags.getClient()); + Invocation.setDiagnosticOptions(&Diags.getDiagnosticOptions()); + if (!Invocation.run()) return false; std::vector Args = Action.takeLastCC1Arguments(); @@ -989,26 +988,40 @@ bool DependencyScanningWorker::scanDependencies( DependencyConsumer &Consumer, DependencyActionController &Controller, DiagnosticConsumer &DC, llvm::IntrusiveRefCntPtr FS, std::optional ModuleName) { + auto FileMgr = + llvm::makeIntrusiveRefCnt(FileSystemOptions{}, FS); + std::vector CCommandLine(CommandLine.size(), nullptr); llvm::transform(CommandLine, CCommandLine.begin(), [](const std::string &Str) { return Str.c_str(); }); auto DiagOpts = CreateAndPopulateDiagOpts(CCommandLine); sanitizeDiagOpts(*DiagOpts); - auto Diags = CompilerInstance::createDiagnostics(*FS, *DiagOpts, &DC, - /*ShouldOwnClient=*/false); - + IntrusiveRefCntPtr Diags = + CompilerInstance::createDiagnostics(FileMgr->getVirtualFileSystem(), + *DiagOpts, &DC, + /*ShouldOwnClient=*/false); + + // Although `Diagnostics` are used only for command-line parsing, the + // custom `DiagConsumer` might expect a `SourceManager` to be present. + SourceManager SrcMgr(*Diags, *FileMgr); + Diags->setSourceManager(&SrcMgr); + // DisableFree is modified by Tooling for running + // in-process; preserve the original value, which is + // always true for a driver invocation. + bool DisableFree = true; DependencyScanningAction Action(Service, WorkingDirectory, Consumer, Controller, DepFS, DepCASFS, CacheFS, + DisableFree, /*EmitDependencyFile=*/false, /*DiagGenerationAsCompilation=*/false, getCASOpts(), ModuleName); bool Success = false; if (CommandLine[1] == "-cc1") { - Success = createAndRunToolInvocation(CommandLine, Action, FS, + Success = createAndRunToolInvocation(CommandLine, Action, *FileMgr, PCHContainerOps, *Diags, Consumer); } else { Success = forEachDriverJob( - CommandLine, *Diags, FS, [&](const driver::Command &Cmd) { + CommandLine, *Diags, *FileMgr, [&](const driver::Command &Cmd) { if (StringRef(Cmd.getCreator().getName()) != "clang") { // Non-clang command. Just pass through to the dependency // consumer. @@ -1028,7 +1041,7 @@ bool DependencyScanningWorker::scanDependencies( // system to ensure that any file system requests that // are made by the driver do not go through the // dependency scanning filesystem. - return createAndRunToolInvocation(std::move(Argv), Action, FS, + return createAndRunToolInvocation(std::move(Argv), Action, *FileMgr, PCHContainerOps, *Diags, Consumer); }); } @@ -1150,7 +1163,7 @@ void DependencyScanningWorker::computeDependenciesFromCompilerInvocation( // FIXME: On Windows, WorkingDirectory is insufficient for making an // absolute path if OutputFile has a root name. llvm::SmallString<128> Path = StringRef(DepFile); - llvm::sys::path::make_absolute(WorkingDirectory, Path); + llvm::sys::fs::make_absolute(WorkingDirectory, Path); DepFile = Path.str().str(); } @@ -1158,6 +1171,7 @@ void DependencyScanningWorker::computeDependenciesFromCompilerInvocation( // compilation. DependencyScanningAction Action(Service, WorkingDirectory, DepsConsumer, Controller, DepFS, DepCASFS, CacheFS, + /*DisableFree=*/false, /*EmitDependencyFile=*/!DepFile.empty(), DiagGenerationAsCompilation, getCASOpts(), /*ModuleName=*/std::nullopt, VerboseOS); @@ -1165,6 +1179,8 @@ void DependencyScanningWorker::computeDependenciesFromCompilerInvocation( // Ignore result; we're just collecting dependencies. // // FIXME: will clients other than -cc1scand care? - (void)Action.runInvocation(std::move(Invocation), BaseFS, + IntrusiveRefCntPtr ActiveFiles = + new FileManager(Invocation->getFileSystemOpts(), BaseFS); + (void)Action.runInvocation(std::move(Invocation), ActiveFiles.get(), PCHContainerOps, &DiagsConsumer); } diff --git a/clang/lib/Tooling/DependencyScanning/InProcessModuleCache.cpp b/clang/lib/Tooling/DependencyScanning/InProcessModuleCache.cpp index d1e543b438225..80db2d47d940e 100644 --- a/clang/lib/Tooling/DependencyScanning/InProcessModuleCache.cpp +++ b/clang/lib/Tooling/DependencyScanning/InProcessModuleCache.cpp @@ -100,13 +100,6 @@ class InProcessModuleCache : public ModuleCache { Timestamp.store(llvm::sys::toTimeT(std::chrono::system_clock::now())); } - void maybePrune(StringRef Path, time_t PruneInterval, - time_t PruneAfter) override { - // FIXME: This only needs to be ran once per build, not in every - // compilation. Call it once per service. - maybePruneImpl(Path, PruneInterval, PruneAfter); - } - InMemoryModuleCache &getInMemoryModuleCache() override { return InMemory; } const InMemoryModuleCache &getInMemoryModuleCache() const override { return InMemory; diff --git a/clang/lib/Tooling/DependencyScanning/IncludeTreeActionController.cpp b/clang/lib/Tooling/DependencyScanning/IncludeTreeActionController.cpp index da1855ed4dd87..90ea9bef9afaa 100644 --- a/clang/lib/Tooling/DependencyScanning/IncludeTreeActionController.cpp +++ b/clang/lib/Tooling/DependencyScanning/IncludeTreeActionController.cpp @@ -282,11 +282,10 @@ void dependencies::addReversePrefixMappingFileSystem( llvm::PrefixMapper ReverseMapper; ReverseMapper.addInverseRange(PrefixMapper.getMappings()); ReverseMapper.sort(); - IntrusiveRefCntPtr FS = + std::unique_ptr FS = llvm::vfs::createPrefixMappingFileSystem( std::move(ReverseMapper), &ScanInstance.getVirtualFileSystem()); - ScanInstance.setVirtualFileSystem(FS); ScanInstance.getFileManager().setVirtualFileSystem(std::move(FS)); } diff --git a/clang/lib/Tooling/Tooling.cpp b/clang/lib/Tooling/Tooling.cpp index af4a0a25127a0..53339566e310e 100644 --- a/clang/lib/Tooling/Tooling.cpp +++ b/clang/lib/Tooling/Tooling.cpp @@ -453,11 +453,12 @@ bool FrontendActionFactory::runInvocation( std::unique_ptr ScopedToolAction(create()); // Create the compiler's actual diagnostics engine. - Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false); + Compiler.createDiagnostics(Files->getVirtualFileSystem(), DiagConsumer, + /*ShouldOwnClient=*/false); if (!Compiler.hasDiagnostics()) return false; - Compiler.createSourceManager(); + Compiler.createSourceManager(*Files); const bool Success = Compiler.ExecuteAction(*ScopedToolAction); diff --git a/clang/test/Analysis/Inputs/taint-generic-config-vfs.json b/clang/test/Analysis/Inputs/taint-generic-config-vfs.json deleted file mode 100644 index 74f3cd99a9707..0000000000000 --- a/clang/test/Analysis/Inputs/taint-generic-config-vfs.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - 'version': 0, - 'use-external-names': true, - 'roots': [ - { - 'name': 'DIR', - 'type': 'directory', - 'contents': [ - { - 'name': 'taint-generic-config-virtual.yaml', - 'type': 'file', - 'external-contents': 'DIR/taint-generic-config.yaml' - } - ] - } - ] -} diff --git a/clang/test/Analysis/model-file-missing.cpp b/clang/test/Analysis/model-file-missing.cpp deleted file mode 100644 index c9dfb4ec1b244..0000000000000 --- a/clang/test/Analysis/model-file-missing.cpp +++ /dev/null @@ -1,3 +0,0 @@ -// RUN: not %clang_analyze_cc1 -analyzer-checker=core -analyzer-config model-path=%t/blah %s -o - 2>&1 | FileCheck %s -// CHECK: error: invalid input for analyzer-config option 'model-path', that expects a filename value -// CHECK-NEXT: 1 error generated diff --git a/clang/test/Analysis/taint-generic.c b/clang/test/Analysis/taint-generic.c index 6017483f06b6d..9d6d2942df4a9 100644 --- a/clang/test/Analysis/taint-generic.c +++ b/clang/test/Analysis/taint-generic.c @@ -1,6 +1,3 @@ -// RUN: rm -rf %t && mkdir %t -// RUN: sed -e "s|DIR|%/S/Inputs|g" %S/Inputs/taint-generic-config-vfs.json > %t/taint-generic-config-vfs.json - // RUN: %clang_analyze_cc1 -Wno-format-security -Wno-pointer-to-int-cast \ // RUN: -Wno-incompatible-library-redeclaration -verify %s \ // RUN: -analyzer-checker=optin.taint.GenericTaint \ @@ -9,8 +6,7 @@ // RUN: -analyzer-checker=security.ArrayBound \ // RUN: -analyzer-checker=debug.ExprInspection \ // RUN: -analyzer-config \ -// RUN: optin.taint.TaintPropagation:Config=%S/Inputs/taint-generic-config-virtual.yaml \ -// RUN: -ivfsoverlay %t/taint-generic-config-vfs.json +// RUN: optin.taint.TaintPropagation:Config=%S/Inputs/taint-generic-config.yaml // RUN: %clang_analyze_cc1 -Wno-format-security -Wno-pointer-to-int-cast \ // RUN: -Wno-incompatible-library-redeclaration -verify %s \ diff --git a/clang/test/CAS/output-path-error.c b/clang/test/CAS/output-path-error.c index a221f3bb29bf0..b217ba48402cf 100644 --- a/clang/test/CAS/output-path-error.c +++ b/clang/test/CAS/output-path-error.c @@ -19,4 +19,4 @@ // RUN: cat %t/output.txt | FileCheck %s --check-prefix=ERROR // CACHE-MISS: remark: compile job cache miss -// ERROR: fatal error: CAS filesystem cannot be initialized from root-id 'llvmcas://{{.*}}': cannot get reference to root FS +// ERROR: fatal error: CAS missing expected root-id diff --git a/clang/test/CAS/pgo-profile-with-pch.c b/clang/test/CAS/pgo-profile-with-pch.c index e1d40f29665db..03ed10cc46047 100644 --- a/clang/test/CAS/pgo-profile-with-pch.c +++ b/clang/test/CAS/pgo-profile-with-pch.c @@ -4,7 +4,7 @@ // RUN: llvm-profdata merge -o %t.profdata %S/Inputs/pgo.profraw // RUN: %clang -cc1depscan -fdepscan=inline -fdepscan-include-tree -o %t-pch.rsp -cc1-args -cc1 -triple x86_64-apple-macosx12.0.0 -emit-pch -O3 -Rcompile-job-cache \ -// RUN: -x c-header %s -o %t.h.pch -fcas-path %t.dir/cas -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata +// RUN: -x c-header %s -o %t.h.pch -fcas-path %t.dir/cas -fprofile-instrument-use-path=%t.profdata // RUN: %clang @%t-pch.rsp 2>&1 | FileCheck %s --check-prefix=CACHE-MISS // RUN: FileCheck %s -check-prefix=PCHPROF -input-file %t-pch.rsp // PCHPROF-NOT: -fprofile-instrument-use-path @@ -14,14 +14,14 @@ // Use the modified profdata file for the main file along with the PCH. // RUN: %clang -cc1depscan -fdepscan=inline -fdepscan-include-tree -o %t.rsp -cc1-args -cc1 -triple x86_64-apple-macosx12.0.0 -emit-obj -O3 -Rcompile-job-cache \ -// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -include-pch %t.h.pch +// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use-path=%t.profdata -include-pch %t.h.pch // RUN: %clang @%t.rsp 2>&1 | FileCheck %s --check-prefix=CACHE-MISS // RUN: FileCheck %s -check-prefix=TUPROF -input-file %t.rsp // TUPROF: -fprofile-instrument-use-path // Check that the modified profdata is ignored when re-scanning for the PCH. // RUN: %clang -cc1depscan -fdepscan=inline -fdepscan-include-tree -o %t-pch2.rsp -cc1-args -cc1 -triple x86_64-apple-macosx12.0.0 -emit-pch -O3 -Rcompile-job-cache \ -// RUN: -x c-header %s -o %t.h.pch -fcas-path %t.dir/cas -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata +// RUN: -x c-header %s -o %t.h.pch -fcas-path %t.dir/cas -fprofile-instrument-use-path=%t.profdata // RUN: diff -u %t-pch.rsp %t-pch2.rsp // CACHE-MISS: remark: compile job cache miss diff --git a/clang/test/CAS/pgo-profile.c b/clang/test/CAS/pgo-profile.c index a474754d69726..cf0f024f2aae0 100644 --- a/clang/test/CAS/pgo-profile.c +++ b/clang/test/CAS/pgo-profile.c @@ -3,7 +3,7 @@ /// Check use pgo profile. // RUN: llvm-profdata merge -o %t.profdata %S/Inputs/pgo.profraw // RUN: %clang -cc1depscan -fdepscan=inline -o %t.rsp -cc1-args -cc1 -triple x86_64-apple-macosx12.0.0 -emit-obj -O3 -Rcompile-job-cache \ -// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata +// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use-path=%t.profdata /// Remove profile data to make sure the cc1 command is not reading from file system. // RUN: rm %t.profdata @@ -13,7 +13,7 @@ /// Check include tree. // RUN: llvm-profdata merge -o %t.profdata %S/Inputs/pgo.profraw // RUN: %clang -cc1depscan -fdepscan=inline -fdepscan-include-tree -o %t1.rsp -cc1-args -cc1 -triple x86_64-apple-macosx12.0.0 -emit-obj -O3 -Rcompile-job-cache \ -// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata +// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use-path=%t.profdata // RUN: rm %t.profdata // RUN: %clang @%t1.rsp 2>&1 | FileCheck %s --check-prefix=CACHE-MISS // RUN: %clang @%t1.rsp 2>&1 | FileCheck %s --check-prefix=CACHE-HIT @@ -21,12 +21,12 @@ /// Check change profile data will cause cache miss. // RUN: llvm-profdata merge -o %t.profdata %S/Inputs/pgo2.profraw // RUN: %clang -cc1depscan -fdepscan=inline -o %t2.rsp -cc1-args -cc1 -triple x86_64-apple-macosx12.0.0 -emit-obj -O3 -Rcompile-job-cache \ -// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata +// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use-path=%t.profdata // RUN: not diff %t.rsp %t2.rsp // RUN: %clang @%t2.rsp 2>&1 | FileCheck %s --check-prefix=CACHE-MISS // RUN: %clang -cc1depscan -fdepscan=inline -fdepscan-include-tree -o %t3.rsp -cc1-args -cc1 -triple x86_64-apple-macosx12.0.0 -emit-obj -O3 -Rcompile-job-cache \ -// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata +// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use-path=%t.profdata // RUN: not diff %t1.rsp %t3.rsp // RUN: %clang @%t3.rsp 2>&1 | FileCheck %s --check-prefix=CACHE-MISS @@ -38,9 +38,9 @@ // RUN: cp %t.profdata %t.dir/a/a.profdata // RUN: cp %t.profdata %t.dir/b/a.profdata // RUN: %clang -cc1depscan -fdepscan=inline -o %t4.rsp -cc1-args -cc1 -triple x86_64-apple-macosx12.0.0 -emit-obj -O3 -Rcompile-job-cache -fdepscan-prefix-map %t.dir/a /^testdir \ -// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.dir/a/a.profdata +// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use-path=%t.dir/a/a.profdata // RUN: %clang -cc1depscan -fdepscan=inline -o %t5.rsp -cc1-args -cc1 -triple x86_64-apple-macosx12.0.0 -emit-obj -O3 -Rcompile-job-cache -fdepscan-prefix-map %t.dir/b /^testdir \ -// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.dir/b/a.profdata +// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use-path=%t.dir/b/a.profdata // RUN: cat %t4.rsp | FileCheck %s --check-prefix=REMAP // RUN: %clang @%t4.rsp 2>&1 | FileCheck %s --check-prefix=CACHE-MISS // RUN: %clang @%t5.rsp 2>&1 | FileCheck %s --check-prefix=CACHE-HIT @@ -55,9 +55,9 @@ // RUN: diff -u %t.dir/cache-key1 %t.dir/cache-key2 // RUN: %clang -cc1depscan -fdepscan=inline -fdepscan-include-tree -o %t4.inc.rsp -cc1-args -cc1 -triple x86_64-apple-macosx12.0.0 -emit-obj -O3 -Rcompile-job-cache -fdepscan-prefix-map %t.dir/a /^testdir \ -// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.dir/a/a.profdata +// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use-path=%t.dir/a/a.profdata // RUN: %clang -cc1depscan -fdepscan=inline -fdepscan-include-tree -o %t5.inc.rsp -cc1-args -cc1 -triple x86_64-apple-macosx12.0.0 -emit-obj -O3 -Rcompile-job-cache -fdepscan-prefix-map %t.dir/b /^testdir \ -// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.dir/b/a.profdata +// RUN: -x c %s -o %t.o -fcas-path %t.dir/cas -fprofile-instrument-use-path=%t.dir/b/a.profdata // RUN: cat %t4.inc.rsp | FileCheck %s --check-prefix=REMAP // RUN: %clang @%t4.inc.rsp 2>&1 | FileCheck %s --check-prefix=CACHE-MISS // RUN: %clang @%t5.inc.rsp 2>&1 | FileCheck %s --check-prefix=CACHE-HIT diff --git a/clang/test/CodeGen/cspgo-instrumentation.c b/clang/test/CodeGen/cspgo-instrumentation.c index f42d68aba0eaa..3f90bb4396d70 100644 --- a/clang/test/CodeGen/cspgo-instrumentation.c +++ b/clang/test/CodeGen/cspgo-instrumentation.c @@ -9,19 +9,19 @@ // RUN: llvm-profdata merge -o %t/noncs.profdata %S/Inputs/pgotestir.proftext // // Ensure Pass PGOInstrumentationUsePass and PGOInstrumentationGenPass are invoked. -// RUN: %clang_cc1 -O2 -fprofile-instrument-use=llvm -fprofile-instrument-use-path=%t/noncs.profdata -fprofile-instrument=csllvm -fprofile-instrument-path=default.profraw %s -fdebug-pass-manager -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN2 +// RUN: %clang_cc1 -O2 -fprofile-instrument-use-path=%t/noncs.profdata -fprofile-instrument=csllvm -fprofile-instrument-path=default.profraw %s -fdebug-pass-manager -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN2 // CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN2: Running pass: PGOInstrumentationUse // CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN2: Running pass: PGOInstrumentationGenCreateVar on // CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN2: Running pass: PGOInstrumentationGen on // Ensure Pass PGOInstrumentationUsePass is invoked only once. -// RUN: %clang_cc1 -O2 -fprofile-instrument-use=llvm -fprofile-instrument-use-path=%t/noncs.profdata %s -fdebug-pass-manager -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-PGOUSEPASS-INVOKED-USE +// RUN: %clang_cc1 -O2 -fprofile-instrument-use-path=%t/noncs.profdata %s -fdebug-pass-manager -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-PGOUSEPASS-INVOKED-USE // CHECK-PGOUSEPASS-INVOKED-USE: Running pass: PGOInstrumentationUse // CHECK-PGOUSEPASS-INVOKED-USE-NOT: Running pass: PGOInstrumentationGenCreateVar // CHECK-PGOUSEPASS-INVOKED-USE-NOT: Running pass: PGOInstrumentationUse // // Ensure Pass PGOInstrumentationUsePass is invoked twice. // RUN: llvm-profdata merge -o %t/cs.profdata %S/Inputs/pgotestir_cs.proftext -// RUN: %clang_cc1 -O2 -fprofile-instrument-use=csllvm -fprofile-instrument-use-path=%t/cs.profdata %s -fdebug-pass-manager -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-PGOUSEPASS-INVOKED-USE2 +// RUN: %clang_cc1 -O2 -fprofile-instrument-use-path=%t/cs.profdata %s -fdebug-pass-manager -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-PGOUSEPASS-INVOKED-USE2 // CHECK-PGOUSEPASS-INVOKED-USE2: Running pass: PGOInstrumentationUse // CHECK-PGOUSEPASS-INVOKED-USE2: Running pass: PGOInstrumentationUse diff --git a/clang/test/CodeGen/cspgo-instrumentation_lto.c b/clang/test/CodeGen/cspgo-instrumentation_lto.c index 5d541c6688a1f..c4296842ae50e 100644 --- a/clang/test/CodeGen/cspgo-instrumentation_lto.c +++ b/clang/test/CodeGen/cspgo-instrumentation_lto.c @@ -4,7 +4,7 @@ // RUN: llvm-profdata merge -o %t/noncs.profdata %S/Inputs/pgotestir.proftext // // Ensure Pass PGOInstrumentationGenPass is not invoked in PreLink. -// RUN: %clang_cc1 -O2 -fprofile-instrument-use=llvm -fprofile-instrument-use-path=%t/noncs.profdata -fprofile-instrument=csllvm %s -flto -fdebug-pass-manager -emit-llvm-bc -o %t/foo_fe_pm.bc 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN-PRE +// RUN: %clang_cc1 -O2 -fprofile-instrument-use-path=%t/noncs.profdata -fprofile-instrument=csllvm %s -flto -fdebug-pass-manager -emit-llvm-bc -o %t/foo_fe_pm.bc 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN-PRE // CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN-PRE: Running pass: PGOInstrumentationUse // CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN-PRE: Running pass: PGOInstrumentationGenCreateVar // CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN-PRE-NOT: Running pass: PGOInstrumentationGen on @@ -18,12 +18,12 @@ // RUN: llvm-profdata merge -o %t/cs.profdata %S/Inputs/pgotestir_cs.proftext // // Ensure Pass PGOInstrumentationUsePass is invoked Once in PreLink. -// RUN: %clang_cc1 -O2 -fprofile-instrument-use=csllvm -fprofile-instrument-use-path=%t/cs.profdata %s -flto -fdebug-pass-manager -emit-llvm-bc -o %t/foo_fe_pm.bc 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-PRE +// RUN: %clang_cc1 -O2 -fprofile-instrument-use-path=%t/cs.profdata %s -flto -fdebug-pass-manager -emit-llvm-bc -o %t/foo_fe_pm.bc 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-PRE // CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-PRE: Running pass: PGOInstrumentationUse // CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-PRE-NOT: Running pass: PGOInstrumentationGenCreateVar // CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-PRE-NOT: Running pass: PGOInstrumentationUse // // Ensure Pass PGOInstrumentationUSEPass is invoked in PostLink. -// RUN: %clang_cc1 -O2 -x ir %t/foo_fe_pm.bc -fdebug-pass-manager -fprofile-instrument-use=csllvm -fprofile-instrument-use-path=%t/cs.profdata -flto -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-POST +// RUN: %clang_cc1 -O2 -x ir %t/foo_fe_pm.bc -fdebug-pass-manager -fprofile-instrument-use-path=%t/cs.profdata -flto -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-POST // CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-POST: Running pass: PGOInstrumentationUse // CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-POST-NOT: Running pass: PGOInstrumentationUse diff --git a/clang/test/CodeGen/cspgo-instrumentation_thinlto.c b/clang/test/CodeGen/cspgo-instrumentation_thinlto.c index 0627f64a69728..f79433827ce17 100644 --- a/clang/test/CodeGen/cspgo-instrumentation_thinlto.c +++ b/clang/test/CodeGen/cspgo-instrumentation_thinlto.c @@ -4,7 +4,7 @@ // RUN: llvm-profdata merge -o %t/noncs.profdata %S/Inputs/pgotestir.proftext // // Ensure Pass PGOInstrumentationGenPass is not invoked in PreLink. -// RUN: %clang_cc1 -O2 -fprofile-instrument-use=llvm -fprofile-instrument-use-path=%t/noncs.profdata -fprofile-instrument=csllvm %s -fprofile-instrument-path=default.profraw -flto=thin -fdebug-pass-manager -emit-llvm-bc -o %t/foo_fe_pm.bc 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN-PRE +// RUN: %clang_cc1 -O2 -fprofile-instrument-use-path=%t/noncs.profdata -fprofile-instrument=csllvm %s -fprofile-instrument-path=default.profraw -flto=thin -fdebug-pass-manager -emit-llvm-bc -o %t/foo_fe_pm.bc 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN-PRE // CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN-PRE: Running pass: PGOInstrumentationUse // CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN-PRE: Running pass: PGOInstrumentationGenCreateVar // CHECK-CSPGOGENPASS-INVOKED-INSTR-GEN-PRE-NOT: Running pass: PGOInstrumentationGen on @@ -19,16 +19,16 @@ // RUN: llvm-profdata merge -o %t/cs.profdata %S/Inputs/pgotestir_cs.proftext // // Ensure Pass PGOInstrumentationUsePass is invoked Once in PreLink. -// RUN: %clang_cc1 -O2 -fprofile-instrument-use=csllvm -fprofile-instrument-use-path=%t/cs.profdata %s -flto=thin -fdebug-pass-manager -emit-llvm-bc -o %t/foo_fe_pm.bc 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-PRE +// RUN: %clang_cc1 -O2 -fprofile-instrument-use-path=%t/cs.profdata %s -flto=thin -fdebug-pass-manager -emit-llvm-bc -o %t/foo_fe_pm.bc 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-PRE // CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-PRE: Running pass: PGOInstrumentationUse // CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-PRE-NOT: Running pass: PGOInstrumentationUse // // RUN: llvm-lto -thinlto -o %t/foo_pm %t/foo_fe_pm.bc // Ensure Pass PGOInstrumentationUSEPass is invoked in PostLink. -// RUN: %clang_cc1 -O2 -x ir %t/foo_fe_pm.bc -fthinlto-index=%t/foo_pm.thinlto.bc -fdebug-pass-manager -fprofile-instrument-use=csllvm -fprofile-instrument-use-path=%t/cs.profdata -flto=thin -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-POST +// RUN: %clang_cc1 -O2 -x ir %t/foo_fe_pm.bc -fthinlto-index=%t/foo_pm.thinlto.bc -fdebug-pass-manager -fprofile-instrument-use-path=%t/cs.profdata -flto=thin -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-POST // CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-POST: Running pass: PGOInstrumentationUse // CHECK-CSPGOUSEPASS-INVOKED-INSTR-USE-POST-NOT: Running pass: PGOInstrumentationUse // // Finally, test if a non-cs profile is passed to PostLink passes, PGO UsePass is not invoked. -// RUN: %clang_cc1 -O2 -x ir %t/foo_fe_pm.bc -fthinlto-index=%t/foo_pm.thinlto.bc -fdebug-pass-manager -fprofile-instrument-use=llvm -fprofile-instrument-use-path=%t/noncs.profdata -flto=thin -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-PGOUSEPASS-INVOKED-INSTR-USE-POST +// RUN: %clang_cc1 -O2 -x ir %t/foo_fe_pm.bc -fthinlto-index=%t/foo_pm.thinlto.bc -fdebug-pass-manager -fprofile-instrument-use-path=%t/noncs.profdata -flto=thin -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-PGOUSEPASS-INVOKED-INSTR-USE-POST // CHECK-PGOUSEPASS-INVOKED-INSTR-USE-POST-NOT: Running pass: PGOInstrumentationUse diff --git a/clang/test/CodeGen/opt-record.c b/clang/test/CodeGen/opt-record.c index f54a6225760aa..391c14b7bbcc2 100644 --- a/clang/test/CodeGen/opt-record.c +++ b/clang/test/CodeGen/opt-record.c @@ -1,7 +1,7 @@ // RUN: %clang_cc1 -O3 -triple x86_64-unknown-linux-gnu -target-cpu x86-64 %s -o %t -opt-record-file %t.yaml -emit-obj // RUN: cat %t.yaml | FileCheck %s // RUN: llvm-profdata merge %S/Inputs/opt-record.proftext -o %t.profdata -// RUN: %clang_cc1 -O3 -triple x86_64-unknown-linux-gnu -target-cpu x86-64 -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata %s -o %t -opt-record-file %t.yaml -emit-obj +// RUN: %clang_cc1 -O3 -triple x86_64-unknown-linux-gnu -target-cpu x86-64 -fprofile-instrument-use-path=%t.profdata %s -o %t -opt-record-file %t.yaml -emit-obj // RUN: cat %t.yaml | FileCheck -check-prefix=CHECK -check-prefix=CHECK-PGO %s // RUN: %clang_cc1 -O3 -triple x86_64-unknown-linux-gnu -target-cpu x86-64 %s -o %t -opt-record-file %t.yaml -opt-record-passes inline -emit-obj // RUN: cat %t.yaml | FileCheck -check-prefix=CHECK-PASSES %s diff --git a/clang/test/CodeGen/pgo-instrumentation.c b/clang/test/CodeGen/pgo-instrumentation.c index 7c878250ae33e..c01658065497e 100644 --- a/clang/test/CodeGen/pgo-instrumentation.c +++ b/clang/test/CodeGen/pgo-instrumentation.c @@ -15,10 +15,10 @@ // Ensure Pass PGOInstrumentationUsePass is invoked. // RUN: llvm-profdata merge -o %t.profdata %S/Inputs/pgotestir.profraw -// RUN: %clang_cc1 -O2 -fprofile-instrument-use=llvm -fprofile-instrument-use-path=%t.profdata %s -fdebug-pass-manager -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-PGOUSEPASS-INVOKED-INSTR-USE +// RUN: %clang_cc1 -O2 -fprofile-instrument-use-path=%t.profdata %s -fdebug-pass-manager -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-PGOUSEPASS-INVOKED-INSTR-USE // CHECK-PGOUSEPASS-INVOKED-INSTR-USE: Running pass: PGOInstrumentationUse on // // Ensure Pass PGOInstrumentationUsePass is not invoked. // RUN: llvm-profdata merge -o %t.profdata %S/Inputs/pgotestclang.profraw -// RUN: %clang_cc1 -O2 -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata %s -fdebug-pass-manager -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-PGOUSEPASS-INVOKED-USE-CLANG +// RUN: %clang_cc1 -O2 -fprofile-instrument-use-path=%t.profdata %s -fdebug-pass-manager -emit-llvm -o - 2>&1 | FileCheck %s -check-prefix=CHECK-PGOUSEPASS-INVOKED-USE-CLANG // CHECK-PGOUSEPASS-INVOKED-USE-CLANG-NOT: Running pass: PGOInstrumentationUse on diff --git a/clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c b/clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c index a12574d28c731..efbcc851ad770 100644 --- a/clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c +++ b/clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c @@ -7,7 +7,7 @@ // RUN: llvm-lto -thinlto -o %t %t1.bo // RUN: %clang_cc1 -triple x86_64-linux-gnu -O2 -x ir %t1.bo -fthinlto-index=%t.thinlto.bc -emit-obj -Rpass-analysis=info 2>&1 | FileCheck %s -check-prefix=CHECK-REMARK // RUN: llvm-profdata merge -o %t2.profdata %S/Inputs/thinlto_expect2.proftext -// RUN: %clang_cc1 -triple x86_64-linux-gnu -O2 -x ir %t1.bo -fthinlto-index=%t.thinlto.bc -fprofile-instrument-use=llvm -fprofile-instrument-use-path=%t2.profdata -emit-obj 2>&1 | FileCheck %s -allow-empty -check-prefix=CHECK-NOWARNING +// RUN: %clang_cc1 -triple x86_64-linux-gnu -O2 -x ir %t1.bo -fthinlto-index=%t.thinlto.bc -fprofile-instrument-use-path=%t2.profdata -emit-obj 2>&1 | FileCheck %s -allow-empty -check-prefix=CHECK-NOWARNING int sum; __attribute__((noinline)) void bar(void) { diff --git a/clang/test/CodeGenCXX/fdebug-info-for-profiling.cpp b/clang/test/CodeGenCXX/fdebug-info-for-profiling.cpp index 63de73c90bd2f..e468a8098d7c8 100644 --- a/clang/test/CodeGenCXX/fdebug-info-for-profiling.cpp +++ b/clang/test/CodeGenCXX/fdebug-info-for-profiling.cpp @@ -13,7 +13,7 @@ // RUN: echo > %t.proftext // RUN: llvm-profdata merge %t.proftext -o %t.profdata -// RUN: %clang_cc1 -emit-llvm -fdebug-pass-manager -O1 -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -fdebug-info-for-profiling %s -o - 2>&1 | FileCheck %s --check-prefix=DISCR +// RUN: %clang_cc1 -emit-llvm -fdebug-pass-manager -O1 -fprofile-instrument-use-path=%t.profdata -fdebug-info-for-profiling %s -o - 2>&1 | FileCheck %s --check-prefix=DISCR // RUN: %clang_cc1 -emit-llvm -fdebug-pass-manager -O1 -fdebug-info-for-profiling -fpseudo-probe-for-profiling %s -o - 2>&1 | FileCheck %s --check-prefix=PROBE // NODISCR-NOT: Running pass: AddDiscriminatorsPass diff --git a/clang/test/CodeGenCXX/profile-remap.cpp b/clang/test/CodeGenCXX/profile-remap.cpp index f077f929f406d..b27f67da58ff9 100644 --- a/clang/test/CodeGenCXX/profile-remap.cpp +++ b/clang/test/CodeGenCXX/profile-remap.cpp @@ -2,9 +2,9 @@ // // RUN: %clang_cc1 -triple x86_64-linux-gnu -fprofile-sample-use=%S/Inputs/profile-remap.samples -fprofile-remapping-file=%S/Inputs/profile-remap.map -O2 %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-SAMPLES // RUN: llvm-profdata merge -output %T.profdata %S/Inputs/profile-remap.proftext -// RUN: %clang_cc1 -triple x86_64-linux-gnu -fprofile-instrument-use=llvm -fprofile-instrument-use-path=%T.profdata -fprofile-remapping-file=%S/Inputs/profile-remap.map -O2 %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-INSTR +// RUN: %clang_cc1 -triple x86_64-linux-gnu -fprofile-instrument-use-path=%T.profdata -fprofile-remapping-file=%S/Inputs/profile-remap.map -O2 %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-INSTR // RUN: llvm-profdata merge -output %T.profdata %S/Inputs/profile-remap_entry.proftext -// RUN: %clang_cc1 -triple x86_64-linux-gnu -fprofile-instrument-use=llvm -fprofile-instrument-use-path=%T.profdata -fprofile-remapping-file=%S/Inputs/profile-remap.map -O2 %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-INSTR +// RUN: %clang_cc1 -triple x86_64-linux-gnu -fprofile-instrument-use-path=%T.profdata -fprofile-remapping-file=%S/Inputs/profile-remap.map -O2 %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-INSTR namespace Foo { struct X {}; diff --git a/clang/test/Driver/Inputs/a.proftext b/clang/test/Driver/Inputs/a.proftext deleted file mode 100644 index 05ab839db07c7..0000000000000 --- a/clang/test/Driver/Inputs/a.proftext +++ /dev/null @@ -1,2 +0,0 @@ -# IR level Instrumentation Flag -:ir diff --git a/clang/test/Driver/cl-options.c b/clang/test/Driver/cl-options.c index 22cb04bc95530..57e16e8795a28 100644 --- a/clang/test/Driver/cl-options.c +++ b/clang/test/Driver/cl-options.c @@ -90,21 +90,16 @@ // RUN: not %clang_cl -### /FAcsu -fprofile-instr-generate -fprofile-instr-use=file -- %s 2>&1 | FileCheck -check-prefix=CHECK-NO-MIX-GEN-USE %s // CHECK-NO-MIX-GEN-USE: '{{[a-z=-]*}}' not allowed with '{{[a-z=-]*}}' -// RUN: rm -rf %t && mkdir %t -// RUN: llvm-profdata merge -o %t/somefile.prof %S/Inputs/a.proftext -// RUN: llvm-profdata merge -o %t/default.profdata %S/Inputs/a.proftext -// RUN: cd %t - // RUN: %clang_cl -### /FA -fprofile-instr-use -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE %s // RUN: %clang_cl -### /FA -fprofile-use -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE %s -// RUN: %clang_cl -### /FA -fprofile-instr-use=%t/somefile.prof -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE-FILE %s -// RUN: %clang_cl -### /FA -fprofile-use=%t/somefile.prof -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE-FILE %s +// RUN: %clang_cl -### /FA -fprofile-instr-use=/tmp/somefile.prof -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE-FILE %s +// RUN: %clang_cl -### /FA -fprofile-use=/tmp/somefile.prof -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE-FILE %s // RUN: %clang_cl -### /FAcsu -fprofile-instr-use -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE %s // RUN: %clang_cl -### /FAcsu -fprofile-use -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE %s -// RUN: %clang_cl -### /FAcsu -fprofile-instr-use=%t/somefile.prof -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE-FILE %s -// RUN: %clang_cl -### /FAcsu -fprofile-use=%t/somefile.prof -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE-FILE %s -// CHECK-PROFILE-USE: "-fprofile-instrument-use-path={{.*}}default.profdata" -// CHECK-PROFILE-USE-FILE: "-fprofile-instrument-use-path={{.*}}somefile.prof" +// RUN: %clang_cl -### /FAcsu -fprofile-instr-use=/tmp/somefile.prof -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE-FILE %s +// RUN: %clang_cl -### /FAcsu -fprofile-use=/tmp/somefile.prof -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE-FILE %s +// CHECK-PROFILE-USE: "-fprofile-instrument-use-path=default.profdata" +// CHECK-PROFILE-USE-FILE: "-fprofile-instrument-use-path=/tmp/somefile.prof" // RUN: %clang_cl /GA -### -- %s 2>&1 | FileCheck -check-prefix=GA %s // GA: -ftls-model=local-exec diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c index a68e60f2a9738..ee7ded265769b 100644 --- a/clang/test/Driver/clang_f_opts.c +++ b/clang/test/Driver/clang_f_opts.c @@ -122,22 +122,16 @@ // CHECK-DISABLE-COVERAGE-NOT: "-fcoverage-mapping" // CHECK-PROFILE-REMAP: "-fprofile-remapping-file=foo/bar.txt" -// RUN: rm -rf %t && mkdir %t -// RUN: llvm-profdata merge -o %t/somefile.prof %S/Inputs/a.proftext -// RUN: llvm-profdata merge -o %t/default.profdata %S/Inputs/a.proftext -// RUN: cd %t - // RUN: %clang -### -S -fprofile-use %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE %s // RUN: %clang -### -S -fprofile-instr-use %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE %s -// RUN: mkdir -p %t/some/dir -// RUN: cp %t/default.profdata %t/some/dir -// RUN: %clang -### -S -fprofile-use=%t/some/dir %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE-DIR %s -// RUN: %clang -### -S -fprofile-instr-use=%t/somefile.prof %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE-FILE %s +// RUN: mkdir -p %t.d/some/dir +// RUN: %clang -### -S -fprofile-use=%t.d/some/dir %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE-DIR %s +// RUN: %clang -### -S -fprofile-instr-use=/tmp/somefile.prof %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-USE-FILE %s // CHECK-PROFILE-USE: "-fprofile-instrument-use-path=default.profdata" -// CHECK-PROFILE-USE-DIR: "-fprofile-instrument-use-path={{.*}}some/dir{{/|\\\\}}default.profdata" -// CHECK-PROFILE-USE-FILE: "-fprofile-instrument-use-path={{.*}}somefile.prof" +// CHECK-PROFILE-USE-DIR: "-fprofile-instrument-use-path={{.*}}.d/some/dir{{/|\\\\}}default.profdata" +// CHECK-PROFILE-USE-FILE: "-fprofile-instrument-use-path=/tmp/somefile.prof" -// RUN: %clang -### -S -fprofile-instr-use=%t/somefile.prof -fdiagnostics-misexpect-tolerance=10 -Wmisexpect %s 2>&1 | FileCheck %s --check-prefix=CHECK-MISEXPECT-TOLLERANCE +// RUN: %clang -### -S -fprofile-instr-use=%t.profdata -fdiagnostics-misexpect-tolerance=10 -Wmisexpect %s 2>&1 | FileCheck %s --check-prefix=CHECK-MISEXPECT-TOLLERANCE // CHECK-MISEXPECT-TOLLERANCE: "-fdiagnostics-misexpect-tolerance=10" // CHECK-MISEXPECT-TOLLERANCE-NOT: argument unused diff --git a/clang/test/Driver/fcs-profile-generate.c b/clang/test/Driver/fcs-profile-generate.c index ecb5aad58fd46..f69fa44be873e 100644 --- a/clang/test/Driver/fcs-profile-generate.c +++ b/clang/test/Driver/fcs-profile-generate.c @@ -1,14 +1,10 @@ -// RUN: rm -rf %t && mkdir %t -// RUN: llvm-profdata merge -o %t/a.profdata %S/Inputs/a.proftext - -// RUN: %clang -### -c -fprofile-use=%t/a.profdata -fcs-profile-generate %s 2>&1 | FileCheck %s +// RUN: %clang -### -c -fprofile-use=a.profdata -fcs-profile-generate %s 2>&1 | FileCheck %s // CHECK: "-fprofile-instrument=csllvm" // CHECK-NOT: "-fprofile-instrument-path= -// CHECK-SAME: "-fprofile-instrument-use=llvm" -// CHECK-SAME: "-fprofile-instrument-use-path={{.*}}a.profdata" +// CHECK-SAME: "-fprofile-instrument-use-path=a.profdata" -// RUN: %clang -### -c -fprofile-use=%t/a.profdata -fcs-profile-generate=dir %s 2>&1 | FileCheck %s --check-prefix=CHECK1 -// CHECK1: "-fprofile-instrument=csllvm"{{.*}} "-fprofile-instrument-path=dir{{/|\\\\}}default_%m.profraw" "-fprofile-instrument-use=llvm" "-fprofile-instrument-use-path={{.*}}a.profdata" +// RUN: %clang -### -c -fprofile-use=a.profdata -fcs-profile-generate=dir %s 2>&1 | FileCheck %s --check-prefix=CHECK1 +// CHECK1: "-fprofile-instrument=csllvm"{{.*}} "-fprofile-instrument-path=dir{{/|\\\\}}default_%m.profraw" "-fprofile-instrument-use-path=a.profdata" /// Degradation case. This usage does not make much sense. // RUN: %clang -### -c -fcs-profile-generate %s 2>&1 | FileCheck %s --check-prefix=NOUSE diff --git a/clang/test/Driver/fsplit-machine-functions.c b/clang/test/Driver/fsplit-machine-functions.c index 153aafba8fbd0..02bab476e831d 100644 --- a/clang/test/Driver/fsplit-machine-functions.c +++ b/clang/test/Driver/fsplit-machine-functions.c @@ -1,13 +1,9 @@ -// RUN: rm -rf %t && mkdir %t -// RUN: llvm-profdata merge -o %t/default.profdata %S/Inputs/a.proftext - -// RUN: %clang -### --target=x86_64 -fprofile-use=%t/default.profdata -fsplit-machine-functions %s 2>&1 | FileCheck %s --check-prefixes=CHECK,LTO-NEG -// RUN: %clang -### --target=aarch64 -fprofile-use=%t/default.profdata -fsplit-machine-functions %s 2>&1 | FileCheck %s --check-prefixes=CHECK,LTO-NEG -// RUN: %clang -### --target=x86_64 -fprofile-use=%t/default.profdata -fsplit-machine-functions -fno-split-machine-functions %s -c 2>&1 | FileCheck -check-prefix=NEG %s +// RUN: %clang -### --target=x86_64 -fprofile-use=default.profdata -fsplit-machine-functions %s 2>&1 | FileCheck %s --check-prefixes=CHECK,LTO-NEG +// RUN: %clang -### --target=aarch64 -fprofile-use=default.profdata -fsplit-machine-functions %s 2>&1 | FileCheck %s --check-prefixes=CHECK,LTO-NEG +// RUN: %clang -### --target=x86_64 -fprofile-use=default.profdata -fsplit-machine-functions -fno-split-machine-functions %s -c 2>&1 | FileCheck -check-prefix=NEG %s // CHECK: "-fsplit-machine-functions" -// CHECK-SAME: "-fprofile-instrument-use=llvm" -// CHECK-SAME: "-fprofile-instrument-use-path={{.*}}default.profdata" +// CHECK-SAME: "-fprofile-instrument-use-path=default.profdata" // NEG-NOT: "-fsplit-machine-functions" diff --git a/clang/test/Frontend/optimization-remark-with-hotness-new-pm.c b/clang/test/Frontend/optimization-remark-with-hotness-new-pm.c index 0c7e96182aebf..173b43ba41bfe 100644 --- a/clang/test/Frontend/optimization-remark-with-hotness-new-pm.c +++ b/clang/test/Frontend/optimization-remark-with-hotness-new-pm.c @@ -15,8 +15,7 @@ // // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \ // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \ -// RUN: -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata \ -// RUN: -Rpass=inline \ +// RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ // RUN: -O1 \ // RUN: -Rpass-analysis=inline -Rpass-missed=inline \ // RUN: -fdiagnostics-show-hotness -verify @@ -35,24 +34,24 @@ // RUN: -verify // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \ // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \ -// RUN: -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ +// RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ // RUN: -O1 \ // RUN: -Rpass-analysis=inline -Rpass-missed=inline \ // RUN: -fdiagnostics-show-hotness -fdiagnostics-hotness-threshold=10 -verify // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \ // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \ -// RUN: -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ +// RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ // RUN: -O1 \ // RUN: -Rpass-analysis=inline 2>&1 | FileCheck -check-prefix=HOTNESS_OFF %s // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \ // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \ -// RUN: -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ +// RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ // RUN: -O1 \ // RUN: -Rpass-analysis=inline -Rno-pass-with-hotness 2>&1 | FileCheck \ // RUN: -check-prefix=HOTNESS_OFF %s // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \ // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \ -// RUN: -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ +// RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ // RUN: -Rpass-analysis=inline -fdiagnostics-show-hotness \ // RUN: -fdiagnostics-hotness-threshold=100 2>&1 \ // RUN: | FileCheck -allow-empty -check-prefix=THRESHOLD %s diff --git a/clang/test/Modules/modules-cache-path-canonicalization-output.c b/clang/test/Modules/modules-cache-path-canonicalization-output.c deleted file mode 100644 index ad71b69e5299e..0000000000000 --- a/clang/test/Modules/modules-cache-path-canonicalization-output.c +++ /dev/null @@ -1,18 +0,0 @@ -// This checks that implicitly-built modules produce identical PCM -// files regardless of the spelling of the same module cache path. - -// RUN: rm -rf %t -// RUN: split-file %s %t - -// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fsyntax-only %t/tu.c \ -// RUN: -fmodules-cache-path=%t/cache -fdisable-module-hash -// RUN: mv %t/cache/M.pcm %t/M.pcm -// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fsyntax-only %t/tu.c \ -// RUN: -fmodules-cache-path=%t/./cache -fdisable-module-hash -// RUN: diff %t/./cache/M.pcm %t/M.pcm - -//--- tu.c -#include "M.h" -//--- M.h -//--- module.modulemap -module M { header "M.h" } diff --git a/clang/test/OpenMP/amdgcn_save_temps.c b/clang/test/OpenMP/amdgcn_save_temps.c deleted file mode 100644 index d838bb1166b6b..0000000000000 --- a/clang/test/OpenMP/amdgcn_save_temps.c +++ /dev/null @@ -1,23 +0,0 @@ - -// REQUIRES: amdgpu-registered-target - -// RUN: %clang_cc1 -E -fopenmp -x c -triple amdgcn-amd-amdhsa -fopenmp-targets=amdgcn-amd-amdhsa -save-temps=cwd %s -o %t-openmp-amdgcn-amd-amdhsa-gfx90a.i -// RUN: %clang_cc1 -fopenmp -x c -triple x86_64-unknown-unknown -fopenmp-targets=amdgcn-amd-amdhsa -save-temps=cwd -emit-llvm-bc %s -o %t-x86_64-unknown-unknown.bc -// RUN: %clang_cc1 -fopenmp -x c -triple amdgcn-amd-amdhsa -fopenmp-targets=amdgcn-amd-amdhsa -save-temps=cwd -emit-llvm -fopenmp-is-target-device -x cpp-output %t-openmp-amdgcn-amd-amdhsa-gfx90a.i -fopenmp-host-ir-file-path %t-x86_64-unknown-unknown.bc -o - | FileCheck %s -// expected-no-diagnostics -#ifndef HEADER -#define HEADER - -#define N 1000 - -int test_amdgcn_save_temps() { - int arr[N]; -#pragma omp target - for (int i = 0; i < N; i++) { - arr[i] = 1; - } - return arr[0]; -} -#endif - -// CHECK: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_test_amdgcn_save_temps diff --git a/clang/test/OpenMP/host-ir-file-vfs.c b/clang/test/OpenMP/host-ir-file-vfs.c deleted file mode 100644 index 394d8fbcc94ac..0000000000000 --- a/clang/test/OpenMP/host-ir-file-vfs.c +++ /dev/null @@ -1,33 +0,0 @@ -// This test checks that the OpenMP host IR file goes through VFS overlays. - -// RUN: rm -rf %t -// RUN: split-file %s %t - -// RUN: sed -e "s|DIR|%/t|g" %t/vfs.json.in > %t/vfs.json -// RUN: %clang_cc1 -fopenmp-simd -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm-bc %t/host.c -o %t/host.bc - -// RUN: %clang_cc1 -fopenmp-simd -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %t/device.c -o - \ -// RUN: -fopenmp-is-target-device -fopenmp-host-ir-file-path %t/virtual/host.bc -ivfsoverlay %t/vfs.json -verify - -//--- vfs.json.in -{ - 'version': 0, - 'use-external-names': true, - 'roots': [ - { - 'name': 'DIR/virtual', - 'type': 'directory', - 'contents': [ - { - 'name': 'host.bc', - 'type': 'file', - 'external-contents': 'DIR/host.bc' - } - ] - } - ] -} - -//--- host.c -//--- device.c -// expected-no-diagnostics diff --git a/clang/test/Profile/c-captured.c b/clang/test/Profile/c-captured.c index e38798983b6c2..3a802494eb6a6 100644 --- a/clang/test/Profile/c-captured.c +++ b/clang/test/Profile/c-captured.c @@ -1,7 +1,7 @@ // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-captured.c %s -o - -emit-llvm -fprofile-instrument=clang | FileCheck -allow-deprecated-dag-overlap -check-prefix=PGOGEN -check-prefix=PGOALL %s // RUN: llvm-profdata merge %S/Inputs/c-captured.proftext -o %t.profdata -// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-captured.c %s -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata | FileCheck -allow-deprecated-dag-overlap -check-prefix=PGOUSE -check-prefix=PGOALL %s +// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-captured.c %s -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata | FileCheck -allow-deprecated-dag-overlap -check-prefix=PGOUSE -check-prefix=PGOALL %s // PGOGEN: @[[DCC:__profc_debug_captured]] = private global [3 x i64] zeroinitializer // PGOGEN: @[[CSC:__profc_c_captured.c___captured_stmt]] = private global [2 x i64] zeroinitializer diff --git a/clang/test/Profile/c-counter-overflows.c b/clang/test/Profile/c-counter-overflows.c index bc12865b32b5d..5cb32bbc30af4 100644 --- a/clang/test/Profile/c-counter-overflows.c +++ b/clang/test/Profile/c-counter-overflows.c @@ -2,7 +2,7 @@ // truncated. // RUN: llvm-profdata merge %S/Inputs/c-counter-overflows.proftext -o %t.profdata -// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-counter-overflows.c %s -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata | FileCheck %s +// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-counter-overflows.c %s -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata | FileCheck %s typedef unsigned long long uint64_t; diff --git a/clang/test/Profile/c-general.c b/clang/test/Profile/c-general.c index ee36a43dac081..2f621ec9b0bf9 100644 --- a/clang/test/Profile/c-general.c +++ b/clang/test/Profile/c-general.c @@ -3,11 +3,11 @@ // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-general.c %s -o - -emit-llvm -fprofile-instrument=clang | FileCheck -allow-deprecated-dag-overlap -check-prefix=PGOGEN %s // RUN: llvm-profdata merge %S/Inputs/c-general.proftext -o %t.profdata -// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-general.c %s -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata | FileCheck -allow-deprecated-dag-overlap -check-prefix=PGOUSE %s -// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-general.c %s -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%S/Inputs/c-general.profdata.v5 | FileCheck -allow-deprecated-dag-overlap -check-prefix=PGOUSE %s -// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-general.c %s -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%S/Inputs/c-general.profdata.v3 | FileCheck -allow-deprecated-dag-overlap -check-prefix=PGOUSE %s +// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-general.c %s -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata | FileCheck -allow-deprecated-dag-overlap -check-prefix=PGOUSE %s +// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-general.c %s -o - -emit-llvm -fprofile-instrument-use-path=%S/Inputs/c-general.profdata.v5 | FileCheck -allow-deprecated-dag-overlap -check-prefix=PGOUSE %s +// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-general.c %s -o - -emit-llvm -fprofile-instrument-use-path=%S/Inputs/c-general.profdata.v3 | FileCheck -allow-deprecated-dag-overlap -check-prefix=PGOUSE %s // Also check compatibility with older profiles. -// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-general.c %s -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%S/Inputs/c-general.profdata.v1 | FileCheck -allow-deprecated-dag-overlap -check-prefix=PGOUSE %s +// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-general.c %s -o - -emit-llvm -fprofile-instrument-use-path=%S/Inputs/c-general.profdata.v1 | FileCheck -allow-deprecated-dag-overlap -check-prefix=PGOUSE %s // RUN: %clang -fprofile-generate -E -dM %s | FileCheck -match-full-lines -check-prefix=PROFGENMACRO %s // RUN: %clang -fprofile-instr-generate -E -dM %s | FileCheck -match-full-lines -check-prefix=PROFGENMACRO %s diff --git a/clang/test/Profile/c-outdated-data.c b/clang/test/Profile/c-outdated-data.c index 7071401599b89..454e4d799e0bb 100644 --- a/clang/test/Profile/c-outdated-data.c +++ b/clang/test/Profile/c-outdated-data.c @@ -4,8 +4,8 @@ // doesn't play well with warnings that have no line number. // RUN: llvm-profdata merge %S/Inputs/c-outdated-data.proftext -o %t.profdata -// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-outdated-data.c %s -o /dev/null -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata 2>&1 | FileCheck %s -check-prefix=NO_MISSING -// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-outdated-data.c %s -o /dev/null -emit-llvm -Wprofile-instr-missing -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata 2>&1 | FileCheck %s -check-prefix=WITH_MISSING +// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-outdated-data.c %s -o /dev/null -emit-llvm -fprofile-instrument-use-path=%t.profdata 2>&1 | FileCheck %s -check-prefix=NO_MISSING +// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-outdated-data.c %s -o /dev/null -emit-llvm -Wprofile-instr-missing -fprofile-instrument-use-path=%t.profdata 2>&1 | FileCheck %s -check-prefix=WITH_MISSING // NO_MISSING: warning: profile data may be out of date: of 3 functions, 2 have mismatched data that will be ignored // NO_MISSING-NOT: 1 has no data diff --git a/clang/test/Profile/c-unprofiled-blocks.c b/clang/test/Profile/c-unprofiled-blocks.c index bcf3e06371e09..e25bbc50de2ba 100644 --- a/clang/test/Profile/c-unprofiled-blocks.c +++ b/clang/test/Profile/c-unprofiled-blocks.c @@ -2,7 +2,7 @@ // runs) shouldn't have any branch weight metadata added. // RUN: llvm-profdata merge %S/Inputs/c-unprofiled-blocks.proftext -o %t.profdata -// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-unprofiled-blocks.c %s -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata | FileCheck -check-prefix=PGOUSE %s +// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-unprofiled-blocks.c %s -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata | FileCheck -check-prefix=PGOUSE %s // PGOUSE-LABEL: @never_called(i32 noundef %i) int never_called(int i) { diff --git a/clang/test/Profile/c-unprofiled.c b/clang/test/Profile/c-unprofiled.c index 3f52d773e1c06..3466079f69bd8 100644 --- a/clang/test/Profile/c-unprofiled.c +++ b/clang/test/Profile/c-unprofiled.c @@ -7,7 +7,7 @@ // doesn't play well with warnings that have no line number. // RUN: llvm-profdata merge %S/Inputs/c-unprofiled.proftext -o %t.profdata -// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-unprofiled.c -I %S/Inputs/ %s -o /dev/null -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -Wprofile-instr-unprofiled 2>&1 | FileCheck %s +// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-unprofiled.c -I %S/Inputs/ %s -o /dev/null -emit-llvm -fprofile-instrument-use-path=%t.profdata -Wprofile-instr-unprofiled 2>&1 | FileCheck %s // CHECK: warning: no profile data available for file "c-unprofiled.c" diff --git a/clang/test/Profile/cxx-class.cpp b/clang/test/Profile/cxx-class.cpp index ce9ddcfc4553f..c38a81e0d86e8 100644 --- a/clang/test/Profile/cxx-class.cpp +++ b/clang/test/Profile/cxx-class.cpp @@ -9,7 +9,7 @@ // RUN: FileCheck --input-file=%tgen -check-prefix=VDTRGEN %s // RUN: llvm-profdata merge %S/Inputs/cxx-class.proftext -o %t.profdata -// RUN: %clang_cc1 %s -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -triple %itanium_abi_triple > %tuse +// RUN: %clang_cc1 %s -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata -triple %itanium_abi_triple > %tuse // RUN: FileCheck --input-file=%tuse -check-prefix=CTRUSE %s // RUN: FileCheck --input-file=%tuse -check-prefix=DTRUSE %s // RUN: FileCheck --input-file=%tuse -check-prefix=MTHUSE %s diff --git a/clang/test/Profile/cxx-hash-v2.cpp b/clang/test/Profile/cxx-hash-v2.cpp index 0696b20bdcac3..995fe008f5236 100644 --- a/clang/test/Profile/cxx-hash-v2.cpp +++ b/clang/test/Profile/cxx-hash-v2.cpp @@ -8,8 +8,8 @@ // RUN: diff %t.hashes %t.hashes.unique // RUN: llvm-profdata merge %S/Inputs/cxx-hash-v2.proftext -o %t.profdata -// RUN: %clang_cc1 -std=c++11 -fexceptions -fcxx-exceptions -triple x86_64-apple-macosx10.9 -main-file-name cxx-hash-v2.mm %s -o /dev/null -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata 2>&1 | FileCheck %s -allow-empty -// RUN: %clang_cc1 -std=c++11 -fexceptions -fcxx-exceptions -triple x86_64-apple-macosx10.9 -main-file-name cxx-hash-v2.mm %s -o /dev/null -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%S/Inputs/cxx-hash-v2.profdata.v5 2>&1 | FileCheck %s -allow-empty +// RUN: %clang_cc1 -std=c++11 -fexceptions -fcxx-exceptions -triple x86_64-apple-macosx10.9 -main-file-name cxx-hash-v2.mm %s -o /dev/null -emit-llvm -fprofile-instrument-use-path=%t.profdata 2>&1 | FileCheck %s -allow-empty +// RUN: %clang_cc1 -std=c++11 -fexceptions -fcxx-exceptions -triple x86_64-apple-macosx10.9 -main-file-name cxx-hash-v2.mm %s -o /dev/null -emit-llvm -fprofile-instrument-use-path=%S/Inputs/cxx-hash-v2.profdata.v5 2>&1 | FileCheck %s -allow-empty // CHECK-NOT: warning: profile data may be out of date diff --git a/clang/test/Profile/cxx-lambda.cpp b/clang/test/Profile/cxx-lambda.cpp index b05fdd3d26b7c..589f922c70782 100644 --- a/clang/test/Profile/cxx-lambda.cpp +++ b/clang/test/Profile/cxx-lambda.cpp @@ -5,7 +5,7 @@ // RUN: FileCheck -allow-deprecated-dag-overlap --input-file=%tgen -check-prefix=LMBGEN %s // RUN: llvm-profdata merge %S/Inputs/cxx-lambda.proftext -o %t.profdata -// RUN: %clang_cc1 -x c++ %s -triple %itanium_abi_triple -main-file-name cxx-lambda.cpp -std=c++11 -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata > %tuse +// RUN: %clang_cc1 -x c++ %s -triple %itanium_abi_triple -main-file-name cxx-lambda.cpp -std=c++11 -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata > %tuse // RUN: FileCheck -allow-deprecated-dag-overlap --input-file=%tuse -check-prefix=PGOUSE %s // RUN: FileCheck -allow-deprecated-dag-overlap --input-file=%tuse -check-prefix=LMBUSE %s diff --git a/clang/test/Profile/cxx-missing-bodies.cpp b/clang/test/Profile/cxx-missing-bodies.cpp index 87541c2825b25..6d34fca482c99 100644 --- a/clang/test/Profile/cxx-missing-bodies.cpp +++ b/clang/test/Profile/cxx-missing-bodies.cpp @@ -2,7 +2,7 @@ // // Don't crash when presented profile data for functions without bodies: // RUN: llvm-profdata merge %S/Inputs/cxx-missing-bodies.proftext -o %t.profdata -// RUN: %clang_cc1 %s -std=c++11 -emit-llvm-only -triple=i386-pc-win32 -fno-rtti -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -w +// RUN: %clang_cc1 %s -std=c++11 -emit-llvm-only -triple=i386-pc-win32 -fno-rtti -fprofile-instrument-use-path=%t.profdata -w // GEN-NOT: __profn{{.*}}??_GA@@UAEPAXI@Z // GEN-NOT: __profn{{.*}}??_DA@@QAEXXZ diff --git a/clang/test/Profile/cxx-never-executed-branch.cpp b/clang/test/Profile/cxx-never-executed-branch.cpp index d7bdd3c67a15d..812f65f3996d3 100644 --- a/clang/test/Profile/cxx-never-executed-branch.cpp +++ b/clang/test/Profile/cxx-never-executed-branch.cpp @@ -1,7 +1,7 @@ // Test that clang doesn't emit llvm.expect when the counter is 0 // RUN: llvm-profdata merge %S/Inputs/cxx-never-executed-branch.proftext -o %t.profdata -// RUN: %clang_cc1 -std=c++20 %s -triple %itanium_abi_triple -O2 -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -disable-llvm-passes | FileCheck %s +// RUN: %clang_cc1 -std=c++20 %s -triple %itanium_abi_triple -O2 -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata -disable-llvm-passes | FileCheck %s int rand(); diff --git a/clang/test/Profile/cxx-rangefor.cpp b/clang/test/Profile/cxx-rangefor.cpp index 43bdaa9b70aeb..58c578c3c1017 100644 --- a/clang/test/Profile/cxx-rangefor.cpp +++ b/clang/test/Profile/cxx-rangefor.cpp @@ -4,7 +4,7 @@ // RUN: FileCheck --input-file=%tgen -check-prefix=CHECK -check-prefix=PGOGEN %s // RUN: llvm-profdata merge %S/Inputs/cxx-rangefor.proftext -o %t.profdata -// RUN: %clang_cc1 -x c++ %s -triple %itanium_abi_triple -main-file-name cxx-rangefor.cpp -std=c++11 -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata > %tuse +// RUN: %clang_cc1 -x c++ %s -triple %itanium_abi_triple -main-file-name cxx-rangefor.cpp -std=c++11 -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata > %tuse // RUN: FileCheck --input-file=%tuse -check-prefix=CHECK -check-prefix=PGOUSE %s // PGOGEN: @[[RFC:__profc__Z9range_forv]] = {{(private|internal)}} global [5 x i64] zeroinitializer diff --git a/clang/test/Profile/cxx-templates.cpp b/clang/test/Profile/cxx-templates.cpp index 09cf11e841dc4..51c8f1f6d1edd 100644 --- a/clang/test/Profile/cxx-templates.cpp +++ b/clang/test/Profile/cxx-templates.cpp @@ -6,7 +6,7 @@ // RUN: FileCheck --input-file=%tgen -check-prefix=T100GEN -check-prefix=ALL %s // RUN: llvm-profdata merge %S/Inputs/cxx-templates.proftext -o %t.profdata -// RUN: %clang_cc1 -x c++ %s -triple %itanium_abi_triple -main-file-name cxx-templates.cpp -std=c++11 -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata > %tuse +// RUN: %clang_cc1 -x c++ %s -triple %itanium_abi_triple -main-file-name cxx-templates.cpp -std=c++11 -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata > %tuse // RUN: FileCheck --input-file=%tuse -check-prefix=T0USE -check-prefix=ALL %s // RUN: FileCheck --input-file=%tuse -check-prefix=T100USE -check-prefix=ALL %s diff --git a/clang/test/Profile/cxx-throws.cpp b/clang/test/Profile/cxx-throws.cpp index fc04add24b97d..e989c2d39dfbb 100644 --- a/clang/test/Profile/cxx-throws.cpp +++ b/clang/test/Profile/cxx-throws.cpp @@ -7,8 +7,8 @@ // RUN: %clang_cc1 %s -o - -emit-llvm -fprofile-instrument=clang -fexceptions -fcxx-exceptions -triple %itanium_abi_triple | FileCheck -check-prefix=PGOGEN-EXC %s // RUN: llvm-profdata merge %S/Inputs/cxx-throws.proftext -o %t.profdata -// RUN: %clang_cc1 %s -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -fexceptions -fcxx-exceptions -triple %itanium_abi_triple | FileCheck -check-prefix=PGOUSE %s -// RUN: %clang_cc1 %s -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -fexceptions -fcxx-exceptions -triple %itanium_abi_triple | FileCheck -check-prefix=PGOUSE-EXC %s +// RUN: %clang_cc1 %s -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata -fexceptions -fcxx-exceptions -triple %itanium_abi_triple | FileCheck -check-prefix=PGOUSE %s +// RUN: %clang_cc1 %s -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata -fexceptions -fcxx-exceptions -triple %itanium_abi_triple | FileCheck -check-prefix=PGOUSE-EXC %s // PGOGEN: @[[THC:__profc__Z6throwsv]] = {{(private|internal)}} global [9 x i64] zeroinitializer // PGOGEN-EXC: @[[THC:__profc__Z6throwsv]] = {{(private|internal)}} global [9 x i64] zeroinitializer diff --git a/clang/test/Profile/func-entry.c b/clang/test/Profile/func-entry.c index 27d11cc254ea8..4a4ca2288352b 100644 --- a/clang/test/Profile/func-entry.c +++ b/clang/test/Profile/func-entry.c @@ -1,7 +1,7 @@ // Test that function entry counts are set correctly. // RUN: llvm-profdata merge %S/Inputs/func-entry.proftext -o %t.profdata -// RUN: %clang_cc1 %s -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata | FileCheck %s +// RUN: %clang_cc1 %s -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use-path=%t.profdata | FileCheck %s void foo(void); diff --git a/clang/test/Profile/misexpect-branch-cold.c b/clang/test/Profile/misexpect-branch-cold.c index 43ef3fcdda0ba..6d34f92a25454 100644 --- a/clang/test/Profile/misexpect-branch-cold.c +++ b/clang/test/Profile/misexpect-branch-cold.c @@ -1,7 +1,7 @@ // Test that misexpect emits no warning when prediction is correct // RUN: llvm-profdata merge %S/Inputs/misexpect-branch.proftext -o %t.profdata -// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -verify -Wmisexpect +// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify -Wmisexpect // expected-no-diagnostics #define likely(x) __builtin_expect(!!(x), 1) diff --git a/clang/test/Profile/misexpect-branch-nonconst-expected-val.c b/clang/test/Profile/misexpect-branch-nonconst-expected-val.c index fa2b4f1755040..c5167b9a2a0b7 100644 --- a/clang/test/Profile/misexpect-branch-nonconst-expected-val.c +++ b/clang/test/Profile/misexpect-branch-nonconst-expected-val.c @@ -1,7 +1,7 @@ // Test that misexpect emits no warning when condition is not a compile-time constant // RUN: llvm-profdata merge %S/Inputs/misexpect-branch-nonconst-expect-arg.proftext -o %t.profdata -// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -verify -Wmisexpect +// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify -Wmisexpect // expected-no-diagnostics int foo(int); diff --git a/clang/test/Profile/misexpect-branch-unpredictable.c b/clang/test/Profile/misexpect-branch-unpredictable.c index ffaf25aed82bd..6c4f90146a2ae 100644 --- a/clang/test/Profile/misexpect-branch-unpredictable.c +++ b/clang/test/Profile/misexpect-branch-unpredictable.c @@ -1,7 +1,7 @@ // Test that misexpect emits no warning when prediction is correct // RUN: llvm-profdata merge %S/Inputs/misexpect-branch.proftext -o %t.profdata -// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -verify -Wmisexpect +// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify -Wmisexpect // expected-no-diagnostics #define unpredictable(x) __builtin_unpredictable(!!(x)) diff --git a/clang/test/Profile/misexpect-branch.c b/clang/test/Profile/misexpect-branch.c index fb7225047fcb0..5c4394405e178 100644 --- a/clang/test/Profile/misexpect-branch.c +++ b/clang/test/Profile/misexpect-branch.c @@ -2,12 +2,12 @@ // test diagnostics are issued when profiling data mis-matches annotations // RUN: llvm-profdata merge %S/Inputs/misexpect-branch.proftext -o %t.profdata -// RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -verify=imprecise -Wmisexpect -// RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -verify=exact -Wmisexpect -debug-info-kind=line-tables-only +// RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify=imprecise -Wmisexpect +// RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify=exact -Wmisexpect -debug-info-kind=line-tables-only // there should be no diagnostics when the tolerance is sufficiently high, or when -Wmisexpect is not requested -// RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -verify=foo -fdiagnostics-misexpect-tolerance=10 -Wmisexpect -debug-info-kind=line-tables-only -// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -verify=foo +// RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify=foo -fdiagnostics-misexpect-tolerance=10 -Wmisexpect -debug-info-kind=line-tables-only +// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify=foo // Ensure we emit an error when we don't use pgo with tolerance threshold // RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fdiagnostics-misexpect-tolerance=10 -Wmisexpect -debug-info-kind=line-tables-only 2>&1 | FileCheck -check-prefix=NO_PGO %s diff --git a/clang/test/Profile/misexpect-switch-default.c b/clang/test/Profile/misexpect-switch-default.c index 89eb64fea420b..cd337b9430171 100644 --- a/clang/test/Profile/misexpect-switch-default.c +++ b/clang/test/Profile/misexpect-switch-default.c @@ -1,7 +1,7 @@ // Test that misexpect detects mis-annotated switch statements for default case // RUN: llvm-profdata merge %S/Inputs/misexpect-switch-default.proftext -o %t.profdata -// RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -verify -Wmisexpect -debug-info-kind=line-tables-only +// RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify -Wmisexpect -debug-info-kind=line-tables-only #define inner_loop 1000 #define outer_loop 20 diff --git a/clang/test/Profile/misexpect-switch-nonconst.c b/clang/test/Profile/misexpect-switch-nonconst.c index f18baea83cc1d..cff3bce0d6d0a 100644 --- a/clang/test/Profile/misexpect-switch-nonconst.c +++ b/clang/test/Profile/misexpect-switch-nonconst.c @@ -1,7 +1,7 @@ // Test that misexpect emits no warning when switch condition is non-const // RUN: llvm-profdata merge %S/Inputs/misexpect-switch-nonconst.proftext -o %t.profdata -// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -verify +// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify // expected-no-diagnostics diff --git a/clang/test/Profile/misexpect-switch-only-default-case.c b/clang/test/Profile/misexpect-switch-only-default-case.c index ef0f124305625..26e8564c81b54 100644 --- a/clang/test/Profile/misexpect-switch-only-default-case.c +++ b/clang/test/Profile/misexpect-switch-only-default-case.c @@ -1,7 +1,7 @@ // Test that misexpect emits no warning when there is only one switch case // RUN: llvm-profdata merge %S/Inputs/misexpect-switch-default-only.proftext -o %t.profdata -// RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -verify -Wmisexpect -debug-info-kind=line-tables-only +// RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify -Wmisexpect -debug-info-kind=line-tables-only // expected-no-diagnostics diff --git a/clang/test/Profile/misexpect-switch.c b/clang/test/Profile/misexpect-switch.c index ae13cf7675706..84a7174f635fd 100644 --- a/clang/test/Profile/misexpect-switch.c +++ b/clang/test/Profile/misexpect-switch.c @@ -1,7 +1,7 @@ // Test that misexpect detects mis-annotated switch statements // RUN: llvm-profdata merge %S/Inputs/misexpect-switch.proftext -o %t.profdata -// RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata -verify -Wmisexpect -debug-info-kind=line-tables-only +// RUN: %clang_cc1 %s -O2 -o - -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify -Wmisexpect -debug-info-kind=line-tables-only #define inner_loop 1000 #define outer_loop 20 diff --git a/clang/test/Profile/objc-general.m b/clang/test/Profile/objc-general.m index a711645e7c833..a3dcb1b2128c6 100644 --- a/clang/test/Profile/objc-general.m +++ b/clang/test/Profile/objc-general.m @@ -3,7 +3,7 @@ // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name objc-general.m %s -o - -emit-llvm -fblocks -fprofile-instrument=clang | FileCheck -check-prefix=PGOGEN %s // RUN: llvm-profdata merge %S/Inputs/objc-general.proftext -o %t.profdata -// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name objc-general.m %s -o - -emit-llvm -fblocks -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata 2>&1 | FileCheck -check-prefix=PGOUSE %s +// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name objc-general.m %s -o - -emit-llvm -fblocks -fprofile-instrument-use-path=%t.profdata 2>&1 | FileCheck -check-prefix=PGOUSE %s // PGOUSE-NOT: warning: profile data may be out of date diff --git a/clang/test/Profile/profile-does-not-exist-ir.c b/clang/test/Profile/profile-does-not-exist-ir.c index cb7bef2b7043b..842a3d44a387b 100644 --- a/clang/test/Profile/profile-does-not-exist-ir.c +++ b/clang/test/Profile/profile-does-not-exist-ir.c @@ -1,8 +1,4 @@ -; RUN: not %clang_cc1 -emit-llvm -x ir %s -o - -fprofile-instrument-use=llvm -fprofile-instrument-use-path=%t.nonexistent.profdata 2>&1 | FileCheck %s +// RUN: not %clang_cc1 -emit-llvm -x ir %s -o - -fprofile-instrument-use-path=%t.nonexistent.profdata 2>&1 | FileCheck %s -; CHECK: error: {{.*}}.nonexistent.profdata: -; CHECK-NOT: Assertion failed - -define i32 @main() { - ret i32 0 -} +// CHECK: error: Error in reading profile {{.*}}.nonexistent.profdata: +// CHECK-NOT: Assertion failed diff --git a/clang/test/Profile/profile-does-not-exist.c b/clang/test/Profile/profile-does-not-exist.c index e9e04bed19b84..88d55d8668ef8 100644 --- a/clang/test/Profile/profile-does-not-exist.c +++ b/clang/test/Profile/profile-does-not-exist.c @@ -1,8 +1,4 @@ -// RUN: not %clang_cc1 -emit-llvm %s -o - -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.nonexistent.profdata 2>&1 | FileCheck %s +// RUN: not %clang_cc1 -emit-llvm %s -o - -fprofile-instrument-use-path=%t.nonexistent.profdata 2>&1 | FileCheck %s // CHECK: error: Error in reading profile {{.*}}.nonexistent.profdata: // CHECK-NOT: Assertion failed - -int main() { - return 0; -} diff --git a/clang/test/Profile/profile-summary.c b/clang/test/Profile/profile-summary.c index 31e8497ed6398..47fd9e85a4539 100644 --- a/clang/test/Profile/profile-summary.c +++ b/clang/test/Profile/profile-summary.c @@ -1,7 +1,7 @@ // Test that profile summary is set correctly. // RUN: llvm-profdata merge %S/Inputs/max-function-count.proftext -o %t.profdata -// RUN: %clang_cc1 %s -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use=clang -fprofile-instrument-use-path=%t.profdata | FileCheck %s +// RUN: %clang_cc1 %s -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use-path=%t.profdata | FileCheck %s // int begin(int i) { if (i) diff --git a/clang/test/VFS/broken-vfs-module-dep.c b/clang/test/VFS/broken-vfs-module-dep.c index 1c371a13e85c9..2336306de8c6d 100644 --- a/clang/test/VFS/broken-vfs-module-dep.c +++ b/clang/test/VFS/broken-vfs-module-dep.c @@ -2,5 +2,6 @@ // RUN: mkdir -p %t // RUN: not %clang_cc1 -module-dependency-dir %t -ivfsoverlay %S/Inputs/invalid-yaml.yaml %s 2>&1 | FileCheck %s +// CHECK: error: Unexpected token // CHECK: error: Unexpected token // CHECK: 1 error generated diff --git a/clang/tools/c-index-test/core_main.cpp b/clang/tools/c-index-test/core_main.cpp index c5dc54b98f3bd..100e708feb721 100644 --- a/clang/tools/c-index-test/core_main.cpp +++ b/clang/tools/c-index-test/core_main.cpp @@ -369,13 +369,12 @@ static bool printSourceSymbolsFromModule(StringRef modulePath, HeaderSearchOptions HSOpts; - auto VFS = llvm::vfs::getRealFileSystem(); - auto DiagOpts = std::make_shared(); IntrusiveRefCntPtr Diags = - CompilerInstance::createDiagnostics(*VFS, *DiagOpts); + CompilerInstance::createDiagnostics(*llvm::vfs::getRealFileSystem(), + *DiagOpts); std::unique_ptr AU = ASTUnit::LoadFromASTFile( - modulePath, *pchRdr, ASTUnit::LoadASTOnly, VFS, DiagOpts, Diags, + modulePath, *pchRdr, ASTUnit::LoadASTOnly, DiagOpts, Diags, FileSystemOpts, HSOpts, /*LangOpts=*/nullptr, /*OnlyLocalDecls=*/true, CaptureDiagsKind::None, /*AllowASTWithCompilerErrors=*/true, diff --git a/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp b/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp index 64cb012788548..0b621b849e92f 100644 --- a/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp +++ b/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp @@ -158,8 +158,8 @@ static bool HandleAST(StringRef AstPath) { std::unique_ptr Unit = ASTUnit::LoadFromASTFile( AstPath, CI->getPCHContainerOperations()->getRawReader(), - ASTUnit::LoadASTOnly, CI->getVirtualFileSystemPtr(), DiagOpts, DiagEngine, - CI->getFileSystemOpts(), CI->getHeaderSearchOpts()); + ASTUnit::LoadASTOnly, DiagOpts, DiagEngine, CI->getFileSystemOpts(), + CI->getHeaderSearchOpts()); if (!Unit) return false; diff --git a/clang/tools/clang-import-test/clang-import-test.cpp b/clang/tools/clang-import-test/clang-import-test.cpp index 2ad194f8e170b..7f5df9259889b 100644 --- a/clang/tools/clang-import-test/clang-import-test.cpp +++ b/clang/tools/clang-import-test/clang-import-test.cpp @@ -207,8 +207,8 @@ std::unique_ptr BuildCompilerInstance() { auto Ins = std::make_unique(std::move(Inv)); - Ins->createVirtualFileSystem(llvm::vfs::getRealFileSystem(), DC.get()); - Ins->createDiagnostics(DC.release(), /*ShouldOwnClient=*/true); + Ins->createDiagnostics(*llvm::vfs::getRealFileSystem(), DC.release(), + /*ShouldOwnClient=*/true); TargetInfo *TI = TargetInfo::CreateTargetInfo( Ins->getDiagnostics(), Ins->getInvocation().getTargetOpts()); @@ -216,7 +216,7 @@ std::unique_ptr BuildCompilerInstance() { Ins->getTarget().adjust(Ins->getDiagnostics(), Ins->getLangOpts(), /*AuxTarget=*/nullptr); Ins->createFileManager(); - Ins->createSourceManager(); + Ins->createSourceManager(Ins->getFileManager()); Ins->createPreprocessor(TU_Complete); return Ins; diff --git a/clang/tools/clang-installapi/ClangInstallAPI.cpp b/clang/tools/clang-installapi/ClangInstallAPI.cpp index 49d84069e86f4..6bc642f971a48 100644 --- a/clang/tools/clang-installapi/ClangInstallAPI.cpp +++ b/clang/tools/clang-installapi/ClangInstallAPI.cpp @@ -114,7 +114,7 @@ static bool run(ArrayRef Args, const char *ProgName) { // Set up compilation. std::unique_ptr CI(new CompilerInstance()); CI->setFileManager(FM.get()); - CI->createDiagnostics(); + CI->createDiagnostics(FM->getVirtualFileSystem()); if (!CI->hasDiagnostics()) return EXIT_FAILURE; diff --git a/clang/tools/driver/cc1_main.cpp b/clang/tools/driver/cc1_main.cpp index 49bb7e5e63d19..d5fc4db7a0e68 100644 --- a/clang/tools/driver/cc1_main.cpp +++ b/clang/tools/driver/cc1_main.cpp @@ -275,11 +275,8 @@ int cc1_main(ArrayRef Argv, const char *Argv0, void *MainAddr) { Clang->getHeaderSearchOpts().ResourceDir = CompilerInvocation::GetResourcesPath(Argv0, MainAddr); - /// Create the actual file system. - Clang->createVirtualFileSystem(llvm::vfs::getRealFileSystem(), DiagsBuffer); - // Create the actual diagnostics engine. - Clang->createDiagnostics(); + Clang->createDiagnostics(*llvm::vfs::getRealFileSystem()); if (!Clang->hasDiagnostics()) return 1; @@ -350,7 +347,8 @@ int cc1_main(ArrayRef Argv, const char *Argv0, void *MainAddr) { // options are stored in the compiler invocation and we can recreate the VFS // from the compiler invocation. if (!Clang->hasFileManager()) - Clang->createFileManager(); + Clang->createFileManager(createVFSFromCompilerInvocation( + Clang->getInvocation(), Clang->getDiagnostics())); llvm::vfs::OnDiskOutputBackend Backend; if (std::optional profilerOutput = diff --git a/clang/tools/driver/cc1as_main.cpp b/clang/tools/driver/cc1as_main.cpp index 207f9f11c4de9..3b4a4b54392df 100644 --- a/clang/tools/driver/cc1as_main.cpp +++ b/clang/tools/driver/cc1as_main.cpp @@ -429,8 +429,7 @@ getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) { } static bool ExecuteAssemblerImpl(AssemblerInvocation &Opts, - DiagnosticsEngine &Diags, - IntrusiveRefCntPtr VFS) { + DiagnosticsEngine &Diags) { // Get the target specific parser. std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error); @@ -453,7 +452,6 @@ static bool ExecuteAssemblerImpl(AssemblerInvocation &Opts, // Record the location of the include directories so that the lexer can find // it later. SrcMgr.setIncludeDirs(Opts.IncludePaths); - SrcMgr.setVirtualFileSystem(VFS); std::unique_ptr MRI(TheTarget->createMCRegInfo(Opts.Triple)); assert(MRI && "Unable to create target register info!"); @@ -649,9 +647,8 @@ static bool ExecuteAssemblerImpl(AssemblerInvocation &Opts, } static bool ExecuteAssembler(AssemblerInvocation &Opts, - DiagnosticsEngine &Diags, - IntrusiveRefCntPtr VFS) { - bool Failed = ExecuteAssemblerImpl(Opts, Diags, VFS); + DiagnosticsEngine &Diags) { + bool Failed = ExecuteAssemblerImpl(Opts, Diags); // Delete output file if there were errors. if (Failed) { @@ -688,8 +685,6 @@ int cc1as_main(ArrayRef Argv, const char *Argv0, void *MainAddr) { IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); DiagnosticsEngine Diags(DiagID, DiagOpts, DiagClient); - auto VFS = vfs::getRealFileSystem(); - // Set an error handler, so that any LLVM backend diagnostics go through our // error handler. ScopedFatalErrorHandler FatalErrorHandler @@ -728,12 +723,11 @@ int cc1as_main(ArrayRef Argv, const char *Argv0, void *MainAddr) { for (unsigned i = 0; i != NumArgs; ++i) Args[i + 1] = Asm.LLVMArgs[i].c_str(); Args[NumArgs + 1] = nullptr; - llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get(), /*Overview=*/"", - /*Errs=*/nullptr, /*VFS=*/VFS.get()); + llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get()); } // Execute the invocation, unless there were parsing errors. - bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags, VFS); + bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags); // If any timers were active but haven't been destroyed yet, print their // results now. diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp index 987fec0bdfb29..aca3577b410b0 100644 --- a/clang/tools/driver/driver.cpp +++ b/clang/tools/driver/driver.cpp @@ -217,8 +217,7 @@ static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient, } static int ExecuteCC1Tool(SmallVectorImpl &ArgV, - const llvm::ToolContext &ToolContext, - IntrusiveRefCntPtr VFS) { + const llvm::ToolContext &ToolContext) { // If we call the cc1 tool from the clangDriver library (through // Driver::CC1Main), we need to clean up the options usage count. The options // are currently global, and they might have been used previously by the @@ -226,8 +225,7 @@ static int ExecuteCC1Tool(SmallVectorImpl &ArgV, llvm::cl::ResetAllOptionOccurrences(); llvm::BumpPtrAllocator A; - llvm::cl::ExpansionContext ECtx(A, llvm::cl::TokenizeGNUCommandLine, - VFS.get()); + llvm::cl::ExpansionContext ECtx(A, llvm::cl::TokenizeGNUCommandLine); if (llvm::Error Err = ECtx.expandResponseFiles(ArgV)) { llvm::errs() << toString(std::move(Err)) << '\n'; return 1; @@ -295,16 +293,14 @@ int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) { bool ClangCLMode = IsClangCL(DriverMode); - auto VFS = llvm::vfs::getRealFileSystem(); - - if (llvm::Error Err = expandResponseFiles(Args, ClangCLMode, A, VFS.get())) { + if (llvm::Error Err = expandResponseFiles(Args, ClangCLMode, A)) { llvm::errs() << toString(std::move(Err)) << '\n'; return 1; } // Handle -cc1 integrated tools. if (Args.size() >= 2 && StringRef(Args[1]).starts_with("-cc1")) - return ExecuteCC1Tool(Args, ToolContext, VFS); + return ExecuteCC1Tool(Args, ToolContext); // Handle options that need handling before the real command line parsing in // Driver::BuildCompilation() @@ -386,6 +382,7 @@ int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) { Diags.takeClient(), std::move(SerializedConsumer))); } + auto VFS = llvm::vfs::getRealFileSystem(); ProcessWarningOptions(Diags, *DiagOpts, *VFS, /*ReportDiags=*/false); Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags, @@ -405,10 +402,10 @@ int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) { if (!SetBackdoorDriverOutputsFromEnvVars(TheDriver)) return 1; - auto ExecuteCC1WithContext = [&ToolContext, - &VFS](SmallVectorImpl &ArgV) { - return ExecuteCC1Tool(ArgV, ToolContext, VFS); - }; + auto ExecuteCC1WithContext = + [&ToolContext](SmallVectorImpl &ArgV) { + return ExecuteCC1Tool(ArgV, ToolContext); + }; if (!UseNewCC1Process) { TheDriver.CC1Main = ExecuteCC1WithContext; // Ensure the CC1Command actually catches cc1 crashes diff --git a/clang/tools/libclang/CDependencies.cpp b/clang/tools/libclang/CDependencies.cpp index 26c8b92435e48..6f765c281c07d 100644 --- a/clang/tools/libclang/CDependencies.cpp +++ b/clang/tools/libclang/CDependencies.cpp @@ -856,14 +856,11 @@ enum CXErrorCode clang_experimental_DependencyScanner_generateReproducer( for (const Command &BuildCommand : TU.Commands) PrintArguments(ScriptOS, BuildCommand.Arguments); - auto RealFS = llvm::vfs::getRealFileSystem(); - RealFS->setCurrentWorkingDirectory(*Opts.WorkingDirectory); - SmallString<128> VFSCachePath = FileCachePath; llvm::sys::path::append(VFSCachePath, "vfs"); std::string VFSCachePathStr = VFSCachePath.str().str(); llvm::FileCollector FileCollector(VFSCachePathStr, - /*OverlayRoot=*/VFSCachePathStr, RealFS); + /*OverlayRoot=*/VFSCachePathStr); for (const auto &FileDep : TU.FileDeps) { FileCollector.addFile(FileDep); } diff --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp index ee87cd66b308b..a3d9340a2db73 100644 --- a/clang/tools/libclang/CIndex.cpp +++ b/clang/tools/libclang/CIndex.cpp @@ -4243,14 +4243,13 @@ enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx, FileSystemOptions FileSystemOpts; HeaderSearchOptions HSOpts; - auto VFS = llvm::vfs::getRealFileSystem(); - auto DiagOpts = std::make_shared(); IntrusiveRefCntPtr Diags = - CompilerInstance::createDiagnostics(*VFS, *DiagOpts); + CompilerInstance::createDiagnostics(*llvm::vfs::getRealFileSystem(), + *DiagOpts); std::unique_ptr AU = ASTUnit::LoadFromASTFile( ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), - ASTUnit::LoadEverything, VFS, DiagOpts, Diags, FileSystemOpts, HSOpts, + ASTUnit::LoadEverything, DiagOpts, Diags, FileSystemOpts, HSOpts, /*LangOpts=*/nullptr, CXXIdx->getOnlyLocalDecls(), CaptureDiagsKind::All, /*AllowASTWithCompilerErrors=*/true, /*UserFilesAreVolatile=*/true); diff --git a/clang/unittests/AST/ExternalASTSourceTest.cpp b/clang/unittests/AST/ExternalASTSourceTest.cpp index 98d708707bc99..11715bb8ce7cd 100644 --- a/clang/unittests/AST/ExternalASTSourceTest.cpp +++ b/clang/unittests/AST/ExternalASTSourceTest.cpp @@ -57,8 +57,7 @@ bool testExternalASTSource(ExternalASTSource *Source, StringRef FileContents) { CompilerInvocation::CreateFromArgs(*Invocation, Args, *InvocationDiags); CompilerInstance Compiler(std::move(Invocation)); - Compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - Compiler.createDiagnostics(); + Compiler.createDiagnostics(*llvm::vfs::getRealFileSystem()); TestFrontendAction Action(Source); return Compiler.ExecuteAction(Action); diff --git a/clang/unittests/CodeGen/TestCompiler.h b/clang/unittests/CodeGen/TestCompiler.h index 1dec035f185c7..a6fec7fb0945d 100644 --- a/clang/unittests/CodeGen/TestCompiler.h +++ b/clang/unittests/CodeGen/TestCompiler.h @@ -36,8 +36,7 @@ struct TestCompiler { clang::CodeGenOptions CGO = clang::CodeGenOptions()) { compiler.getLangOpts() = LO; compiler.getCodeGenOpts() = CGO; - compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - compiler.createDiagnostics(); + compiler.createDiagnostics(*llvm::vfs::getRealFileSystem()); std::string TrStr = llvm::Triple::normalize(llvm::sys::getProcessTriple()); llvm::Triple Tr(TrStr); @@ -52,7 +51,7 @@ struct TestCompiler { PtrSize = TInfo.getPointerWidth(clang::LangAS::Default) / 8; compiler.createFileManager(); - compiler.createSourceManager(); + compiler.createSourceManager(compiler.getFileManager()); compiler.createPreprocessor(clang::TU_Prefix); compiler.createASTContext(); diff --git a/clang/unittests/Driver/ToolChainTest.cpp b/clang/unittests/Driver/ToolChainTest.cpp index 56a961370c0be..670090a01b0d3 100644 --- a/clang/unittests/Driver/ToolChainTest.cpp +++ b/clang/unittests/Driver/ToolChainTest.cpp @@ -579,8 +579,7 @@ TEST(CompilerInvocation, SplitSwarfSingleCrash) { TEST(ToolChainTest, UEFICallingConventionTest) { clang::CompilerInstance compiler; - compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - compiler.createDiagnostics(); + compiler.createDiagnostics(*llvm::vfs::getRealFileSystem()); std::string TrStr = "x86_64-unknown-uefi"; llvm::Triple Tr(TrStr); diff --git a/clang/unittests/Frontend/ASTUnitTest.cpp b/clang/unittests/Frontend/ASTUnitTest.cpp index 268dab2b169a3..afa64b5e90a6d 100644 --- a/clang/unittests/Frontend/ASTUnitTest.cpp +++ b/clang/unittests/Frontend/ASTUnitTest.cpp @@ -97,8 +97,7 @@ TEST_F(ASTUnitTest, SaveLoadPreservesLangOptionsInPrintingPolicy) { std::unique_ptr AU = ASTUnit::LoadFromASTFile( ASTFileName, PCHContainerOps->getRawReader(), ASTUnit::LoadEverything, - llvm::vfs::getRealFileSystem(), DiagOpts, Diags, FileSystemOptions(), - HSOpts); + DiagOpts, Diags, FileSystemOptions(), HSOpts); if (!AU) FAIL() << "failed to load ASTUnit"; diff --git a/clang/unittests/Frontend/CodeGenActionTest.cpp b/clang/unittests/Frontend/CodeGenActionTest.cpp index 182afdc7ea313..b2792c44ba5fe 100644 --- a/clang/unittests/Frontend/CodeGenActionTest.cpp +++ b/clang/unittests/Frontend/CodeGenActionTest.cpp @@ -52,8 +52,7 @@ TEST(CodeGenTest, TestNullCodeGen) { Invocation->getFrontendOpts().ProgramAction = EmitLLVM; Invocation->getTargetOpts().Triple = "i386-unknown-linux-gnu"; CompilerInstance Compiler(std::move(Invocation)); - Compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - Compiler.createDiagnostics(); + Compiler.createDiagnostics(*llvm::vfs::getRealFileSystem()); EXPECT_TRUE(Compiler.hasDiagnostics()); std::unique_ptr Act(new NullCodeGenAction); @@ -70,8 +69,7 @@ TEST(CodeGenTest, CodeGenFromIRMemBuffer) { Invocation->getFrontendOpts().ProgramAction = frontend::EmitLLVMOnly; Invocation->getTargetOpts().Triple = "i386-unknown-linux-gnu"; CompilerInstance Compiler(std::move(Invocation)); - Compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - Compiler.createDiagnostics(); + Compiler.createDiagnostics(*llvm::vfs::getRealFileSystem()); EXPECT_TRUE(Compiler.hasDiagnostics()); EmitLLVMOnlyAction Action; diff --git a/clang/unittests/Frontend/CompilerInstanceTest.cpp b/clang/unittests/Frontend/CompilerInstanceTest.cpp index e0f228668b884..459a3864887e1 100644 --- a/clang/unittests/Frontend/CompilerInstanceTest.cpp +++ b/clang/unittests/Frontend/CompilerInstanceTest.cpp @@ -33,7 +33,7 @@ TEST(CompilerInstance, DefaultVFSOverlayFromInvocation) { SmallString<256> CurrentPath; sys::fs::current_path(CurrentPath); - sys::path::make_absolute(CurrentPath, FileName); + sys::fs::make_absolute(CurrentPath, FileName); // Mount the VFS file itself on the path 'virtual.file'. Makes this test // a bit shorter than creating a new dummy file just for this purpose. @@ -72,7 +72,6 @@ TEST(CompilerInstance, DefaultVFSOverlayFromInvocation) { // in the CompilerInvocation (as we don't explicitly set our own). CompilerInstance Instance(std::move(CInvok)); Instance.setDiagnostics(Diags.get()); - Instance.createVirtualFileSystem(); Instance.createFileManager(); // Check if the virtual file exists which means that our VFS is used by the @@ -136,9 +135,8 @@ TEST(CompilerInstance, MultipleInputsCleansFileIDs) { ASSERT_TRUE(CInvok) << "could not create compiler invocation"; CompilerInstance Instance(std::move(CInvok)); - Instance.setVirtualFileSystem(VFS); Instance.setDiagnostics(Diags.get()); - Instance.createFileManager(); + Instance.createFileManager(VFS); // Run once for `a.cc` and then for `a.h`. This makes sure we get the same // file ID for `b.h` in the second run as `a.h` from first run. diff --git a/clang/unittests/Frontend/FrontendActionTest.cpp b/clang/unittests/Frontend/FrontendActionTest.cpp index 125940b44170c..4e040783c923e 100644 --- a/clang/unittests/Frontend/FrontendActionTest.cpp +++ b/clang/unittests/Frontend/FrontendActionTest.cpp @@ -91,8 +91,7 @@ TEST(ASTFrontendAction, Sanity) { invocation->getFrontendOpts().ProgramAction = frontend::ParseSyntaxOnly; invocation->getTargetOpts().Triple = "i386-unknown-linux-gnu"; CompilerInstance compiler(std::move(invocation)); - compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - compiler.createDiagnostics(); + compiler.createDiagnostics(*llvm::vfs::getRealFileSystem()); TestASTFrontendAction test_action; ASSERT_TRUE(compiler.ExecuteAction(test_action)); @@ -111,8 +110,7 @@ TEST(ASTFrontendAction, IncrementalParsing) { invocation->getFrontendOpts().ProgramAction = frontend::ParseSyntaxOnly; invocation->getTargetOpts().Triple = "i386-unknown-linux-gnu"; CompilerInstance compiler(std::move(invocation)); - compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - compiler.createDiagnostics(); + compiler.createDiagnostics(*llvm::vfs::getRealFileSystem()); TestASTFrontendAction test_action(/*enableIncrementalProcessing=*/true); ASSERT_TRUE(compiler.ExecuteAction(test_action)); @@ -138,8 +136,7 @@ TEST(ASTFrontendAction, LateTemplateIncrementalParsing) { invocation->getFrontendOpts().ProgramAction = frontend::ParseSyntaxOnly; invocation->getTargetOpts().Triple = "i386-unknown-linux-gnu"; CompilerInstance compiler(std::move(invocation)); - compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - compiler.createDiagnostics(); + compiler.createDiagnostics(*llvm::vfs::getRealFileSystem()); TestASTFrontendAction test_action(/*enableIncrementalProcessing=*/true, /*actOnEndOfTranslationUnit=*/true); @@ -184,8 +181,7 @@ TEST(PreprocessorFrontendAction, EndSourceFile) { Invocation->getFrontendOpts().ProgramAction = frontend::ParseSyntaxOnly; Invocation->getTargetOpts().Triple = "i386-unknown-linux-gnu"; CompilerInstance Compiler(std::move(Invocation)); - Compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - Compiler.createDiagnostics(); + Compiler.createDiagnostics(*llvm::vfs::getRealFileSystem()); TestPPCallbacks *Callbacks = new TestPPCallbacks; TestPPCallbacksFrontendAction TestAction(Callbacks); @@ -246,8 +242,8 @@ TEST(ASTFrontendAction, ExternalSemaSource) { Invocation->getTargetOpts().Triple = "i386-unknown-linux-gnu"; CompilerInstance Compiler(std::move(Invocation)); auto *TDC = new TypoDiagnosticConsumer; - Compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - Compiler.createDiagnostics(TDC, /*ShouldOwnClient=*/true); + Compiler.createDiagnostics(*llvm::vfs::getRealFileSystem(), TDC, + /*ShouldOwnClient=*/true); Compiler.setExternalSemaSource(new TypoExternalSemaSource(Compiler)); SyntaxOnlyAction TestAction; @@ -278,8 +274,7 @@ TEST(GeneratePCHFrontendAction, CacheGeneratedPCH) { Invocation->getFrontendOpts().ProgramAction = frontend::GeneratePCH; Invocation->getTargetOpts().Triple = "x86_64-apple-darwin19.0.0"; CompilerInstance Compiler(std::move(Invocation)); - Compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - Compiler.createDiagnostics(); + Compiler.createDiagnostics(*llvm::vfs::getRealFileSystem()); GeneratePCHAction TestAction; ASSERT_TRUE(Compiler.ExecuteAction(TestAction)); diff --git a/clang/unittests/Frontend/OutputStreamTest.cpp b/clang/unittests/Frontend/OutputStreamTest.cpp index 9e288f86351ca..dfb5a544cb88a 100644 --- a/clang/unittests/Frontend/OutputStreamTest.cpp +++ b/clang/unittests/Frontend/OutputStreamTest.cpp @@ -38,8 +38,7 @@ TEST(FrontendOutputTests, TestOutputStream) { new raw_svector_ostream(IRBuffer)); Compiler.setOutputStream(std::move(IRStream)); - Compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - Compiler.createDiagnostics(); + Compiler.createDiagnostics(*llvm::vfs::getRealFileSystem()); bool Success = ExecuteCompilerInvocation(&Compiler); EXPECT_TRUE(Success); @@ -63,8 +62,8 @@ TEST(FrontendOutputTests, TestVerboseOutputStreamShared) { Compiler.setOutputStream(std::make_unique()); DiagnosticOptions DiagOpts; - Compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); - Compiler.createDiagnostics(new TextDiagnosticPrinter(llvm::nulls(), DiagOpts), + Compiler.createDiagnostics(*llvm::vfs::getRealFileSystem(), + new TextDiagnosticPrinter(llvm::nulls(), DiagOpts), true); Compiler.setVerboseOutputStream(VerboseStream); @@ -93,8 +92,8 @@ TEST(FrontendOutputTests, TestVerboseOutputStreamOwned) { Compiler.setOutputStream(std::make_unique()); DiagnosticOptions DiagOpts; - Compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); Compiler.createDiagnostics( + *llvm::vfs::getRealFileSystem(), new TextDiagnosticPrinter(llvm::nulls(), DiagOpts), true); Compiler.setVerboseOutputStream(std::move(VerboseStream)); diff --git a/clang/unittests/Serialization/ForceCheckFileInputTest.cpp b/clang/unittests/Serialization/ForceCheckFileInputTest.cpp index 70e9fad858767..970eeef3c953e 100644 --- a/clang/unittests/Serialization/ForceCheckFileInputTest.cpp +++ b/clang/unittests/Serialization/ForceCheckFileInputTest.cpp @@ -91,8 +91,10 @@ export int aa = 43; Instance.getFrontendOpts().OutputFile = BMIPath; - Instance.createVirtualFileSystem(CIOpts.VFS); - Instance.createFileManager(); + if (auto VFSWithRemapping = createVFSFromCompilerInvocation( + Instance.getInvocation(), Instance.getDiagnostics(), CIOpts.VFS)) + CIOpts.VFS = VFSWithRemapping; + Instance.createFileManager(CIOpts.VFS); Instance.getHeaderSearchOpts().ValidateASTInputFilesContent = true; @@ -121,9 +123,8 @@ export int aa = 43; CompilerInstance Clang(std::move(Invocation)); Clang.setDiagnostics(Diags.get()); - Clang.createVirtualFileSystem(CIOpts.VFS); - Clang.createFileManager(); - Clang.createSourceManager(); + FileManager *FM = Clang.createFileManager(CIOpts.VFS); + Clang.createSourceManager(*FM); EXPECT_TRUE(Clang.createTarget()); Clang.createPreprocessor(TU_Complete); diff --git a/clang/unittests/Serialization/ModuleCacheTest.cpp b/clang/unittests/Serialization/ModuleCacheTest.cpp index dbf2076b40396..de6e13a738cb8 100644 --- a/clang/unittests/Serialization/ModuleCacheTest.cpp +++ b/clang/unittests/Serialization/ModuleCacheTest.cpp @@ -121,7 +121,6 @@ TEST_F(ModuleCacheTest, CachedModuleNewPath) { createInvocationAndEnableFree(Args, CIOpts); ASSERT_TRUE(Invocation); CompilerInstance Instance(std::move(Invocation)); - Instance.setVirtualFileSystem(CIOpts.VFS); Instance.setDiagnostics(Diags.get()); SyntaxOnlyAction Action; ASSERT_TRUE(Instance.ExecuteAction(Action)); @@ -146,7 +145,6 @@ TEST_F(ModuleCacheTest, CachedModuleNewPath) { CompilerInstance Instance2(std::move(Invocation2), Instance.getPCHContainerOperations(), &Instance.getModuleCache()); - Instance2.setVirtualFileSystem(CIOpts.VFS); Instance2.setDiagnostics(Diags.get()); SyntaxOnlyAction Action2; ASSERT_FALSE(Instance2.ExecuteAction(Action2)); @@ -173,7 +171,6 @@ TEST_F(ModuleCacheTest, CachedModuleNewPathAllowErrors) { createInvocationAndEnableFree(Args, CIOpts); ASSERT_TRUE(Invocation); CompilerInstance Instance(std::move(Invocation)); - Instance.setVirtualFileSystem(CIOpts.VFS); Instance.setDiagnostics(Diags.get()); SyntaxOnlyAction Action; ASSERT_TRUE(Instance.ExecuteAction(Action)); @@ -192,7 +189,6 @@ TEST_F(ModuleCacheTest, CachedModuleNewPathAllowErrors) { CompilerInstance Instance2(std::move(Invocation2), Instance.getPCHContainerOperations(), &Instance.getModuleCache()); - Instance2.setVirtualFileSystem(CIOpts.VFS); Instance2.setDiagnostics(Diags.get()); SyntaxOnlyAction Action2; ASSERT_FALSE(Instance2.ExecuteAction(Action2)); diff --git a/clang/unittests/Serialization/NoCommentsTest.cpp b/clang/unittests/Serialization/NoCommentsTest.cpp index f091e51e86c93..05efeef990d43 100644 --- a/clang/unittests/Serialization/NoCommentsTest.cpp +++ b/clang/unittests/Serialization/NoCommentsTest.cpp @@ -99,7 +99,6 @@ void foo() {} ASSERT_TRUE(Invocation); CompilerInstance Instance(std::move(Invocation)); - Instance.createVirtualFileSystem(CIOpts.VFS); Instance.setDiagnostics(Diags.get()); Instance.getFrontendOpts().OutputFile = CacheBMIPath; GenerateReducedModuleInterfaceAction Action; diff --git a/clang/unittests/Serialization/PreambleInNamedModulesTest.cpp b/clang/unittests/Serialization/PreambleInNamedModulesTest.cpp index 9f7ec8182f748..c43520f79b02c 100644 --- a/clang/unittests/Serialization/PreambleInNamedModulesTest.cpp +++ b/clang/unittests/Serialization/PreambleInNamedModulesTest.cpp @@ -113,8 +113,12 @@ export using ::E; auto Clang = std::make_unique(std::move(Invocation)); Clang->setDiagnostics(Diags.get()); - Clang->createVirtualFileSystem(VFS); - Clang->createFileManager(); + + if (auto VFSWithRemapping = createVFSFromCompilerInvocation( + Clang->getInvocation(), Clang->getDiagnostics(), VFS)) + VFS = VFSWithRemapping; + + Clang->createFileManager(VFS); EXPECT_TRUE(Clang->createTarget()); Buffer.release(); diff --git a/clang/unittests/Support/TimeProfilerTest.cpp b/clang/unittests/Support/TimeProfilerTest.cpp index d85743da31358..85d36b5d21423 100644 --- a/clang/unittests/Support/TimeProfilerTest.cpp +++ b/clang/unittests/Support/TimeProfilerTest.cpp @@ -53,6 +53,8 @@ bool compileFromString(StringRef Code, StringRef Standard, StringRef File, FS->addFile(Header.getKey(), 0, MemoryBuffer::getMemBuffer(Header.getValue())); } + llvm::IntrusiveRefCntPtr Files( + new FileManager(FileSystemOptions(), FS)); auto Invocation = std::make_shared(); std::vector Args = {Standard.data(), File.data()}; @@ -62,9 +64,8 @@ bool compileFromString(StringRef Code, StringRef Standard, StringRef File, CompilerInvocation::CreateFromArgs(*Invocation, Args, *InvocationDiags); CompilerInstance Compiler(std::move(Invocation)); - Compiler.setVirtualFileSystem(std::move(FS)); - Compiler.createDiagnostics(); - Compiler.createFileManager(); + Compiler.createDiagnostics(Files->getVirtualFileSystem()); + Compiler.setFileManager(Files.get()); class TestFrontendAction : public ASTFrontendAction { private: diff --git a/clang/unittests/Tooling/DependencyScanning/DependencyScannerTest.cpp b/clang/unittests/Tooling/DependencyScanning/DependencyScannerTest.cpp index b2583441f1ecd..80d47658daafb 100644 --- a/clang/unittests/Tooling/DependencyScanning/DependencyScannerTest.cpp +++ b/clang/unittests/Tooling/DependencyScanning/DependencyScannerTest.cpp @@ -65,11 +65,12 @@ class TestDependencyScanningAction : public tooling::ToolAction { std::move(PCHContainerOps)); Compiler.setFileManager(FileMgr); - Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false); + Compiler.createDiagnostics(FileMgr->getVirtualFileSystem(), DiagConsumer, + /*ShouldOwnClient=*/false); if (!Compiler.hasDiagnostics()) return false; - Compiler.createSourceManager(); + Compiler.createSourceManager(*FileMgr); Compiler.addDependencyCollector(std::make_shared( Compiler.getInvocation().getDependencyOutputOpts(), Deps)); diff --git a/flang/lib/Frontend/CompilerInvocation.cpp b/flang/lib/Frontend/CompilerInvocation.cpp index acb2a4dc0cd5e..f55d866435997 100644 --- a/flang/lib/Frontend/CompilerInvocation.cpp +++ b/flang/lib/Frontend/CompilerInvocation.cpp @@ -22,7 +22,6 @@ #include "flang/Tools/TargetSetup.h" #include "flang/Version.inc" #include "clang/Basic/DiagnosticDriver.h" -#include "clang/Basic/DiagnosticFrontend.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Driver/CommonArgs.h" #include "clang/Driver/Driver.h" @@ -1216,7 +1215,7 @@ static bool parseOpenMPArgs(CompilerInvocation &res, llvm::opt::ArgList &args, clang::driver::options::OPT_fopenmp_host_ir_file_path)) { res.getLangOpts().OMPHostIRFile = arg->getValue(); if (!llvm::sys::fs::exists(res.getLangOpts().OMPHostIRFile)) - diags.Report(clang::diag::err_omp_host_ir_file_not_found) + diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found) << res.getLangOpts().OMPHostIRFile; } diff --git a/flang/lib/Frontend/FrontendActions.cpp b/flang/lib/Frontend/FrontendActions.cpp index 692fbb1aea147..b5f4f9421f633 100644 --- a/flang/lib/Frontend/FrontendActions.cpp +++ b/flang/lib/Frontend/FrontendActions.cpp @@ -926,18 +926,20 @@ void CodeGenAction::runOptimizationPipeline(llvm::raw_pwrite_stream &os) { pgoOpt = llvm::PGOOptions(opts.InstrProfileOutput.empty() ? llvm::driver::getDefaultProfileGenName() : opts.InstrProfileOutput, - "", "", opts.MemoryProfileUsePath, + "", "", opts.MemoryProfileUsePath, nullptr, llvm::PGOOptions::IRInstr, llvm::PGOOptions::NoCSAction, llvm::PGOOptions::ColdFuncOpt::Default, false, /*PseudoProbeForProfiling=*/false, false); } else if (opts.hasProfileIRUse()) { + llvm::IntrusiveRefCntPtr VFS = + llvm::vfs::getRealFileSystem(); // -fprofile-use. auto CSAction = opts.hasProfileCSIRUse() ? llvm::PGOOptions::CSIRUse : llvm::PGOOptions::NoCSAction; pgoOpt = llvm::PGOOptions( opts.ProfileInstrumentUsePath, "", opts.ProfileRemappingFile, - opts.MemoryProfileUsePath, llvm::PGOOptions::IRUse, CSAction, + opts.MemoryProfileUsePath, VFS, llvm::PGOOptions::IRUse, CSAction, llvm::PGOOptions::ColdFuncOpt::Default, false); } diff --git a/lldb/source/Commands/CommandObjectTarget.cpp b/lldb/source/Commands/CommandObjectTarget.cpp index 62d245734c288..dbebbbd38093e 100644 --- a/lldb/source/Commands/CommandObjectTarget.cpp +++ b/lldb/source/Commands/CommandObjectTarget.cpp @@ -2210,9 +2210,7 @@ class CommandObjectTargetModulesDumpClangPCMInfo : public CommandObjectParsed { const char *clang_args[] = {"clang", pcm_path}; clang::CompilerInstance compiler(clang::createInvocation(clang_args)); - compiler.setVirtualFileSystem( - FileSystem::Instance().GetVirtualFileSystem()); - compiler.createDiagnostics(); + compiler.createDiagnostics(*FileSystem::Instance().GetVirtualFileSystem()); // Pass empty deleter to not attempt to free memory that was allocated // outside of the current scope, possibly statically. diff --git a/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp b/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp index 2f267fa0b724b..8f88e4a2f1726 100644 --- a/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp +++ b/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp @@ -801,16 +801,14 @@ ClangExpressionParser::ClangExpressionParser( m_compiler = std::make_unique(); // Make sure clang uses the same VFS as LLDB. - m_compiler->setVirtualFileSystem( - FileSystem::Instance().GetVirtualFileSystem()); - m_compiler->createFileManager(); + m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem()); // 2. Configure the compiler with a set of default options that are // appropriate for most situations. SetupTargetOpts(*m_compiler, *target_sp); // 3. Create and install the target on the compiler. - m_compiler->createDiagnostics(); + m_compiler->createDiagnostics(m_compiler->getVirtualFileSystem()); // Limit the number of error diagnostics we emit. // A value of 0 means no limit for both LLDB and Clang. m_compiler->getDiagnostics().setErrorLimit(target_sp->GetExprErrorLimit()); @@ -873,7 +871,7 @@ ClangExpressionParser::ClangExpressionParser( // 6. Set up the source management objects inside the compiler m_compiler->createFileManager(); if (!m_compiler->hasSourceManager()) - m_compiler->createSourceManager(); + m_compiler->createSourceManager(m_compiler->getFileManager()); m_compiler->createPreprocessor(TU_Complete); switch (expr.Language().AsLanguageType()) { diff --git a/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp b/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp index 14f08d3039b81..e314ffb1260dd 100644 --- a/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp +++ b/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp @@ -745,8 +745,7 @@ ClangModulesDeclVendor::Create(Target &target) { auto instance = std::make_unique(invocation); // Make sure clang uses the same VFS as LLDB. - instance->setVirtualFileSystem(FileSystem::Instance().GetVirtualFileSystem()); - instance->createFileManager(); + instance->createFileManager(FileSystem::Instance().GetVirtualFileSystem()); instance->setDiagnostics(diagnostics_engine.get()); std::unique_ptr action(new clang::SyntaxOnlyAction); diff --git a/lldb/source/Plugins/ExpressionParser/Clang/ModuleDependencyCollector.h b/lldb/source/Plugins/ExpressionParser/Clang/ModuleDependencyCollector.h index dcba0d9c34962..4fe727460fdb9 100644 --- a/lldb/source/Plugins/ExpressionParser/Clang/ModuleDependencyCollector.h +++ b/lldb/source/Plugins/ExpressionParser/Clang/ModuleDependencyCollector.h @@ -19,8 +19,8 @@ class ModuleDependencyCollectorAdaptor public: ModuleDependencyCollectorAdaptor( std::shared_ptr file_collector) - : clang::ModuleDependencyCollector("", llvm::vfs::getRealFileSystem()), - m_file_collector(file_collector) {} + : clang::ModuleDependencyCollector(""), m_file_collector(file_collector) { + } void addFile(llvm::StringRef Filename, llvm::StringRef FileDst = {}) override { diff --git a/llvm/include/llvm/CodeGen/AsmPrinter.h b/llvm/include/llvm/CodeGen/AsmPrinter.h index 0982820e69a35..dafe887bc0f3b 100644 --- a/llvm/include/llvm/CodeGen/AsmPrinter.h +++ b/llvm/include/llvm/CodeGen/AsmPrinter.h @@ -16,7 +16,6 @@ #define LLVM_CODEGEN_ASMPRINTER_H #include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Analysis/ProfileSummaryInfo.h" @@ -89,10 +88,6 @@ namespace remarks { class RemarkStreamer; } -namespace vfs { -class FileSystem; -} - /// This class is intended to be used as a driving class for all asm writers. class LLVM_ABI AsmPrinter : public MachineFunctionPass { public: @@ -111,9 +106,6 @@ class LLVM_ABI AsmPrinter : public MachineFunctionPass { /// generating (such as the current section etc). std::unique_ptr OutStreamer; - /// The VFS to resolve asm include directives. - IntrusiveRefCntPtr VFS; - /// The current machine function. MachineFunction *MF = nullptr; diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h index 21f4a9ef313c0..206ad4a4ef85f 100644 --- a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h +++ b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h @@ -38,10 +38,6 @@ class Loop; class LoopAnalysis; class LoopInfo; -namespace vfs { -class FileSystem; -} // namespace vfs - /// Move the instruction after an InsertPoint to the beginning of another /// BasicBlock. /// @@ -1350,7 +1346,7 @@ class OpenMPIRBuilder { /// any. LLVM_ABI static TargetRegionEntryInfo getTargetEntryUniqueInfo(FileIdentifierInfoCallbackTy CallBack, - vfs::FileSystem &VFS, StringRef ParentName = ""); + StringRef ParentName = ""); /// Enum class for the RedctionGen CallBack type to be used. enum class ReductionGenCBKind { Clang, MLIR }; @@ -3495,8 +3491,7 @@ class OpenMPIRBuilder { /// \param HostFilePath The path to the host IR file, /// used to load in offload metadata for the device, allowing host and device /// to maintain the same metadata mapping. - LLVM_ABI void loadOffloadInfoMetadata(vfs::FileSystem &VFS, - StringRef HostFilePath); + LLVM_ABI void loadOffloadInfoMetadata(StringRef HostFilePath); /// Gets (if variable with the given name already exist) or creates /// internal global variable with the specified Name. The created variable has diff --git a/llvm/include/llvm/Passes/PassBuilder.h b/llvm/include/llvm/Passes/PassBuilder.h index 1567307ed14bd..e60a04067d102 100644 --- a/llvm/include/llvm/Passes/PassBuilder.h +++ b/llvm/include/llvm/Passes/PassBuilder.h @@ -36,6 +36,10 @@ class StringRef; class AAManager; class TargetMachine; class ModuleSummaryIndex; +template class IntrusiveRefCntPtr; +namespace vfs { +class FileSystem; +} // namespace vfs /// Tunable parameters for passes in the default pipelines. class PipelineTuningOptions { @@ -109,7 +113,6 @@ class PassBuilder { PipelineTuningOptions PTO; std::optional PGOOpt; PassInstrumentationCallbacks *PIC; - IntrusiveRefCntPtr FS; public: /// A struct to capture parsed pass pipeline names. @@ -129,8 +132,7 @@ class PassBuilder { TargetMachine *TM = nullptr, PipelineTuningOptions PTO = PipelineTuningOptions(), std::optional PGOOpt = std::nullopt, - PassInstrumentationCallbacks *PIC = nullptr, - IntrusiveRefCntPtr FS = vfs::getRealFileSystem()); + PassInstrumentationCallbacks *PIC = nullptr); /// Cross register the analysis managers through their proxies. /// @@ -632,7 +634,8 @@ class PassBuilder { bool RunProfileGen, bool IsCS, bool AtomicCounterUpdate, std::string ProfileFile, - std::string ProfileRemappingFile); + std::string ProfileRemappingFile, + IntrusiveRefCntPtr FS); /// Returns PIC. External libraries can use this to register pass /// instrumentation callbacks. @@ -640,11 +643,6 @@ class PassBuilder { return PIC; } - /// Returns the virtual file system. - IntrusiveRefCntPtr getVirtualFileSystemPtr() const { - return FS; - } - // Invoke the callbacks registered for the various extension points. // Custom pipelines should use these to invoke the callbacks registered // by TargetMachines and other clients. @@ -776,7 +774,8 @@ class PassBuilder { void addPGOInstrPasses(ModulePassManager &MPM, OptimizationLevel Level, bool RunProfileGen, bool IsCS, bool AtomicCounterUpdate, std::string ProfileFile, - std::string ProfileRemappingFile); + std::string ProfileRemappingFile, + IntrusiveRefCntPtr FS); void addPostPGOLoopRotation(ModulePassManager &MPM, OptimizationLevel Level); bool isInstrumentedPGOUse() const; diff --git a/llvm/include/llvm/Support/CommandLine.h b/llvm/include/llvm/Support/CommandLine.h index b81df756247c9..ca725b8ac8712 100644 --- a/llvm/include/llvm/Support/CommandLine.h +++ b/llvm/include/llvm/Support/CommandLine.h @@ -69,7 +69,6 @@ namespace cl { LLVM_ABI bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview = "", raw_ostream *Errs = nullptr, - vfs::FileSystem *VFS = nullptr, const char *EnvVar = nullptr, bool LongOptionsUseDoubleDash = false); @@ -2193,8 +2192,7 @@ class ExpansionContext { SmallVectorImpl &NewArgv); public: - LLVM_ABI ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T, - vfs::FileSystem *FS = nullptr); + LLVM_ABI ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T); ExpansionContext &setMarkEOLs(bool X) { MarkEOLs = X; diff --git a/llvm/include/llvm/Support/FileCollector.h b/llvm/include/llvm/Support/FileCollector.h index 9fa11ba362241..b00bf3174e654 100644 --- a/llvm/include/llvm/Support/FileCollector.h +++ b/llvm/include/llvm/Support/FileCollector.h @@ -81,28 +81,19 @@ class LLVM_ABI FileCollector : public FileCollectorBase { /// Canonicalize a pair of virtual and real paths. LLVM_ABI PathStorage canonicalize(StringRef SrcPath); - /// Return the underlying file system. - vfs::FileSystem &getFileSystem() const { return *VFS; }; - - explicit PathCanonicalizer(IntrusiveRefCntPtr VFS) - : VFS(std::move(VFS)) {} - private: /// Replace with a (mostly) real path, or don't modify. Resolves symlinks /// in the directory, using \a CachedDirs to avoid redundant lookups, but /// leaves the filename as a possible symlink. void updateWithRealPath(SmallVectorImpl &Path); - IntrusiveRefCntPtr VFS; - StringMap CachedDirs; }; /// \p Root is the directory where collected files are will be stored. /// \p OverlayRoot is VFS mapping root. /// \p Root directory gets created in copyFiles unless it already exists. - FileCollector(std::string Root, std::string OverlayRoot, - IntrusiveRefCntPtr VFS); + FileCollector(std::string Root, std::string OverlayRoot); /// Write the yaml mapping (for the VFS) to the given file. std::error_code writeMapping(StringRef MappingFile); diff --git a/llvm/include/llvm/Support/FileSystem.h b/llvm/include/llvm/Support/FileSystem.h index a8cea9d787510..3228dcec13a76 100644 --- a/llvm/include/llvm/Support/FileSystem.h +++ b/llvm/include/llvm/Support/FileSystem.h @@ -266,6 +266,18 @@ class file_status : public basic_file_status { /// @name Physical Operators /// @{ +/// Make \a path an absolute path. +/// +/// Makes \a path absolute using the \a current_directory if it is not already. +/// An empty \a path will result in the \a current_directory. +/// +/// /absolute/path => /absolute/path +/// relative/../path => /relative/../path +/// +/// @param path A path that is modified to be an absolute path. +LLVM_ABI void make_absolute(const Twine ¤t_directory, + SmallVectorImpl &path); + /// Make \a path an absolute path. /// /// Makes \a path absolute using the current directory if it is not already. An diff --git a/llvm/include/llvm/Support/PGOOptions.h b/llvm/include/llvm/Support/PGOOptions.h index fb1dc0cf4aa0a..6527a18258bf8 100644 --- a/llvm/include/llvm/Support/PGOOptions.h +++ b/llvm/include/llvm/Support/PGOOptions.h @@ -14,10 +14,16 @@ #ifndef LLVM_SUPPORT_PGOOPTIONS_H #define LLVM_SUPPORT_PGOOPTIONS_H +#include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Error.h" namespace llvm { + +namespace vfs { +class FileSystem; +} // namespace vfs + /// A struct capturing PGO tunables. struct PGOOptions { enum PGOAction { NoAction, IRInstr, IRUse, SampleUse }; @@ -25,7 +31,9 @@ struct PGOOptions { enum class ColdFuncOpt { Default, OptSize, MinSize, OptNone }; LLVM_ABI PGOOptions(std::string ProfileFile, std::string CSProfileGenFile, std::string ProfileRemappingFile, - std::string MemoryProfile, PGOAction Action = NoAction, + std::string MemoryProfile, + IntrusiveRefCntPtr FS, + PGOAction Action = NoAction, CSPGOAction CSAction = NoCSAction, ColdFuncOpt ColdType = ColdFuncOpt::Default, bool DebugInfoForProfiling = false, @@ -45,6 +53,7 @@ struct PGOOptions { bool DebugInfoForProfiling; bool PseudoProbeForProfiling; bool AtomicCounterUpdate; + IntrusiveRefCntPtr FS; }; } // namespace llvm diff --git a/llvm/include/llvm/Support/Path.h b/llvm/include/llvm/Support/Path.h index a8e0f338ec203..0cb517146c04b 100644 --- a/llvm/include/llvm/Support/Path.h +++ b/llvm/include/llvm/Support/Path.h @@ -566,18 +566,6 @@ LLVM_ABI bool is_absolute_gnu(const Twine &path, Style style = Style::native); /// @result True if the path is relative, false if it is not. LLVM_ABI bool is_relative(const Twine &path, Style style = Style::native); -/// Make \a path an absolute path. -/// -/// Makes \a path absolute using the \a current_directory if it is not already. -/// An empty \a path will result in the \a current_directory. -/// -/// /absolute/path => /absolute/path -/// relative/../path => /relative/../path -/// -/// @param path A path that is modified to be an absolute path. -LLVM_ABI void make_absolute(const Twine ¤t_directory, - SmallVectorImpl &path); - } // end namespace path } // end namespace sys } // end namespace llvm diff --git a/llvm/include/llvm/Support/SourceMgr.h b/llvm/include/llvm/Support/SourceMgr.h index 8320006ff5f6e..e4a27ade1f6bb 100644 --- a/llvm/include/llvm/Support/SourceMgr.h +++ b/llvm/include/llvm/Support/SourceMgr.h @@ -96,25 +96,22 @@ class SourceMgr { DiagHandlerTy DiagHandler = nullptr; void *DiagContext = nullptr; - // Optional file system for finding include files. + // Filesystem for finding includes, if not the real FS. IntrusiveRefCntPtr FS; bool isValidBufferID(unsigned i) const { return i && i <= Buffers.size(); } public: - /// Create new source manager without support for include files. SourceMgr(); - /// Create new source manager with the capability of finding include files - /// via the provided file system. - explicit SourceMgr(IntrusiveRefCntPtr FS); SourceMgr(const SourceMgr &) = delete; SourceMgr &operator=(const SourceMgr &) = delete; SourceMgr(SourceMgr &&); SourceMgr &operator=(SourceMgr &&); ~SourceMgr(); - IntrusiveRefCntPtr getVirtualFileSystem() const; - void setVirtualFileSystem(IntrusiveRefCntPtr FS); + /// Specify a \a vfs::FileSystem for finding includes. + explicit SourceMgr(IntrusiveRefCntPtr FS); + void setFileSystem(IntrusiveRefCntPtr FS); /// Return the include directories of this source manager. ArrayRef getIncludeDirs() const { return IncludeDirectories; } diff --git a/llvm/include/llvm/Support/VirtualFileSystem.h b/llvm/include/llvm/Support/VirtualFileSystem.h index 9dfd122fb4cb3..64a2a3ea1609c 100644 --- a/llvm/include/llvm/Support/VirtualFileSystem.h +++ b/llvm/include/llvm/Support/VirtualFileSystem.h @@ -1164,10 +1164,14 @@ class LLVM_ABI RedirectingFileSystem }; /// Collect all pairs of entries from the -/// \p VFS. This is used by the module dependency collector to forward +/// \p YAMLFilePath. This is used by the module dependency collector to forward /// the entries into the reproducer output VFS YAML file. -void collectVFSEntries(RedirectingFileSystem &VFS, - SmallVectorImpl &CollectedEntries); +LLVM_ABI void collectVFSFromYAML( + std::unique_ptr Buffer, + llvm::SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath, + SmallVectorImpl &CollectedEntries, + void *DiagContext = nullptr, + IntrusiveRefCntPtr ExternalFS = getRealFileSystem()); class YAMLVFSWriter { std::vector Mappings; diff --git a/llvm/include/llvm/Transforms/Instrumentation/DataFlowSanitizer.h b/llvm/include/llvm/Transforms/Instrumentation/DataFlowSanitizer.h index 9c9d6afe1872f..af3662e4a6565 100644 --- a/llvm/include/llvm/Transforms/Instrumentation/DataFlowSanitizer.h +++ b/llvm/include/llvm/Transforms/Instrumentation/DataFlowSanitizer.h @@ -10,7 +10,6 @@ #include "llvm/IR/PassManager.h" #include "llvm/Support/Compiler.h" -#include "llvm/Support/VirtualFileSystem.h" #include #include @@ -20,13 +19,11 @@ class Module; class DataFlowSanitizerPass : public PassInfoMixin { private: std::vector ABIListFiles; - IntrusiveRefCntPtr FS; public: DataFlowSanitizerPass( - const std::vector &ABIListFiles = std::vector(), - IntrusiveRefCntPtr FS = vfs::getRealFileSystem()) - : ABIListFiles(ABIListFiles), FS(std::move(FS)) {} + const std::vector &ABIListFiles = std::vector()) + : ABIListFiles(ABIListFiles) {} LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM); static bool isRequired() { return true; } }; diff --git a/llvm/include/llvm/Transforms/Instrumentation/GCOVProfiler.h b/llvm/include/llvm/Transforms/Instrumentation/GCOVProfiler.h index 43ef86b08517a..4d3ead29af0d2 100644 --- a/llvm/include/llvm/Transforms/Instrumentation/GCOVProfiler.h +++ b/llvm/include/llvm/Transforms/Instrumentation/GCOVProfiler.h @@ -14,22 +14,17 @@ #include "llvm/IR/PassManager.h" #include "llvm/Support/Compiler.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Transforms/Utils/Instrumentation.h" namespace llvm { /// The gcov-style instrumentation pass class GCOVProfilerPass : public PassInfoMixin { public: - GCOVProfilerPass( - const GCOVOptions &Options = GCOVOptions::getDefault(), - IntrusiveRefCntPtr VFS = vfs::getRealFileSystem()) - : GCOVOpts(Options), VFS(std::move(VFS)) {} + GCOVProfilerPass(const GCOVOptions &Options = GCOVOptions::getDefault()) : GCOVOpts(Options) { } LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM); private: GCOVOptions GCOVOpts; - IntrusiveRefCntPtr VFS; }; } // namespace llvm diff --git a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp index 725d362ebe4c6..be0a1c3b0a0c2 100644 --- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp +++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp @@ -117,7 +117,6 @@ #include "llvm/Support/MathExtras.h" #include "llvm/Support/Path.h" #include "llvm/Support/VCSRevision.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetMachine.h" @@ -464,7 +463,6 @@ void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { } bool AsmPrinter::doInitialization(Module &M) { - VFS = vfs::getRealFileSystem(); auto *MMIWP = getAnalysisIfAvailable(); MMI = MMIWP ? &MMIWP->getMMI() : nullptr; HasSplitStack = false; diff --git a/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp b/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp index 8dd8b9da9c50c..c364ffc6eb8c1 100644 --- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp +++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp @@ -36,7 +36,6 @@ #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" using namespace llvm; @@ -99,7 +98,6 @@ void AsmPrinter::emitInlineAsm(StringRef Str, const MCSubtargetInfo &STI, unsigned BufNum = addInlineAsmDiagBuffer(Str, LocMDNode); SourceMgr &SrcMgr = *MMI->getContext().getInlineSourceManager(); SrcMgr.setIncludeDirs(MCOptions.IASSearchPaths); - SrcMgr.setVirtualFileSystem(VFS); std::unique_ptr Parser( createMCAsmParser(SrcMgr, OutContext, *OutStreamer, *MAI, BufNum)); diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp index 3dbbe8dec26cd..840ca8364e218 100644 --- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp +++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp @@ -51,7 +51,6 @@ #include "llvm/Support/CommandLine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" @@ -9849,19 +9848,17 @@ void OffloadEntriesInfoManager::getTargetRegionEntryFnName( TargetRegionEntryInfo OpenMPIRBuilder::getTargetEntryUniqueInfo(FileIdentifierInfoCallbackTy CallBack, - vfs::FileSystem &VFS, StringRef ParentName) { sys::fs::UniqueID ID(0xdeadf17e, 0); auto FileIDInfo = CallBack(); uint64_t FileID = 0; - if (ErrorOr Status = VFS.status(std::get<0>(FileIDInfo))) { - ID = Status->getUniqueID(); - FileID = Status->getUniqueID().getFile(); - } else { - // If the inode ID could not be determined, create a hash value - // the current file name and use that as an ID. + std::error_code EC = sys::fs::getUniqueID(std::get<0>(FileIDInfo), ID); + // If the inode ID could not be determined, create a hash value + // the current file name and use that as an ID. + if (EC) FileID = hash_value(std::get<0>(FileIDInfo)); - } + else + FileID = ID.getFile(); return TargetRegionEntryInfo(ParentName, ID.getDevice(), FileID, std::get<1>(FileIDInfo)); @@ -10086,12 +10083,11 @@ void OpenMPIRBuilder::loadOffloadInfoMetadata(Module &M) { } } -void OpenMPIRBuilder::loadOffloadInfoMetadata(vfs::FileSystem &VFS, - StringRef HostFilePath) { +void OpenMPIRBuilder::loadOffloadInfoMetadata(StringRef HostFilePath) { if (HostFilePath.empty()) return; - auto Buf = VFS.getBufferForFile(HostFilePath); + auto Buf = MemoryBuffer::getFile(HostFilePath); if (std::error_code Err = Buf.getError()) { report_fatal_error(("error opening host file from host file path inside of " "OpenMPIRBuilder: " + diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp index 783514eae9011..5e8cd12fe040b 100644 --- a/llvm/lib/LTO/LTOBackend.cpp +++ b/llvm/lib/LTO/LTOBackend.cpp @@ -240,26 +240,27 @@ static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM, unsigned OptLevel, bool IsThinLTO, ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary) { + auto FS = vfs::getRealFileSystem(); std::optional PGOOpt; if (!Conf.SampleProfile.empty()) PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping, - /*MemoryProfile=*/"", PGOOptions::SampleUse, + /*MemoryProfile=*/"", FS, PGOOptions::SampleUse, PGOOptions::NoCSAction, PGOOptions::ColdFuncOpt::Default, true); else if (Conf.RunCSIRInstr) { PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping, - /*MemoryProfile=*/"", PGOOptions::IRUse, + /*MemoryProfile=*/"", FS, PGOOptions::IRUse, PGOOptions::CSIRInstr, PGOOptions::ColdFuncOpt::Default, Conf.AddFSDiscriminator); } else if (!Conf.CSIRProfile.empty()) { - PGOOpt = - PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping, - /*MemoryProfile=*/"", PGOOptions::IRUse, PGOOptions::CSIRUse, - PGOOptions::ColdFuncOpt::Default, Conf.AddFSDiscriminator); + PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping, + /*MemoryProfile=*/"", FS, PGOOptions::IRUse, + PGOOptions::CSIRUse, PGOOptions::ColdFuncOpt::Default, + Conf.AddFSDiscriminator); NoPGOWarnMismatch = !Conf.PGOWarnMismatch; } else if (Conf.AddFSDiscriminator) { - PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", PGOOptions::NoAction, - PGOOptions::NoCSAction, + PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr, + PGOOptions::NoAction, PGOOptions::NoCSAction, PGOOptions::ColdFuncOpt::Default, true); } TM->setPGOOption(PGOOpt); diff --git a/llvm/lib/Passes/PassBuilder.cpp b/llvm/lib/Passes/PassBuilder.cpp index b3f884481c643..8968ffa3a5c4b 100644 --- a/llvm/lib/Passes/PassBuilder.cpp +++ b/llvm/lib/Passes/PassBuilder.cpp @@ -479,9 +479,8 @@ class RequireAllMachineFunctionPropertiesPass PassBuilder::PassBuilder(TargetMachine *TM, PipelineTuningOptions PTO, std::optional PGOOpt, - PassInstrumentationCallbacks *PIC, - IntrusiveRefCntPtr FS) - : TM(TM), PTO(PTO), PGOOpt(PGOOpt), PIC(PIC), FS(std::move(FS)) { + PassInstrumentationCallbacks *PIC) + : TM(TM), PTO(PTO), PGOOpt(PGOOpt), PIC(PIC) { if (TM) TM->registerPassBuilderCallbacks(*this); if (PIC) { diff --git a/llvm/lib/Passes/PassBuilderPipelines.cpp b/llvm/lib/Passes/PassBuilderPipelines.cpp index 6e9c20fa7db2c..27718be09a0f0 100644 --- a/llvm/lib/Passes/PassBuilderPipelines.cpp +++ b/llvm/lib/Passes/PassBuilderPipelines.cpp @@ -856,7 +856,8 @@ void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, OptimizationLevel Level, bool RunProfileGen, bool IsCS, bool AtomicCounterUpdate, std::string ProfileFile, - std::string ProfileRemappingFile) { + std::string ProfileRemappingFile, + IntrusiveRefCntPtr FS) { assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!"); if (!RunProfileGen) { @@ -891,11 +892,10 @@ void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, MPM.addPass(InstrProfilingLoweringPass(Options, IsCS)); } -void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM, - bool RunProfileGen, bool IsCS, - bool AtomicCounterUpdate, - std::string ProfileFile, - std::string ProfileRemappingFile) { +void PassBuilder::addPGOInstrPassesForO0( + ModulePassManager &MPM, bool RunProfileGen, bool IsCS, + bool AtomicCounterUpdate, std::string ProfileFile, + std::string ProfileRemappingFile, IntrusiveRefCntPtr FS) { if (!RunProfileGen) { assert(!ProfileFile.empty() && "Profile use expecting a profile file!"); MPM.addPass( @@ -1141,8 +1141,8 @@ PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level, if (LoadSampleProfile) { // Annotate sample profile right after early FPM to ensure freshness of // the debug info. - MPM.addPass(SampleProfileLoaderPass( - PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, Phase, FS)); + MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile, + PGOOpt->ProfileRemappingFile, Phase)); // Cache ProfileSummaryAnalysis once to avoid the potential need to insert // RequireAnalysisPass for PSI before subsequent non-module passes. MPM.addPass(RequireAnalysisPass()); @@ -1238,7 +1238,8 @@ PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level, addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/IsPGOInstrGen, /*IsCS=*/false, PGOOpt->AtomicCounterUpdate, - PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile); + PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, + PGOOpt->FS); } else if (IsCtxProfGen || IsCtxProfUse) { MPM.addPass(PGOInstrumentationGen(PGOInstrumentationType::CTXPROF)); // In pre-link, we just want the instrumented IR. We use the contextual @@ -1261,10 +1262,10 @@ PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level, addPostPGOLoopRotation(MPM, Level); MPM.addPass(PGOCtxProfLoweringPass()); } else if (IsColdFuncOnlyInstrGen) { - addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, /* IsCS */ false, - /* AtomicCounterUpdate */ false, - InstrumentColdFuncOnlyPath, - /* ProfileRemappingFile */ ""); + addPGOInstrPasses( + MPM, Level, /* RunProfileGen */ true, /* IsCS */ false, + /* AtomicCounterUpdate */ false, InstrumentColdFuncOnlyPath, + /* ProfileRemappingFile */ "", IntrusiveRefCntPtr()); } if (IsPGOInstrGen || IsPGOInstrUse || IsCtxProfGen) @@ -1275,7 +1276,7 @@ PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level, EnableSampledInstr)); if (IsMemprofUse) - MPM.addPass(MemProfUsePass(PGOOpt->MemoryProfile, FS)); + MPM.addPass(MemProfUsePass(PGOOpt->MemoryProfile, PGOOpt->FS)); if (PGOOpt && (PGOOpt->Action == PGOOptions::IRUse || PGOOpt->Action == PGOOptions::SampleUse)) @@ -1484,11 +1485,13 @@ PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level, if (PGOOpt->CSAction == PGOOptions::CSIRInstr) addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true, /*IsCS=*/true, PGOOpt->AtomicCounterUpdate, - PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile); + PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile, + PGOOpt->FS); else if (PGOOpt->CSAction == PGOOptions::CSIRUse) addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false, /*IsCS=*/true, PGOOpt->AtomicCounterUpdate, - PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile); + PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, + PGOOpt->FS); } // Re-compute GlobalsAA here prior to function passes. This is particularly @@ -2088,11 +2091,13 @@ PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, if (PGOOpt->CSAction == PGOOptions::CSIRInstr) addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true, /*IsCS=*/true, PGOOpt->AtomicCounterUpdate, - PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile); + PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile, + PGOOpt->FS); else if (PGOOpt->CSAction == PGOOptions::CSIRUse) addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false, /*IsCS=*/true, PGOOpt->AtomicCounterUpdate, - PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile); + PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, + PGOOpt->FS); } // Break up allocas @@ -2254,7 +2259,7 @@ PassBuilder::buildO0DefaultPipeline(OptimizationLevel Level, MPM, /*RunProfileGen=*/(PGOOpt->Action == PGOOptions::IRInstr), /*IsCS=*/false, PGOOpt->AtomicCounterUpdate, PGOOpt->ProfileFile, - PGOOpt->ProfileRemappingFile); + PGOOpt->ProfileRemappingFile, PGOOpt->FS); // Instrument function entry and exit before all inlining. MPM.addPass(createModuleToFunctionPassAdaptor( diff --git a/llvm/lib/Support/CommandLine.cpp b/llvm/lib/Support/CommandLine.cpp index 134df0df4cd99..8491633df97e8 100644 --- a/llvm/lib/Support/CommandLine.cpp +++ b/llvm/lib/Support/CommandLine.cpp @@ -188,7 +188,6 @@ class CommandLineParser { bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview, raw_ostream *Errs = nullptr, - vfs::FileSystem *VFS = nullptr, bool LongOptionsUseDoubleDash = false); void forEachSubCommand(Option &Opt, function_ref Action) { @@ -1402,9 +1401,8 @@ bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, return true; } -ExpansionContext::ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T, - vfs::FileSystem *FS) - : Saver(A), Tokenizer(T), FS(FS ? FS : vfs::getRealFileSystem().get()) {} +ExpansionContext::ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T) + : Saver(A), Tokenizer(T), FS(vfs::getRealFileSystem().get()) {} bool ExpansionContext::findConfigFile(StringRef FileName, SmallVectorImpl &FilePath) { @@ -1463,7 +1461,7 @@ Error ExpansionContext::readConfigFile(StringRef CfgFile, static void initCommonOptions(); bool cl::ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview, raw_ostream *Errs, - vfs::FileSystem *VFS, const char *EnvVar, + const char *EnvVar, bool LongOptionsUseDoubleDash) { initCommonOptions(); SmallVector NewArgv; @@ -1484,8 +1482,8 @@ bool cl::ParseCommandLineOptions(int argc, const char *const *argv, int NewArgc = static_cast(NewArgv.size()); // Parse all options. - return GlobalParser->ParseCommandLineOptions( - NewArgc, &NewArgv[0], Overview, Errs, VFS, LongOptionsUseDoubleDash); + return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview, + Errs, LongOptionsUseDoubleDash); } /// Reset all options at least once, so that we can parse different options. @@ -1505,17 +1503,17 @@ void CommandLineParser::ResetAllOptionOccurrences() { } } -bool CommandLineParser::ParseCommandLineOptions( - int argc, const char *const *argv, StringRef Overview, raw_ostream *Errs, - vfs::FileSystem *VFS, bool LongOptionsUseDoubleDash) { +bool CommandLineParser::ParseCommandLineOptions(int argc, + const char *const *argv, + StringRef Overview, + raw_ostream *Errs, + bool LongOptionsUseDoubleDash) { assert(hasOptions() && "No options specified!"); ProgramOverview = Overview; bool IgnoreErrors = Errs; if (!Errs) Errs = &errs(); - if (!VFS) - VFS = vfs::getRealFileSystem().get(); bool ErrorParsing = false; // Expand response files. @@ -1526,7 +1524,7 @@ bool CommandLineParser::ParseCommandLineOptions( #else auto Tokenize = cl::TokenizeGNUCommandLine; #endif - ExpansionContext ECtx(A, Tokenize, VFS); + ExpansionContext ECtx(A, Tokenize); if (Error Err = ECtx.expandResponseFiles(newArgv)) { *Errs << toString(std::move(Err)) << '\n'; return false; diff --git a/llvm/lib/Support/FileCollector.cpp b/llvm/lib/Support/FileCollector.cpp index bf236171c1cf3..29436f85c2f23 100644 --- a/llvm/lib/Support/FileCollector.cpp +++ b/llvm/lib/Support/FileCollector.cpp @@ -49,9 +49,8 @@ static bool isCaseSensitivePath(StringRef Path) { return true; } -FileCollector::FileCollector(std::string Root, std::string OverlayRoot, - IntrusiveRefCntPtr VFS) - : Root(Root), OverlayRoot(OverlayRoot), Canonicalizer(std::move(VFS)) { +FileCollector::FileCollector(std::string Root, std::string OverlayRoot) + : Root(Root), OverlayRoot(OverlayRoot) { assert(sys::path::is_absolute(Root) && "Root not absolute"); assert(sys::path::is_absolute(OverlayRoot) && "OverlayRoot not absolute"); } @@ -68,8 +67,9 @@ void FileCollector::PathCanonicalizer::updateWithRealPath( SmallString<256> RealPath; auto DirWithSymlink = CachedDirs.find(Directory); if (DirWithSymlink == CachedDirs.end()) { - // FIXME: What if there is nothing on disk? - if (VFS->getRealPath(Directory, RealPath)) + // FIXME: Should this be a call to FileSystem::getRealpath(), in some + // cases? What if there is nothing on disk? + if (sys::fs::real_path(Directory, RealPath)) return; CachedDirs[Directory] = std::string(RealPath); } else { @@ -88,9 +88,9 @@ void FileCollector::PathCanonicalizer::updateWithRealPath( } /// Make Path absolute. -static void makeAbsolute(vfs::FileSystem &VFS, SmallVectorImpl &Path) { +static void makeAbsolute(SmallVectorImpl &Path) { // We need an absolute src path to append to the root. - VFS.makeAbsolute(Path); + sys::fs::make_absolute(Path); // Canonicalize src to a native path to avoid mixed separator styles. sys::path::native(Path); @@ -105,7 +105,7 @@ FileCollector::PathCanonicalizer::PathStorage FileCollector::PathCanonicalizer::canonicalize(StringRef SrcPath) { PathStorage Paths; Paths.VirtualPath = SrcPath; - makeAbsolute(*VFS, Paths.VirtualPath); + makeAbsolute(Paths.VirtualPath); // If a ".." component is present after a symlink component, remove_dots may // lead to the wrong real destination path. Let the source be canonicalized diff --git a/llvm/lib/Support/PGOOptions.cpp b/llvm/lib/Support/PGOOptions.cpp index ecfb0ca33f16c..5981dff9e0946 100644 --- a/llvm/lib/Support/PGOOptions.cpp +++ b/llvm/lib/Support/PGOOptions.cpp @@ -13,7 +13,8 @@ using namespace llvm; PGOOptions::PGOOptions(std::string ProfileFile, std::string CSProfileGenFile, std::string ProfileRemappingFile, - std::string MemoryProfile, PGOAction Action, + std::string MemoryProfile, + IntrusiveRefCntPtr FS, PGOAction Action, CSPGOAction CSAction, ColdFuncOpt ColdType, bool DebugInfoForProfiling, bool PseudoProbeForProfiling, bool AtomicCounterUpdate) @@ -23,7 +24,7 @@ PGOOptions::PGOOptions(std::string ProfileFile, std::string CSProfileGenFile, DebugInfoForProfiling(DebugInfoForProfiling || (Action == SampleUse && !PseudoProbeForProfiling)), PseudoProbeForProfiling(PseudoProbeForProfiling), - AtomicCounterUpdate(AtomicCounterUpdate) { + AtomicCounterUpdate(AtomicCounterUpdate), FS(std::move(FS)) { // Note, we do allow ProfileFile.empty() for Action=IRUse LTO can // callback with IRUse action without ProfileFile. @@ -46,6 +47,10 @@ PGOOptions::PGOOptions(std::string ProfileFile, std::string CSProfileGenFile, assert(this->Action != NoAction || this->CSAction != NoCSAction || !this->MemoryProfile.empty() || this->DebugInfoForProfiling || this->PseudoProbeForProfiling); + + // If we need to use the profile, the VFS cannot be nullptr. + assert(this->FS || !(this->Action == IRUse || this->CSAction == CSIRUse || + !this->MemoryProfile.empty())); } PGOOptions::PGOOptions(const PGOOptions &) = default; diff --git a/llvm/lib/Support/Path.cpp b/llvm/lib/Support/Path.cpp index 3e066665f4155..761d29e960887 100644 --- a/llvm/lib/Support/Path.cpp +++ b/llvm/lib/Support/Path.cpp @@ -700,55 +700,6 @@ bool is_relative(const Twine &path, Style style) { return !is_absolute(path, style); } -void make_absolute(const Twine ¤t_directory, - SmallVectorImpl &path) { - StringRef p(path.data(), path.size()); - - bool rootDirectory = has_root_directory(p); - bool rootName = has_root_name(p); - - // Already absolute. - if ((rootName || is_style_posix(Style::native)) && rootDirectory) - return; - - // All the following conditions will need the current directory. - SmallString<128> current_dir; - current_directory.toVector(current_dir); - - // Relative path. Prepend the current directory. - if (!rootName && !rootDirectory) { - // Append path to the current directory. - append(current_dir, p); - // Set path to the result. - path.swap(current_dir); - return; - } - - if (!rootName && rootDirectory) { - StringRef cdrn = root_name(current_dir); - SmallString<128> curDirRootName(cdrn.begin(), cdrn.end()); - append(curDirRootName, p); - // Set path to the result. - path.swap(curDirRootName); - return; - } - - if (rootName && !rootDirectory) { - StringRef pRootName = root_name(p); - StringRef bRootDirectory = root_directory(current_dir); - StringRef bRelativePath = relative_path(current_dir); - StringRef pRelativePath = relative_path(p); - - SmallString<128> res; - append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath); - path.swap(res); - return; - } - - llvm_unreachable("All rootName and rootDirectory combinations should have " - "occurred above!"); -} - StringRef remove_leading_dotslash(StringRef Path, Style style) { // Remove leading "./" (or ".//" or "././" etc.) while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) { @@ -952,6 +903,55 @@ getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix, return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name); } +void make_absolute(const Twine ¤t_directory, + SmallVectorImpl &path) { + StringRef p(path.data(), path.size()); + + bool rootDirectory = path::has_root_directory(p); + bool rootName = path::has_root_name(p); + + // Already absolute. + if ((rootName || is_style_posix(Style::native)) && rootDirectory) + return; + + // All of the following conditions will need the current directory. + SmallString<128> current_dir; + current_directory.toVector(current_dir); + + // Relative path. Prepend the current directory. + if (!rootName && !rootDirectory) { + // Append path to the current directory. + path::append(current_dir, p); + // Set path to the result. + path.swap(current_dir); + return; + } + + if (!rootName && rootDirectory) { + StringRef cdrn = path::root_name(current_dir); + SmallString<128> curDirRootName(cdrn.begin(), cdrn.end()); + path::append(curDirRootName, p); + // Set path to the result. + path.swap(curDirRootName); + return; + } + + if (rootName && !rootDirectory) { + StringRef pRootName = path::root_name(p); + StringRef bRootDirectory = path::root_directory(current_dir); + StringRef bRelativePath = path::relative_path(current_dir); + StringRef pRelativePath = path::relative_path(p); + + SmallString<128> res; + path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath); + path.swap(res); + return; + } + + llvm_unreachable("All rootName and rootDirectory combinations should have " + "occurred above!"); +} + std::error_code make_absolute(SmallVectorImpl &path) { if (path::is_absolute(path)) return {}; @@ -960,7 +960,7 @@ std::error_code make_absolute(SmallVectorImpl &path) { if (std::error_code ec = current_path(current_dir)) return ec; - path::make_absolute(current_dir, path); + make_absolute(current_dir, path); return {}; } diff --git a/llvm/lib/Support/SourceMgr.cpp b/llvm/lib/Support/SourceMgr.cpp index 708b7668ed7a0..4a69ccc7605bc 100644 --- a/llvm/lib/Support/SourceMgr.cpp +++ b/llvm/lib/Support/SourceMgr.cpp @@ -41,17 +41,14 @@ static const size_t TabStop = 8; // Out of line to avoid needing definition of vfs::FileSystem in header. SourceMgr::SourceMgr() = default; -SourceMgr::SourceMgr(IntrusiveRefCntPtr FS) - : FS(std::move(FS)) {} +SourceMgr::~SourceMgr() = default; SourceMgr::SourceMgr(SourceMgr &&) = default; SourceMgr &SourceMgr::operator=(SourceMgr &&) = default; -SourceMgr::~SourceMgr() = default; -IntrusiveRefCntPtr SourceMgr::getVirtualFileSystem() const { - return FS; -} +SourceMgr::SourceMgr(IntrusiveRefCntPtr FS) + : FS(std::move(FS)) {} -void SourceMgr::setVirtualFileSystem(IntrusiveRefCntPtr FS) { +void SourceMgr::setFileSystem(IntrusiveRefCntPtr FS) { this->FS = std::move(FS); } @@ -69,11 +66,10 @@ unsigned SourceMgr::AddIncludeFile(const std::string &Filename, ErrorOr> SourceMgr::OpenIncludeFile(const std::string &Filename, std::string &IncludedFile) { - auto GetFile = [this](StringRef Path) { + auto getFile = [this](StringRef Path) { return FS ? FS->getBufferForFile(Path) : MemoryBuffer::getFile(Path); }; - - ErrorOr> NewBufOrErr = GetFile(Filename); + ErrorOr> NewBufOrErr = getFile(Filename); SmallString<64> Buffer(Filename); // If the file didn't exist directly, see if it's in an include path. @@ -81,7 +77,7 @@ SourceMgr::OpenIncludeFile(const std::string &Filename, ++i) { Buffer = IncludeDirectories[i]; sys::path::append(Buffer, Filename); - NewBufOrErr = GetFile(Buffer); + NewBufOrErr = getFile(Buffer); } if (NewBufOrErr) diff --git a/llvm/lib/Support/VirtualFileSystem.cpp b/llvm/lib/Support/VirtualFileSystem.cpp index 8a27110b88876..312e930f967e7 100644 --- a/llvm/lib/Support/VirtualFileSystem.cpp +++ b/llvm/lib/Support/VirtualFileSystem.cpp @@ -135,7 +135,7 @@ std::error_code FileSystem::makeAbsolute(SmallVectorImpl &Path) const { if (!WorkingDir) return WorkingDir.getError(); - sys::path::make_absolute(WorkingDir.get(), Path); + llvm::sys::fs::make_absolute(WorkingDir.get(), Path); return {}; } @@ -302,7 +302,7 @@ class RealFileSystem : public FileSystem { if (!WD || !*WD) return Path; Path.toVector(Storage); - sys::path::make_absolute(WD->get().Resolved, Storage); + sys::fs::make_absolute(WD->get().Resolved, Storage); return Storage; } @@ -1909,12 +1909,7 @@ class llvm::vfs::RedirectingFileSystemParser { FullPath = FS->getOverlayFileDir(); assert(!FullPath.empty() && "External contents prefix directory must exist"); - SmallString<256> AbsFullPath = Value; - if (FS->makeAbsolute(FullPath, AbsFullPath)) { - error(N, "failed to make 'external-contents' absolute"); - return nullptr; - } - FullPath = AbsFullPath; + llvm::sys::path::append(FullPath, Value); } else { FullPath = Value; } @@ -1979,7 +1974,7 @@ class llvm::vfs::RedirectingFileSystemParser { EC = FS->makeAbsolute(FullPath, Name); Name = canonicalize(Name); } else { - EC = FS->makeAbsolute(Name); + EC = sys::fs::make_absolute(Name); } if (EC) { assert(NameValueNode && "Name presence should be checked earlier"); @@ -2210,7 +2205,7 @@ RedirectingFileSystem::create(std::unique_ptr Buffer, // FS->OverlayFileDir => //dummy.cache/vfs // SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath); - std::error_code EC = FS->makeAbsolute(OverlayAbsDir); + std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir); assert(!EC && "Overlay dir final path must be absolute"); (void)EC; FS->setOverlayFileDir(OverlayAbsDir); @@ -2746,9 +2741,19 @@ static void getVFSEntries(RedirectingFileSystem::Entry *SrcE, Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath())); } -void vfs::collectVFSEntries(RedirectingFileSystem &VFS, - SmallVectorImpl &CollectedEntries) { - ErrorOr RootResult = VFS.lookupPath("/"); +void vfs::collectVFSFromYAML(std::unique_ptr Buffer, + SourceMgr::DiagHandlerTy DiagHandler, + StringRef YAMLFilePath, + SmallVectorImpl &CollectedEntries, + void *DiagContext, + IntrusiveRefCntPtr ExternalFS) { + std::unique_ptr VFS = RedirectingFileSystem::create( + std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext, + std::move(ExternalFS)); + if (!VFS) + return; + ErrorOr RootResult = + VFS->lookupPath("/"); if (!RootResult) return; SmallVector Components; diff --git a/llvm/lib/TableGen/Main.cpp b/llvm/lib/TableGen/Main.cpp index ce43123da883c..f545706d6fe30 100644 --- a/llvm/lib/TableGen/Main.cpp +++ b/llvm/lib/TableGen/Main.cpp @@ -26,7 +26,6 @@ #include "llvm/Support/SMLoc.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/ToolOutputFile.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" @@ -131,7 +130,6 @@ int llvm::TableGenMain(const char *argv0, // Record the location of the include directory so that the lexer can find // it later. SrcMgr.setIncludeDirs(IncludeDirs); - SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem()); TGParser Parser(SrcMgr, MacroNames, Records, NoWarnOnUnusedTemplateArgs); diff --git a/llvm/lib/TableGen/Parser.cpp b/llvm/lib/TableGen/Parser.cpp index db45054061524..2c3726a339bb8 100644 --- a/llvm/lib/TableGen/Parser.cpp +++ b/llvm/lib/TableGen/Parser.cpp @@ -9,7 +9,6 @@ #include "llvm/TableGen/Parser.h" #include "TGParser.h" #include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/TableGen/Record.h" using namespace llvm; @@ -22,7 +21,6 @@ bool llvm::TableGenParseFile(SourceMgr &InputSrcMgr, RecordKeeper &Records) { SrcMgr = SourceMgr(); SrcMgr.takeSourceBuffersFrom(InputSrcMgr); SrcMgr.setIncludeDirs(InputSrcMgr.getIncludeDirs()); - SrcMgr.setVirtualFileSystem(InputSrcMgr.getVirtualFileSystem()); SrcMgr.setDiagHandler(InputSrcMgr.getDiagHandler(), InputSrcMgr.getDiagContext()); diff --git a/llvm/lib/Target/ARM/ARMExpandPseudoInsts.cpp b/llvm/lib/Target/ARM/ARMExpandPseudoInsts.cpp index 9f34375c9feaf..52302241fe365 100644 --- a/llvm/lib/Target/ARM/ARMExpandPseudoInsts.cpp +++ b/llvm/lib/Target/ARM/ARMExpandPseudoInsts.cpp @@ -27,8 +27,6 @@ #include "llvm/MC/MCAsmInfo.h" #include "llvm/Support/Debug.h" -#include - using namespace llvm; #define DEBUG_TYPE "arm-pseudo" diff --git a/llvm/lib/Target/X86/X86InstrInfo.cpp b/llvm/lib/Target/X86/X86InstrInfo.cpp index 5e103185fa906..abf365eedec39 100644 --- a/llvm/lib/Target/X86/X86InstrInfo.cpp +++ b/llvm/lib/Target/X86/X86InstrInfo.cpp @@ -44,7 +44,6 @@ #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetOptions.h" -#include #include using namespace llvm; diff --git a/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp index 480ff4a8c3cb9..61fef1387d82a 100644 --- a/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp +++ b/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp @@ -572,8 +572,7 @@ class DataFlowSanitizer { const uint64_t NumOfElementsInArgOrgTLS = ArgTLSSize / OriginWidthBytes; public: - DataFlowSanitizer(const std::vector &ABIListFiles, - IntrusiveRefCntPtr FS); + DataFlowSanitizer(const std::vector &ABIListFiles); bool runImpl(Module &M, llvm::function_ref GetTLI); @@ -868,11 +867,12 @@ bool LibAtomicFunction(const Function &F) { } // end anonymous namespace DataFlowSanitizer::DataFlowSanitizer( - const std::vector &ABIListFiles, - IntrusiveRefCntPtr FS) { + const std::vector &ABIListFiles) { std::vector AllABIListFiles(std::move(ABIListFiles)); llvm::append_range(AllABIListFiles, ClABIListFiles); - ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles, *FS)); + // FIXME: should we propagate vfs::FileSystem to this constructor? + ABIList.set( + SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem())); CombineTaintLookupTableNames.insert_range(ClCombineTaintLookupTables); } @@ -3471,7 +3471,7 @@ PreservedAnalyses DataFlowSanitizerPass::run(Module &M, AM.getResult(M).getManager(); return FAM.getResult(F); }; - if (!DataFlowSanitizer(ABIListFiles, FS).runImpl(M, GetTLI)) + if (!DataFlowSanitizer(ABIListFiles).runImpl(M, GetTLI)) return PreservedAnalyses::all(); PreservedAnalyses PA = PreservedAnalyses::none(); diff --git a/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp b/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp index d8422755c28b8..e5bf2d1187a89 100644 --- a/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp +++ b/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp @@ -35,7 +35,6 @@ #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/Regex.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Instrumentation/CFGMST.h" #include "llvm/Transforms/Instrumentation/GCOVProfiler.h" @@ -93,10 +92,8 @@ class GCOVFunction; class GCOVProfiler { public: - GCOVProfiler() - : GCOVProfiler(GCOVOptions::getDefault(), *vfs::getRealFileSystem()) {} - GCOVProfiler(const GCOVOptions &Opts, vfs::FileSystem &VFS) - : Options(Opts), VFS(VFS) {} + GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {} + GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {} bool runOnModule(Module &M, function_ref GetBFI, function_ref GetBPI, @@ -113,7 +110,6 @@ class GCOVProfiler { os->write_zeros(4 - s.size() % 4); } void writeBytes(const char *Bytes, int Size) { os->write(Bytes, Size); } - vfs::FileSystem &getVirtualFileSystem() const { return VFS; } private: // Create the .gcno files for the Module based on DebugInfo. @@ -170,7 +166,6 @@ class GCOVProfiler { std::vector ExcludeRe; DenseSet ExecBlocks; StringMap InstrumentedFiles; - vfs::FileSystem &VFS; }; struct BBInfo { @@ -219,10 +214,10 @@ static StringRef getFunctionName(const DISubprogram *SP) { /// Prefer relative paths in the coverage notes. Clang also may split /// up absolute paths into a directory and filename component. When /// the relative path doesn't exist, reconstruct the absolute path. -static SmallString<128> getFilename(const DIScope *SP, vfs::FileSystem &VFS) { +static SmallString<128> getFilename(const DIScope *SP) { SmallString<128> Path; StringRef RelPath = SP->getFilename(); - if (VFS.exists(RelPath)) + if (sys::fs::exists(RelPath)) Path = RelPath; else sys::path::append(Path, SP->getDirectory(), SP->getFilename()); @@ -362,7 +357,7 @@ namespace { void writeOut(uint32_t CfgChecksum) { write(GCOV_TAG_FUNCTION); - SmallString<128> Filename = getFilename(SP, P->getVirtualFileSystem()); + SmallString<128> Filename = getFilename(SP); uint32_t BlockLen = 3 + wordsOfString(getFunctionName(SP)); BlockLen += 1 + wordsOfString(Filename) + 4; @@ -460,7 +455,7 @@ bool GCOVProfiler::isFunctionInstrumented(const Function &F) { if (FilterRe.empty() && ExcludeRe.empty()) { return true; } - SmallString<128> Filename = getFilename(F.getSubprogram(), VFS); + SmallString<128> Filename = getFilename(F.getSubprogram()); auto It = InstrumentedFiles.find(Filename); if (It != InstrumentedFiles.end()) { return It->second; @@ -472,7 +467,7 @@ bool GCOVProfiler::isFunctionInstrumented(const Function &F) { // Path can be // /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/*.h so for // such a case we must get the real_path. - if (VFS.getRealPath(Filename, RealPath)) { + if (sys::fs::real_path(Filename, RealPath)) { // real_path can fail with path like "foo.c". RealFilename = Filename; } else { @@ -529,10 +524,9 @@ std::string GCOVProfiler::mangleName(const DICompileUnit *CU, SmallString<128> Filename = CU->getFilename(); sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda"); StringRef FName = sys::path::filename(Filename); - ErrorOr CWD = VFS.getCurrentWorkingDirectory(); - if (!CWD) + SmallString<128> CurPath; + if (sys::fs::current_path(CurPath)) return std::string(FName); - SmallString<128> CurPath{*CWD}; sys::path::append(CurPath, FName); return std::string(CurPath); } @@ -560,7 +554,7 @@ bool GCOVProfiler::runOnModule( PreservedAnalyses GCOVProfilerPass::run(Module &M, ModuleAnalysisManager &AM) { - GCOVProfiler Profiler(GCOVOpts, *VFS); + GCOVProfiler Profiler(GCOVOpts); FunctionAnalysisManager &FAM = AM.getResult(M).getManager(); @@ -795,7 +789,7 @@ bool GCOVProfiler::emitProfileNotes( // Add the function line number to the lines of the entry block // to have a counter for the function definition. uint32_t Line = SP->getLine(); - auto Filename = getFilename(SP, VFS); + auto Filename = getFilename(SP); BranchProbabilityInfo *BPI = GetBPI(F); BlockFrequencyInfo *BFI = GetBFI(F); @@ -887,7 +881,7 @@ bool GCOVProfiler::emitProfileNotes( if (SP != getDISubprogram(Scope)) continue; - GCOVLines &Lines = Block.getFile(getFilename(Loc->getScope(), VFS)); + GCOVLines &Lines = Block.getFile(getFilename(Loc->getScope())); Lines.addLine(Loc.getLine()); } Line = 0; diff --git a/llvm/tools/dsymutil/Reproducer.cpp b/llvm/tools/dsymutil/Reproducer.cpp index 0c1d3f90af299..31e49cdd0518c 100644 --- a/llvm/tools/dsymutil/Reproducer.cpp +++ b/llvm/tools/dsymutil/Reproducer.cpp @@ -37,10 +37,9 @@ ReproducerGenerate::ReproducerGenerate(std::error_code &EC, int Argc, char **Argv, bool GenerateOnExit) : Root(createReproducerDir(EC)), GenerateOnExit(GenerateOnExit) { llvm::append_range(Args, ArrayRef(Argv, Argc)); - auto RealFS = vfs::getRealFileSystem(); if (!Root.empty()) - FC = std::make_shared(Root, Root, RealFS); - VFS = FileCollector::createCollectorVFS(std::move(RealFS), FC); + FC = std::make_shared(Root, Root); + VFS = FileCollector::createCollectorVFS(vfs::getRealFileSystem(), FC); } ReproducerGenerate::~ReproducerGenerate() { diff --git a/llvm/tools/llvm-config/llvm-config.cpp b/llvm/tools/llvm-config/llvm-config.cpp index 7f8c55ab00989..49df8fdcb7f79 100644 --- a/llvm/tools/llvm-config/llvm-config.cpp +++ b/llvm/tools/llvm-config/llvm-config.cpp @@ -357,18 +357,18 @@ int main(int argc, char **argv) { ActivePrefix = CurrentExecPrefix; { SmallString<256> Path(LLVM_INSTALL_INCLUDEDIR); - sys::path::make_absolute(ActivePrefix, Path); + sys::fs::make_absolute(ActivePrefix, Path); ActiveIncludeDir = std::string(Path); } { SmallString<256> Path(LLVM_TOOLS_INSTALL_DIR); - sys::path::make_absolute(ActivePrefix, Path); + sys::fs::make_absolute(ActivePrefix, Path); ActiveBinDir = std::string(Path); } ActiveLibDir = ActivePrefix + "/lib" + LLVM_LIBDIR_SUFFIX; { SmallString<256> Path(LLVM_INSTALL_PACKAGE_DIR); - sys::path::make_absolute(ActivePrefix, Path); + sys::fs::make_absolute(ActivePrefix, Path); ActiveCMakeDir = std::string(Path); } ActiveIncludeOption = "-I" + ActiveIncludeDir; diff --git a/llvm/tools/llvm-dwp/llvm-dwp.cpp b/llvm/tools/llvm-dwp/llvm-dwp.cpp index 1fb2a654381d1..e34fcadfde5fc 100644 --- a/llvm/tools/llvm-dwp/llvm-dwp.cpp +++ b/llvm/tools/llvm-dwp/llvm-dwp.cpp @@ -94,7 +94,7 @@ getDWOFilenames(StringRef ExecFilename) { dwarf::toString(Die.find(dwarf::DW_AT_comp_dir), ""); if (!DWOCompDir.empty()) { SmallString<16> DWOPath(DWOName); - sys::path::make_absolute(DWOCompDir, DWOPath); + sys::fs::make_absolute(DWOCompDir, DWOPath); if (!sys::fs::exists(DWOPath) && sys::fs::exists(DWOName)) DWOPaths.push_back(std::move(DWOName)); else diff --git a/llvm/tools/llvm-mc-assemble-fuzzer/llvm-mc-assemble-fuzzer.cpp b/llvm/tools/llvm-mc-assemble-fuzzer/llvm-mc-assemble-fuzzer.cpp index 5b4d3cd13c2b8..615a39ee9bb4d 100644 --- a/llvm/tools/llvm-mc-assemble-fuzzer/llvm-mc-assemble-fuzzer.cpp +++ b/llvm/tools/llvm-mc-assemble-fuzzer/llvm-mc-assemble-fuzzer.cpp @@ -31,7 +31,6 @@ #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/ToolOutputFile.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include "llvm/TargetParser/Host.h" #include "llvm/TargetParser/SubtargetFeature.h" @@ -143,7 +142,6 @@ int AssembleOneInput(const uint8_t *Data, size_t Size) { static const std::vector NoIncludeDirs; SrcMgr.setIncludeDirs(NoIncludeDirs); - SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem()); static std::string ArchName; std::string Error; diff --git a/llvm/tools/llvm-mc/llvm-mc.cpp b/llvm/tools/llvm-mc/llvm-mc.cpp index b5746fdeb7a00..fd7fd399d15af 100644 --- a/llvm/tools/llvm-mc/llvm-mc.cpp +++ b/llvm/tools/llvm-mc/llvm-mc.cpp @@ -41,7 +41,6 @@ #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/ToolOutputFile.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/WithColor.h" #include "llvm/TargetParser/Host.h" #include @@ -435,7 +434,6 @@ int main(int argc, char **argv) { // Record the location of the include directories so that the lexer can find // it later. SrcMgr.setIncludeDirs(IncludeDirs); - SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem()); std::unique_ptr MRI(TheTarget->createMCRegInfo(TripleName)); assert(MRI && "Unable to create target register info!"); diff --git a/llvm/tools/llvm-ml/llvm-ml.cpp b/llvm/tools/llvm-ml/llvm-ml.cpp index 504ac9d12486d..c8e49edd34e04 100644 --- a/llvm/tools/llvm-ml/llvm-ml.cpp +++ b/llvm/tools/llvm-ml/llvm-ml.cpp @@ -41,7 +41,6 @@ #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/ToolOutputFile.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/WithColor.h" #include "llvm/TargetParser/Host.h" #include @@ -316,7 +315,6 @@ int llvm_ml_main(int Argc, char **Argv, const llvm::ToolContext &) { } } SrcMgr.setIncludeDirs(IncludeDirs); - SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem()); std::unique_ptr MRI(TheTarget->createMCRegInfo(TripleName)); assert(MRI && "Unable to create target register info!"); diff --git a/llvm/tools/llvm-opt-report/OptReport.cpp b/llvm/tools/llvm-opt-report/OptReport.cpp index e4b4fc287b8c1..68ed92c8bacea 100644 --- a/llvm/tools/llvm-opt-report/OptReport.cpp +++ b/llvm/tools/llvm-opt-report/OptReport.cpp @@ -274,7 +274,7 @@ static bool writeReport(LocationInfoTy &LocationInfo) { for (auto &FI : LocationInfo) { SmallString<128> FileName(FI.first); if (!InputRelDir.empty()) - sys::path::make_absolute(InputRelDir, FileName); + sys::fs::make_absolute(InputRelDir, FileName); const auto &FileInfo = FI.second; diff --git a/llvm/tools/obj2yaml/obj2yaml.cpp b/llvm/tools/obj2yaml/obj2yaml.cpp index 94c38d1032c22..63c8cc55ee2d4 100644 --- a/llvm/tools/obj2yaml/obj2yaml.cpp +++ b/llvm/tools/obj2yaml/obj2yaml.cpp @@ -104,7 +104,7 @@ int main(int argc, char *argv[]) { cl::HideUnrelatedOptions(Cat); cl::ParseCommandLineOptions( argc, argv, "Dump a YAML description from an object file", nullptr, - nullptr, nullptr, /*LongOptionsUseDoubleDash=*/true); + nullptr, /*LongOptionsUseDoubleDash=*/true); std::error_code EC; std::unique_ptr Out( diff --git a/llvm/tools/opt/NewPMDriver.cpp b/llvm/tools/opt/NewPMDriver.cpp index a32af1d787269..7d168a6ceb17c 100644 --- a/llvm/tools/opt/NewPMDriver.cpp +++ b/llvm/tools/opt/NewPMDriver.cpp @@ -357,25 +357,27 @@ bool llvm::runPassPipeline( bool ShouldPreserveBitcodeUseListOrder, bool EmitSummaryIndex, bool EmitModuleHash, bool EnableDebugify, bool VerifyDIPreserve, bool UnifiedLTO) { + auto FS = vfs::getRealFileSystem(); std::optional P; switch (PGOKindFlag) { case InstrGen: - P = PGOOptions(ProfileFile, "", "", MemoryProfileFile, PGOOptions::IRInstr, - PGOOptions::NoCSAction, PGOColdFuncAttr); + P = PGOOptions(ProfileFile, "", "", MemoryProfileFile, FS, + PGOOptions::IRInstr, PGOOptions::NoCSAction, + PGOColdFuncAttr); break; case InstrUse: - P = PGOOptions(ProfileFile, "", ProfileRemappingFile, MemoryProfileFile, + P = PGOOptions(ProfileFile, "", ProfileRemappingFile, MemoryProfileFile, FS, PGOOptions::IRUse, PGOOptions::NoCSAction, PGOColdFuncAttr); break; case SampleUse: - P = PGOOptions(ProfileFile, "", ProfileRemappingFile, MemoryProfileFile, + P = PGOOptions(ProfileFile, "", ProfileRemappingFile, MemoryProfileFile, FS, PGOOptions::SampleUse, PGOOptions::NoCSAction, PGOColdFuncAttr); break; case NoPGO: if (DebugInfoForProfiling || PseudoProbeForProfiling || !MemoryProfileFile.empty()) - P = PGOOptions("", "", "", MemoryProfileFile, PGOOptions::NoAction, + P = PGOOptions("", "", "", MemoryProfileFile, FS, PGOOptions::NoAction, PGOOptions::NoCSAction, PGOColdFuncAttr, DebugInfoForProfiling, PseudoProbeForProfiling); else @@ -397,7 +399,7 @@ bool llvm::runPassPipeline( P->CSProfileGenFile = CSProfileGenFile; } else P = PGOOptions("", CSProfileGenFile, ProfileRemappingFile, - /*MemoryProfile=*/"", PGOOptions::NoAction, + /*MemoryProfile=*/"", FS, PGOOptions::NoAction, PGOOptions::CSIRInstr); } else /* CSPGOKindFlag == CSInstrUse */ { if (!P) { diff --git a/llvm/tools/yaml2obj/yaml2obj.cpp b/llvm/tools/yaml2obj/yaml2obj.cpp index 662648b599954..dcd6dfcd3de2a 100644 --- a/llvm/tools/yaml2obj/yaml2obj.cpp +++ b/llvm/tools/yaml2obj/yaml2obj.cpp @@ -115,7 +115,7 @@ int main(int argc, char **argv) { cl::HideUnrelatedOptions(Cat); cl::ParseCommandLineOptions( argc, argv, "Create an object file from a YAML description", nullptr, - nullptr, nullptr, /*LongOptionsUseDoubleDash=*/true); + nullptr, /*LongOptionsUseDoubleDash=*/true); constexpr StringRef ProgName = "yaml2obj"; auto ErrHandler = [&](const Twine &Msg) { diff --git a/llvm/unittests/Support/CommandLineTest.cpp b/llvm/unittests/Support/CommandLineTest.cpp index 15d47a7642980..3df4107ebf439 100644 --- a/llvm/unittests/Support/CommandLineTest.cpp +++ b/llvm/unittests/Support/CommandLineTest.cpp @@ -1901,20 +1901,20 @@ TEST(CommandLineTest, LongOptions) { // Fails because `-ab` is treated as `-a -b`, so `-a` is seen twice, and // `val1` is unexpected. - EXPECT_FALSE(cl::ParseCommandLineOptions(4, args1, StringRef(), &OS, nullptr, - nullptr, true)); + EXPECT_FALSE(cl::ParseCommandLineOptions(4, args1, StringRef(), + &OS, nullptr, true)); EXPECT_FALSE(Errs.empty()); Errs.clear(); cl::ResetAllOptionOccurrences(); // Works because `-a` is treated differently than `--ab`. - EXPECT_TRUE(cl::ParseCommandLineOptions(4, args2, StringRef(), &OS, nullptr, - nullptr, true)); + EXPECT_TRUE(cl::ParseCommandLineOptions(4, args2, StringRef(), + &OS, nullptr, true)); EXPECT_TRUE(Errs.empty()); Errs.clear(); cl::ResetAllOptionOccurrences(); // Works because `-ab` is treated as `-a -b`, and `--ab` is a long option. - EXPECT_TRUE(cl::ParseCommandLineOptions(4, args3, StringRef(), &OS, nullptr, - nullptr, true)); + EXPECT_TRUE(cl::ParseCommandLineOptions(4, args3, StringRef(), + &OS, nullptr, true)); EXPECT_TRUE(OptA); EXPECT_TRUE(OptBLong); EXPECT_STREQ("val1", OptAB.c_str()); diff --git a/llvm/unittests/Support/FileCollectorTest.cpp b/llvm/unittests/Support/FileCollectorTest.cpp index 0ece86947b4f2..184d0e3fdfd17 100644 --- a/llvm/unittests/Support/FileCollectorTest.cpp +++ b/llvm/unittests/Support/FileCollectorTest.cpp @@ -43,8 +43,7 @@ class TestingFileCollector : public FileCollector { TEST(FileCollectorTest, addFile) { TempDir root("add_file_root", /*Unique*/ true); std::string root_fs(root.path()); - TestingFileCollector FileCollector(root_fs, root_fs, - vfs::getRealFileSystem()); + TestingFileCollector FileCollector(root_fs, root_fs); FileCollector.addFile("/path/to/a"); FileCollector.addFile("/path/to/b"); @@ -78,8 +77,7 @@ TEST(FileCollectorTest, addDirectory) { TempFile c(ccc.str()); std::string root_fs(file_root.path()); - TestingFileCollector FileCollector(root_fs, root_fs, - vfs::getRealFileSystem()); + TestingFileCollector FileCollector(root_fs, root_fs); FileCollector.addDirectory(file_root.path()); @@ -107,8 +105,7 @@ TEST(FileCollectorTest, copyFiles) { // Create file collector and add files. TempDir root("copy_files_root", /*Unique*/ true); std::string root_fs(root.path()); - TestingFileCollector FileCollector(root_fs, root_fs, - vfs::getRealFileSystem()); + TestingFileCollector FileCollector(root_fs, root_fs); FileCollector.addFile(a.path()); FileCollector.addFile(b.path()); FileCollector.addFile(c.path()); @@ -136,8 +133,7 @@ TEST(FileCollectorTest, recordAndConstructDirectory) { // Create file collector and add files. TempDir root("copy_files_root", /*Unique*/ true); std::string root_fs(root.path()); - TestingFileCollector FileCollector(root_fs, root_fs, - vfs::getRealFileSystem()); + TestingFileCollector FileCollector(root_fs, root_fs); FileCollector.addFile(a.path()); // The empty directory isn't seen until we add it. @@ -173,8 +169,7 @@ TEST(FileCollectorTest, recordVFSAccesses) { // Create file collector and add files. TempDir root("copy_files_root", /*Unique*/ true); std::string root_fs(root.path()); - auto Collector = std::make_shared( - root_fs, root_fs, vfs::getRealFileSystem()); + auto Collector = std::make_shared(root_fs, root_fs); auto VFS = FileCollector::createCollectorVFS(vfs::getRealFileSystem(), Collector); VFS->status(a.path()); @@ -221,8 +216,7 @@ TEST(FileCollectorTest, Symlinks) { // Root where files are copied to. TempDir reproducer_root("reproducer_root", /*Unique*/ true); std::string root_fs(reproducer_root.path()); - TestingFileCollector FileCollector(root_fs, root_fs, - vfs::getRealFileSystem()); + TestingFileCollector FileCollector(root_fs, root_fs); // Add all the files to the collector. FileCollector.addFile(a.path()); @@ -270,8 +264,7 @@ TEST(FileCollectorTest, recordVFSSymlinkAccesses) { // Create file collector and add files. TempDir root("copy_files_root", true); std::string root_fs(root.path()); - auto Collector = std::make_shared( - root_fs, root_fs, vfs::getRealFileSystem()); + auto Collector = std::make_shared(root_fs, root_fs); auto VFS = FileCollector::createCollectorVFS(vfs::getRealFileSystem(), Collector); SmallString<256> Output; diff --git a/llvm/unittests/Support/Path.cpp b/llvm/unittests/Support/Path.cpp index e6d411d1babe4..355aa6b9ade06 100644 --- a/llvm/unittests/Support/Path.cpp +++ b/llvm/unittests/Support/Path.cpp @@ -255,14 +255,14 @@ TEST(Support, Path) { { SmallString<32> Relative("foo.cpp"); - path::make_absolute("/root", Relative); + sys::fs::make_absolute("/root", Relative); Relative[5] = '/'; // Fix up windows paths. ASSERT_EQ("/root/foo.cpp", Relative); } { SmallString<32> Relative("foo.cpp"); - path::make_absolute("//root", Relative); + sys::fs::make_absolute("//root", Relative); Relative[6] = '/'; // Fix up windows paths. ASSERT_EQ("//root/foo.cpp", Relative); } diff --git a/llvm/unittests/Support/SourceMgrTest.cpp b/llvm/unittests/Support/SourceMgrTest.cpp index 8121d339f6fa4..41d09ab5adc75 100644 --- a/llvm/unittests/Support/SourceMgrTest.cpp +++ b/llvm/unittests/Support/SourceMgrTest.cpp @@ -566,13 +566,3 @@ TEST_F(SourceMgrTest, PrintWithoutLoc) { Diag.print(nullptr, OS, false, false, false); EXPECT_EQ("message\n", Output); } - -TEST_F(SourceMgrTest, IncludeDirs) { - auto VFS = makeIntrusiveRefCnt(); - VFS->addFile("include/file", 0, MemoryBuffer::getMemBuffer("contents")); - SM.setVirtualFileSystem(std::move(VFS)); - SM.setIncludeDirs({"include"}); - std::string ResolvedPath; - unsigned NumBuffers = SM.AddIncludeFile("file", SMLoc(), ResolvedPath); - EXPECT_EQ(NumBuffers, 1u); -} diff --git a/llvm/unittests/Support/VirtualFileSystemTest.cpp b/llvm/unittests/Support/VirtualFileSystemTest.cpp index e740784cb9acd..c150d12338b1f 100644 --- a/llvm/unittests/Support/VirtualFileSystemTest.cpp +++ b/llvm/unittests/Support/VirtualFileSystemTest.cpp @@ -1954,30 +1954,7 @@ TEST_F(VFSFromYAMLTest, ReturnsExternalPathVFSHit) { EXPECT_EQ(0, NumDiagnostics); } -TEST_F(VFSFromYAMLTest, RelativeFileDirWithOverlayRelativeSetting) { - auto Lower = makeIntrusiveRefCnt(); - Lower->addDirectory("//root/foo/bar"); - Lower->addRegularFile("//root/foo/bar/a"); - Lower->setCurrentWorkingDirectory("//root/foo"); - IntrusiveRefCntPtr FS = - getFromYAMLString("{\n" - " 'case-sensitive': false,\n" - " 'overlay-relative': true,\n" - " 'roots': [\n" - " { 'name': '//root/foo/bar/b', 'type': 'file',\n" - " 'external-contents': 'a'\n" - " }\n" - " ]\n" - "}", - Lower, "bar/overlay"); - - ASSERT_NE(FS.get(), nullptr); - ErrorOr S = FS->status("//root/foo/bar/b"); - ASSERT_FALSE(S.getError()); - EXPECT_EQ("//root/foo/bar/a", S->getName()); -} - -TEST_F(VFSFromYAMLTest, RootRelativeToOverlayDirTest) { +TEST_F(VFSFromYAMLTest, RootRelativeTest) { IntrusiveRefCntPtr Lower(new DummyFileSystem()); Lower->addDirectory("//root/foo/bar"); Lower->addRegularFile("//root/foo/bar/a"); @@ -2040,35 +2017,6 @@ TEST_F(VFSFromYAMLTest, RootRelativeToOverlayDirTest) { #endif } -TEST_F(VFSFromYAMLTest, RootRelativeToCWDTest) { - auto Lower = makeIntrusiveRefCnt(); - Lower->addDirectory("//root/foo/bar"); - Lower->addRegularFile("//root/foo/bar/a"); - Lower->addDirectory("//root/foo/bar/cwd"); - Lower->addRegularFile("//root/foo/bar/cwd/a"); - Lower->setCurrentWorkingDirectory("//root/foo/bar/cwd"); - IntrusiveRefCntPtr FS = - getFromYAMLString("{\n" - " 'case-sensitive': false,\n" - " 'root-relative': 'cwd',\n" - " 'roots': [\n" - " { 'name': 'b', 'type': 'file',\n" - " 'external-contents': '//root/foo/bar/a'\n" - " }\n" - " ]\n" - "}", - Lower, "//root/foo/bar/overlay"); - - ASSERT_NE(FS.get(), nullptr); - - ErrorOr S1 = FS->status("//root/foo/bar/b"); - ASSERT_TRUE(S1.getError()); - - ErrorOr S2 = FS->status("//root/foo/bar/cwd/b"); - ASSERT_FALSE(S2.getError()); - EXPECT_EQ("//root/foo/bar/a", S2->getName()); -} - TEST_F(VFSFromYAMLTest, ReturnsInternalPathVFSHit) { IntrusiveRefCntPtr BaseFS( new vfs::InMemoryFileSystem); @@ -2560,7 +2508,6 @@ TEST_F(VFSFromYAMLTest, RelativePaths) { SmallString<128> CWD; EC = llvm::sys::fs::current_path(CWD); ASSERT_FALSE(EC); - Lower->setCurrentWorkingDirectory(CWD); // Filename at root level without a parent directory. IntrusiveRefCntPtr FS = getFromYAMLString( diff --git a/llvm/utils/FileCheck/FileCheck.cpp b/llvm/utils/FileCheck/FileCheck.cpp index 185b6b30994fc..9cf3a3164dfec 100644 --- a/llvm/utils/FileCheck/FileCheck.cpp +++ b/llvm/utils/FileCheck/FileCheck.cpp @@ -735,7 +735,7 @@ int main(int argc, char **argv) { InitLLVM X(argc, argv); cl::ParseCommandLineOptions(argc, argv, /*Overview*/ "", /*Errs*/ nullptr, - /*VFS*/ nullptr, "FILECHECK_OPTS"); + "FILECHECK_OPTS"); // Select -dump-input* values. The -help documentation specifies the default // value and which value to choose if an option is specified multiple times. diff --git a/llvm/utils/split-file/split-file.cpp b/llvm/utils/split-file/split-file.cpp index c7e9ff4b2b682..672877adaba31 100644 --- a/llvm/utils/split-file/split-file.cpp +++ b/llvm/utils/split-file/split-file.cpp @@ -148,7 +148,6 @@ int main(int argc, const char **argv) { "Split input into multiple parts separated by regex '^(.|//)--- ' and " "extract the part specified by '^(.|//)--- '\n", nullptr, - /*VFS=*/nullptr, /*EnvVar=*/nullptr, /*LongOptionsUseDoubleDash=*/true); diff --git a/mlir/lib/IR/Diagnostics.cpp b/mlir/lib/IR/Diagnostics.cpp index 2467441eb7071..3e337951bcd3f 100644 --- a/mlir/lib/IR/Diagnostics.cpp +++ b/mlir/lib/IR/Diagnostics.cpp @@ -378,10 +378,8 @@ struct SourceMgrDiagnosticHandlerImpl { } // Otherwise, try to load the source file. - auto bufferOrErr = llvm::MemoryBuffer::getFile(filename); - if (!bufferOrErr) - return 0; - unsigned id = mgr.AddNewSourceBuffer(std::move(*bufferOrErr), SMLoc()); + std::string ignored; + unsigned id = mgr.AddIncludeFile(std::string(filename), SMLoc(), ignored); filenameToBufId[filename] = id; return id; } diff --git a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp index e8a057b686c61..f8ea6ee07447b 100644 --- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp +++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp @@ -36,7 +36,6 @@ #include "llvm/IR/MDBuilder.h" #include "llvm/IR/ReplaceConstant.h" #include "llvm/Support/FileSystem.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/TargetParser/Triple.h" #include "llvm/Transforms/Utils/ModuleUtils.h" @@ -3534,10 +3533,8 @@ getDeclareTargetRefPtrSuffix(LLVM::GlobalOp globalOp, llvm::StringRef(loc.getFilename()), loc.getLine()); }; - auto vfs = llvm::vfs::getRealFileSystem(); os << llvm::format( - "_%x", - ompBuilder.getTargetEntryUniqueInfo(fileInfoCallBack, *vfs).FileID); + "_%x", ompBuilder.getTargetEntryUniqueInfo(fileInfoCallBack).FileID); } os << "_decl_tgt_ref_ptr"; @@ -5811,12 +5808,10 @@ convertDeclareTargetAttr(Operation *op, mlir::omp::DeclareTargetAttr attribute, lineNo); }; - auto vfs = llvm::vfs::getRealFileSystem(); - ompBuilder->registerTargetGlobalVariable( captureClause, deviceClause, isDeclaration, isExternallyVisible, - ompBuilder->getTargetEntryUniqueInfo(fileInfoCallBack, *vfs), - mangledName, generatedRefs, /*OpenMPSimd*/ false, targetTriple, + ompBuilder->getTargetEntryUniqueInfo(fileInfoCallBack), mangledName, + generatedRefs, /*OpenMPSimd*/ false, targetTriple, /*GlobalInitializer*/ nullptr, /*VariableLinkage*/ nullptr, gVal->getType(), gVal); @@ -5826,9 +5821,9 @@ convertDeclareTargetAttr(Operation *op, mlir::omp::DeclareTargetAttr attribute, ompBuilder->Config.hasRequiresUnifiedSharedMemory())) { ompBuilder->getAddrOfDeclareTargetVar( captureClause, deviceClause, isDeclaration, isExternallyVisible, - ompBuilder->getTargetEntryUniqueInfo(fileInfoCallBack, *vfs), - mangledName, generatedRefs, /*OpenMPSimd*/ false, targetTriple, - gVal->getType(), /*GlobalInitializer*/ nullptr, + ompBuilder->getTargetEntryUniqueInfo(fileInfoCallBack), mangledName, + generatedRefs, /*OpenMPSimd*/ false, targetTriple, gVal->getType(), + /*GlobalInitializer*/ nullptr, /*VariableLinkage*/ nullptr); } } @@ -6190,9 +6185,7 @@ LogicalResult OpenMPDialectLLVMIRTranslationInterface::amendOperation( if (auto filepathAttr = dyn_cast(attr)) { llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder(); - auto VFS = llvm::vfs::getRealFileSystem(); - ompBuilder->loadOffloadInfoMetadata(*VFS, - filepathAttr.getValue()); + ompBuilder->loadOffloadInfoMetadata(filepathAttr.getValue()); return success(); } return failure(); diff --git a/mlir/lib/Tools/PDLL/Parser/Parser.cpp b/mlir/lib/Tools/PDLL/Parser/Parser.cpp index f6d665b6e0162..50e10447ee468 100644 --- a/mlir/lib/Tools/PDLL/Parser/Parser.cpp +++ b/mlir/lib/Tools/PDLL/Parser/Parser.cpp @@ -28,7 +28,6 @@ #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/SaveAndRestore.h" #include "llvm/Support/ScopedPrinter.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Parser.h" #include @@ -829,7 +828,6 @@ LogicalResult Parser::parseTdInclude(StringRef filename, llvm::SMRange fileLoc, llvm::SourceMgr tdSrcMgr; tdSrcMgr.AddNewSourceBuffer(std::move(*includeBuffer), SMLoc()); tdSrcMgr.setIncludeDirs(parserSrcMgr.getIncludeDirs()); - tdSrcMgr.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); // This class provides a context argument for the llvm::SourceMgr diagnostic // handler. diff --git a/mlir/lib/Tools/mlir-pdll-lsp-server/PDLLServer.cpp b/mlir/lib/Tools/mlir-pdll-lsp-server/PDLLServer.cpp index acc84a8b98f2f..84f529ae16401 100644 --- a/mlir/lib/Tools/mlir-pdll-lsp-server/PDLLServer.cpp +++ b/mlir/lib/Tools/mlir-pdll-lsp-server/PDLLServer.cpp @@ -31,7 +31,6 @@ #include "llvm/ADT/TypeSwitch.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" -#include "llvm/Support/VirtualFileSystem.h" #include using namespace mlir; @@ -390,7 +389,6 @@ PDLDocument::PDLDocument(const lsp::URIForFile &uri, StringRef contents, llvm::append_range(includeDirs, extraDirs); sourceMgr.setIncludeDirs(includeDirs); - sourceMgr.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc()); astContext.getDiagEngine().setHandlerFn([&](const ast::Diagnostic &diag) { diff --git a/mlir/lib/Tools/tblgen-lsp-server/TableGenServer.cpp b/mlir/lib/Tools/tblgen-lsp-server/TableGenServer.cpp index fa30674282394..5faeeae839f44 100644 --- a/mlir/lib/Tools/tblgen-lsp-server/TableGenServer.cpp +++ b/mlir/lib/Tools/tblgen-lsp-server/TableGenServer.cpp @@ -17,7 +17,6 @@ #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/Path.h" -#include "llvm/Support/VirtualFileSystem.h" #include "llvm/TableGen/Parser.h" #include "llvm/TableGen/Record.h" #include @@ -438,7 +437,6 @@ void TableGenTextFile::initialize(const lsp::URIForFile &uri, return; } sourceMgr.setIncludeDirs(includeDirs); - sourceMgr.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc()); // This class provides a context argument for the SourceMgr diagnostic diff --git a/mlir/tools/mlir-pdll/mlir-pdll.cpp b/mlir/tools/mlir-pdll/mlir-pdll.cpp index 905becd7745f3..88a5f3639c962 100644 --- a/mlir/tools/mlir-pdll/mlir-pdll.cpp +++ b/mlir/tools/mlir-pdll/mlir-pdll.cpp @@ -19,7 +19,6 @@ #include "llvm/Support/InitLLVM.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/ToolOutputFile.h" -#include "llvm/Support/VirtualFileSystem.h" #include using namespace mlir; @@ -42,7 +41,6 @@ processBuffer(raw_ostream &os, std::unique_ptr chunkBuffer, bool dumpODS, std::set *includedFiles) { llvm::SourceMgr sourceMgr; sourceMgr.setIncludeDirs(includeDirs); - sourceMgr.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); sourceMgr.AddNewSourceBuffer(std::move(chunkBuffer), SMLoc()); // If we are dumping ODS information, also enable documentation to ensure the