[clang-tools-extra] f71ffd3 - [clang-tools-extra] Use std::optional instead of llvm::Optional (NFC)

Kazu Hirata via cfe-commits cfe-commits at lists.llvm.org
Sat Jan 7 20:19:49 PST 2023


Author: Kazu Hirata
Date: 2023-01-07T20:19:42-08:00
New Revision: f71ffd3b735b4d6ae3c12be1806cdd6205b3b378

URL: https://github.com/llvm/llvm-project/commit/f71ffd3b735b4d6ae3c12be1806cdd6205b3b378
DIFF: https://github.com/llvm/llvm-project/commit/f71ffd3b735b4d6ae3c12be1806cdd6205b3b378.diff

LOG: [clang-tools-extra] Use std::optional instead of llvm::Optional (NFC)

This patch replaces (llvm::|)Optional< with std::optional<.  I'll post
a separate patch to clean up the "using" declarations, #include
"llvm/ADT/Optional.h", etc.

This is part of an effort to migrate from llvm::Optional to
std::optional:

https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716

Added: 
    

Modified: 
    clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp
    clang-tools-extra/clang-doc/HTMLGenerator.cpp
    clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.cpp
    clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.h
    clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp
    clang-tools-extra/clang-query/Query.cpp
    clang-tools-extra/clang-query/QueryParser.cpp
    clang-tools-extra/clang-query/tool/ClangQuery.cpp
    clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
    clang-tools-extra/clang-tidy/ClangTidyCheck.h
    clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
    clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
    clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
    clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp
    clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp
    clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.cpp
    clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.cpp
    clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.cpp
    clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp
    clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp
    clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp
    clang-tools-extra/clang-tidy/abseil/DurationRewriter.h
    clang-tools-extra/clang-tidy/abseil/DurationSubtractionCheck.cpp
    clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
    clang-tools-extra/clang-tidy/abseil/TimeComparisonCheck.cpp
    clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp
    clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
    clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h
    clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp
    clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp
    clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.h
    clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
    clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp
    clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.h
    clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp
    clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp
    clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp
    clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h
    clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
    clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
    clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
    clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp
    clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
    clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
    clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
    clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp
    clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
    clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp
    clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp
    clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
    clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp
    clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h
    clang-tools-extra/clang-tidy/mpi/BufferDerefCheck.h
    clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.h
    clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp
    clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
    clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
    clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
    clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
    clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
    clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
    clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
    clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
    clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp
    clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp
    clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp
    clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
    clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
    clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp
    clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.h
    clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp
    clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
    clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp
    clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.h
    clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp
    clang-tools-extra/clang-tidy/utils/FixItHintUtils.h
    clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
    clang-tools-extra/clang-tidy/utils/IncludeInserter.h
    clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp
    clang-tools-extra/clang-tidy/utils/IncludeSorter.h
    clang-tools-extra/clang-tidy/utils/LexerUtils.cpp
    clang-tools-extra/clang-tidy/utils/LexerUtils.h
    clang-tools-extra/clang-tidy/utils/Matchers.h
    clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp
    clang-tools-extra/clang-tidy/utils/NamespaceAliaser.h
    clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
    clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.h
    clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
    clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
    clang-tools-extra/clang-tidy/utils/TypeTraits.cpp
    clang-tools-extra/clang-tidy/utils/TypeTraits.h
    clang-tools-extra/clang-tidy/utils/UsingInserter.cpp
    clang-tools-extra/clang-tidy/utils/UsingInserter.h
    clang-tools-extra/clangd/AST.cpp
    clang-tools-extra/clangd/AST.h
    clang-tools-extra/clangd/ClangdLSPServer.cpp
    clang-tools-extra/clangd/ClangdLSPServer.h
    clang-tools-extra/clangd/ClangdServer.cpp
    clang-tools-extra/clangd/ClangdServer.h
    clang-tools-extra/clangd/CodeComplete.cpp
    clang-tools-extra/clangd/CodeComplete.h
    clang-tools-extra/clangd/CompileCommands.cpp
    clang-tools-extra/clangd/CompileCommands.h
    clang-tools-extra/clangd/ConfigCompile.cpp
    clang-tools-extra/clangd/Diagnostics.cpp
    clang-tools-extra/clangd/Diagnostics.h
    clang-tools-extra/clangd/DraftStore.cpp
    clang-tools-extra/clangd/DraftStore.h
    clang-tools-extra/clangd/DumpAST.cpp
    clang-tools-extra/clangd/ExpectedTypes.cpp
    clang-tools-extra/clangd/ExpectedTypes.h
    clang-tools-extra/clangd/FS.cpp
    clang-tools-extra/clangd/FS.h
    clang-tools-extra/clangd/FeatureModule.h
    clang-tools-extra/clangd/FindSymbols.cpp
    clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
    clang-tools-extra/clangd/GlobalCompilationDatabase.h
    clang-tools-extra/clangd/HeaderSourceSwitch.cpp
    clang-tools-extra/clangd/HeaderSourceSwitch.h
    clang-tools-extra/clangd/Headers.cpp
    clang-tools-extra/clangd/Headers.h
    clang-tools-extra/clangd/Hover.cpp
    clang-tools-extra/clangd/Hover.h
    clang-tools-extra/clangd/IncludeCleaner.cpp
    clang-tools-extra/clangd/IncludeCleaner.h
    clang-tools-extra/clangd/IncludeFixer.cpp
    clang-tools-extra/clangd/IncludeFixer.h
    clang-tools-extra/clangd/InlayHints.cpp
    clang-tools-extra/clangd/JSONTransport.cpp
    clang-tools-extra/clangd/ParsedAST.cpp
    clang-tools-extra/clangd/ParsedAST.h
    clang-tools-extra/clangd/Protocol.h
    clang-tools-extra/clangd/Quality.cpp
    clang-tools-extra/clangd/Quality.h
    clang-tools-extra/clangd/Selection.cpp
    clang-tools-extra/clangd/SemanticHighlighting.cpp
    clang-tools-extra/clangd/SemanticSelection.cpp
    clang-tools-extra/clangd/SourceCode.cpp
    clang-tools-extra/clangd/SourceCode.h
    clang-tools-extra/clangd/SystemIncludeExtractor.cpp
    clang-tools-extra/clangd/TUScheduler.cpp
    clang-tools-extra/clangd/TUScheduler.h
    clang-tools-extra/clangd/XRefs.cpp
    clang-tools-extra/clangd/XRefs.h
    clang-tools-extra/clangd/index/Background.cpp
    clang-tools-extra/clangd/index/Background.h
    clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp
    clang-tools-extra/clangd/index/BackgroundQueue.cpp
    clang-tools-extra/clangd/index/FileIndex.cpp
    clang-tools-extra/clangd/index/FileIndex.h
    clang-tools-extra/clangd/index/Index.h
    clang-tools-extra/clangd/index/IndexAction.cpp
    clang-tools-extra/clangd/index/Serialization.h
    clang-tools-extra/clangd/index/StdLib.cpp
    clang-tools-extra/clangd/index/StdLib.h
    clang-tools-extra/clangd/index/SymbolCollector.cpp
    clang-tools-extra/clangd/index/SymbolCollector.h
    clang-tools-extra/clangd/index/YAMLSerialization.cpp
    clang-tools-extra/clangd/index/dex/Dex.cpp
    clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
    clang-tools-extra/clangd/index/remote/server/Server.cpp
    clang-tools-extra/clangd/refactor/InsertionPoint.cpp
    clang-tools-extra/clangd/refactor/Rename.cpp
    clang-tools-extra/clangd/refactor/Rename.h
    clang-tools-extra/clangd/refactor/Tweak.h
    clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
    clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
    clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp
    clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
    clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
    clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp
    clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
    clang-tools-extra/clangd/tool/Check.cpp
    clang-tools-extra/clangd/tool/ClangdMain.cpp
    clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
    clang-tools-extra/clangd/unittests/ClangdTests.cpp
    clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
    clang-tools-extra/clangd/unittests/ConfigTesting.h
    clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp
    clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
    clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
    clang-tools-extra/clangd/unittests/HeadersTests.cpp
    clang-tools-extra/clangd/unittests/LSPBinderTests.cpp
    clang-tools-extra/clangd/unittests/LSPClient.cpp
    clang-tools-extra/clangd/unittests/PreambleTests.cpp
    clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
    clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
    clang-tools-extra/clangd/unittests/SymbolInfoTests.cpp
    clang-tools-extra/clangd/unittests/SyncAPI.cpp
    clang-tools-extra/clangd/unittests/SyncAPI.h
    clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
    clang-tools-extra/clangd/unittests/TestFS.cpp
    clang-tools-extra/clangd/unittests/TestFS.h
    clang-tools-extra/clangd/unittests/TestWorkspace.cpp
    clang-tools-extra/clangd/unittests/TestWorkspace.h
    clang-tools-extra/clangd/unittests/XRefsTests.cpp
    clang-tools-extra/clangd/unittests/support/FileCacheTests.cpp
    clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp
    clang-tools-extra/clangd/xpc/XPCTransport.cpp
    clang-tools-extra/docs/clang-tidy/checks/bugprone/unchecked-optional-access.rst
    clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h
    clang-tools-extra/pseudo/lib/DirectiveTree.cpp
    clang-tools-extra/pseudo/lib/Forest.cpp
    clang-tools-extra/pseudo/lib/GLR.cpp
    clang-tools-extra/pseudo/tool/ClangPseudo.cpp
    clang-tools-extra/unittests/clang-tidy/AddConstTest.cpp
    clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
    clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
    clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp

Removed: 
    


################################################################################
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 43ecfd8f0ccce..d055bf369de46 100644
--- a/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp
+++ b/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp
@@ -156,7 +156,7 @@ groupReplacements(const TUReplacements &TUs, const TUDiagnostics &TUDs,
 
   auto AddToGroup = [&](const tooling::Replacement &R,
                         const tooling::TranslationUnitDiagnostics *SourceTU,
-                        const llvm::Optional<std::string> BuildDir) {
+                        const std::optional<std::string> BuildDir) {
     // Use the file manager to deduplicate paths. FileEntries are
     // automatically canonicalized. Since relative paths can come from 
diff erent
     // build directories, make them absolute immediately.

diff  --git a/clang-tools-extra/clang-doc/HTMLGenerator.cpp b/clang-tools-extra/clang-doc/HTMLGenerator.cpp
index 589a3232c90c9..b61780ca4d971 100644
--- a/clang-tools-extra/clang-doc/HTMLGenerator.cpp
+++ b/clang-tools-extra/clang-doc/HTMLGenerator.cpp
@@ -309,7 +309,7 @@ static std::unique_ptr<TagNode> genLink(const Twine &Text, const Twine &Link) {
 
 static std::unique_ptr<HTMLNode>
 genReference(const Reference &Type, StringRef CurrentDirectory,
-             llvm::Optional<StringRef> JumpToSection = std::nullopt) {
+             std::optional<StringRef> JumpToSection = std::nullopt) {
   if (Type.Path.empty()) {
     if (!JumpToSection)
       return std::make_unique<TextNode>(Type.Name);
@@ -438,7 +438,7 @@ genReferencesBlock(const std::vector<Reference> &References,
 
 static std::unique_ptr<TagNode>
 writeFileDefinition(const Location &L,
-                    llvm::Optional<StringRef> RepositoryUrl = std::nullopt) {
+                    std::optional<StringRef> RepositoryUrl = std::nullopt) {
   if (!L.IsFileInRootDir || !RepositoryUrl)
     return std::make_unique<TagNode>(
         HTMLTag::TAG_P, "Defined at line " + std::to_string(L.LineNumber) +

diff  --git a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.cpp b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.cpp
index 2cee43845aaa0..f07e9c95d1077 100644
--- a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.cpp
+++ b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.cpp
@@ -21,7 +21,7 @@
 namespace clang {
 namespace find_all_symbols {
 
-llvm::Optional<SymbolInfo>
+std::optional<SymbolInfo>
 FindAllMacros::CreateMacroSymbol(const Token &MacroNameTok,
                                  const MacroInfo *info) {
   std::string FilePath =

diff  --git a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.h b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.h
index 99a7f5deccdcf..1f13f3ddd15ee 100644
--- a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.h
+++ b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.h
@@ -45,8 +45,8 @@ class FindAllMacros : public clang::PPCallbacks {
   void EndOfMainFile() override;
 
 private:
-  llvm::Optional<SymbolInfo> CreateMacroSymbol(const Token &MacroNameTok,
-                                               const MacroInfo *MD);
+  std::optional<SymbolInfo> CreateMacroSymbol(const Token &MacroNameTok,
+                                              const MacroInfo *MD);
   // Not a callback, just a common path for all usage types.
   void MacroUsed(const Token &Name, const MacroDefinition &MD);
 

diff  --git a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp
index 8608ba74ce9f4..e067414f7d178 100644
--- a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp
+++ b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp
@@ -70,7 +70,7 @@ std::vector<SymbolInfo::Context> GetContexts(const NamedDecl *ND) {
   return Contexts;
 }
 
-llvm::Optional<SymbolInfo>
+std::optional<SymbolInfo>
 CreateSymbolInfo(const NamedDecl *ND, const SourceManager &SM,
                  const HeaderMapCollector *Collector) {
   SymbolInfo::SymbolKind Type;

diff  --git a/clang-tools-extra/clang-query/Query.cpp b/clang-tools-extra/clang-query/Query.cpp
index d1db851c12971..c436d6fa94986 100644
--- a/clang-tools-extra/clang-query/Query.cpp
+++ b/clang-tools-extra/clang-query/Query.cpp
@@ -184,7 +184,7 @@ bool MatchQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const {
     std::vector<BoundNodes> Matches;
     DynTypedMatcher MaybeBoundMatcher = Matcher;
     if (QS.BindRoot) {
-      llvm::Optional<DynTypedMatcher> M = Matcher.tryBind("root");
+      std::optional<DynTypedMatcher> M = Matcher.tryBind("root");
       if (M)
         MaybeBoundMatcher = *M;
     }

diff  --git a/clang-tools-extra/clang-query/QueryParser.cpp b/clang-tools-extra/clang-query/QueryParser.cpp
index 77621d252aeda..41933625a4fa0 100644
--- a/clang-tools-extra/clang-query/QueryParser.cpp
+++ b/clang-tools-extra/clang-query/QueryParser.cpp
@@ -276,7 +276,7 @@ QueryRef QueryParser::doParse() {
     Diagnostics Diag;
     auto MatcherSource = Line.ltrim();
     auto OrigMatcherSource = MatcherSource;
-    Optional<DynTypedMatcher> Matcher = Parser::parseMatcherExpression(
+    std::optional<DynTypedMatcher> Matcher = Parser::parseMatcherExpression(
         MatcherSource, nullptr, &QS.NamedValues, &Diag);
     if (!Matcher) {
       return makeInvalidQueryFromDiagnostics(Diag);

diff  --git a/clang-tools-extra/clang-query/tool/ClangQuery.cpp b/clang-tools-extra/clang-query/tool/ClangQuery.cpp
index 6ba2b1a4412da..da7ac27014480 100644
--- a/clang-tools-extra/clang-query/tool/ClangQuery.cpp
+++ b/clang-tools-extra/clang-query/tool/ClangQuery.cpp
@@ -169,7 +169,7 @@ int main(int argc, const char **argv) {
     LE.setListCompleter([&QS](StringRef Line, size_t Pos) {
       return QueryParser::complete(Line, Pos, QS);
     });
-    while (llvm::Optional<std::string> Line = LE.readLine()) {
+    while (std::optional<std::string> Line = LE.readLine()) {
       QueryRef Q = QueryParser::parse(*Line, QS);
       Q->run(llvm::outs(), QS);
       llvm::outs().flush();

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index 8f90becf8ab2d..498140e5f13a5 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -52,7 +52,7 @@ ClangTidyCheck::OptionsView::OptionsView(
     : NamePrefix((CheckName + ".").str()), CheckOptions(CheckOptions),
       Context(Context) {}
 
-llvm::Optional<StringRef>
+std::optional<StringRef>
 ClangTidyCheck::OptionsView::get(StringRef LocalName) const {
   if (Context->getOptionsCollector())
     Context->getOptionsCollector()->insert((NamePrefix + LocalName).str());
@@ -81,7 +81,7 @@ findPriorityOption(const ClangTidyOptions::OptionMap &Options,
   return IterGlobal;
 }
 
-llvm::Optional<StringRef>
+std::optional<StringRef>
 ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const {
   auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName,
                                  Context->getOptionsCollector());
@@ -90,8 +90,8 @@ ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const {
   return std::nullopt;
 }
 
-static Optional<bool> getAsBool(StringRef Value,
-                                const llvm::Twine &LookupName) {
+static std::optional<bool> getAsBool(StringRef Value,
+                                     const llvm::Twine &LookupName) {
 
   if (std::optional<bool> Parsed = llvm::yaml::parseBool(Value))
     return *Parsed;
@@ -104,9 +104,9 @@ static Optional<bool> getAsBool(StringRef Value,
 }
 
 template <>
-llvm::Optional<bool>
+std::optional<bool>
 ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const {
-  if (llvm::Optional<StringRef> ValueOr = get(LocalName)) {
+  if (std::optional<StringRef> ValueOr = get(LocalName)) {
     if (auto Result = getAsBool(*ValueOr, NamePrefix + LocalName))
       return Result;
     diagnoseBadBooleanOption(NamePrefix + LocalName, *ValueOr);
@@ -115,7 +115,7 @@ ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const {
 }
 
 template <>
-llvm::Optional<bool>
+std::optional<bool>
 ClangTidyCheck::OptionsView::getLocalOrGlobal<bool>(StringRef LocalName) const {
   auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName,
                                  Context->getOptionsCollector());
@@ -146,7 +146,7 @@ void ClangTidyCheck::OptionsView::store<bool>(
   store(Options, LocalName, Value ? StringRef("true") : StringRef("false"));
 }
 
-llvm::Optional<int64_t> ClangTidyCheck::OptionsView::getEnumInt(
+std::optional<int64_t> ClangTidyCheck::OptionsView::getEnumInt(
     StringRef LocalName, ArrayRef<NameAndValue> Mapping, bool CheckGlobal,
     bool IgnoreCase) const {
   if (!CheckGlobal && Context->getOptionsCollector())

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
index f2486eab5dfaa..796b354ec2fa5 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -156,7 +156,7 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
     /// Reads the option with the check-local name \p LocalName from the
     /// ``CheckOptions``. If the corresponding key is not present, return
     /// ``std::nullopt``.
-    llvm::Optional<StringRef> get(StringRef LocalName) const;
+    std::optional<StringRef> get(StringRef LocalName) const;
 
     /// Read a named option from the ``Context``.
     ///
@@ -171,7 +171,7 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
     /// global ``CheckOptions``. Gets local option first. If local is not
     /// present, falls back to get global option. If global option is not
     /// present either, return ``std::nullopt``.
-    llvm::Optional<StringRef> getLocalOrGlobal(StringRef LocalName) const;
+    std::optional<StringRef> getLocalOrGlobal(StringRef LocalName) const;
 
     /// Read a named option from the ``Context``.
     ///
@@ -191,9 +191,9 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
     /// If the corresponding key can't be parsed as a ``T``, emit a
     /// diagnostic and return ``std::nullopt``.
     template <typename T>
-    std::enable_if_t<std::is_integral<T>::value, llvm::Optional<T>>
+    std::enable_if_t<std::is_integral<T>::value, std::optional<T>>
     get(StringRef LocalName) const {
-      if (llvm::Optional<StringRef> Value = get(LocalName)) {
+      if (std::optional<StringRef> Value = get(LocalName)) {
         T Result{};
         if (!StringRef(*Value).getAsInteger(10, Result))
           return Result;
@@ -228,9 +228,9 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
     /// If the corresponding key can't be parsed as a ``T``, emit a
     /// diagnostic and return ``std::nullopt``.
     template <typename T>
-    std::enable_if_t<std::is_integral<T>::value, llvm::Optional<T>>
+    std::enable_if_t<std::is_integral<T>::value, std::optional<T>>
     getLocalOrGlobal(StringRef LocalName) const {
-      llvm::Optional<StringRef> ValueOr = get(LocalName);
+      std::optional<StringRef> ValueOr = get(LocalName);
       bool IsGlobal = false;
       if (!ValueOr) {
         IsGlobal = true;
@@ -275,9 +275,9 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
     /// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
     /// supply the mapping required to convert between ``T`` and a string.
     template <typename T>
-    std::enable_if_t<std::is_enum<T>::value, llvm::Optional<T>>
+    std::enable_if_t<std::is_enum<T>::value, std::optional<T>>
     get(StringRef LocalName, bool IgnoreCase = false) const {
-      if (llvm::Optional<int64_t> ValueOr =
+      if (std::optional<int64_t> ValueOr =
               getEnumInt(LocalName, typeEraseMapping<T>(), false, IgnoreCase))
         return static_cast<T>(*ValueOr);
       return std::nullopt;
@@ -315,9 +315,9 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
     /// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
     /// supply the mapping required to convert between ``T`` and a string.
     template <typename T>
-    std::enable_if_t<std::is_enum<T>::value, llvm::Optional<T>>
+    std::enable_if_t<std::is_enum<T>::value, std::optional<T>>
     getLocalOrGlobal(StringRef LocalName, bool IgnoreCase = false) const {
-      if (llvm::Optional<int64_t> ValueOr =
+      if (std::optional<int64_t> ValueOr =
               getEnumInt(LocalName, typeEraseMapping<T>(), true, IgnoreCase))
         return static_cast<T>(*ValueOr);
       return std::nullopt;
@@ -379,9 +379,9 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
   private:
     using NameAndValue = std::pair<int64_t, StringRef>;
 
-    llvm::Optional<int64_t> getEnumInt(StringRef LocalName,
-                                       ArrayRef<NameAndValue> Mapping,
-                                       bool CheckGlobal, bool IgnoreCase) const;
+    std::optional<int64_t> getEnumInt(StringRef LocalName,
+                                      ArrayRef<NameAndValue> Mapping,
+                                      bool CheckGlobal, bool IgnoreCase) const;
 
     template <typename T>
     std::enable_if_t<std::is_enum<T>::value, std::vector<NameAndValue>>
@@ -434,7 +434,7 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
 /// If the corresponding key can't be parsed as a bool, emit a
 /// diagnostic and return ``std::nullopt``.
 template <>
-llvm::Optional<bool>
+std::optional<bool>
 ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const;
 
 /// Read a named option from the ``Context`` and parse it as a bool.
@@ -446,7 +446,7 @@ ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const;
 /// If the corresponding key can't be parsed as a bool, emit a
 /// diagnostic and return \p Default.
 template <>
-llvm::Optional<bool>
+std::optional<bool>
 ClangTidyCheck::OptionsView::getLocalOrGlobal<bool>(StringRef LocalName) const;
 
 /// Stores an option with the check-local name \p LocalName with

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
index 05ca2573dc4ea..558190e5e13b5 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -256,7 +256,7 @@ void ClangTidyContext::setProfileStoragePrefix(StringRef Prefix) {
   ProfilePrefix = std::string(Prefix);
 }
 
-llvm::Optional<ClangTidyProfiling::StorageParams>
+std::optional<ClangTidyProfiling::StorageParams>
 ClangTidyContext::getProfileStorageParams() const {
   if (ProfilePrefix.empty())
     return std::nullopt;

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
index 475f38d334caf..ac5e896bcb851 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
@@ -170,7 +170,7 @@ class ClangTidyContext {
 
   /// Control storage of profile date.
   void setProfileStoragePrefix(StringRef ProfilePrefix);
-  llvm::Optional<ClangTidyProfiling::StorageParams>
+  std::optional<ClangTidyProfiling::StorageParams>
   getProfileStorageParams() const;
 
   /// Should be called when starting to process new translation unit.

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
index cf790f9f579a1..43001a37f2f8a 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -290,7 +290,7 @@ void FileOptionsBaseProvider::addRawFileOptions(
   StringRef Path = llvm::sys::path::parent_path(AbsolutePath);
   for (StringRef CurrentPath = Path; !CurrentPath.empty();
        CurrentPath = llvm::sys::path::parent_path(CurrentPath)) {
-    llvm::Optional<OptionsSource> Result;
+    std::optional<OptionsSource> Result;
 
     auto Iter = CachedOptions.find(CurrentPath);
     if (Iter != CachedOptions.end())
@@ -360,7 +360,7 @@ FileOptionsProvider::getRawOptions(StringRef FileName) {
   return RawOptions;
 }
 
-llvm::Optional<OptionsSource>
+std::optional<OptionsSource>
 FileOptionsBaseProvider::tryReadConfigFile(StringRef Directory) {
   assert(!Directory.empty());
 

diff  --git a/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp b/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp
index 0cfdda3b5dedd..32465a4dc0ba1 100644
--- a/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp
+++ b/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp
@@ -40,7 +40,7 @@ class ExpandModularHeadersPPCallbacks::FileRecorder {
       return;
 
     // FIXME: Why is this happening? We might be losing contents here.
-    llvm::Optional<StringRef> Data = ContentCache.getBufferDataIfLoaded();
+    std::optional<StringRef> Data = ContentCache.getBufferDataIfLoaded();
     if (!Data)
       return;
 

diff  --git a/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp b/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp
index 7a822cd55bed4..7c9f4a0b121f4 100644
--- a/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp
+++ b/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp
@@ -46,8 +46,8 @@ enum class NoLintType { NoLint, NoLintNextLine, NoLintBegin, NoLintEnd };
 
 // Convert a string like "NOLINTNEXTLINE" to its enum `Type::NoLintNextLine`.
 // Return `std::nullopt` if the string is unrecognized.
-static Optional<NoLintType> strToNoLintType(StringRef Str) {
-  auto Type = llvm::StringSwitch<Optional<NoLintType>>(Str)
+static std::optional<NoLintType> strToNoLintType(StringRef Str) {
+  auto Type = llvm::StringSwitch<std::optional<NoLintType>>(Str)
                   .Case("NOLINT", NoLintType::NoLint)
                   .Case("NOLINTNEXTLINE", NoLintType::NoLintNextLine)
                   .Case("NOLINTBEGIN", NoLintType::NoLintBegin)
@@ -82,7 +82,8 @@ class NoLintToken {
   //   to NOLINT(*).
   // - An empty string means nothing is suppressed - equivalent to NOLINT().
   // - Negative globs ignored (which would effectively disable the suppression).
-  NoLintToken(NoLintType Type, size_t Pos, const Optional<std::string> &Checks)
+  NoLintToken(NoLintType Type, size_t Pos,
+              const std::optional<std::string> &Checks)
       : Type(Type), Pos(Pos), ChecksGlob(std::make_unique<CachedGlobList>(
                                   Checks.value_or("*"),
                                   /*KeepNegativeGlobs=*/false)) {
@@ -97,13 +98,13 @@ class NoLintToken {
   size_t Pos;
 
   // If this NOLINT specifies checks, return the checks.
-  Optional<std::string> checks() const { return Checks; }
+  std::optional<std::string> checks() const { return Checks; }
 
   // Whether this NOLINT applies to the provided check.
   bool suppresses(StringRef Check) const { return ChecksGlob->contains(Check); }
 
 private:
-  Optional<std::string> Checks;
+  std::optional<std::string> Checks;
   std::unique_ptr<CachedGlobList> ChecksGlob;
 };
 
@@ -128,13 +129,13 @@ static SmallVector<NoLintToken> getNoLints(StringRef Buffer) {
       ++Pos;
 
     // Is this a recognized NOLINT type?
-    const Optional<NoLintType> NoLintType =
+    const std::optional<NoLintType> NoLintType =
         strToNoLintType(Buffer.slice(NoLintPos, Pos));
     if (!NoLintType)
       continue;
 
     // Get checks, if specified.
-    Optional<std::string> Checks;
+    std::optional<std::string> Checks;
     if (Pos < Buffer.size() && Buffer[Pos] == '(') {
       size_t ClosingBracket = Buffer.find_first_of("\n)", ++Pos);
       if (ClosingBracket != StringRef::npos && Buffer[ClosingBracket] == ')') {
@@ -305,8 +306,8 @@ static bool withinNoLintBlock(ArrayRef<NoLintBlockToken> NoLintBlocks,
 }
 
 // Get the file contents as a string.
-static Optional<StringRef> getBuffer(const SourceManager &SrcMgr, FileID File,
-                                     bool AllowIO) {
+static std::optional<StringRef> getBuffer(const SourceManager &SrcMgr,
+                                          FileID File, bool AllowIO) {
   return AllowIO ? SrcMgr.getBufferDataOrNone(File)
                  : SrcMgr.getBufferDataIfLoaded(File);
 }
@@ -326,12 +327,12 @@ bool NoLintDirectiveHandler::Impl::diagHasNoLint(
 
   // We will only see NOLINTs in user-authored sources. No point reading the
   // file if it is a <built-in>.
-  Optional<StringRef> FileName = SrcMgr.getNonBuiltinFilenameForID(File);
+  std::optional<StringRef> FileName = SrcMgr.getNonBuiltinFilenameForID(File);
   if (!FileName)
     return false;
 
   // Get file contents.
-  Optional<StringRef> Buffer = getBuffer(SrcMgr, File, AllowIO);
+  std::optional<StringRef> Buffer = getBuffer(SrcMgr, File, AllowIO);
   if (!Buffer)
     return false;
 

diff  --git a/clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.cpp
index 585b7c1310e26..edf6a174ef525 100644
--- a/clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.cpp
@@ -39,7 +39,7 @@ void DurationAdditionCheck::check(const MatchFinder::MatchResult &Result) {
   if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid())
     return;
 
-  llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(
+  std::optional<DurationScale> Scale = getScaleForTimeInverse(
       Result.Nodes.getNodeAs<clang::FunctionDecl>("function_decl")->getName());
   if (!Scale)
     return;

diff  --git a/clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.cpp
index 39c7ba4fc9b4a..859aad7a579db 100644
--- a/clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.cpp
@@ -31,7 +31,7 @@ void DurationComparisonCheck::registerMatchers(MatchFinder *Finder) {
 void DurationComparisonCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *Binop = Result.Nodes.getNodeAs<BinaryOperator>("binop");
 
-  llvm::Optional<DurationScale> Scale = getScaleForDurationInverse(
+  std::optional<DurationScale> Scale = getScaleForDurationInverse(
       Result.Nodes.getNodeAs<FunctionDecl>("function_decl")->getName());
   if (!Scale)
     return;

diff  --git a/clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.cpp
index 3a83e6707efc1..328f6f13b80b3 100644
--- a/clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.cpp
@@ -45,7 +45,7 @@ void DurationConversionCastCheck::check(
   const auto *Arg = Result.Nodes.getNodeAs<Expr>("arg");
   StringRef ConversionFuncName = FuncDecl->getName();
 
-  llvm::Optional<DurationScale> Scale =
+  std::optional<DurationScale> Scale =
       getScaleForDurationInverse(ConversionFuncName);
   if (!Scale)
     return;

diff  --git a/clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp
index 09512347accab..fcb4a8550a6a8 100644
--- a/clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp
@@ -55,7 +55,7 @@ void DurationFactoryFloatCheck::check(const MatchFinder::MatchResult &Result) {
   if (Arg->getBeginLoc().isMacroID())
     return;
 
-  llvm::Optional<std::string> SimpleArg = stripFloatCast(Result, *Arg);
+  std::optional<std::string> SimpleArg = stripFloatCast(Result, *Arg);
   if (!SimpleArg)
     SimpleArg = stripFloatLiteralFraction(Result, *Arg);
 

diff  --git a/clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp
index b33f1e364a669..24b3f56d2b455 100644
--- a/clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp
@@ -22,9 +22,9 @@ namespace abseil {
 // Given the name of a duration factory function, return the appropriate
 // `DurationScale` for that factory.  If no factory can be found for
 // `FactoryName`, return `std::nullopt`.
-static llvm::Optional<DurationScale>
+static std::optional<DurationScale>
 getScaleForFactory(llvm::StringRef FactoryName) {
-  return llvm::StringSwitch<llvm::Optional<DurationScale>>(FactoryName)
+  return llvm::StringSwitch<std::optional<DurationScale>>(FactoryName)
       .Case("Nanoseconds", DurationScale::Nanoseconds)
       .Case("Microseconds", DurationScale::Microseconds)
       .Case("Milliseconds", DurationScale::Milliseconds)
@@ -48,7 +48,7 @@ static double getValue(const IntegerLiteral *IntLit,
 // Given the scale of a duration and a `Multiplier`, determine if `Multiplier`
 // would produce a new scale.  If so, return a tuple containing the new scale
 // and a suitable Multiplier for that scale, otherwise `std::nullopt`.
-static llvm::Optional<std::tuple<DurationScale, double>>
+static std::optional<std::tuple<DurationScale, double>>
 getNewScaleSingleStep(DurationScale OldScale, double Multiplier) {
   switch (OldScale) {
   case DurationScale::Hours:
@@ -95,10 +95,10 @@ getNewScaleSingleStep(DurationScale OldScale, double Multiplier) {
 
 // Given the scale of a duration and a `Multiplier`, determine if `Multiplier`
 // would produce a new scale.  If so, return it, otherwise `std::nullopt`.
-static llvm::Optional<DurationScale> getNewScale(DurationScale OldScale,
-                                                 double Multiplier) {
+static std::optional<DurationScale> getNewScale(DurationScale OldScale,
+                                                double Multiplier) {
   while (Multiplier != 1.0) {
-    llvm::Optional<std::tuple<DurationScale, double>> Result =
+    std::optional<std::tuple<DurationScale, double>> Result =
         getNewScaleSingleStep(OldScale, Multiplier);
     if (!Result)
       break;
@@ -155,14 +155,14 @@ void DurationFactoryScaleCheck::check(const MatchFinder::MatchResult &Result) {
   }
 
   const auto *CallDecl = Result.Nodes.getNodeAs<FunctionDecl>("call_decl");
-  llvm::Optional<DurationScale> MaybeScale =
+  std::optional<DurationScale> MaybeScale =
       getScaleForFactory(CallDecl->getName());
   if (!MaybeScale)
     return;
 
   DurationScale Scale = *MaybeScale;
   const Expr *Remainder;
-  llvm::Optional<DurationScale> NewScale;
+  std::optional<DurationScale> NewScale;
 
   // We next handle the cases of multiplication and division.
   if (const auto *MultBinOp =
@@ -195,7 +195,7 @@ void DurationFactoryScaleCheck::check(const MatchFinder::MatchResult &Result) {
     // For division, we only check the RHS.
     const auto *FloatLit = llvm::cast<FloatingLiteral>(DivBinOp->getRHS());
 
-    llvm::Optional<DurationScale> NewScale =
+    std::optional<DurationScale> NewScale =
         getNewScale(Scale, 1.0 / FloatLit->getValueAsApproximateDouble());
     if (NewScale) {
       const Expr *Remainder = DivBinOp->getLHS();

diff  --git a/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp b/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp
index c2325c11e2adc..d96093fdd8d2b 100644
--- a/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp
@@ -27,7 +27,7 @@ struct DurationScale2IndexFunctor {
 };
 
 /// Returns an integer if the fractional part of a `FloatingLiteral` is `0`.
-static llvm::Optional<llvm::APSInt>
+static std::optional<llvm::APSInt>
 truncateIfIntegral(const FloatingLiteral &FloatLiteral) {
   double Value = FloatLiteral.getValueAsApproximateDouble();
   if (std::fmod(Value, 1) == 0) {
@@ -70,7 +70,7 @@ getDurationInverseForScale(DurationScale Scale) {
 
 /// If `Node` is a call to the inverse of `Scale`, return that inverse's
 /// argument, otherwise std::nullopt.
-static llvm::Optional<std::string>
+static std::optional<std::string>
 rewriteInverseDurationCall(const MatchFinder::MatchResult &Result,
                            DurationScale Scale, const Expr &Node) {
   const std::pair<llvm::StringRef, llvm::StringRef> &InverseFunctions =
@@ -89,7 +89,7 @@ rewriteInverseDurationCall(const MatchFinder::MatchResult &Result,
 
 /// If `Node` is a call to the inverse of `Scale`, return that inverse's
 /// argument, otherwise std::nullopt.
-static llvm::Optional<std::string>
+static std::optional<std::string>
 rewriteInverseTimeCall(const MatchFinder::MatchResult &Result,
                        DurationScale Scale, const Expr &Node) {
   llvm::StringRef InverseFunction = getTimeInverseForScale(Scale);
@@ -185,7 +185,7 @@ bool isLiteralZero(const MatchFinder::MatchResult &Result, const Expr &Node) {
   return false;
 }
 
-llvm::Optional<std::string>
+std::optional<std::string>
 stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result,
                const Expr &Node) {
   if (const Expr *MaybeCastArg = selectFirst<const Expr>(
@@ -205,12 +205,12 @@ stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result,
   return std::nullopt;
 }
 
-llvm::Optional<std::string>
+std::optional<std::string>
 stripFloatLiteralFraction(const MatchFinder::MatchResult &Result,
                           const Expr &Node) {
   if (const auto *LitFloat = llvm::dyn_cast<FloatingLiteral>(&Node))
     // Attempt to simplify a `Duration` factory call with a literal argument.
-    if (llvm::Optional<llvm::APSInt> IntValue = truncateIfIntegral(*LitFloat))
+    if (std::optional<llvm::APSInt> IntValue = truncateIfIntegral(*LitFloat))
       return toString(*IntValue, /*radix=*/10);
 
   return std::nullopt;
@@ -219,11 +219,11 @@ stripFloatLiteralFraction(const MatchFinder::MatchResult &Result,
 std::string simplifyDurationFactoryArg(const MatchFinder::MatchResult &Result,
                                        const Expr &Node) {
   // Check for an explicit cast to `float` or `double`.
-  if (llvm::Optional<std::string> MaybeArg = stripFloatCast(Result, Node))
+  if (std::optional<std::string> MaybeArg = stripFloatCast(Result, Node))
     return *MaybeArg;
 
   // Check for floats without fractional components.
-  if (llvm::Optional<std::string> MaybeArg =
+  if (std::optional<std::string> MaybeArg =
           stripFloatLiteralFraction(Result, Node))
     return *MaybeArg;
 
@@ -231,7 +231,7 @@ std::string simplifyDurationFactoryArg(const MatchFinder::MatchResult &Result,
   return tooling::fixit::getText(Node, *Result.Context).str();
 }
 
-llvm::Optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name) {
+std::optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name) {
   static const llvm::StringMap<DurationScale> ScaleMap(
       {{"ToDoubleHours", DurationScale::Hours},
        {"ToInt64Hours", DurationScale::Hours},
@@ -253,7 +253,7 @@ llvm::Optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name) {
   return ScaleIter->second;
 }
 
-llvm::Optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name) {
+std::optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name) {
   static const llvm::StringMap<DurationScale> ScaleMap(
       {{"ToUnixHours", DurationScale::Hours},
        {"ToUnixMinutes", DurationScale::Minutes},
@@ -275,7 +275,7 @@ std::string rewriteExprFromNumberToDuration(
   const Expr &RootNode = *Node->IgnoreParenImpCasts();
 
   // First check to see if we can undo a complementary function call.
-  if (llvm::Optional<std::string> MaybeRewrite =
+  if (std::optional<std::string> MaybeRewrite =
           rewriteInverseDurationCall(Result, Scale, RootNode))
     return *MaybeRewrite;
 
@@ -293,7 +293,7 @@ std::string rewriteExprFromNumberToTime(
   const Expr &RootNode = *Node->IgnoreParenImpCasts();
 
   // First check to see if we can undo a complementary function call.
-  if (llvm::Optional<std::string> MaybeRewrite =
+  if (std::optional<std::string> MaybeRewrite =
           rewriteInverseTimeCall(Result, Scale, RootNode))
     return *MaybeRewrite;
 

diff  --git a/clang-tools-extra/clang-tidy/abseil/DurationRewriter.h b/clang-tools-extra/clang-tidy/abseil/DurationRewriter.h
index a23dfaf9bcef4..c73418886a675 100644
--- a/clang-tools-extra/clang-tidy/abseil/DurationRewriter.h
+++ b/clang-tools-extra/clang-tidy/abseil/DurationRewriter.h
@@ -44,7 +44,7 @@ bool isLiteralZero(const ast_matchers::MatchFinder::MatchResult &Result,
 ///
 /// If `Node` represents an explicit cast to a floating point type, return
 /// the textual context of the cast argument, otherwise `std::nullopt`.
-llvm::Optional<std::string>
+std::optional<std::string>
 stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result,
                const Expr &Node);
 
@@ -52,7 +52,7 @@ stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result,
 ///
 /// If `Node` represents a floating point literal with a zero fractional part,
 /// return the textual context of the integral part, otherwise `std::nullopt`.
-llvm::Optional<std::string>
+std::optional<std::string>
 stripFloatLiteralFraction(const ast_matchers::MatchFinder::MatchResult &Result,
                           const Expr &Node);
 
@@ -65,11 +65,11 @@ simplifyDurationFactoryArg(const ast_matchers::MatchFinder::MatchResult &Result,
 
 /// Given the name of an inverse Duration function (e.g., `ToDoubleSeconds`),
 /// return its `DurationScale`, or `std::nullopt` if a match is not found.
-llvm::Optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name);
+std::optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name);
 
 /// Given the name of an inverse Time function (e.g., `ToUnixSeconds`),
 /// return its `DurationScale`, or `std::nullopt` if a match is not found.
-llvm::Optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name);
+std::optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name);
 
 /// Given a `Scale` return the fully qualified inverse functions for it.
 /// The first returned value is the inverse for `double`, and the second

diff  --git a/clang-tools-extra/clang-tidy/abseil/DurationSubtractionCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationSubtractionCheck.cpp
index 4d12fd337ace5..21425b4f6fa7a 100644
--- a/clang-tools-extra/clang-tidy/abseil/DurationSubtractionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/DurationSubtractionCheck.cpp
@@ -38,7 +38,7 @@ void DurationSubtractionCheck::check(const MatchFinder::MatchResult &Result) {
   if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid())
     return;
 
-  llvm::Optional<DurationScale> Scale =
+  std::optional<DurationScale> Scale =
       getScaleForDurationInverse(FuncDecl->getName());
   if (!Scale)
     return;

diff  --git a/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp b/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
index 36e670ea8c36d..02d96dbd402aa 100644
--- a/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
@@ -22,8 +22,8 @@ namespace {
 
 AST_MATCHER(StringLiteral, lengthIsOne) { return Node.getLength() == 1; }
 
-llvm::Optional<std::string> makeCharacterLiteral(const StringLiteral *Literal,
-                                                 const ASTContext &Context) {
+std::optional<std::string> makeCharacterLiteral(const StringLiteral *Literal,
+                                                const ASTContext &Context) {
   assert(Literal->getLength() == 1 &&
          "Only single character string should be matched");
   assert(Literal->getCharByteWidth() == 1 &&
@@ -106,7 +106,7 @@ void FasterStrsplitDelimiterCheck::check(
   if (Literal->getBeginLoc().isMacroID() || Literal->getEndLoc().isMacroID())
     return;
 
-  llvm::Optional<std::string> Replacement =
+  std::optional<std::string> Replacement =
       makeCharacterLiteral(Literal, *Result.Context);
   if (!Replacement)
     return;

diff  --git a/clang-tools-extra/clang-tidy/abseil/TimeComparisonCheck.cpp b/clang-tools-extra/clang-tidy/abseil/TimeComparisonCheck.cpp
index ddbde758684f3..fa6fcd877b799 100644
--- a/clang-tools-extra/clang-tidy/abseil/TimeComparisonCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/TimeComparisonCheck.cpp
@@ -32,7 +32,7 @@ void TimeComparisonCheck::registerMatchers(MatchFinder *Finder) {
 void TimeComparisonCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *Binop = Result.Nodes.getNodeAs<BinaryOperator>("binop");
 
-  llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(
+  std::optional<DurationScale> Scale = getScaleForTimeInverse(
       Result.Nodes.getNodeAs<FunctionDecl>("function_decl")->getName());
   if (!Scale)
     return;

diff  --git a/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp b/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp
index 9f2fba454cbdd..7e8a94e0ecb45 100644
--- a/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp
@@ -97,7 +97,7 @@ void TimeSubtractionCheck::registerMatchers(MatchFinder *Finder) {
   for (const char *ScaleName :
        {"Hours", "Minutes", "Seconds", "Millis", "Micros", "Nanos"}) {
     std::string TimeInverse = (llvm::Twine("ToUnix") + ScaleName).str();
-    llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(TimeInverse);
+    std::optional<DurationScale> Scale = getScaleForTimeInverse(TimeInverse);
     assert(Scale && "Unknown scale encountered");
 
     auto TimeInverseMatcher = callExpr(callee(
@@ -135,7 +135,7 @@ void TimeSubtractionCheck::check(const MatchFinder::MatchResult &Result) {
   if (insideMacroDefinition(Result, BinOp->getSourceRange()))
     return;
 
-  llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(InverseName);
+  std::optional<DurationScale> Scale = getScaleForTimeInverse(InverseName);
   if (!Scale)
     return;
 

diff  --git a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
index 2676540ab2c58..5b6da9a524816 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
@@ -35,7 +35,7 @@ void BadSignalToKillThreadCheck::check(const MatchFinder::MatchResult &Result) {
            KeyValue.first->hasMacroDefinition();
   };
   const auto TryExpandAsInteger =
-      [](Preprocessor::macro_iterator It) -> Optional<unsigned> {
+      [](Preprocessor::macro_iterator It) -> std::optional<unsigned> {
     if (It == PP->macro_end())
       return std::nullopt;
     const MacroInfo *MI = PP->getMacroInfo(It->first);

diff  --git a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h
index 3a5919d5121a1..f3f7f88c3c0eb 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h
@@ -28,7 +28,7 @@ class BadSignalToKillThreadCheck : public ClangTidyCheck {
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
   void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
                            Preprocessor *ModuleExpanderPP) override;
-  Optional<unsigned> SigtermValue;
+  std::optional<unsigned> SigtermValue;
 };
 
 } // namespace bugprone

diff  --git a/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp
index 23244dceefdab..2c525ec1e5a5e 100644
--- a/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp
@@ -953,7 +953,7 @@ static inline bool isDerivedToBase(const CXXRecordDecl *Derived,
          Base->isCompleteDefinition() && Derived->isDerivedFrom(Base);
 }
 
-static Optional<QualType>
+static std::optional<QualType>
 approximateStandardConversionSequence(const TheCheck &Check, QualType From,
                                       QualType To, const ASTContext &Ctx) {
   LLVM_DEBUG(llvm::dbgs() << ">>> approximateStdConv for LType:\n";
@@ -1128,7 +1128,7 @@ class UserDefinedConversionSelector {
 
   /// Selects the best conversion function that is applicable from the
   /// prepared set of potential conversion functions taken.
-  Optional<PreparedConversion> operator()() const {
+  std::optional<PreparedConversion> operator()() const {
     if (FlaggedConversions.empty()) {
       LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Empty.\n");
       return {};
@@ -1138,7 +1138,7 @@ class UserDefinedConversionSelector {
       return FlaggedConversions.front();
     }
 
-    Optional<PreparedConversion> BestConversion;
+    std::optional<PreparedConversion> BestConversion;
     unsigned short HowManyGoodConversions = 0;
     for (const auto &Prepared : FlaggedConversions) {
       LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Candidate flags: "
@@ -1192,7 +1192,7 @@ class UserDefinedConversionSelector {
 
 } // namespace
 
-static Optional<ConversionSequence>
+static std::optional<ConversionSequence>
 tryConversionOperators(const TheCheck &Check, const CXXRecordDecl *RD,
                        QualType ToType) {
   if (!RD || !RD->isCompleteDefinition())
@@ -1218,7 +1218,7 @@ tryConversionOperators(const TheCheck &Check, const CXXRecordDecl *RD,
     ConversionSet.addConversion(Con, Con->getConversionType(), ToType);
   }
 
-  if (Optional<UserDefinedConversionSelector::PreparedConversion>
+  if (std::optional<UserDefinedConversionSelector::PreparedConversion>
           SelectedConversion = ConversionSet()) {
     QualType RecordType{RD->getTypeForDecl(), 0};
 
@@ -1243,7 +1243,7 @@ tryConversionOperators(const TheCheck &Check, const CXXRecordDecl *RD,
   return {};
 }
 
-static Optional<ConversionSequence>
+static std::optional<ConversionSequence>
 tryConvertingConstructors(const TheCheck &Check, QualType FromType,
                           const CXXRecordDecl *RD) {
   if (!RD || !RD->isCompleteDefinition())
@@ -1269,7 +1269,7 @@ tryConvertingConstructors(const TheCheck &Check, QualType FromType,
     ConversionSet.addConversion(Con, FromType, Con->getParamDecl(0)->getType());
   }
 
-  if (Optional<UserDefinedConversionSelector::PreparedConversion>
+  if (std::optional<UserDefinedConversionSelector::PreparedConversion>
           SelectedConversion = ConversionSet()) {
     QualType RecordType{RD->getTypeForDecl(), 0};
 
@@ -1324,7 +1324,7 @@ approximateImplicitConversion(const TheCheck &Check, QualType LType,
   ConversionSequence ImplicitSeq{LType, RType};
   QualType WorkType = LType;
 
-  Optional<QualType> AfterFirstStdConv =
+  std::optional<QualType> AfterFirstStdConv =
       approximateStandardConversionSequence(Check, LType, RType, Ctx);
   if (AfterFirstStdConv) {
     LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Standard "
@@ -1344,7 +1344,7 @@ approximateImplicitConversion(const TheCheck &Check, QualType LType,
     bool FoundConversionOperator = false, FoundConvertingCtor = false;
 
     if (const auto *LRD = WorkType->getAsCXXRecordDecl()) {
-      Optional<ConversionSequence> ConversionOperatorResult =
+      std::optional<ConversionSequence> ConversionOperatorResult =
           tryConversionOperators(Check, LRD, RType);
       if (ConversionOperatorResult) {
         LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Found "
@@ -1359,7 +1359,7 @@ approximateImplicitConversion(const TheCheck &Check, QualType LType,
       // Use the original "LType" here, and not WorkType, because the
       // conversion to the converting constructors' parameters will be
       // modelled in the recursive call.
-      Optional<ConversionSequence> ConvCtorResult =
+      std::optional<ConversionSequence> ConvCtorResult =
           tryConvertingConstructors(Check, LType, RRD);
       if (ConvCtorResult) {
         LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Found "
@@ -1676,7 +1676,7 @@ class PassedToSameFunction {
       if (!CalledFn)
         continue;
 
-      llvm::Optional<unsigned> TargetIdx;
+      std::optional<unsigned> TargetIdx;
       unsigned NumFnParams = CalledFn->getNumParams();
       for (unsigned Idx = 0; Idx < NumFnParams; ++Idx)
         if (CalledFn->getParamDecl(Idx) == PassedToParam)

diff  --git a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp
index 601949bfb16a8..e09092d842d49 100644
--- a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp
@@ -60,7 +60,7 @@ void ImplicitWideningOfMultiplicationResultCheck::storeOptions(
   Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
 }
 
-llvm::Optional<FixItHint>
+std::optional<FixItHint>
 ImplicitWideningOfMultiplicationResultCheck::includeStddefHeader(
     SourceLocation File) {
   return IncludeInserter.createIncludeInsertion(

diff  --git a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.h b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.h
index 74152efa47366..ed68bb6cea767 100644
--- a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.h
@@ -26,7 +26,7 @@ class ImplicitWideningOfMultiplicationResultCheck : public ClangTidyCheck {
   bool ShouldUseCXXStaticCast;
   bool ShouldUseCXXHeader;
 
-  llvm::Optional<FixItHint> includeStddefHeader(SourceLocation File);
+  std::optional<FixItHint> includeStddefHeader(SourceLocation File);
 
   void handleImplicitCastExpr(const ImplicitCastExpr *ICE);
   void handlePointerOffsetting(const Expr *E);

diff  --git a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
index ce58f1e50f0e9..35f12d25e9587 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
@@ -676,15 +676,15 @@ void NotNullTerminatedResultCheck::registerMatchers(MatchFinder *Finder) {
   //===--------------------------------------------------------------------===//
 
   struct CallContext {
-    CallContext(StringRef Name, Optional<unsigned> DestinationPos,
-                Optional<unsigned> SourcePos, unsigned LengthPos,
+    CallContext(StringRef Name, std::optional<unsigned> DestinationPos,
+                std::optional<unsigned> SourcePos, unsigned LengthPos,
                 bool WithIncrease)
         : Name(Name), DestinationPos(DestinationPos), SourcePos(SourcePos),
           LengthPos(LengthPos), WithIncrease(WithIncrease){};
 
     StringRef Name;
-    Optional<unsigned> DestinationPos;
-    Optional<unsigned> SourcePos;
+    std::optional<unsigned> DestinationPos;
+    std::optional<unsigned> SourcePos;
     unsigned LengthPos;
     bool WithIncrease;
   };
@@ -797,7 +797,7 @@ void NotNullTerminatedResultCheck::check(
     return;
 
   if (WantToUseSafeFunctions && PP->isMacroDefined("__STDC_LIB_EXT1__")) {
-    Optional<bool> AreSafeFunctionsWanted;
+    std::optional<bool> AreSafeFunctionsWanted;
 
     Preprocessor::macro_iterator It = PP->macro_begin();
     while (It != PP->macro_end() && !AreSafeFunctionsWanted) {

diff  --git a/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp
index 560e9a157b467..c6409c0fc2da4 100644
--- a/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp
@@ -69,7 +69,7 @@ static bool hasReservedDoubleUnderscore(StringRef Name,
   return Name.startswith("__");
 }
 
-static Optional<std::string>
+static std::optional<std::string>
 getDoubleUnderscoreFixup(StringRef Name, const LangOptions &LangOpts) {
   if (hasReservedDoubleUnderscore(Name, LangOpts))
     return collapseConsecutive(Name, '_');
@@ -80,7 +80,7 @@ static bool startsWithUnderscoreCapital(StringRef Name) {
   return Name.size() >= 2 && Name[0] == '_' && std::isupper(Name[1]);
 }
 
-static Optional<std::string> getUnderscoreCapitalFixup(StringRef Name) {
+static std::optional<std::string> getUnderscoreCapitalFixup(StringRef Name) {
   if (startsWithUnderscoreCapital(Name))
     return std::string(Name.drop_front(1));
   return std::nullopt;
@@ -91,7 +91,7 @@ static bool startsWithUnderscoreInGlobalNamespace(StringRef Name,
   return IsInGlobalNamespace && Name.size() >= 1 && Name[0] == '_';
 }
 
-static Optional<std::string>
+static std::optional<std::string>
 getUnderscoreGlobalNamespaceFixup(StringRef Name, bool IsInGlobalNamespace) {
   if (startsWithUnderscoreInGlobalNamespace(Name, IsInGlobalNamespace))
     return std::string(Name.drop_front(1));
@@ -107,7 +107,7 @@ static std::string getNonReservedFixup(std::string Name) {
   return Name;
 }
 
-static Optional<RenamerClangTidyCheck::FailureInfo>
+static std::optional<RenamerClangTidyCheck::FailureInfo>
 getFailureInfoImpl(StringRef Name, bool IsInGlobalNamespace,
                    const LangOptions &LangOpts, bool Invert,
                    ArrayRef<StringRef> AllowedIdentifiers) {
@@ -121,7 +121,7 @@ getFailureInfoImpl(StringRef Name, bool IsInGlobalNamespace,
 
   using FailureInfo = RenamerClangTidyCheck::FailureInfo;
   if (!Invert) {
-    Optional<FailureInfo> Info;
+    std::optional<FailureInfo> Info;
     auto AppendFailure = [&](StringRef Kind, std::string &&Fixup) {
       if (!Info) {
         Info = FailureInfo{std::string(Kind), std::move(Fixup)};
@@ -153,7 +153,7 @@ getFailureInfoImpl(StringRef Name, bool IsInGlobalNamespace,
   return std::nullopt;
 }
 
-Optional<RenamerClangTidyCheck::FailureInfo>
+std::optional<RenamerClangTidyCheck::FailureInfo>
 ReservedIdentifierCheck::getDeclFailureInfo(const NamedDecl *Decl,
                                             const SourceManager &) const {
   assert(Decl && Decl->getIdentifier() && !Decl->getName().empty() &&
@@ -164,7 +164,7 @@ ReservedIdentifierCheck::getDeclFailureInfo(const NamedDecl *Decl,
                             getLangOpts(), Invert, AllowedIdentifiers);
 }
 
-Optional<RenamerClangTidyCheck::FailureInfo>
+std::optional<RenamerClangTidyCheck::FailureInfo>
 ReservedIdentifierCheck::getMacroFailureInfo(const Token &MacroNameTok,
                                              const SourceManager &) const {
   return getFailureInfoImpl(MacroNameTok.getIdentifierInfo()->getName(), true,

diff  --git a/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.h b/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.h
index 99c1dbe3363eb..f7a8c4ccbe355 100644
--- a/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.h
@@ -41,10 +41,10 @@ class ReservedIdentifierCheck final : public RenamerClangTidyCheck {
   void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
 
 private:
-  llvm::Optional<FailureInfo>
+  std::optional<FailureInfo>
   getDeclFailureInfo(const NamedDecl *Decl,
                      const SourceManager &SM) const override;
-  llvm::Optional<FailureInfo>
+  std::optional<FailureInfo>
   getMacroFailureInfo(const Token &MacroNameTok,
                       const SourceManager &SM) const override;
   DiagInfo getDiagInfo(const NamingCheckId &ID,

diff  --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp
index 177882777f07d..f3d2e3d7d1ffd 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp
@@ -81,7 +81,7 @@ void SuspiciousIncludePPCallbacks::InclusionDirective(
 
   SourceLocation DiagLoc = FilenameRange.getBegin().getLocWithOffset(1);
 
-  const Optional<StringRef> IFE =
+  const std::optional<StringRef> IFE =
       utils::getFileExtension(FileName, Check.ImplementationFileExtensions);
   if (!IFE)
     return;

diff  --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp
index a1d04dc966adb..57d0ff62b4c12 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp
@@ -17,8 +17,8 @@ namespace clang {
 namespace tidy {
 namespace bugprone {
 
-static llvm::Optional<uint64_t> tryEvaluateSizeExpr(const Expr *SizeExpr,
-                                                    const ASTContext &Ctx) {
+static std::optional<uint64_t> tryEvaluateSizeExpr(const Expr *SizeExpr,
+                                                   const ASTContext &Ctx) {
   Expr::EvalResult Result;
   if (SizeExpr->EvaluateAsRValue(Result, Ctx))
     return Ctx.toBits(
@@ -42,7 +42,7 @@ void SuspiciousMemoryComparisonCheck::check(
 
   const Expr *SizeExpr = CE->getArg(2);
   assert(SizeExpr != nullptr && "Third argument of memcmp is mandatory.");
-  llvm::Optional<uint64_t> ComparedBits = tryEvaluateSizeExpr(SizeExpr, Ctx);
+  std::optional<uint64_t> ComparedBits = tryEvaluateSizeExpr(SizeExpr, Ctx);
 
   for (unsigned int ArgIndex = 0; ArgIndex < 2; ++ArgIndex) {
     const Expr *ArgExpr = CE->getArg(ArgIndex);

diff  --git a/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp
index 89d39d2898160..c8976e4d07d5b 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp
@@ -36,7 +36,7 @@ using llvm::Optional;
 
 static constexpr llvm::StringLiteral FuncID("fun");
 
-static Optional<std::vector<SourceLocation>>
+static std::optional<std::vector<SourceLocation>>
 analyzeFunction(const FunctionDecl &FuncDecl, ASTContext &ASTCtx,
                 UncheckedOptionalAccessModelOptions ModelOptions) {
   using dataflow::ControlFlowContext;
@@ -54,8 +54,8 @@ analyzeFunction(const FunctionDecl &FuncDecl, ASTContext &ASTCtx,
   UncheckedOptionalAccessModel Analysis(ASTCtx);
   UncheckedOptionalAccessDiagnoser Diagnoser(ModelOptions);
   std::vector<SourceLocation> Diagnostics;
-  Expected<std::vector<
-      Optional<DataflowAnalysisState<UncheckedOptionalAccessModel::Lattice>>>>
+  Expected<std::vector<std::optional<
+      DataflowAnalysisState<UncheckedOptionalAccessModel::Lattice>>>>
       BlockToOutputState = dataflow::runDataflowAnalysis(
           *Context, Analysis, Env,
           [&ASTCtx, &Diagnoser, &Diagnostics](
@@ -97,7 +97,7 @@ void UncheckedOptionalAccessCheck::check(
   if (FuncDecl->isTemplated())
     return;
 
-  if (Optional<std::vector<SourceLocation>> Errors =
+  if (std::optional<std::vector<SourceLocation>> Errors =
           analyzeFunction(*FuncDecl, *Result.Context, ModelOptions))
     for (const SourceLocation &Loc : *Errors)
       diag(Loc, "unchecked access to optional value");

diff  --git a/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h b/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h
index 052d6c6d5a6c4..4e76e5992204b 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h
@@ -19,7 +19,8 @@ namespace tidy {
 namespace bugprone {
 
 /// Warns when the code is unwrapping a `std::optional<T>`, `absl::optional<T>`,
-/// or `base::Optional<T>` object without assuring that it contains a value.
+/// or `base::std::optional<T>` object without assuring that it contains a
+/// value.
 ///
 /// For the user-facing documentation see:
 /// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/unchecked-optional-access.html

diff  --git a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
index 6c4fa9c55609e..f8a8617232316 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -260,7 +260,7 @@ void UseAfterMoveFinder::getDeclRefs(
     llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
   DeclRefs->clear();
   for (const auto &Elem : *Block) {
-    Optional<CFGStmt> S = Elem.getAs<CFGStmt>();
+    std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
     if (!S)
       continue;
 
@@ -356,7 +356,7 @@ void UseAfterMoveFinder::getReinits(
   Stmts->clear();
   DeclRefs->clear();
   for (const auto &Elem : *Block) {
-    Optional<CFGStmt> S = Elem.getAs<CFGStmt>();
+    std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
     if (!S)
       continue;
 

diff  --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
index d75990823ce5f..75cc360d3b783 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
@@ -80,7 +80,7 @@ void InitVariablesCheck::check(const MatchFinder::MatchResult &Result) {
     return;
 
   QualType TypePtr = MatchedDecl->getType();
-  llvm::Optional<const char *> InitializationString;
+  std::optional<const char *> InitializationString;
   bool AddMathInclude = false;
 
   if (TypePtr->isEnumeralType())

diff  --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
index 6692baca99d53..8c7ae7326a910 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
@@ -71,7 +71,7 @@ void ProBoundsConstantArrayIndexCheck::check(
   if (IndexExpr->isValueDependent())
     return; // We check in the specialization.
 
-  Optional<llvm::APSInt> Index =
+  std::optional<llvm::APSInt> Index =
       IndexExpr->getIntegerConstantExpr(*Result.Context);
   if (!Index) {
     SourceRange BaseRange;

diff  --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp
index 234ddd4ae9364..98b48bd6fb1c2 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp
@@ -48,7 +48,7 @@ void VirtualClassDestructorCheck::registerMatchers(MatchFinder *Finder) {
       this);
 }
 
-static Optional<CharSourceRange>
+static std::optional<CharSourceRange>
 getVirtualKeywordRange(const CXXDestructorDecl &Destructor,
                        const SourceManager &SM, const LangOptions &LangOpts) {
   if (Destructor.getLocation().isMacroID())
@@ -62,7 +62,8 @@ getVirtualKeywordRange(const CXXDestructorDecl &Destructor,
 
   /// Range ends with \c StartOfNextToken so that any whitespace after \c
   /// virtual is included.
-  Optional<Token> NextToken = Lexer::findNextToken(VirtualEndLoc, SM, LangOpts);
+  std::optional<Token> NextToken =
+      Lexer::findNextToken(VirtualEndLoc, SM, LangOpts);
   if (!NextToken)
     return std::nullopt;
   SourceLocation StartOfNextToken = NextToken->getLocation();

diff  --git a/clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp b/clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
index 1055d26e534ca..36e1b3f92a15a 100644
--- a/clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
+++ b/clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
@@ -23,7 +23,7 @@ static const llvm::StringRef RenameCaseToSuiteMessage =
     "Google Test APIs named with 'case' are deprecated; use equivalent APIs "
     "named with 'suite'";
 
-static llvm::Optional<llvm::StringRef>
+static std::optional<llvm::StringRef>
 getNewMacroName(llvm::StringRef MacroName) {
   std::pair<llvm::StringRef, llvm::StringRef> ReplacementMap[] = {
       {"TYPED_TEST_CASE", "TYPED_TEST_SUITE"},
@@ -98,7 +98,7 @@ class UpgradeGoogletestCasePPCallback : public PPCallbacks {
 
     std::string Name = PP->getSpelling(MacroNameTok);
 
-    llvm::Optional<llvm::StringRef> Replacement = getNewMacroName(Name);
+    std::optional<llvm::StringRef> Replacement = getNewMacroName(Name);
     if (!Replacement)
       return;
 

diff  --git a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
index 7c3811ceb4da9..40f5b134a37f7 100644
--- a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
@@ -505,7 +505,8 @@ static bool retrieveIntegerConstantExpr(const MatchFinder::MatchResult &Result,
   ConstExpr = Result.Nodes.getNodeAs<Expr>(CstId);
   if (!ConstExpr)
     return false;
-  Optional<llvm::APSInt> R = ConstExpr->getIntegerConstantExpr(*Result.Context);
+  std::optional<llvm::APSInt> R =
+      ConstExpr->getIntegerConstantExpr(*Result.Context);
   if (!R)
     return false;
   Value = *R;
@@ -1309,7 +1310,7 @@ void RedundantExpressionCheck::check(const MatchFinder::MatchResult &Result) {
           "left-right-shift-confusion")) {
     const auto *ShiftingConst = Result.Nodes.getNodeAs<Expr>("shift-const");
     assert(ShiftingConst && "Expr* 'ShiftingConst' is nullptr!");
-    Optional<llvm::APSInt> ShiftingValue =
+    std::optional<llvm::APSInt> ShiftingValue =
         ShiftingConst->getIntegerConstantExpr(*Result.Context);
 
     if (!ShiftingValue)
@@ -1317,7 +1318,7 @@ void RedundantExpressionCheck::check(const MatchFinder::MatchResult &Result) {
 
     const auto *AndConst = Result.Nodes.getNodeAs<Expr>("and-const");
     assert(AndConst && "Expr* 'AndCont' is nullptr!");
-    Optional<llvm::APSInt> AndValue =
+    std::optional<llvm::APSInt> AndValue =
         AndConst->getIntegerConstantExpr(*Result.Context);
     if (!AndValue)
       return;

diff  --git a/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp b/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
index eaa7022321f92..6203e19edce3c 100644
--- a/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
@@ -140,7 +140,7 @@ SourceLocation StaticAssertCheck::getLastParenLoc(const ASTContext *ASTCtx,
   const LangOptions &Opts = ASTCtx->getLangOpts();
   const SourceManager &SM = ASTCtx->getSourceManager();
 
-  llvm::Optional<llvm::MemoryBufferRef> Buffer =
+  std::optional<llvm::MemoryBufferRef> Buffer =
       SM.getBufferOrNone(SM.getFileID(AssertLoc));
   if (!Buffer)
     return SourceLocation();

diff  --git a/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp b/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp
index 900077ee87b83..1d818c576dc2f 100644
--- a/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp
@@ -22,8 +22,8 @@ static constexpr std::array<StringRef, 5> DeprecatedTypes = {
     "::std::ios_base::seek_dir", "::std::ios_base::streamoff",
     "::std::ios_base::streampos"};
 
-static llvm::Optional<const char *> getReplacementType(StringRef Type) {
-  return llvm::StringSwitch<llvm::Optional<const char *>>(Type)
+static std::optional<const char *> getReplacementType(StringRef Type) {
+  return llvm::StringSwitch<std::optional<const char *>>(Type)
       .Case("io_state", "iostate")
       .Case("open_mode", "openmode")
       .Case("seek_dir", "seekdir")

diff  --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
index 2db958ce8e697..51de77ba4dd57 100644
--- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
@@ -672,7 +672,7 @@ void LoopConvertCheck::doConversion(
       CharSourceRange::getTokenRange(ParenRange), Range));
 
   if (Descriptor.NeedsReverseCall && !getReverseHeader().empty()) {
-    if (Optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
+    if (std::optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
             Context->getSourceManager().getFileID(Loop->getBeginLoc()),
             getReverseHeader()))
       FixIts.push_back(*Insertion);

diff  --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp
index 7253b1daf6aef..0cad244bd0383 100644
--- a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp
@@ -445,7 +445,7 @@ static bool arrayMatchesBoundExpr(ASTContext *Context,
       Context->getAsConstantArrayType(ArrayType);
   if (!ConstType)
     return false;
-  Optional<llvm::APSInt> ConditionSize =
+  std::optional<llvm::APSInt> ConditionSize =
       ConditionExpr->getIntegerConstantExpr(*Context);
   if (!ConditionSize)
     return false;

diff  --git a/clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp b/clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp
index fd96cb2ede977..6c35e24177a3c 100644
--- a/clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp
@@ -61,7 +61,7 @@ const {0} &operator=(const {0} &) = delete{1})cpp",
   /// \returns \c true if the next token after the given \p MacroLoc is \b not a
   /// semicolon.
   bool shouldAppendSemi(SourceRange MacroLoc) {
-    llvm::Optional<Token> Next = Lexer::findNextToken(
+    std::optional<Token> Next = Lexer::findNextToken(
         MacroLoc.getEnd(), PP.getSourceManager(), PP.getLangOpts());
     return !(Next && Next->is(tok::semi));
   }

diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index adf070866893b..aac7c8866e1eb 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -345,7 +345,7 @@ void UseEqualsDefaultCheck::check(const MatchFinder::MatchResult &Result) {
         *Body, Result.Context->getSourceManager(),
         Result.Context->getLangOpts());
     // Skipping comments, check for a semicolon after Body->getSourceRange()
-    Optional<Token> Token = utils::lexer::findNextTokenSkippingComments(
+    std::optional<Token> Token = utils::lexer::findNextTokenSkippingComments(
         UnifiedEnd, Result.Context->getSourceManager(),
         Result.Context->getLangOpts());
     StringRef Replacement =

diff  --git a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp
index 6023fddb75add..070ba9a5451c4 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp
@@ -178,7 +178,7 @@ static bool isSpecifier(Token T) {
                    tok::kw_static, tok::kw_friend, tok::kw_virtual);
 }
 
-static llvm::Optional<ClassifiedToken>
+static std::optional<ClassifiedToken>
 classifyToken(const FunctionDecl &F, Preprocessor &PP, Token Tok) {
   ClassifiedToken CT;
   CT.T = Tok;
@@ -218,7 +218,7 @@ classifyToken(const FunctionDecl &F, Preprocessor &PP, Token Tok) {
   return CT;
 }
 
-llvm::Optional<SmallVector<ClassifiedToken, 8>>
+std::optional<SmallVector<ClassifiedToken, 8>>
 UseTrailingReturnTypeCheck::classifyTokensBeforeFunctionName(
     const FunctionDecl &F, const ASTContext &Ctx, const SourceManager &SM,
     const LangOptions &LangOpts) {
@@ -252,7 +252,7 @@ UseTrailingReturnTypeCheck::classifyTokensBeforeFunctionName(
       T.setKind(Info.getTokenID());
     }
 
-    if (llvm::Optional<ClassifiedToken> CT = classifyToken(F, *PP, T))
+    if (std::optional<ClassifiedToken> CT = classifyToken(F, *PP, T))
       ClassifiedTokens.push_back(*CT);
     else {
       diag(F.getLocation(), Message);
@@ -294,7 +294,7 @@ SourceRange UseTrailingReturnTypeCheck::findReturnTypeAndCVSourceRange(
     return ReturnTypeRange;
 
   // Include qualifiers to the left and right of the return type.
-  llvm::Optional<SmallVector<ClassifiedToken, 8>> MaybeTokens =
+  std::optional<SmallVector<ClassifiedToken, 8>> MaybeTokens =
       classifyTokensBeforeFunctionName(F, Ctx, SM, LangOpts);
   if (!MaybeTokens)
     return {};
@@ -346,7 +346,7 @@ void UseTrailingReturnTypeCheck::keepSpecifiers(
 
   // Tokenize return type. If it contains macros which contain a mix of
   // qualifiers, specifiers and types, give up.
-  llvm::Optional<SmallVector<ClassifiedToken, 8>> MaybeTokens =
+  std::optional<SmallVector<ClassifiedToken, 8>> MaybeTokens =
       classifyTokensBeforeFunctionName(F, Ctx, SM, LangOpts);
   if (!MaybeTokens)
     return;

diff  --git a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h
index fa9dd407233d5..e28e0be7f45a9 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h
+++ b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h
@@ -45,7 +45,7 @@ class UseTrailingReturnTypeCheck : public ClangTidyCheck {
   SourceLocation findTrailingReturnTypeSourceLocation(
       const FunctionDecl &F, const FunctionTypeLoc &FTL, const ASTContext &Ctx,
       const SourceManager &SM, const LangOptions &LangOpts);
-  llvm::Optional<SmallVector<ClassifiedToken, 8>>
+  std::optional<SmallVector<ClassifiedToken, 8>>
   classifyTokensBeforeFunctionName(const FunctionDecl &F, const ASTContext &Ctx,
                                    const SourceManager &SM,
                                    const LangOptions &LangOpts);

diff  --git a/clang-tools-extra/clang-tidy/mpi/BufferDerefCheck.h b/clang-tools-extra/clang-tidy/mpi/BufferDerefCheck.h
index 676654c2c2716..6c3323150e5c6 100644
--- a/clang-tools-extra/clang-tidy/mpi/BufferDerefCheck.h
+++ b/clang-tools-extra/clang-tidy/mpi/BufferDerefCheck.h
@@ -45,7 +45,7 @@ class BufferDerefCheck : public ClangTidyCheck {
 
   enum class IndirectionType : unsigned char { Pointer, Array };
 
-  Optional<ento::mpi::MPIFunctionClassifier> FuncClassifier;
+  std::optional<ento::mpi::MPIFunctionClassifier> FuncClassifier;
 };
 
 } // namespace mpi

diff  --git a/clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.h b/clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.h
index 261fec40160b1..d27e27837b3b1 100644
--- a/clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.h
+++ b/clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.h
@@ -46,7 +46,7 @@ class TypeMismatchCheck : public ClangTidyCheck {
                       ArrayRef<const Expr *> BufferExprs,
                       ArrayRef<StringRef> MPIDatatypes, const LangOptions &LO);
 
-  Optional<ento::mpi::MPIFunctionClassifier> FuncClassifier;
+  std::optional<ento::mpi::MPIFunctionClassifier> FuncClassifier;
 };
 
 } // namespace mpi

diff  --git a/clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp b/clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp
index 5127eaa557951..cd979a61cfd06 100644
--- a/clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp
+++ b/clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp
@@ -52,7 +52,7 @@ AST_POLYMORPHIC_MATCHER(isObjCManagedLifetime,
          QT.getQualifiers().getObjCLifetime() > Qualifiers::OCL_ExplicitNone;
 }
 
-static llvm::Optional<FixItHint>
+static std::optional<FixItHint>
 fixItHintReplacementForOwnershipString(StringRef Text, CharSourceRange Range,
                                        StringRef Ownership) {
   size_t Index = Text.find(Ownership);
@@ -65,7 +65,7 @@ fixItHintReplacementForOwnershipString(StringRef Text, CharSourceRange Range,
                                       UnsafeUnretainedText);
 }
 
-static llvm::Optional<FixItHint>
+static std::optional<FixItHint>
 fixItHintForVarDecl(const VarDecl *VD, const SourceManager &SM,
                     const LangOptions &LangOpts) {
   assert(VD && "VarDecl parameter must not be null");
@@ -85,11 +85,11 @@ fixItHintForVarDecl(const VarDecl *VD, const SourceManager &SM,
   }
 
   StringRef VarDeclText = Lexer::getSourceText(Range, SM, LangOpts);
-  if (llvm::Optional<FixItHint> Hint =
+  if (std::optional<FixItHint> Hint =
           fixItHintReplacementForOwnershipString(VarDeclText, Range, WeakText))
     return Hint;
 
-  if (llvm::Optional<FixItHint> Hint = fixItHintReplacementForOwnershipString(
+  if (std::optional<FixItHint> Hint = fixItHintReplacementForOwnershipString(
           VarDeclText, Range, StrongText))
     return Hint;
 

diff  --git a/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp b/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
index 190524720949b..427e9f0792f2f 100644
--- a/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
@@ -22,7 +22,7 @@ namespace performance {
 
 namespace {
 
-llvm::Optional<std::string> makeCharacterLiteral(const StringLiteral *Literal) {
+std::optional<std::string> makeCharacterLiteral(const StringLiteral *Literal) {
   std::string Result;
   {
     llvm::raw_string_ostream OS(Result);

diff  --git a/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp b/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
index d2899852bf133..8ffbd9f3fd6bf 100644
--- a/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
@@ -82,7 +82,7 @@ bool ForRangeCopyCheck::handleConstValueCopy(const VarDecl &LoopVar,
   } else if (!LoopVar.getType().isConstQualified()) {
     return false;
   }
-  llvm::Optional<bool> Expensive =
+  std::optional<bool> Expensive =
       utils::type_traits::isExpensiveToCopy(LoopVar.getType(), Context);
   if (!Expensive || !*Expensive)
     return false;
@@ -92,7 +92,7 @@ bool ForRangeCopyCheck::handleConstValueCopy(const VarDecl &LoopVar,
            "copy in each iteration; consider making this a reference")
       << utils::fixit::changeVarDeclToReference(LoopVar, Context);
   if (!LoopVar.getType().isConstQualified()) {
-    if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
+    if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
             LoopVar, Context, DeclSpec::TQ::TQ_const))
       Diagnostic << *Fix;
   }
@@ -102,7 +102,7 @@ bool ForRangeCopyCheck::handleConstValueCopy(const VarDecl &LoopVar,
 bool ForRangeCopyCheck::handleCopyIsOnlyConstReferenced(
     const VarDecl &LoopVar, const CXXForRangeStmt &ForRange,
     ASTContext &Context) {
-  llvm::Optional<bool> Expensive =
+  std::optional<bool> Expensive =
       utils::type_traits::isExpensiveToCopy(LoopVar.getType(), Context);
   if (LoopVar.getType().isConstQualified() || !Expensive || !*Expensive)
     return false;
@@ -123,7 +123,7 @@ bool ForRangeCopyCheck::handleCopyIsOnlyConstReferenced(
         "loop variable is copied but only used as const reference; consider "
         "making it a const reference");
 
-    if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
+    if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
             LoopVar, Context, DeclSpec::TQ::TQ_const))
       Diag << *Fix << utils::fixit::changeVarDeclToReference(LoopVar, Context);
 

diff  --git a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
index 249c00265da9d..7cdd4d3fb0014 100644
--- a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
+++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
@@ -36,14 +36,14 @@ void recordFixes(const VarDecl &Var, ASTContext &Context,
                  DiagnosticBuilder &Diagnostic) {
   Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context);
   if (!Var.getType().isLocalConstQualified()) {
-    if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
+    if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
             Var, Context, DeclSpec::TQ::TQ_const))
       Diagnostic << *Fix;
   }
 }
 
-llvm::Optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc,
-                                                    SourceManager &SM) {
+std::optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc,
+                                                   SourceManager &SM) {
   bool Invalid;
   const char *TextAfter = SM.getCharacterData(Loc, &Invalid);
   if (Invalid) {
@@ -59,7 +59,7 @@ void recordRemoval(const DeclStmt &Stmt, ASTContext &Context,
   // Attempt to remove trailing comments as well.
   auto Tok = utils::lexer::findNextTokenSkippingComments(Stmt.getEndLoc(), SM,
                                                          Context.getLangOpts());
-  llvm::Optional<SourceLocation> PastNewLine =
+  std::optional<SourceLocation> PastNewLine =
       firstLocAfterNewLine(Stmt.getEndLoc(), SM);
   if (Tok && PastNewLine) {
     auto BeforeFirstTokenAfterComment = Tok->getLocation().getLocWithOffset(-1);

diff  --git a/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp b/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
index c3f742e06d09e..6afe8fe555bf6 100644
--- a/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
@@ -151,7 +151,7 @@ void UnnecessaryValueParamCheck::check(const MatchFinder::MatchResult &Result) {
     // whether it is const or not as constness can 
diff er between definition and
     // declaration.
     if (!CurrentParam.getType().getCanonicalType().isConstQualified()) {
-      if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
+      if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
               CurrentParam, *Result.Context, DeclSpec::TQ::TQ_const))
         Diag << *Fix;
     }

diff  --git a/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp b/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
index e1ad21aaa3abd..4196ef8f2d922 100644
--- a/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp
@@ -25,7 +25,7 @@ namespace readability {
 // return type. Returns `std::nullopt` when the return type is not
 // `const`-qualified or `const` does not appear in `Def`'s source, like when the
 // type is an alias or a macro.
-static llvm::Optional<Token>
+static std::optional<Token>
 findConstToRemove(const FunctionDecl *Def,
                   const MatchFinder::MatchResult &Result) {
   if (!Def->getReturnType().isLocalConstQualified())
@@ -83,7 +83,7 @@ struct CheckResult {
 static CheckResult checkDef(const clang::FunctionDecl *Def,
                             const MatchFinder::MatchResult &MatchResult) {
   CheckResult Result;
-  llvm::Optional<Token> Tok = findConstToRemove(Def, MatchResult);
+  std::optional<Token> Tok = findConstToRemove(Def, MatchResult);
   if (!Tok)
     return Result;
 
@@ -96,7 +96,7 @@ static CheckResult checkDef(const clang::FunctionDecl *Def,
   // single warning at the definition.
   for (const FunctionDecl *Decl = Def->getPreviousDecl(); Decl != nullptr;
        Decl = Decl->getPreviousDecl()) {
-    if (llvm::Optional<Token> T = findConstToRemove(Decl, MatchResult))
+    if (std::optional<Token> T = findConstToRemove(Decl, MatchResult))
       Result.Hints.push_back(FixItHint::CreateRemoval(
           CharSourceRange::getCharRange(T->getLocation(), T->getEndLoc())));
     else

diff  --git a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
index 416952cda8065..6da558e6f24b5 100644
--- a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
@@ -219,7 +219,7 @@ class FunctionASTVisitor final
   // Used to efficiently know the last type of the binary sequence operator
   // that was encountered. It would make sense for the function call to start
   // the new sequence, thus it is a stack.
-  using OBO = Optional<BinaryOperator::Opcode>;
+  using OBO = std::optional<BinaryOperator::Opcode>;
   std::stack<OBO, SmallVector<OBO, 4>> BinaryOperatorsStack;
 
 public:
@@ -332,7 +332,8 @@ class FunctionASTVisitor final
 
     // We might encounter a function call, which starts a new sequence, thus
     // we need to save the current previous binary operator.
-    const Optional<BinaryOperator::Opcode> BinOpCopy(CurrentBinaryOperator);
+    const std::optional<BinaryOperator::Opcode> BinOpCopy(
+        CurrentBinaryOperator);
 
     // Record the operator that we are currently processing and traverse it.
     CurrentBinaryOperator = Op->getOpcode();

diff  --git a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
index 6aaa46d1c787c..7f9004ae26d41 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -229,7 +229,7 @@ static StringRef const HungarainNotationUserDefinedTypes[] = {
 // clang-format on
 
 IdentifierNamingCheck::NamingStyle::NamingStyle(
-    llvm::Optional<IdentifierNamingCheck::CaseType> Case,
+    std::optional<IdentifierNamingCheck::CaseType> Case,
     const std::string &Prefix, const std::string &Suffix,
     const std::string &IgnoredRegexpStr, HungarianPrefixType HPType)
     : Case(Case), Prefix(Prefix), Suffix(Suffix),
@@ -250,7 +250,7 @@ IdentifierNamingCheck::FileStyle IdentifierNamingCheck::getFileStyleFromOptions(
   HungarianNotation.loadDefaultConfig(HNOption);
   HungarianNotation.loadFileConfig(Options, HNOption);
 
-  SmallVector<llvm::Optional<IdentifierNamingCheck::NamingStyle>, 0> Styles;
+  SmallVector<std::optional<IdentifierNamingCheck::NamingStyle>, 0> Styles;
   Styles.resize(SK_Count);
   SmallString<64> StyleString;
   for (unsigned I = 0; I < SK_Count; ++I) {
@@ -802,7 +802,7 @@ void IdentifierNamingCheck::HungarianNotation::loadDefaultConfig(
 void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   RenamerClangTidyCheck::storeOptions(Opts);
   SmallString<64> StyleString;
-  ArrayRef<llvm::Optional<NamingStyle>> Styles = MainFileStyle->getStyles();
+  ArrayRef<std::optional<NamingStyle>> Styles = MainFileStyle->getStyles();
   for (size_t I = 0; I < SK_Count; ++I) {
     if (!Styles[I])
       continue;
@@ -1068,7 +1068,7 @@ std::string IdentifierNamingCheck::fixupWithStyle(
 
 StyleKind IdentifierNamingCheck::findStyleKind(
     const NamedDecl *D,
-    ArrayRef<llvm::Optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
+    ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
     bool IgnoreMainLikeFunctions) const {
   assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
          "Decl must be an explicit identifier with a name.");
@@ -1353,11 +1353,11 @@ StyleKind IdentifierNamingCheck::findStyleKind(
   return SK_Invalid;
 }
 
-llvm::Optional<RenamerClangTidyCheck::FailureInfo>
+std::optional<RenamerClangTidyCheck::FailureInfo>
 IdentifierNamingCheck::getFailureInfo(
     StringRef Type, StringRef Name, const NamedDecl *ND,
     SourceLocation Location,
-    ArrayRef<llvm::Optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
+    ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
     const IdentifierNamingCheck::HungarianNotationOption &HNOption,
     StyleKind SK, const SourceManager &SM, bool IgnoreFailedSplit) const {
   if (SK == SK_Invalid || !NamingStyles[SK])
@@ -1389,7 +1389,7 @@ IdentifierNamingCheck::getFailureInfo(
                                             std::move(Fixup)};
 }
 
-llvm::Optional<RenamerClangTidyCheck::FailureInfo>
+std::optional<RenamerClangTidyCheck::FailureInfo>
 IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl,
                                           const SourceManager &SM) const {
   SourceLocation Loc = Decl->getLocation();
@@ -1405,7 +1405,7 @@ IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl,
                         SM, IgnoreFailedSplit);
 }
 
-llvm::Optional<RenamerClangTidyCheck::FailureInfo>
+std::optional<RenamerClangTidyCheck::FailureInfo>
 IdentifierNamingCheck::getMacroFailureInfo(const Token &MacroNameTok,
                                            const SourceManager &SM) const {
   SourceLocation Loc = MacroNameTok.getLocation();

diff  --git a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
index a3ff2d55fa773..5b9087c856cfa 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
@@ -58,7 +58,7 @@ class IdentifierNamingCheck final : public RenamerClangTidyCheck {
   struct HungarianNotationOption {
     HungarianNotationOption() : HPType(HungarianPrefixType::HPT_Off) {}
 
-    llvm::Optional<CaseType> Case;
+    std::optional<CaseType> Case;
     HungarianPrefixType HPType;
     llvm::StringMap<std::string> General;
     llvm::StringMap<std::string> CString;
@@ -70,14 +70,14 @@ class IdentifierNamingCheck final : public RenamerClangTidyCheck {
   struct NamingStyle {
     NamingStyle() = default;
 
-    NamingStyle(llvm::Optional<CaseType> Case, const std::string &Prefix,
+    NamingStyle(std::optional<CaseType> Case, const std::string &Prefix,
                 const std::string &Suffix, const std::string &IgnoredRegexpStr,
                 HungarianPrefixType HPType);
     NamingStyle(const NamingStyle &O) = delete;
     NamingStyle &operator=(NamingStyle &&O) = default;
     NamingStyle(NamingStyle &&O) = default;
 
-    llvm::Optional<CaseType> Case;
+    std::optional<CaseType> Case;
     std::string Prefix;
     std::string Suffix;
     // Store both compiled and non-compiled forms so original value can be
@@ -121,12 +121,12 @@ class IdentifierNamingCheck final : public RenamerClangTidyCheck {
 
   struct FileStyle {
     FileStyle() : IsActive(false), IgnoreMainLikeFunctions(false) {}
-    FileStyle(SmallVectorImpl<Optional<NamingStyle>> &&Styles,
+    FileStyle(SmallVectorImpl<std::optional<NamingStyle>> &&Styles,
               HungarianNotationOption HNOption, bool IgnoreMainLike)
         : Styles(std::move(Styles)), HNOption(std::move(HNOption)),
           IsActive(true), IgnoreMainLikeFunctions(IgnoreMainLike) {}
 
-    ArrayRef<Optional<NamingStyle>> getStyles() const {
+    ArrayRef<std::optional<NamingStyle>> getStyles() const {
       assert(IsActive);
       return Styles;
     }
@@ -140,7 +140,7 @@ class IdentifierNamingCheck final : public RenamerClangTidyCheck {
     bool isIgnoringMainLikeFunction() const { return IgnoreMainLikeFunctions; }
 
   private:
-    SmallVector<Optional<NamingStyle>, 0> Styles;
+    SmallVector<std::optional<NamingStyle>, 0> Styles;
     HungarianNotationOption HNOption;
     bool IsActive;
     bool IgnoreMainLikeFunctions;
@@ -169,13 +169,13 @@ class IdentifierNamingCheck final : public RenamerClangTidyCheck {
 
   StyleKind findStyleKind(
       const NamedDecl *D,
-      ArrayRef<llvm::Optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
+      ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
       bool IgnoreMainLikeFunctions) const;
 
-  llvm::Optional<RenamerClangTidyCheck::FailureInfo> getFailureInfo(
+  std::optional<RenamerClangTidyCheck::FailureInfo> getFailureInfo(
       StringRef Type, StringRef Name, const NamedDecl *ND,
       SourceLocation Location,
-      ArrayRef<llvm::Optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
+      ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
       const IdentifierNamingCheck::HungarianNotationOption &HNOption,
       StyleKind SK, const SourceManager &SM, bool IgnoreFailedSplit) const;
 
@@ -183,10 +183,10 @@ class IdentifierNamingCheck final : public RenamerClangTidyCheck {
                                  bool IncludeMainLike) const;
 
 private:
-  llvm::Optional<FailureInfo>
+  std::optional<FailureInfo>
   getDeclFailureInfo(const NamedDecl *Decl,
                      const SourceManager &SM) const override;
-  llvm::Optional<FailureInfo>
+  std::optional<FailureInfo>
   getMacroFailureInfo(const Token &MacroNameTok,
                       const SourceManager &SM) const override;
   DiagInfo getDiagInfo(const NamingCheckId &ID,

diff  --git a/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp b/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp
index bc3d40db1c6da..1a4c6ff83b6ac 100644
--- a/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp
@@ -106,7 +106,7 @@ static bool typeIsMemberPointer(const Type *T) {
 /// // [  ][              ] [         ] - The ranges here are inclusive
 /// \endcode
 /// \todo Generalize this function to take other declarations than \c VarDecl.
-static Optional<std::vector<SourceRange>>
+static std::optional<std::vector<SourceRange>>
 declRanges(const DeclStmt *DS, const SourceManager &SM,
            const LangOptions &LangOpts) {
   std::size_t DeclCount = std::distance(DS->decl_begin(), DS->decl_end());
@@ -201,7 +201,7 @@ declRanges(const DeclStmt *DS, const SourceManager &SM,
   return Slices;
 }
 
-static Optional<std::vector<StringRef>>
+static std::optional<std::vector<StringRef>>
 collectSourceRanges(llvm::ArrayRef<SourceRange> Ranges, const SourceManager &SM,
                     const LangOptions &LangOpts) {
   std::vector<StringRef> Snippets;
@@ -252,12 +252,12 @@ void IsolateDeclarationCheck::check(const MatchFinder::MatchResult &Result) {
       diag(WholeDecl->getBeginLoc(),
            "multiple declarations in a single statement reduces readability");
 
-  Optional<std::vector<SourceRange>> PotentialRanges =
+  std::optional<std::vector<SourceRange>> PotentialRanges =
       declRanges(WholeDecl, *Result.SourceManager, getLangOpts());
   if (!PotentialRanges)
     return;
 
-  Optional<std::vector<StringRef>> PotentialSnippets = collectSourceRanges(
+  std::optional<std::vector<StringRef>> PotentialSnippets = collectSourceRanges(
       *PotentialRanges, *Result.SourceManager, getLangOpts());
 
   if (!PotentialSnippets)

diff  --git a/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp b/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp
index c53565c260408..270a527ba7627 100644
--- a/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp
@@ -46,7 +46,7 @@ static bool locationsInSameFile(const SourceManager &Sources,
          Sources.getFileID(Loc1) == Sources.getFileID(Loc2);
 }
 
-static llvm::Optional<std::string>
+static std::optional<std::string>
 getNamespaceNameAsWritten(SourceLocation &Loc, const SourceManager &Sources,
                           const LangOptions &LangOpts) {
   // Loc should be at the begin of the namespace decl (usually, `namespace`
@@ -56,7 +56,7 @@ getNamespaceNameAsWritten(SourceLocation &Loc, const SourceManager &Sources,
   // the opening brace can result from attributes.
   std::string Result;
   int Nesting = 0;
-  while (llvm::Optional<Token> T = utils::lexer::findNextTokenSkippingComments(
+  while (std::optional<Token> T = utils::lexer::findNextTokenSkippingComments(
              Loc, Sources, LangOpts)) {
     Loc = T->getLocation();
     if (T->is(tok::l_brace))
@@ -111,7 +111,7 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) {
       return;
   }
 
-  llvm::Optional<std::string> NamespaceNameAsWritten =
+  std::optional<std::string> NamespaceNameAsWritten =
       getNamespaceNameAsWritten(LBraceLoc, Sources, getLangOpts());
   if (!NamespaceNameAsWritten)
     return;

diff  --git a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp
index c2ec9312bd709..630eff00e048d 100644
--- a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp
@@ -29,8 +29,8 @@ AST_MATCHER_P(QualType, hasUnqualifiedType,
 
 enum class Qualifier { Const, Volatile, Restrict };
 
-llvm::Optional<Token> findQualToken(const VarDecl *Decl, Qualifier Qual,
-                                    const MatchFinder::MatchResult &Result) {
+std::optional<Token> findQualToken(const VarDecl *Decl, Qualifier Qual,
+                                   const MatchFinder::MatchResult &Result) {
   // Since either of the locs can be in a macro, use `makeFileCharRange` to be
   // sure that we have a consistent `CharSourceRange`, located entirely in the
   // source file.
@@ -60,7 +60,7 @@ llvm::Optional<Token> findQualToken(const VarDecl *Decl, Qualifier Qual,
                                           *Result.SourceManager);
 }
 
-llvm::Optional<SourceRange>
+std::optional<SourceRange>
 getTypeSpecifierLocation(const VarDecl *Var,
                          const MatchFinder::MatchResult &Result) {
   SourceRange TypeSpecifier(
@@ -75,8 +75,8 @@ getTypeSpecifierLocation(const VarDecl *Var,
   return TypeSpecifier;
 }
 
-llvm::Optional<SourceRange> mergeReplacementRange(SourceRange &TypeSpecifier,
-                                                  const Token &ConstToken) {
+std::optional<SourceRange> mergeReplacementRange(SourceRange &TypeSpecifier,
+                                                 const Token &ConstToken) {
   if (TypeSpecifier.getBegin().getLocWithOffset(-1) == ConstToken.getEndLoc()) {
     TypeSpecifier.setBegin(ConstToken.getLocation());
     return std::nullopt;
@@ -162,7 +162,7 @@ void QualifiedAutoCheck::registerMatchers(MatchFinder *Finder) {
 void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
   if (const auto *Var = Result.Nodes.getNodeAs<VarDecl>("auto")) {
     SourceRange TypeSpecifier;
-    if (llvm::Optional<SourceRange> TypeSpec =
+    if (std::optional<SourceRange> TypeSpec =
             getTypeSpecifierLocation(Var, Result)) {
       TypeSpecifier = *TypeSpec;
     } else
@@ -171,10 +171,10 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
     llvm::SmallVector<SourceRange, 4> RemoveQualifiersRange;
     auto CheckQualifier = [&](bool IsPresent, Qualifier Qual) {
       if (IsPresent) {
-        llvm::Optional<Token> Token = findQualToken(Var, Qual, Result);
+        std::optional<Token> Token = findQualToken(Var, Qual, Result);
         if (!Token || Token->getLocation().isMacroID())
           return true; // Disregard this VarDecl.
-        if (llvm::Optional<SourceRange> Result =
+        if (std::optional<SourceRange> Result =
                 mergeReplacementRange(TypeSpecifier, *Token))
           RemoveQualifiersRange.push_back(*Result);
       }
@@ -235,25 +235,24 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
               // explicitly.
 
     if (Var->getType().isLocalConstQualified()) {
-      llvm::Optional<Token> Token =
-          findQualToken(Var, Qualifier::Const, Result);
+      std::optional<Token> Token = findQualToken(Var, Qualifier::Const, Result);
       if (!Token || Token->getLocation().isMacroID())
         return;
     }
     if (Var->getType().isLocalVolatileQualified()) {
-      llvm::Optional<Token> Token =
+      std::optional<Token> Token =
           findQualToken(Var, Qualifier::Volatile, Result);
       if (!Token || Token->getLocation().isMacroID())
         return;
     }
     if (Var->getType().isLocalRestrictQualified()) {
-      llvm::Optional<Token> Token =
+      std::optional<Token> Token =
           findQualToken(Var, Qualifier::Restrict, Result);
       if (!Token || Token->getLocation().isMacroID())
         return;
     }
 
-    if (llvm::Optional<SourceRange> TypeSpec =
+    if (std::optional<SourceRange> TypeSpec =
             getTypeSpecifierLocation(Var, Result)) {
       if (TypeSpec->isInvalid() || TypeSpec->getBegin().isMacroID() ||
           TypeSpec->getEnd().isMacroID())
@@ -275,7 +274,7 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
       // Const isn't wrapped in the auto type, so must be declared explicitly.
       return;
 
-    if (llvm::Optional<SourceRange> TypeSpec =
+    if (std::optional<SourceRange> TypeSpec =
             getTypeSpecifierLocation(Var, Result)) {
       if (TypeSpec->isInvalid() || TypeSpec->getBegin().isMacroID() ||
           TypeSpec->getEnd().isMacroID())

diff  --git a/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
index de250bbc6ce90..3e020377f16e4 100644
--- a/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
@@ -41,7 +41,7 @@ getConstructExpr(const CXXCtorInitializer &CtorInit) {
   return dyn_cast<CXXConstructExpr>(InitExpr);
 }
 
-static llvm::Optional<SourceRange>
+static std::optional<SourceRange>
 getConstructExprArgRange(const CXXConstructExpr &Construct) {
   SourceLocation B, E;
   for (const Expr *Arg : Construct.arguments()) {
@@ -155,7 +155,7 @@ void RedundantStringInitCheck::check(const MatchFinder::MatchResult &Result) {
     const CXXConstructExpr *Construct = getConstructExpr(*CtorInit);
     if (!Construct)
       return;
-    if (llvm::Optional<SourceRange> RemovalRange =
+    if (std::optional<SourceRange> RemovalRange =
             getConstructExprArgRange(*Construct))
       diag(CtorInit->getMemberLocation(), "redundant string initialization")
           << FixItHint::CreateRemoval(*RemovalRange);

diff  --git a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
index 5e96a4917b07f..18a3bf6aa6397 100644
--- a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -298,7 +298,7 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor<Visitor> {
   }
 
   // Extracts a bool if an expression is (true|false|!true|!false);
-  static Optional<bool> getAsBoolLiteral(const Expr *E, bool FilterMacro) {
+  static std::optional<bool> getAsBoolLiteral(const Expr *E, bool FilterMacro) {
     if (const auto *Bool = dyn_cast<CXXBoolLiteralExpr>(E)) {
       if (FilterMacro && Bool->getBeginLoc().isMacroID())
         return std::nullopt;
@@ -308,7 +308,7 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor<Visitor> {
       if (FilterMacro && UnaryOp->getBeginLoc().isMacroID())
         return std::nullopt;
       if (UnaryOp->getOpcode() == UO_LNot)
-        if (Optional<bool> Res = getAsBoolLiteral(
+        if (std::optional<bool> Res = getAsBoolLiteral(
                 UnaryOp->getSubExpr()->IgnoreImplicit(), FilterMacro))
           return !*Res;
     }
@@ -330,7 +330,7 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor<Visitor> {
     const auto *RS = dyn_cast<ReturnStmt>(S);
     if (!RS || !RS->getRetValue())
       return {};
-    if (Optional<bool> Ret =
+    if (std::optional<bool> Ret =
             getAsBoolLiteral(RS->getRetValue()->IgnoreImplicit(), false)) {
       return {RS->getRetValue(), *Ret};
     }
@@ -365,7 +365,7 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor<Visitor> {
      * if (false) ThenStmt(); else ElseStmt() -> ElseStmt();
      */
     Expr *Cond = If->getCond()->IgnoreImplicit();
-    if (Optional<bool> Bool = getAsBoolLiteral(Cond, true)) {
+    if (std::optional<bool> Bool = getAsBoolLiteral(Cond, true)) {
       if (*Bool)
         Check->replaceWithThenStatement(Context, If, Cond);
       else
@@ -400,7 +400,7 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor<Visitor> {
           const auto *BO = dyn_cast<BinaryOperator>(S);
           if (!BO || BO->getOpcode() != BO_Assign)
             return {};
-          Optional<bool> RightasBool =
+          std::optional<bool> RightasBool =
               getAsBoolLiteral(BO->getRHS()->IgnoreImplicit(), false);
           if (!RightasBool)
             return {};
@@ -439,9 +439,9 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor<Visitor> {
      * Condition ? true : false; -> Condition
      * Condition ? false : true; -> !Condition;
      */
-    if (Optional<bool> Then =
+    if (std::optional<bool> Then =
             getAsBoolLiteral(Cond->getTrueExpr()->IgnoreImplicit(), false)) {
-      if (Optional<bool> Else =
+      if (std::optional<bool> Else =
               getAsBoolLiteral(Cond->getFalseExpr()->IgnoreImplicit(), false)) {
         if (*Then != *Else)
           Check->replaceWithCondition(Context, Cond, *Else);
@@ -785,16 +785,16 @@ static BinaryOperatorKind getDemorganFlippedOperator(BinaryOperatorKind BO) {
 
 static bool flipDemorganSide(SmallVectorImpl<FixItHint> &Fixes,
                              const ASTContext &Ctx, const Expr *E,
-                             Optional<BinaryOperatorKind> OuterBO);
+                             std::optional<BinaryOperatorKind> OuterBO);
 
 /// Inverts \p BinOp, Removing \p Parens if they exist and are safe to remove.
 /// returns \c true if there is any issue building the Fixes, \c false
 /// otherwise.
-static bool flipDemorganBinaryOperator(SmallVectorImpl<FixItHint> &Fixes,
-                                       const ASTContext &Ctx,
-                                       const BinaryOperator *BinOp,
-                                       Optional<BinaryOperatorKind> OuterBO,
-                                       const ParenExpr *Parens = nullptr) {
+static bool
+flipDemorganBinaryOperator(SmallVectorImpl<FixItHint> &Fixes,
+                           const ASTContext &Ctx, const BinaryOperator *BinOp,
+                           std::optional<BinaryOperatorKind> OuterBO,
+                           const ParenExpr *Parens = nullptr) {
   switch (BinOp->getOpcode()) {
   case BO_LAnd:
   case BO_LOr: {
@@ -871,7 +871,7 @@ static bool flipDemorganBinaryOperator(SmallVectorImpl<FixItHint> &Fixes,
 
 static bool flipDemorganSide(SmallVectorImpl<FixItHint> &Fixes,
                              const ASTContext &Ctx, const Expr *E,
-                             Optional<BinaryOperatorKind> OuterBO) {
+                             std::optional<BinaryOperatorKind> OuterBO) {
   if (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->getOpcode() == UO_LNot) {
     //  if we have a not operator, '!a', just remove the '!'.
     if (cast<UnaryOperator>(E)->getOperatorLoc().isMacroID())

diff  --git a/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp b/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp
index 8272a550249db..3972dc3d4d48f 100644
--- a/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp
@@ -582,8 +582,8 @@ bool SuspiciousCallArgumentCheck::isHeuristicEnabled(Heuristic H) const {
   return llvm::is_contained(AppliedHeuristics, H);
 }
 
-Optional<int8_t> SuspiciousCallArgumentCheck::getBound(Heuristic H,
-                                                       BoundKind BK) const {
+std::optional<int8_t>
+SuspiciousCallArgumentCheck::getBound(Heuristic H, BoundKind BK) const {
   auto Idx = static_cast<std::size_t>(H);
   assert(Idx < HeuristicCount);
 
@@ -783,7 +783,7 @@ bool SuspiciousCallArgumentCheck::areNamesSimilar(StringRef Arg,
                                                   StringRef Param, Heuristic H,
                                                   BoundKind BK) const {
   int8_t Threshold = -1;
-  if (Optional<int8_t> GotBound = getBound(H, BK))
+  if (std::optional<int8_t> GotBound = getBound(H, BK))
     Threshold = *GotBound;
 
   switch (H) {

diff  --git a/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.h b/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.h
index 698d9cf52c1c1..ec48b8c439efa 100644
--- a/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.h
+++ b/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.h
@@ -72,7 +72,7 @@ class SuspiciousCallArgumentCheck : public ClangTidyCheck {
   llvm::StringMap<std::string> AbbreviationDictionary;
 
   bool isHeuristicEnabled(Heuristic H) const;
-  Optional<int8_t> getBound(Heuristic H, BoundKind BK) const;
+  std::optional<int8_t> getBound(Heuristic H, BoundKind BK) const;
 
   // Runtime information of the currently analyzed function call.
   SmallVector<QualType, SmallVectorSize> ArgTypes;

diff  --git a/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp b/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp
index e6fe75799c32a..b40c841dd7948 100644
--- a/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp
@@ -61,11 +61,11 @@ constexpr llvm::StringLiteral FloatingLiteralCheck::Suffixes;
 struct NewSuffix {
   SourceRange LiteralLocation;
   StringRef OldSuffix;
-  llvm::Optional<FixItHint> FixIt;
+  std::optional<FixItHint> FixIt;
 };
 
-llvm::Optional<SourceLocation> getMacroAwareLocation(SourceLocation Loc,
-                                                     const SourceManager &SM) {
+std::optional<SourceLocation> getMacroAwareLocation(SourceLocation Loc,
+                                                    const SourceManager &SM) {
   // Do nothing if the provided location is invalid.
   if (Loc.isInvalid())
     return std::nullopt;
@@ -76,17 +76,17 @@ llvm::Optional<SourceLocation> getMacroAwareLocation(SourceLocation Loc,
   return SpellingLoc;
 }
 
-llvm::Optional<SourceRange> getMacroAwareSourceRange(SourceRange Loc,
-                                                     const SourceManager &SM) {
-  llvm::Optional<SourceLocation> Begin =
+std::optional<SourceRange> getMacroAwareSourceRange(SourceRange Loc,
+                                                    const SourceManager &SM) {
+  std::optional<SourceLocation> Begin =
       getMacroAwareLocation(Loc.getBegin(), SM);
-  llvm::Optional<SourceLocation> End = getMacroAwareLocation(Loc.getEnd(), SM);
+  std::optional<SourceLocation> End = getMacroAwareLocation(Loc.getEnd(), SM);
   if (!Begin || !End)
     return std::nullopt;
   return SourceRange(*Begin, *End);
 }
 
-llvm::Optional<std::string>
+std::optional<std::string>
 getNewSuffix(llvm::StringRef OldSuffix,
              const std::vector<StringRef> &NewSuffixes) {
   // If there is no config, just uppercase the entirety of the suffix.
@@ -105,7 +105,7 @@ getNewSuffix(llvm::StringRef OldSuffix,
 }
 
 template <typename LiteralType>
-llvm::Optional<NewSuffix>
+std::optional<NewSuffix>
 shouldReplaceLiteralSuffix(const Expr &Literal,
                            const std::vector<StringRef> &NewSuffixes,
                            const SourceManager &SM, const LangOptions &LO) {
@@ -121,7 +121,7 @@ shouldReplaceLiteralSuffix(const Expr &Literal,
       utils::rangeCanBeFixed(ReplacementDsc.LiteralLocation, &SM);
 
   // The literal may have macro expansion, we need the final expanded src range.
-  llvm::Optional<SourceRange> Range =
+  std::optional<SourceRange> Range =
       getMacroAwareSourceRange(ReplacementDsc.LiteralLocation, SM);
   if (!Range)
     return std::nullopt;
@@ -172,7 +172,7 @@ shouldReplaceLiteralSuffix(const Expr &Literal,
          "We still should have some chars left.");
 
   // And get the replacement suffix.
-  llvm::Optional<std::string> NewSuffix =
+  std::optional<std::string> NewSuffix =
       getNewSuffix(ReplacementDsc.OldSuffix, NewSuffixes);
   if (!NewSuffix || ReplacementDsc.OldSuffix == *NewSuffix)
     return std::nullopt; // The suffix was already the way it should be.

diff  --git a/clang-tools-extra/clang-tidy/utils/ExprSequence.cpp b/clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
index 3ca854dba67f4..ae10be607a2f2 100644
--- a/clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
+++ b/clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
@@ -189,7 +189,7 @@ StmtToBlockMap::StmtToBlockMap(const CFG *TheCFG, ASTContext *TheContext)
     : Context(TheContext) {
   for (const auto *B : *TheCFG) {
     for (const auto &Elem : *B) {
-      if (Optional<CFGStmt> S = Elem.getAs<CFGStmt>())
+      if (std::optional<CFGStmt> S = Elem.getAs<CFGStmt>())
         Map[S->getStmt()] = B;
     }
   }

diff  --git a/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp b/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp
index 6b1fe062fdd75..4e01409d49762 100644
--- a/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp
+++ b/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp
@@ -54,7 +54,7 @@ bool parseFileExtensions(StringRef AllFileExtensions,
   return true;
 }
 
-llvm::Optional<StringRef>
+std::optional<StringRef>
 getFileExtension(StringRef FileName, const FileExtensionsSet &FileExtensions) {
   StringRef Extension = llvm::sys::path::extension(FileName);
   if (Extension.empty())

diff  --git a/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.h b/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.h
index a79cf9a45a129..ed1c05ed2bba6 100644
--- a/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.h
+++ b/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.h
@@ -55,7 +55,7 @@ bool parseFileExtensions(StringRef AllFileExtensions,
 
 /// Decides whether a file has a header file extension.
 /// Returns the file extension, if included in the provided set.
-llvm::Optional<StringRef>
+std::optional<StringRef>
 getFileExtension(StringRef FileName, const FileExtensionsSet &FileExtensions);
 
 /// Decides whether a file has one of the specified file extensions.

diff  --git a/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp b/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp
index 2e96f29ffb458..62ba137723231 100644
--- a/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp
+++ b/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp
@@ -42,7 +42,7 @@ static bool locDangerous(SourceLocation S) {
   return S.isInvalid() || S.isMacroID();
 }
 
-static Optional<SourceLocation>
+static std::optional<SourceLocation>
 skipLParensBackwards(SourceLocation Start, const ASTContext &Context) {
   if (locDangerous(Start))
     return std::nullopt;
@@ -63,8 +63,8 @@ skipLParensBackwards(SourceLocation Start, const ASTContext &Context) {
   return Start;
 }
 
-static Optional<FixItHint> fixIfNotDangerous(SourceLocation Loc,
-                                             StringRef Text) {
+static std::optional<FixItHint> fixIfNotDangerous(SourceLocation Loc,
+                                                  StringRef Text) {
   if (locDangerous(Loc))
     return std::nullopt;
   return FixItHint::CreateInsertion(Loc, Text);
@@ -79,17 +79,17 @@ static std::string buildQualifier(DeclSpec::TQ Qualifier,
   return (llvm::Twine(DeclSpec::getSpecifierName(Qualifier)) + " ").str();
 }
 
-static Optional<FixItHint> changeValue(const VarDecl &Var,
-                                       DeclSpec::TQ Qualifier,
-                                       QualifierTarget QualTarget,
-                                       QualifierPolicy QualPolicy,
-                                       const ASTContext &Context) {
+static std::optional<FixItHint> changeValue(const VarDecl &Var,
+                                            DeclSpec::TQ Qualifier,
+                                            QualifierTarget QualTarget,
+                                            QualifierPolicy QualPolicy,
+                                            const ASTContext &Context) {
   switch (QualPolicy) {
   case QualifierPolicy::Left:
     return fixIfNotDangerous(Var.getTypeSpecStartLoc(),
                              buildQualifier(Qualifier));
   case QualifierPolicy::Right:
-    Optional<SourceLocation> IgnoredParens =
+    std::optional<SourceLocation> IgnoredParens =
         skipLParensBackwards(Var.getLocation(), Context);
 
     if (IgnoredParens)
@@ -99,20 +99,20 @@ static Optional<FixItHint> changeValue(const VarDecl &Var,
   llvm_unreachable("Unknown QualifierPolicy enum");
 }
 
-static Optional<FixItHint> changePointerItself(const VarDecl &Var,
-                                               DeclSpec::TQ Qualifier,
-                                               const ASTContext &Context) {
+static std::optional<FixItHint> changePointerItself(const VarDecl &Var,
+                                                    DeclSpec::TQ Qualifier,
+                                                    const ASTContext &Context) {
   if (locDangerous(Var.getLocation()))
     return std::nullopt;
 
-  Optional<SourceLocation> IgnoredParens =
+  std::optional<SourceLocation> IgnoredParens =
       skipLParensBackwards(Var.getLocation(), Context);
   if (IgnoredParens)
     return fixIfNotDangerous(*IgnoredParens, buildQualifier(Qualifier));
   return std::nullopt;
 }
 
-static Optional<FixItHint>
+static std::optional<FixItHint>
 changePointer(const VarDecl &Var, DeclSpec::TQ Qualifier, const Type *Pointee,
               QualifierTarget QualTarget, QualifierPolicy QualPolicy,
               const ASTContext &Context) {
@@ -139,7 +139,7 @@ changePointer(const VarDecl &Var, DeclSpec::TQ Qualifier, const Type *Pointee,
       if (locDangerous(BeforeStar))
         return std::nullopt;
 
-      Optional<SourceLocation> IgnoredParens =
+      std::optional<SourceLocation> IgnoredParens =
           skipLParensBackwards(BeforeStar, Context);
 
       if (IgnoredParens)
@@ -163,7 +163,7 @@ changePointer(const VarDecl &Var, DeclSpec::TQ Qualifier, const Type *Pointee,
   return std::nullopt;
 }
 
-static Optional<FixItHint>
+static std::optional<FixItHint>
 changeReferencee(const VarDecl &Var, DeclSpec::TQ Qualifier, QualType Pointee,
                  QualifierTarget QualTarget, QualifierPolicy QualPolicy,
                  const ASTContext &Context) {
@@ -174,7 +174,7 @@ changeReferencee(const VarDecl &Var, DeclSpec::TQ Qualifier, QualType Pointee,
   SourceLocation BeforeRef = lexer::findPreviousAnyTokenKind(
       Var.getLocation(), Context.getSourceManager(), Context.getLangOpts(),
       tok::amp, tok::ampamp);
-  Optional<SourceLocation> IgnoredParens =
+  std::optional<SourceLocation> IgnoredParens =
       skipLParensBackwards(BeforeRef, Context);
   if (IgnoredParens)
     return fixIfNotDangerous(*IgnoredParens, buildQualifier(Qualifier, true));
@@ -182,11 +182,11 @@ changeReferencee(const VarDecl &Var, DeclSpec::TQ Qualifier, QualType Pointee,
   return std::nullopt;
 }
 
-Optional<FixItHint> addQualifierToVarDecl(const VarDecl &Var,
-                                          const ASTContext &Context,
-                                          DeclSpec::TQ Qualifier,
-                                          QualifierTarget QualTarget,
-                                          QualifierPolicy QualPolicy) {
+std::optional<FixItHint> addQualifierToVarDecl(const VarDecl &Var,
+                                               const ASTContext &Context,
+                                               DeclSpec::TQ Qualifier,
+                                               QualifierTarget QualTarget,
+                                               QualifierPolicy QualPolicy) {
   assert((QualPolicy == QualifierPolicy::Left ||
           QualPolicy == QualifierPolicy::Right) &&
          "Unexpected Insertion Policy");

diff  --git a/clang-tools-extra/clang-tidy/utils/FixItHintUtils.h b/clang-tools-extra/clang-tidy/utils/FixItHintUtils.h
index ec2ed50d9c7da..3ce07195c5a05 100644
--- a/clang-tools-extra/clang-tidy/utils/FixItHintUtils.h
+++ b/clang-tools-extra/clang-tidy/utils/FixItHintUtils.h
@@ -42,7 +42,7 @@ enum class QualifierTarget {
 
 /// \brief Creates fix to qualify ``VarDecl`` with the specified \c Qualifier.
 /// Requires that `Var` is isolated in written code like in `int foo = 42;`.
-Optional<FixItHint>
+std::optional<FixItHint>
 addQualifierToVarDecl(const VarDecl &Var, const ASTContext &Context,
                       DeclSpec::TQ Qualifier,
                       QualifierTarget CT = QualifierTarget::Pointee,

diff  --git a/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp b/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
index ced2a73aa7688..58afc47fc69e2 100644
--- a/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
+++ b/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
@@ -68,7 +68,7 @@ IncludeSorter &IncludeInserter::getOrCreate(FileID FileID) {
   return *Entry;
 }
 
-llvm::Optional<FixItHint>
+std::optional<FixItHint>
 IncludeInserter::createIncludeInsertion(FileID FileID, llvm::StringRef Header) {
   bool IsAngled = Header.consume_front("<");
   if (IsAngled != Header.consume_back(">"))
@@ -83,7 +83,7 @@ IncludeInserter::createIncludeInsertion(FileID FileID, llvm::StringRef Header) {
   return getOrCreate(FileID).createIncludeInsertion(Header, IsAngled);
 }
 
-llvm::Optional<FixItHint>
+std::optional<FixItHint>
 IncludeInserter::createMainFileIncludeInsertion(StringRef Header) {
   assert(SourceMgr && "SourceMgr shouldn't be null; did you remember to call "
                       "registerPreprocessor()?");

diff  --git a/clang-tools-extra/clang-tidy/utils/IncludeInserter.h b/clang-tools-extra/clang-tidy/utils/IncludeInserter.h
index 0f4ba11acb05c..75e6ddf5948b9 100644
--- a/clang-tools-extra/clang-tidy/utils/IncludeInserter.h
+++ b/clang-tools-extra/clang-tidy/utils/IncludeInserter.h
@@ -72,15 +72,15 @@ class IncludeInserter {
   /// inclusion directive, otherwise uses quotes.
   /// Returns ``std::nullopt`` on error or if the inclusion directive already
   /// exists.
-  llvm::Optional<FixItHint> createIncludeInsertion(FileID FileID,
-                                                   llvm::StringRef Header);
+  std::optional<FixItHint> createIncludeInsertion(FileID FileID,
+                                                  llvm::StringRef Header);
 
   /// Creates a \p Header inclusion directive fixit in the main file.
   /// When \p Header is enclosed in angle brackets, uses angle brackets in the
   /// inclusion directive, otherwise uses quotes.
   /// Returns ``std::nullopt`` on error or if the inclusion directive already
   /// exists.
-  llvm::Optional<FixItHint>
+  std::optional<FixItHint>
   createMainFileIncludeInsertion(llvm::StringRef Header);
 
   IncludeSorter::IncludeStyle getStyle() const { return Style; }

diff  --git a/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp b/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp
index 5b25d10d031a2..dbb3b38b5aa4b 100644
--- a/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp
+++ b/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp
@@ -150,8 +150,8 @@ void IncludeSorter::addInclude(StringRef FileName, bool IsAngled,
     IncludeBucket[Kind].push_back(FileName.str());
 }
 
-Optional<FixItHint> IncludeSorter::createIncludeInsertion(StringRef FileName,
-                                                          bool IsAngled) {
+std::optional<FixItHint>
+IncludeSorter::createIncludeInsertion(StringRef FileName, bool IsAngled) {
   std::string IncludeStmt;
   if (Style == IncludeStyle::IS_Google_ObjC) {
     IncludeStmt = IsAngled

diff  --git a/clang-tools-extra/clang-tidy/utils/IncludeSorter.h b/clang-tools-extra/clang-tidy/utils/IncludeSorter.h
index 21fe5e48219c0..3ee924e4de84a 100644
--- a/clang-tools-extra/clang-tidy/utils/IncludeSorter.h
+++ b/clang-tools-extra/clang-tidy/utils/IncludeSorter.h
@@ -48,7 +48,8 @@ class IncludeSorter {
   /// Creates a quoted inclusion directive in the right sort order. Returns
   /// std::nullopt on error or if header inclusion directive for header already
   /// exists.
-  Optional<FixItHint> createIncludeInsertion(StringRef FileName, bool IsAngled);
+  std::optional<FixItHint> createIncludeInsertion(StringRef FileName,
+                                                  bool IsAngled);
 
 private:
   typedef SmallVector<SourceRange, 1> SourceRangeVector;

diff  --git a/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp b/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp
index 8bdbc1d19b9ae..413ca683ee707 100644
--- a/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp
+++ b/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp
@@ -78,10 +78,10 @@ SourceLocation findNextTerminator(SourceLocation Start, const SourceManager &SM,
   return findNextAnyTokenKind(Start, SM, LangOpts, tok::comma, tok::semi);
 }
 
-Optional<Token> findNextTokenSkippingComments(SourceLocation Start,
-                                              const SourceManager &SM,
-                                              const LangOptions &LangOpts) {
-  Optional<Token> CurrentToken;
+std::optional<Token>
+findNextTokenSkippingComments(SourceLocation Start, const SourceManager &SM,
+                              const LangOptions &LangOpts) {
+  std::optional<Token> CurrentToken;
   do {
     CurrentToken = Lexer::findNextToken(Start, SM, LangOpts);
   } while (CurrentToken && CurrentToken->is(tok::comment));
@@ -98,7 +98,7 @@ bool rangeContainsExpansionsOrDirectives(SourceRange Range,
     if (Loc.isMacroID())
       return true;
 
-    llvm::Optional<Token> Tok = Lexer::findNextToken(Loc, SM, LangOpts);
+    std::optional<Token> Tok = Lexer::findNextToken(Loc, SM, LangOpts);
 
     if (!Tok)
       return true;
@@ -112,10 +112,10 @@ bool rangeContainsExpansionsOrDirectives(SourceRange Range,
   return false;
 }
 
-llvm::Optional<Token> getQualifyingToken(tok::TokenKind TK,
-                                         CharSourceRange Range,
-                                         const ASTContext &Context,
-                                         const SourceManager &SM) {
+std::optional<Token> getQualifyingToken(tok::TokenKind TK,
+                                        CharSourceRange Range,
+                                        const ASTContext &Context,
+                                        const SourceManager &SM) {
   assert((TK == tok::kw_const || TK == tok::kw_volatile ||
           TK == tok::kw_restrict) &&
          "TK is not a qualifier keyword");
@@ -123,8 +123,8 @@ llvm::Optional<Token> getQualifyingToken(tok::TokenKind TK,
   StringRef File = SM.getBufferData(LocInfo.first);
   Lexer RawLexer(SM.getLocForStartOfFile(LocInfo.first), Context.getLangOpts(),
                  File.begin(), File.data() + LocInfo.second, File.end());
-  llvm::Optional<Token> LastMatchBeforeTemplate;
-  llvm::Optional<Token> LastMatchAfterTemplate;
+  std::optional<Token> LastMatchBeforeTemplate;
+  std::optional<Token> LastMatchAfterTemplate;
   bool SawTemplate = false;
   Token Tok;
   while (!RawLexer.LexFromRawLexer(Tok) &&
@@ -172,7 +172,7 @@ static SourceLocation getSemicolonAfterStmtEndLoc(const SourceLocation &EndLoc,
     //  F     (      foo()               ;   )
     //  ^ EndLoc         ^ SpellingLoc   ^ next token of SpellingLoc
     const SourceLocation SpellingLoc = SM.getSpellingLoc(EndLoc);
-    Optional<Token> NextTok =
+    std::optional<Token> NextTok =
         findNextTokenSkippingComments(SpellingLoc, SM, LangOpts);
 
     // Was the next token found successfully?
@@ -188,7 +188,8 @@ static SourceLocation getSemicolonAfterStmtEndLoc(const SourceLocation &EndLoc,
     //  ^ EndLoc         ^ SpellingLoc  ) ^ next token of EndLoc
   }
 
-  Optional<Token> NextTok = findNextTokenSkippingComments(EndLoc, SM, LangOpts);
+  std::optional<Token> NextTok =
+      findNextTokenSkippingComments(EndLoc, SM, LangOpts);
 
   // Testing for semicolon again avoids some issues with macros.
   if (NextTok && NextTok->is(tok::TokenKind::semi))

diff  --git a/clang-tools-extra/clang-tidy/utils/LexerUtils.h b/clang-tools-extra/clang-tidy/utils/LexerUtils.h
index f67e0cb96ea99..7af487dd0d742 100644
--- a/clang-tools-extra/clang-tidy/utils/LexerUtils.h
+++ b/clang-tools-extra/clang-tidy/utils/LexerUtils.h
@@ -68,7 +68,8 @@ SourceLocation findNextAnyTokenKind(SourceLocation Start,
                                     const LangOptions &LangOpts, TokenKind TK,
                                     TokenKinds... TKs) {
   while (true) {
-    Optional<Token> CurrentToken = Lexer::findNextToken(Start, SM, LangOpts);
+    std::optional<Token> CurrentToken =
+        Lexer::findNextToken(Start, SM, LangOpts);
 
     if (!CurrentToken)
       return SourceLocation();
@@ -87,9 +88,9 @@ SourceLocation findNextAnyTokenKind(SourceLocation Start,
 }
 
 // Finds next token that's not a comment.
-Optional<Token> findNextTokenSkippingComments(SourceLocation Start,
-                                              const SourceManager &SM,
-                                              const LangOptions &LangOpts);
+std::optional<Token> findNextTokenSkippingComments(SourceLocation Start,
+                                                   const SourceManager &SM,
+                                                   const LangOptions &LangOpts);
 
 /// Re-lex the provide \p Range and return \c false if either a macro spans
 /// multiple tokens, a pre-processor directive or failure to retrieve the
@@ -103,10 +104,10 @@ bool rangeContainsExpansionsOrDirectives(SourceRange Range,
 /// must be valid with respect to ``SM``.  Returns ``std::nullopt`` if no
 /// qualifying tokens are found.
 /// \note: doesn't support member function qualifiers.
-llvm::Optional<Token> getQualifyingToken(tok::TokenKind TK,
-                                         CharSourceRange Range,
-                                         const ASTContext &Context,
-                                         const SourceManager &SM);
+std::optional<Token> getQualifyingToken(tok::TokenKind TK,
+                                        CharSourceRange Range,
+                                        const ASTContext &Context,
+                                        const SourceManager &SM);
 
 /// Stmt->getEndLoc does not always behave the same way depending on Token type.
 /// See implementation for exceptions.

diff  --git a/clang-tools-extra/clang-tidy/utils/Matchers.h b/clang-tools-extra/clang-tidy/utils/Matchers.h
index 5a0e4599abf93..28c9389da7168 100644
--- a/clang-tools-extra/clang-tidy/utils/Matchers.h
+++ b/clang-tools-extra/clang-tidy/utils/Matchers.h
@@ -24,7 +24,7 @@ AST_MATCHER(BinaryOperator, isRelationalOperator) {
 AST_MATCHER(BinaryOperator, isEqualityOperator) { return Node.isEqualityOp(); }
 
 AST_MATCHER(QualType, isExpensiveToCopy) {
-  llvm::Optional<bool> IsExpensive =
+  std::optional<bool> IsExpensive =
       utils::type_traits::isExpensiveToCopy(Node, Finder->getASTContext());
   return IsExpensive && *IsExpensive;
 }

diff  --git a/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp b/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp
index 71a06f8e8e66a..93561232fe7a5 100644
--- a/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp
+++ b/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp
@@ -27,7 +27,7 @@ AST_MATCHER_P(NamespaceAliasDecl, hasTargetNamespace,
   return innerMatcher.matches(*Node.getNamespace(), Finder, Builder);
 }
 
-Optional<FixItHint>
+std::optional<FixItHint>
 NamespaceAliaser::createAlias(ASTContext &Context, const Stmt &Statement,
                               StringRef Namespace,
                               const std::vector<std::string> &Abbreviations) {

diff  --git a/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.h b/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.h
index 934ce1341dc9a..f655cfb9946c8 100644
--- a/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.h
+++ b/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.h
@@ -29,7 +29,7 @@ class NamespaceAliaser {
   // Adds a namespace alias for \p Namespace valid near \p
   // Statement. Picks the first available name from \p Abbreviations.
   // Returns ``std::nullopt`` if an alias already exists or there is an error.
-  llvm::Optional<FixItHint>
+  std::optional<FixItHint>
   createAlias(ASTContext &Context, const Stmt &Statement,
               llvm::StringRef Namespace,
               const std::vector<std::string> &Abbreviations);

diff  --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
index 80a500592333f..e3c22c357ec7a 100644
--- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -446,7 +446,7 @@ void RenamerClangTidyCheck::check(const MatchFinder::MatchResult &Result) {
     if (isa<ClassTemplateSpecializationDecl>(Decl))
       return;
 
-    Optional<FailureInfo> MaybeFailure =
+    std::optional<FailureInfo> MaybeFailure =
         getDeclFailureInfo(Decl, *Result.SourceManager);
     if (!MaybeFailure)
       return;
@@ -477,7 +477,7 @@ void RenamerClangTidyCheck::check(const MatchFinder::MatchResult &Result) {
 void RenamerClangTidyCheck::checkMacro(SourceManager &SourceMgr,
                                        const Token &MacroNameTok,
                                        const MacroInfo *MI) {
-  Optional<FailureInfo> MaybeFailure =
+  std::optional<FailureInfo> MaybeFailure =
       getMacroFailureInfo(MacroNameTok, SourceMgr);
   if (!MaybeFailure)
     return;

diff  --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.h b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.h
index 2f3b79e73a1c8..9b9f3a3c3e7fa 100644
--- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.h
@@ -126,13 +126,13 @@ class RenamerClangTidyCheck : public ClangTidyCheck {
   /// Overridden by derived classes, returns information about if and how a Decl
   /// failed the check. A 'std::nullopt' result means the Decl did not fail the
   /// check.
-  virtual llvm::Optional<FailureInfo>
+  virtual std::optional<FailureInfo>
   getDeclFailureInfo(const NamedDecl *Decl, const SourceManager &SM) const = 0;
 
   /// Overridden by derived classes, returns information about if and how a
   /// macro failed the check. A 'std::nullopt' result means the macro did not
   /// fail the check.
-  virtual llvm::Optional<FailureInfo>
+  virtual std::optional<FailureInfo>
   getMacroFailureInfo(const Token &MacroNameTok,
                       const SourceManager &SM) const = 0;
 

diff  --git a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
index b5e4b2b74a323..f69be2f6dcbdf 100644
--- a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
@@ -68,12 +68,12 @@ TransformerClangTidyCheck::TransformerClangTidyCheck(StringRef Name,
 // we would be accessing `getLangOpts` and `Options` before the underlying
 // `ClangTidyCheck` instance was properly initialized.
 TransformerClangTidyCheck::TransformerClangTidyCheck(
-    std::function<Optional<RewriteRuleWith<std::string>>(const LangOptions &,
-                                                         const OptionsView &)>
+    std::function<std::optional<RewriteRuleWith<std::string>>(
+        const LangOptions &, const OptionsView &)>
         MakeRule,
     StringRef Name, ClangTidyContext *Context)
     : TransformerClangTidyCheck(Name, Context) {
-  if (Optional<RewriteRuleWith<std::string>> R =
+  if (std::optional<RewriteRuleWith<std::string>> R =
           MakeRule(getLangOpts(), Options))
     setRule(std::move(*R));
 }

diff  --git a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
index 8ba15297cd957..f0868f689f082 100644
--- a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
@@ -50,7 +50,7 @@ class TransformerClangTidyCheck : public ClangTidyCheck {
   ///
   /// See \c setRule for constraints on the rule.
   TransformerClangTidyCheck(
-      std::function<Optional<transformer::RewriteRuleWith<std::string>>(
+      std::function<std::optional<transformer::RewriteRuleWith<std::string>>(
           const LangOptions &, const OptionsView &)>
           MakeRule,
       StringRef Name, ClangTidyContext *Context);

diff  --git a/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp b/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp
index 70a6ca17769f6..0dbbd5279368e 100644
--- a/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp
+++ b/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp
@@ -39,8 +39,8 @@ bool hasDeletedCopyConstructor(QualType Type) {
 
 } // namespace
 
-llvm::Optional<bool> isExpensiveToCopy(QualType Type,
-                                       const ASTContext &Context) {
+std::optional<bool> isExpensiveToCopy(QualType Type,
+                                      const ASTContext &Context) {
   if (Type->isDependentType() || Type->isIncompleteType())
     return std::nullopt;
   return !Type.isTriviallyCopyableType(Context) &&

diff  --git a/clang-tools-extra/clang-tidy/utils/TypeTraits.h b/clang-tools-extra/clang-tidy/utils/TypeTraits.h
index 37db6ef24e8ef..52751393ac6d2 100644
--- a/clang-tools-extra/clang-tidy/utils/TypeTraits.h
+++ b/clang-tools-extra/clang-tidy/utils/TypeTraits.h
@@ -19,8 +19,7 @@ namespace utils {
 namespace type_traits {
 
 /// Returns `true` if `Type` is expensive to copy.
-llvm::Optional<bool> isExpensiveToCopy(QualType Type,
-                                       const ASTContext &Context);
+std::optional<bool> isExpensiveToCopy(QualType Type, const ASTContext &Context);
 
 /// Returns `true` if `Type` is trivially default constructible.
 bool isTriviallyDefaultConstructible(QualType Type, const ASTContext &Context);

diff  --git a/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp b/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp
index 2a10d99c0dba8..22bef9af47a87 100644
--- a/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp
+++ b/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp
@@ -30,7 +30,7 @@ static StringRef getUnqualifiedName(StringRef QualifiedName) {
 UsingInserter::UsingInserter(const SourceManager &SourceMgr)
     : SourceMgr(SourceMgr) {}
 
-Optional<FixItHint> UsingInserter::createUsingDeclaration(
+std::optional<FixItHint> UsingInserter::createUsingDeclaration(
     ASTContext &Context, const Stmt &Statement, StringRef QualifiedName) {
   StringRef UnqualifiedName = getUnqualifiedName(QualifiedName);
   const FunctionDecl *Function = getSurroundingFunction(Context, Statement);

diff  --git a/clang-tools-extra/clang-tidy/utils/UsingInserter.h b/clang-tools-extra/clang-tidy/utils/UsingInserter.h
index b23025bd5a784..809833a637b6c 100644
--- a/clang-tools-extra/clang-tidy/utils/UsingInserter.h
+++ b/clang-tools-extra/clang-tidy/utils/UsingInserter.h
@@ -29,7 +29,7 @@ class UsingInserter {
 
   // Creates a \p using declaration fixit. Returns ``std::nullopt`` on error
   // or if the using declaration already exists.
-  llvm::Optional<FixItHint>
+  std::optional<FixItHint>
   createUsingDeclaration(ASTContext &Context, const Stmt &Statement,
                          llvm::StringRef QualifiedName);
 

diff  --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index d33960a0f5cf4..9576d74187bc4 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -45,7 +45,7 @@ namespace clang {
 namespace clangd {
 
 namespace {
-llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>>
+std::optional<llvm::ArrayRef<TemplateArgumentLoc>>
 getTemplateSpecializationArgLocs(const NamedDecl &ND) {
   if (auto *Func = llvm::dyn_cast<FunctionDecl>(&ND)) {
     if (const ASTTemplateArgumentListInfo *Args =
@@ -267,7 +267,7 @@ std::string printTemplateSpecializationArgs(const NamedDecl &ND) {
   std::string TemplateArgs;
   llvm::raw_string_ostream OS(TemplateArgs);
   PrintingPolicy Policy(ND.getASTContext().getLangOpts());
-  if (llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>> Args =
+  if (std::optional<llvm::ArrayRef<TemplateArgumentLoc>> Args =
           getTemplateSpecializationArgLocs(ND)) {
     printTemplateArgumentList(OS, *Args, Policy);
   } else if (auto *Cls = llvm::dyn_cast<ClassTemplateSpecializationDecl>(&ND)) {
@@ -564,8 +564,7 @@ class DeducedTypeVisitor : public RecursiveASTVisitor<DeducedTypeVisitor> {
 };
 } // namespace
 
-llvm::Optional<QualType> getDeducedType(ASTContext &ASTCtx,
-                                        SourceLocation Loc) {
+std::optional<QualType> getDeducedType(ASTContext &ASTCtx, SourceLocation Loc) {
   if (!Loc.isValid())
     return {};
   DeducedTypeVisitor V(Loc);
@@ -798,11 +797,11 @@ class ForwardingCallVisitor
     ArrayRef<const ParmVarDecl *> Tail;
     // If the parameters were resolved to another forwarding FunctionDecl, this
     // is it.
-    Optional<FunctionDecl *> PackTarget;
+    std::optional<FunctionDecl *> PackTarget;
   };
 
   // The output of this visitor
-  Optional<ForwardingInfo> Info;
+  std::optional<ForwardingInfo> Info;
 
 private:
   // inspects the given callee with the given args to check whether it
@@ -844,7 +843,7 @@ class ForwardingCallVisitor
 
   // Returns the beginning of the expanded pack represented by Parameters
   // in the given arguments, if it is there.
-  llvm::Optional<size_t> findPack(typename CallExpr::arg_range Args) {
+  std::optional<size_t> findPack(typename CallExpr::arg_range Args) {
     // find the argument directly referring to the first parameter
     assert(Parameters.size() <= static_cast<size_t>(llvm::size(Args)));
     for (auto Begin = Args.begin(), End = Args.end() - Parameters.size() + 1;

diff  --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index fbbee899d0ed3..bdc0862e96347 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -152,7 +152,7 @@ QualType declaredType(const TypeDecl *D);
 /// Retrieves the deduced type at a given location (auto, decltype).
 /// It will return the underlying type.
 /// If the type is an undeduced auto, returns the type itself.
-llvm::Optional<QualType> getDeducedType(ASTContext &, SourceLocation Loc);
+std::optional<QualType> getDeducedType(ASTContext &, SourceLocation Loc);
 
 // Find the abbreviated-function-template `auto` within a type, or returns null.
 // Similar to getContainedAutoTypeLoc, but these `auto`s are

diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index 7d7517679f9d9..53d5a7825e46b 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -245,7 +245,7 @@ class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
   // clangd receives the reply from the LSP client.
   // Return a call id of the request.
   llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
-    llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
+    std::optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
     int ID;
     {
       std::lock_guard<std::mutex> Mutex(CallMutex);
@@ -516,7 +516,7 @@ void ClangdLSPServer::onInitialize(const InitializeParams &Params,
     // rather want to propagate information from LSPServer's context into the
     // Server, CDB, etc.
     WithContext MainContext(BackgroundContext.clone());
-    llvm::Optional<WithContextValue> WithOffsetEncoding;
+    std::optional<WithContextValue> WithOffsetEncoding;
     if (Opts.Encoding)
       WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.Encoding);
     Server.emplace(*CDB, TFS, Opts,
@@ -908,7 +908,7 @@ flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
                        const URIForFile &FileURI) {
   std::vector<SymbolInformation> Results;
   std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
-      [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
+      [&](const DocumentSymbol &S, std::optional<llvm::StringRef> ParentName) {
         SymbolInformation SI;
         SI.containerName = std::string(ParentName ? "" : *ParentName);
         SI.name = S.name;
@@ -949,7 +949,7 @@ void ClangdLSPServer::onFoldingRange(
   Server->foldingRanges(Params.textDocument.uri.file(), std::move(Reply));
 }
 
-static llvm::Optional<Command> asCommand(const CodeAction &Action) {
+static std::optional<Command> asCommand(const CodeAction &Action) {
   Command Cmd;
   if (Action.command && Action.edit)
     return std::nullopt; // Not representable. (We never emit these anyway).
@@ -1149,7 +1149,7 @@ void ClangdLSPServer::onSwitchSourceHeader(
   Server->switchSourceHeader(
       Params.uri.file(),
       [Reply = std::move(Reply),
-       Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
+       Params](llvm::Expected<std::optional<clangd::Path>> Path) mutable {
         if (!Path)
           return Reply(Path.takeError());
         if (*Path)

diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.h b/clang-tools-extra/clangd/ClangdLSPServer.h
index 1b1f4ad848fa3..3659fd89d2e71 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.h
+++ b/clang-tools-extra/clangd/ClangdLSPServer.h
@@ -44,7 +44,7 @@ class ClangdLSPServer : private ClangdServer::Callbacks,
     /// set via LSP (extensions) only.
     bool UseDirBasedCDB = true;
     /// The offset-encoding to use, or std::nullopt to negotiate it over LSP.
-    llvm::Optional<OffsetEncoding> Encoding;
+    std::optional<OffsetEncoding> Encoding;
     /// If set, periodically called to release memory.
     /// Consider malloc_trim(3)
     std::function<void()> MemoryCleanup = nullptr;
@@ -292,9 +292,9 @@ class ClangdLSPServer : private ClangdServer::Callbacks,
   // The CDB is created by the "initialize" LSP method.
   std::unique_ptr<GlobalCompilationDatabase> BaseCDB;
   // CDB is BaseCDB plus any commands overridden via LSP extensions.
-  llvm::Optional<OverlayCDB> CDB;
+  std::optional<OverlayCDB> CDB;
   // The ClangdServer is created by the "initialize" LSP method.
-  llvm::Optional<ClangdServer> Server;
+  std::optional<ClangdServer> Server;
 };
 } // namespace clangd
 } // namespace clang

diff  --git a/clang-tools-extra/clangd/ClangdServer.cpp b/clang-tools-extra/clangd/ClangdServer.cpp
index 5a9b2edbffec2..74ad3c9847be4 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -393,7 +393,7 @@ void ClangdServer::codeComplete(PathRef File, Position Pos,
     if (auto Reason = isCancelled())
       return CB(llvm::make_error<CancelledError>(Reason));
 
-    llvm::Optional<SpeculativeFuzzyFind> SpecFuzzyFind;
+    std::optional<SpeculativeFuzzyFind> SpecFuzzyFind;
     if (!IP->Preamble) {
       // No speculation in Fallback mode, as it's supposed to be much faster
       // without compiling.
@@ -471,7 +471,7 @@ void ClangdServer::signatureHelp(PathRef File, Position Pos,
                                  std::move(Action));
 }
 
-void ClangdServer::formatFile(PathRef File, llvm::Optional<Range> Rng,
+void ClangdServer::formatFile(PathRef File, std::optional<Range> Rng,
                               Callback<tooling::Replacements> CB) {
   auto Code = getDraft(File);
   if (!Code)
@@ -538,7 +538,7 @@ void ClangdServer::formatOnType(PathRef File, Position Pos,
 }
 
 void ClangdServer::prepareRename(PathRef File, Position Pos,
-                                 llvm::Optional<std::string> NewName,
+                                 std::optional<std::string> NewName,
                                  const RenameOptions &RenameOpts,
                                  Callback<RenameResult> CB) {
   auto Action = [Pos, File = File.str(), CB = std::move(CB),
@@ -672,7 +672,7 @@ void ClangdServer::applyTweak(PathRef File, Range Sel, StringRef TweakID,
     auto Selections = tweakSelection(Sel, *InpAST, FS.get());
     if (!Selections)
       return CB(Selections.takeError());
-    llvm::Optional<llvm::Expected<Tweak::Effect>> Effect;
+    std::optional<llvm::Expected<Tweak::Effect>> Effect;
     // Try each selection, take the first one that prepare()s.
     // If they all fail, Effect will hold get the last error.
     for (const auto &Selection : *Selections) {
@@ -714,7 +714,7 @@ void ClangdServer::locateSymbolAt(PathRef File, Position Pos,
 }
 
 void ClangdServer::switchSourceHeader(
-    PathRef Path, Callback<llvm::Optional<clangd::Path>> CB) {
+    PathRef Path, Callback<std::optional<clangd::Path>> CB) {
   // We want to return the result as fast as possible, strategy is:
   //  1) use the file-only heuristic, it requires some IO but it is much
   //     faster than building AST, but it only works when .h/.cc files are in
@@ -1029,7 +1029,7 @@ llvm::StringMap<TUScheduler::FileStats> ClangdServer::fileStats() const {
 }
 
 [[nodiscard]] bool
-ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
+ClangdServer::blockUntilIdleForTest(std::optional<double> TimeoutSeconds) {
   // Order is important here: we don't want to block on A and then B,
   // if B might schedule work on A.
 
@@ -1056,8 +1056,8 @@ ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
   // Then on the last iteration, verify they're idle without waiting.
   //
   // There's a small chance they're juggling work and we didn't catch them :-(
-  for (llvm::Optional<double> Timeout :
-       {TimeoutSeconds, TimeoutSeconds, llvm::Optional<double>(0)}) {
+  for (std::optional<double> Timeout :
+       {TimeoutSeconds, TimeoutSeconds, std::optional<double>(0)}) {
     if (!CDB.blockUntilIdle(timeoutSeconds(Timeout)))
       return false;
     if (BackgroundIdx && !BackgroundIdx->blockUntilIdleForTest(Timeout))

diff  --git a/clang-tools-extra/clangd/ClangdServer.h b/clang-tools-extra/clangd/ClangdServer.h
index 097fed1344648..40b9183f067d3 100644
--- a/clang-tools-extra/clangd/ClangdServer.h
+++ b/clang-tools-extra/clangd/ClangdServer.h
@@ -137,13 +137,13 @@ class ClangdServer {
     /// Clangd's workspace root. Relevant for "workspace" operations not bound
     /// to a particular file.
     /// FIXME: If not set, should use the current working directory.
-    llvm::Optional<std::string> WorkspaceRoot;
+    std::optional<std::string> WorkspaceRoot;
 
     /// The resource directory is used to find internal headers, overriding
     /// defaults and -resource-dir compiler flag).
     /// If None, ClangdServer calls CompilerInvocation::GetResourcePath() to
     /// obtain the standard resource directory.
-    llvm::Optional<std::string> ResourceDir = std::nullopt;
+    std::optional<std::string> ResourceDir = std::nullopt;
 
     /// Time to wait after a new file version before computing diagnostics.
     DebouncePolicy UpdateDebounce = DebouncePolicy{
@@ -241,7 +241,7 @@ class ClangdServer {
   /// Switch to a corresponding source file when given a header file, and vice
   /// versa.
   void switchSourceHeader(PathRef Path,
-                          Callback<llvm::Optional<clangd::Path>> CB);
+                          Callback<std::optional<clangd::Path>> CB);
 
   /// Get document highlights for a given position.
   void findDocumentHighlights(PathRef File, Position Pos,
@@ -304,7 +304,7 @@ class ClangdServer {
 
   /// Run formatting for the \p File with content \p Code.
   /// If \p Rng is non-null, formats only that region.
-  void formatFile(PathRef File, llvm::Optional<Range> Rng,
+  void formatFile(PathRef File, std::optional<Range> Rng,
                   Callback<tooling::Replacements> CB);
 
   /// Run formatting after \p TriggerText was typed at \p Pos in \p File with
@@ -316,7 +316,7 @@ class ClangdServer {
   ///
   /// If NewName is provided, it performs a name validation.
   void prepareRename(PathRef File, Position Pos,
-                     llvm::Optional<std::string> NewName,
+                     std::optional<std::string> NewName,
                      const RenameOptions &RenameOpts,
                      Callback<RenameResult> CB);
 
@@ -398,7 +398,7 @@ class ClangdServer {
   // FIXME: various subcomponents each get the full timeout, so it's more of
   // an order of magnitude than a hard deadline.
   [[nodiscard]] bool
-  blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds = 10);
+  blockUntilIdleForTest(std::optional<double> TimeoutSeconds = 10);
 
   /// Builds a nested representation of memory used by components.
   void profile(MemoryTree &MT) const;
@@ -436,13 +436,13 @@ class ClangdServer {
   bool PreambleParseForwardingFunctions = false;
 
   // GUARDED_BY(CachedCompletionFuzzyFindRequestMutex)
-  llvm::StringMap<llvm::Optional<FuzzyFindRequest>>
+  llvm::StringMap<std::optional<FuzzyFindRequest>>
       CachedCompletionFuzzyFindRequestByFile;
   mutable std::mutex CachedCompletionFuzzyFindRequestMutex;
 
-  llvm::Optional<std::string> WorkspaceRoot;
-  llvm::Optional<AsyncTaskRunner> IndexTasks; // for stdlib indexing.
-  llvm::Optional<TUScheduler> WorkScheduler;
+  std::optional<std::string> WorkspaceRoot;
+  std::optional<AsyncTaskRunner> IndexTasks; // for stdlib indexing.
+  std::optional<TUScheduler> WorkScheduler;
   // Invalidation policy used for actions that we assume are "transient".
   TUScheduler::ASTActionInvalidation Transient;
 

diff  --git a/clang-tools-extra/clangd/CodeComplete.cpp b/clang-tools-extra/clangd/CodeComplete.cpp
index 42e6ef2bc2314..b6d7da1b360ed 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -265,7 +265,7 @@ struct CompletionCandidate {
   }
 
   // The best header to include if include insertion is allowed.
-  llvm::Optional<llvm::StringRef>
+  std::optional<llvm::StringRef>
   headerToInsertIfAllowed(const CodeCompleteOptions &Opts) const {
     if (Opts.InsertIncludes == CodeCompleteOptions::NeverInsert ||
         RankedIncludeHeaders.empty())
@@ -647,7 +647,7 @@ struct SpecifiedScope {
   std::vector<std::string> AccessibleScopes;
   // The full scope qualifier as typed by the user (without the leading "::").
   // Set if the qualifier is not fully resolved by Sema.
-  llvm::Optional<std::string> UnresolvedQualifier;
+  std::optional<std::string> UnresolvedQualifier;
 
   // Construct scopes being queried in indexes. The results are deduplicated.
   // This method format the scopes to match the index request representation.
@@ -1232,7 +1232,7 @@ struct SemaCompleteInput {
   PathRef FileName;
   size_t Offset;
   const PreambleData &Preamble;
-  const llvm::Optional<PreamblePatch> Patch;
+  const std::optional<PreamblePatch> Patch;
   const ParseInputs &ParseInput;
 };
 
@@ -1454,24 +1454,24 @@ class CodeCompleteFlow {
   int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0;
   bool Incomplete = false; // Would more be available with a higher limit?
   CompletionPrefix HeuristicPrefix;
-  llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
+  std::optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
   Range ReplacedRange;
   std::vector<std::string> QueryScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
-  llvm::Optional<ScopeDistance> ScopeProximity;
-  llvm::Optional<OpaqueType> PreferredType; // Initialized once Sema runs.
+  std::optional<ScopeDistance> ScopeProximity;
+  std::optional<OpaqueType> PreferredType; // Initialized once Sema runs.
   // Whether to query symbols from any scope. Initialized once Sema runs.
   bool AllScopes = false;
   llvm::StringSet<> ContextWords;
   // Include-insertion and proximity scoring rely on the include structure.
   // This is available after Sema has run.
-  llvm::Optional<IncludeInserter> Inserter;  // Available during runWithSema.
-  llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
+  std::optional<IncludeInserter> Inserter;  // Available during runWithSema.
+  std::optional<URIDistance> FileProximity; // Initialized once Sema runs.
   /// Speculative request based on the cached request and the filter text before
   /// the cursor.
   /// Initialized right before sema run. This is only set if `SpecFuzzyFind` is
   /// set and contains a cached request.
-  llvm::Optional<FuzzyFindRequest> SpecReq;
+  std::optional<FuzzyFindRequest> SpecReq;
 
 public:
   // A CodeCompleteFlow object is only useful for calling run() exactly once.
@@ -1834,7 +1834,7 @@ class CodeCompleteFlow {
     return std::move(Top).items();
   }
 
-  llvm::Optional<float> fuzzyScore(const CompletionCandidate &C) {
+  std::optional<float> fuzzyScore(const CompletionCandidate &C) {
     // Macros can be very spammy, so we only support prefix completion.
     if (((C.SemaResult &&
           C.SemaResult->Kind == CodeCompletionResult::RK_Macro) ||
@@ -1949,7 +1949,7 @@ class CodeCompleteFlow {
   }
 
   CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
-    llvm::Optional<CodeCompletionBuilder> Builder;
+    std::optional<CodeCompletionBuilder> Builder;
     for (const auto &Item : Bundle) {
       CodeCompletionString *SemaCCS =
           Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
@@ -2062,7 +2062,7 @@ CodeCompleteResult codeCompleteComment(PathRef FileName, unsigned Offset,
 // If Offset is inside what looks like argument comment (e.g.
 // "/*^" or "/* foo^"), returns new offset pointing to the start of the /*
 // (place where semaCodeComplete should run).
-llvm::Optional<unsigned>
+std::optional<unsigned>
 maybeFunctionArgumentCommentStart(llvm::StringRef Content) {
   while (!Content.empty() && isAsciiIdentifierContinue(Content.back()))
     Content = Content.drop_back();

diff  --git a/clang-tools-extra/clangd/CodeComplete.h b/clang-tools-extra/clangd/CodeComplete.h
index e88e9b3734b22..4f7fcd7f3f8ba 100644
--- a/clang-tools-extra/clangd/CodeComplete.h
+++ b/clang-tools-extra/clangd/CodeComplete.h
@@ -57,7 +57,7 @@ struct CodeCompleteOptions {
   /// If none, the implementation may choose an appropriate behavior.
   /// (In practice, ClangdLSPServer enables bundling if the client claims
   /// to supports signature help).
-  llvm::Optional<bool> BundleOverloads;
+  std::optional<bool> BundleOverloads;
 
   /// Limit the number of results returned (0 means no limit).
   /// If more results are available, we set CompletionList.isIncomplete.
@@ -175,7 +175,7 @@ struct CodeCompletion {
   // Type to be displayed for this completion.
   std::string ReturnType;
   // The parsed documentation comment.
-  llvm::Optional<markup::Document> Documentation;
+  std::optional<markup::Document> Documentation;
   CompletionItemKind Kind = CompletionItemKind::Missing;
   // This completion item may represent several symbols that can be inserted in
   // the same way, such as function overloads. In this case BundleSize > 1, and
@@ -194,7 +194,7 @@ struct CodeCompletion {
     // Empty for non-symbol completions, or when not known.
     std::string Header;
     // Present if Header should be inserted to use this item.
-    llvm::Optional<TextEdit> Insertion;
+    std::optional<TextEdit> Insertion;
   };
   // All possible include headers ranked by preference. By default, the first
   // include is used.
@@ -247,7 +247,7 @@ struct CodeCompleteResult {
   // Example: foo.pb^ -> foo.push_back()
   //              ~~
   // Typically matches the textEdit.range of Completions, but not guaranteed to.
-  llvm::Optional<Range> CompletionRange;
+  std::optional<Range> CompletionRange;
   // Usually the source will be parsed with a real C++ parser.
   // But heuristics may be used instead if e.g. the preamble is not ready.
   bool RanParser = true;
@@ -260,10 +260,10 @@ raw_ostream &operator<<(raw_ostream &, const CodeCompleteResult &);
 struct SpeculativeFuzzyFind {
   /// A cached request from past code completions.
   /// Set by caller of `codeComplete()`.
-  llvm::Optional<FuzzyFindRequest> CachedReq;
+  std::optional<FuzzyFindRequest> CachedReq;
   /// The actual request used by `codeComplete()`.
   /// Set by `codeComplete()`. This can be used by callers to update cache.
-  llvm::Optional<FuzzyFindRequest> NewReq;
+  std::optional<FuzzyFindRequest> NewReq;
   /// The result is consumed by `codeComplete()` if speculation succeeded.
   /// NOTE: the destructor will wait for the async call to finish.
   std::future<std::pair<bool /*Incomplete*/, SymbolSlab>> Result;

diff  --git a/clang-tools-extra/clangd/CompileCommands.cpp b/clang-tools-extra/clangd/CompileCommands.cpp
index 6669103a62dcb..3b7e25789cea1 100644
--- a/clang-tools-extra/clangd/CompileCommands.cpp
+++ b/clang-tools-extra/clangd/CompileCommands.cpp
@@ -38,7 +38,7 @@ namespace {
 
 // Query apple's `xcrun` launcher, which is the source of truth for "how should"
 // clang be invoked on this system.
-llvm::Optional<std::string> queryXcrun(llvm::ArrayRef<llvm::StringRef> Argv) {
+std::optional<std::string> queryXcrun(llvm::ArrayRef<llvm::StringRef> Argv) {
   auto Xcrun = llvm::sys::findProgramByName("xcrun");
   if (!Xcrun) {
     log("Couldn't find xcrun. Hopefully you have a non-apple toolchain...");
@@ -118,7 +118,7 @@ std::string detectClangPath() {
 
 // On mac, /usr/bin/clang sets SDKROOT and then invokes the real clang.
 // The effect of this is to set -isysroot correctly. We do the same.
-llvm::Optional<std::string> detectSysroot() {
+std::optional<std::string> detectSysroot() {
 #ifndef __APPLE__
   return std::nullopt;
 #endif
@@ -141,7 +141,7 @@ std::string detectStandardResourceDir() {
 // Where possible it should be an absolute path with sensible directory, but
 // with the original basename.
 static std::string resolveDriver(llvm::StringRef Driver, bool FollowSymlink,
-                                 llvm::Optional<std::string> ClangPath) {
+                                 std::optional<std::string> ClangPath) {
   auto SiblingOf = [&](llvm::StringRef AbsPath) {
     llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath);
     llvm::sys::path::append(Result, llvm::sys::path::filename(Driver));
@@ -256,7 +256,7 @@ void CommandMangler::operator()(tooling::CompileCommand &Command,
   // In practice only the extension of the file matters, so do this only when
   // it 
diff ers.
   llvm::StringRef FileExtension = llvm::sys::path::extension(File);
-  llvm::Optional<std::string> TransferFrom;
+  std::optional<std::string> TransferFrom;
   auto SawInput = [&](llvm::StringRef Input) {
     if (llvm::sys::path::extension(Input) != FileExtension)
       TransferFrom.emplace(Input);

diff  --git a/clang-tools-extra/clangd/CompileCommands.h b/clang-tools-extra/clangd/CompileCommands.h
index 561d9ea2f9ed3..eb318d18baf63 100644
--- a/clang-tools-extra/clangd/CompileCommands.h
+++ b/clang-tools-extra/clangd/CompileCommands.h
@@ -28,11 +28,11 @@ namespace clangd {
 //  - injecting -isysroot flags on mac as the system clang does
 struct CommandMangler {
   // Absolute path to clang.
-  llvm::Optional<std::string> ClangPath;
+  std::optional<std::string> ClangPath;
   // Directory containing builtin headers.
-  llvm::Optional<std::string> ResourceDir;
+  std::optional<std::string> ResourceDir;
   // Root for searching for standard library (passed to -isysroot).
-  llvm::Optional<std::string> Sysroot;
+  std::optional<std::string> Sysroot;
   SystemIncludeExtractorFn SystemIncludeExtractor;
 
   // A command-mangler that doesn't know anything about the system.

diff  --git a/clang-tools-extra/clangd/ConfigCompile.cpp b/clang-tools-extra/clangd/ConfigCompile.cpp
index e1a511d0a082a..f0cf9370fc3f5 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -103,7 +103,7 @@ struct FragmentCompiler {
   std::string FragmentDirectory;
   bool Trusted = false;
 
-  llvm::Optional<llvm::Regex>
+  std::optional<llvm::Regex>
   compileRegex(const Located<std::string> &Text,
                llvm::Regex::RegexFlags Flags = llvm::Regex::NoFlags) {
     std::string Anchored = "^(" + *Text + ")$";
@@ -142,7 +142,7 @@ struct FragmentCompiler {
     FragmentCompiler &Outer;
     llvm::StringRef EnumName;
     const Located<std::string> &Input;
-    llvm::Optional<T> Result;
+    std::optional<T> Result;
     llvm::SmallVector<llvm::StringLiteral> ValidValues;
 
   public:
@@ -158,7 +158,7 @@ struct FragmentCompiler {
       return *this;
     }
 
-    llvm::Optional<T> value() {
+    std::optional<T> value() {
       if (!Result)
         Outer.diag(
             Warning,
@@ -173,7 +173,7 @@ struct FragmentCompiler {
   // Attempt to parse a specified string into an enum.
   // Yields std::nullopt and produces a diagnostic on failure.
   //
-  // Optional<T> Value = compileEnum<En>("Foo", Frag.Foo)
+  // std::optional<T> Value = compileEnum<En>("Foo", Frag.Foo)
   //    .map("Foo", Enum::Foo)
   //    .map("Bar", Enum::Bar)
   //    .value();
@@ -291,7 +291,7 @@ struct FragmentCompiler {
     }
 
     if (F.CompilationDatabase) {
-      llvm::Optional<Config::CDBSearchSpec> Spec;
+      std::optional<Config::CDBSearchSpec> Spec;
       if (**F.CompilationDatabase == "Ancestors") {
         Spec.emplace();
         Spec->Policy = Config::CDBSearchSpec::Ancestors;

diff  --git a/clang-tools-extra/clangd/Diagnostics.cpp b/clang-tools-extra/clangd/Diagnostics.cpp
index 6c8cf5c52217f..326df0a5e203c 100644
--- a/clang-tools-extra/clangd/Diagnostics.cpp
+++ b/clang-tools-extra/clangd/Diagnostics.cpp
@@ -907,9 +907,9 @@ llvm::StringRef normalizeSuppressedCode(llvm::StringRef Code) {
   return Code;
 }
 
-llvm::Optional<std::string> getDiagnosticDocURI(Diag::DiagSource Source,
-                                                unsigned ID,
-                                                llvm::StringRef Name) {
+std::optional<std::string> getDiagnosticDocURI(Diag::DiagSource Source,
+                                               unsigned ID,
+                                               llvm::StringRef Name) {
   switch (Source) {
   case Diag::Unknown:
     break;

diff  --git a/clang-tools-extra/clangd/Diagnostics.h b/clang-tools-extra/clangd/Diagnostics.h
index b1a1f0170d346..ca6b92f26dbb3 100644
--- a/clang-tools-extra/clangd/Diagnostics.h
+++ b/clang-tools-extra/clangd/Diagnostics.h
@@ -62,7 +62,7 @@ struct DiagBase {
   // May be relative, absolute or even artificially constructed.
   std::string File;
   // Absolute path to containing file, if available.
-  llvm::Optional<std::string> AbsFile;
+  std::optional<std::string> AbsFile;
 
   clangd::Range Range;
   DiagnosticsEngine::Level Severity = DiagnosticsEngine::Note;
@@ -128,8 +128,8 @@ CodeAction toCodeAction(const Fix &D, const URIForFile &File);
 int getSeverity(DiagnosticsEngine::Level L);
 
 /// Returns a URI providing more information about a particular diagnostic.
-llvm::Optional<std::string> getDiagnosticDocURI(Diag::DiagSource, unsigned ID,
-                                                llvm::StringRef Name);
+std::optional<std::string> getDiagnosticDocURI(Diag::DiagSource, unsigned ID,
+                                               llvm::StringRef Name);
 
 /// StoreDiags collects the diagnostics that can later be reported by
 /// clangd. It groups all notes for a diagnostic into a single Diag
@@ -171,9 +171,9 @@ class StoreDiags : public DiagnosticConsumer {
   LevelAdjuster Adjuster = nullptr;
   DiagCallback DiagCB = nullptr;
   std::vector<Diag> Output;
-  llvm::Optional<LangOptions> LangOpts;
-  llvm::Optional<Diag> LastDiag;
-  llvm::Optional<FullSourceLoc> LastDiagLoc; // Valid only when LastDiag is set.
+  std::optional<LangOptions> LangOpts;
+  std::optional<Diag> LastDiag;
+  std::optional<FullSourceLoc> LastDiagLoc;  // Valid only when LastDiag is set.
   bool LastDiagOriginallyError = false;      // Valid only when LastDiag is set.
   SourceManager *OrigSrcMgr = nullptr;
 

diff  --git a/clang-tools-extra/clangd/DraftStore.cpp b/clang-tools-extra/clangd/DraftStore.cpp
index 7df70e69bdf31..66e45b0c04ce3 100644
--- a/clang-tools-extra/clangd/DraftStore.cpp
+++ b/clang-tools-extra/clangd/DraftStore.cpp
@@ -16,7 +16,7 @@
 namespace clang {
 namespace clangd {
 
-llvm::Optional<DraftStore::Draft> DraftStore::getDraft(PathRef File) const {
+std::optional<DraftStore::Draft> DraftStore::getDraft(PathRef File) const {
   std::lock_guard<std::mutex> Lock(Mutex);
 
   auto It = Drafts.find(File);

diff  --git a/clang-tools-extra/clangd/DraftStore.h b/clang-tools-extra/clangd/DraftStore.h
index a19fe55890b1c..0d5204215f8c9 100644
--- a/clang-tools-extra/clangd/DraftStore.h
+++ b/clang-tools-extra/clangd/DraftStore.h
@@ -34,7 +34,7 @@ class DraftStore {
 
   /// \return Contents of the stored document.
   /// For untracked files, a std::nullopt is returned.
-  llvm::Optional<Draft> getDraft(PathRef File) const;
+  std::optional<Draft> getDraft(PathRef File) const;
 
   /// \return List of names of the drafts in this store.
   std::vector<Path> getActiveFiles() const;

diff  --git a/clang-tools-extra/clangd/DumpAST.cpp b/clang-tools-extra/clangd/DumpAST.cpp
index 438733d44f13f..2bf75e65a9efb 100644
--- a/clang-tools-extra/clangd/DumpAST.cpp
+++ b/clang-tools-extra/clangd/DumpAST.cpp
@@ -88,7 +88,7 @@ class DumpVisitor : public RecursiveASTVisitor<DumpVisitor> {
   // Range: most nodes have getSourceRange(), with a couple of exceptions.
   // We only return it if it's valid at both ends and there are no macros.
 
-  template <typename T> llvm::Optional<Range> getRange(const T &Node) {
+  template <typename T> std::optional<Range> getRange(const T &Node) {
     SourceRange SR = getSourceRange(Node);
     auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(SR));
     if (!Spelled)

diff  --git a/clang-tools-extra/clangd/ExpectedTypes.cpp b/clang-tools-extra/clangd/ExpectedTypes.cpp
index 563612aa745ca..deea8a50111e6 100644
--- a/clang-tools-extra/clangd/ExpectedTypes.cpp
+++ b/clang-tools-extra/clangd/ExpectedTypes.cpp
@@ -40,8 +40,7 @@ static const Type *toEquivClass(ASTContext &Ctx, QualType T) {
   return T.getTypePtr();
 }
 
-static llvm::Optional<QualType>
-typeOfCompletion(const CodeCompletionResult &R) {
+static std::optional<QualType> typeOfCompletion(const CodeCompletionResult &R) {
   const NamedDecl *D = R.Declaration;
   // Templates do not have a type on their own, look at the templated decl.
   if (auto *Template = dyn_cast_or_null<TemplateDecl>(D))
@@ -63,7 +62,7 @@ typeOfCompletion(const CodeCompletionResult &R) {
 }
 } // namespace
 
-llvm::Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
+std::optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
   if (T.isNull())
     return std::nullopt;
   const Type *C = toEquivClass(Ctx, T);
@@ -77,12 +76,11 @@ llvm::Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
 
 OpaqueType::OpaqueType(std::string Data) : Data(std::move(Data)) {}
 
-llvm::Optional<OpaqueType> OpaqueType::fromType(ASTContext &Ctx,
-                                                QualType Type) {
+std::optional<OpaqueType> OpaqueType::fromType(ASTContext &Ctx, QualType Type) {
   return encode(Ctx, Type);
 }
 
-llvm::Optional<OpaqueType>
+std::optional<OpaqueType>
 OpaqueType::fromCompletionResult(ASTContext &Ctx,
                                  const CodeCompletionResult &R) {
   auto T = typeOfCompletion(R);

diff  --git a/clang-tools-extra/clangd/ExpectedTypes.h b/clang-tools-extra/clangd/ExpectedTypes.h
index 6cfd0936def6e..8182e7684416d 100644
--- a/clang-tools-extra/clangd/ExpectedTypes.h
+++ b/clang-tools-extra/clangd/ExpectedTypes.h
@@ -35,11 +35,11 @@ namespace clangd {
 class OpaqueType {
 public:
   /// Create a type from a code completion result.
-  static llvm::Optional<OpaqueType>
+  static std::optional<OpaqueType>
   fromCompletionResult(ASTContext &Ctx, const CodeCompletionResult &R);
   /// Construct an instance from a clang::QualType. This is usually a
   /// PreferredType from a clang's completion context.
-  static llvm::Optional<OpaqueType> fromType(ASTContext &Ctx, QualType Type);
+  static std::optional<OpaqueType> fromType(ASTContext &Ctx, QualType Type);
 
   /// Get the raw byte representation of the type. You can only rely on the
   /// types being equal iff their raw representation is the same. The particular
@@ -55,7 +55,7 @@ class OpaqueType {
   }
 
 private:
-  static llvm::Optional<OpaqueType> encode(ASTContext &Ctx, QualType Type);
+  static std::optional<OpaqueType> encode(ASTContext &Ctx, QualType Type);
   explicit OpaqueType(std::string Data);
 
   std::string Data;

diff  --git a/clang-tools-extra/clangd/FS.cpp b/clang-tools-extra/clangd/FS.cpp
index 587b9212188c0..3622d35d9d525 100644
--- a/clang-tools-extra/clangd/FS.cpp
+++ b/clang-tools-extra/clangd/FS.cpp
@@ -36,7 +36,7 @@ void PreambleFileStatusCache::update(const llvm::vfs::FileSystem &FS,
   StatCache.insert({PathStore, std::move(S)});
 }
 
-llvm::Optional<llvm::vfs::Status>
+std::optional<llvm::vfs::Status>
 PreambleFileStatusCache::lookup(llvm::StringRef File) const {
   // Canonicalize to match the cached form.
   // Lookup tends to be first by absolute path, so no need to make absolute.

diff  --git a/clang-tools-extra/clangd/FS.h b/clang-tools-extra/clangd/FS.h
index 96b04dc7c9e57..16a0a4997fb07 100644
--- a/clang-tools-extra/clangd/FS.h
+++ b/clang-tools-extra/clangd/FS.h
@@ -45,7 +45,7 @@ class PreambleFileStatusCache {
   void update(const llvm::vfs::FileSystem &FS, llvm::vfs::Status S);
 
   /// \p Path is a path stored in preamble.
-  llvm::Optional<llvm::vfs::Status> lookup(llvm::StringRef Path) const;
+  std::optional<llvm::vfs::Status> lookup(llvm::StringRef Path) const;
 
   /// Returns a VFS that collects file status.
   /// Only cache stats for files that exist because

diff  --git a/clang-tools-extra/clangd/FeatureModule.h b/clang-tools-extra/clangd/FeatureModule.h
index eb4232f26b065..7b6883507be3f 100644
--- a/clang-tools-extra/clangd/FeatureModule.h
+++ b/clang-tools-extra/clangd/FeatureModule.h
@@ -138,7 +138,7 @@ class FeatureModule {
   using OutgoingMethod = llvm::unique_function<void(const P &, Callback<R>)>;
 
 private:
-  llvm::Optional<Facilities> Fac;
+  std::optional<Facilities> Fac;
 };
 
 /// A FeatureModuleSet is a collection of feature modules installed in clangd.

diff  --git a/clang-tools-extra/clangd/FindSymbols.cpp b/clang-tools-extra/clangd/FindSymbols.cpp
index 682ca79a746dc..6e6dbb208fba9 100644
--- a/clang-tools-extra/clangd/FindSymbols.cpp
+++ b/clang-tools-extra/clangd/FindSymbols.cpp
@@ -220,7 +220,7 @@ std::string getSymbolDetail(ASTContext &Ctx, const NamedDecl &ND) {
   return std::move(OS.str());
 }
 
-llvm::Optional<DocumentSymbol> declToSym(ASTContext &Ctx, const NamedDecl &ND) {
+std::optional<DocumentSymbol> declToSym(ASTContext &Ctx, const NamedDecl &ND) {
   auto &SM = Ctx.getSourceManager();
 
   SourceLocation BeginLoc = SM.getSpellingLoc(SM.getFileLoc(ND.getBeginLoc()));

diff  --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
index 37f6173d30e6c..9e32fce9ab328 100644
--- a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
+++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
@@ -354,7 +354,7 @@ DirectoryBasedGlobalCompilationDatabase::
 DirectoryBasedGlobalCompilationDatabase::
     ~DirectoryBasedGlobalCompilationDatabase() = default;
 
-llvm::Optional<tooling::CompileCommand>
+std::optional<tooling::CompileCommand>
 DirectoryBasedGlobalCompilationDatabase::getCompileCommand(PathRef File) const {
   CDBLookupRequest Req;
   Req.FileName = File;
@@ -398,7 +398,7 @@ DirectoryBasedGlobalCompilationDatabase::getDirectoryCaches(
   return Ret;
 }
 
-llvm::Optional<DirectoryBasedGlobalCompilationDatabase::CDBLookupResult>
+std::optional<DirectoryBasedGlobalCompilationDatabase::CDBLookupResult>
 DirectoryBasedGlobalCompilationDatabase::lookupCDB(
     CDBLookupRequest Request) const {
   assert(llvm::sys::path::is_absolute(Request.FileName) &&
@@ -476,7 +476,7 @@ class DirectoryBasedGlobalCompilationDatabase::BroadcastThread {
     Context Ctx;
   };
   std::deque<Task> Queue;
-  llvm::Optional<Task> ActiveTask;
+  std::optional<Task> ActiveTask;
   std::thread Thread; // Must be last member.
 
   // Thread body: this is just the basic queue procesing boilerplate.
@@ -725,7 +725,7 @@ bool DirectoryBasedGlobalCompilationDatabase::blockUntilIdle(
   return Broadcaster->blockUntilIdle(Timeout);
 }
 
-llvm::Optional<ProjectInfo>
+std::optional<ProjectInfo>
 DirectoryBasedGlobalCompilationDatabase::getProjectInfo(PathRef File) const {
   CDBLookupRequest Req;
   Req.FileName = File;
@@ -744,9 +744,9 @@ OverlayCDB::OverlayCDB(const GlobalCompilationDatabase *Base,
     : DelegatingCDB(Base), Mangler(std::move(Mangler)),
       FallbackFlags(std::move(FallbackFlags)) {}
 
-llvm::Optional<tooling::CompileCommand>
+std::optional<tooling::CompileCommand>
 OverlayCDB::getCompileCommand(PathRef File) const {
-  llvm::Optional<tooling::CompileCommand> Cmd;
+  std::optional<tooling::CompileCommand> Cmd;
   {
     std::lock_guard<std::mutex> Lock(Mutex);
     auto It = Commands.find(removeDots(File));
@@ -772,8 +772,8 @@ tooling::CompileCommand OverlayCDB::getFallbackCommand(PathRef File) const {
   return Cmd;
 }
 
-void OverlayCDB::setCompileCommand(
-    PathRef File, llvm::Optional<tooling::CompileCommand> Cmd) {
+void OverlayCDB::setCompileCommand(PathRef File,
+                                   std::optional<tooling::CompileCommand> Cmd) {
   // We store a canonical version internally to prevent mismatches between set
   // and get compile commands. Also it assures clients listening to broadcasts
   // doesn't receive 
diff erent names for the same file.
@@ -801,14 +801,14 @@ DelegatingCDB::DelegatingCDB(std::unique_ptr<GlobalCompilationDatabase> Base)
   BaseOwner = std::move(Base);
 }
 
-llvm::Optional<tooling::CompileCommand>
+std::optional<tooling::CompileCommand>
 DelegatingCDB::getCompileCommand(PathRef File) const {
   if (!Base)
     return std::nullopt;
   return Base->getCompileCommand(File);
 }
 
-llvm::Optional<ProjectInfo> DelegatingCDB::getProjectInfo(PathRef File) const {
+std::optional<ProjectInfo> DelegatingCDB::getProjectInfo(PathRef File) const {
   if (!Base)
     return std::nullopt;
   return Base->getProjectInfo(File);

diff  --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.h b/clang-tools-extra/clangd/GlobalCompilationDatabase.h
index 04481fa6ea227..12cf280dfd540 100644
--- a/clang-tools-extra/clangd/GlobalCompilationDatabase.h
+++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.h
@@ -38,11 +38,11 @@ class GlobalCompilationDatabase {
   virtual ~GlobalCompilationDatabase() = default;
 
   /// If there are any known-good commands for building this file, returns one.
-  virtual llvm::Optional<tooling::CompileCommand>
+  virtual std::optional<tooling::CompileCommand>
   getCompileCommand(PathRef File) const = 0;
 
   /// Finds the closest project to \p File.
-  virtual llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const {
+  virtual std::optional<ProjectInfo> getProjectInfo(PathRef File) const {
     return std::nullopt;
   }
 
@@ -72,10 +72,10 @@ class DelegatingCDB : public GlobalCompilationDatabase {
   DelegatingCDB(const GlobalCompilationDatabase *Base);
   DelegatingCDB(std::unique_ptr<GlobalCompilationDatabase> Base);
 
-  llvm::Optional<tooling::CompileCommand>
+  std::optional<tooling::CompileCommand>
   getCompileCommand(PathRef File) const override;
 
-  llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const override;
+  std::optional<ProjectInfo> getProjectInfo(PathRef File) const override;
 
   tooling::CompileCommand getFallbackCommand(PathRef File) const override;
 
@@ -116,12 +116,12 @@ class DirectoryBasedGlobalCompilationDatabase
   /// Scans File's parents looking for compilation databases.
   /// Any extra flags will be added.
   /// Might trigger OnCommandChanged, if CDB wasn't broadcasted yet.
-  llvm::Optional<tooling::CompileCommand>
+  std::optional<tooling::CompileCommand>
   getCompileCommand(PathRef File) const override;
 
   /// Returns the path to first directory containing a compilation database in
   /// \p File's parents.
-  llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const override;
+  std::optional<ProjectInfo> getProjectInfo(PathRef File) const override;
 
   bool blockUntilIdle(Deadline Timeout) const override;
 
@@ -150,7 +150,7 @@ class DirectoryBasedGlobalCompilationDatabase
     std::shared_ptr<const tooling::CompilationDatabase> CDB;
     ProjectInfo PI;
   };
-  llvm::Optional<CDBLookupResult> lookupCDB(CDBLookupRequest Request) const;
+  std::optional<CDBLookupResult> lookupCDB(CDBLookupRequest Request) const;
 
   class BroadcastThread;
   std::unique_ptr<BroadcastThread> Broadcaster;
@@ -186,14 +186,14 @@ class OverlayCDB : public DelegatingCDB {
              std::vector<std::string> FallbackFlags = {},
              CommandMangler Mangler = nullptr);
 
-  llvm::Optional<tooling::CompileCommand>
+  std::optional<tooling::CompileCommand>
   getCompileCommand(PathRef File) const override;
   tooling::CompileCommand getFallbackCommand(PathRef File) const override;
 
   /// Sets or clears the compilation command for a particular file.
   void
   setCompileCommand(PathRef File,
-                    llvm::Optional<tooling::CompileCommand> CompilationCommand);
+                    std::optional<tooling::CompileCommand> CompilationCommand);
 
 private:
   mutable std::mutex Mutex;

diff  --git a/clang-tools-extra/clangd/HeaderSourceSwitch.cpp b/clang-tools-extra/clangd/HeaderSourceSwitch.cpp
index ded7a43d4ea14..2351858cc6297 100644
--- a/clang-tools-extra/clangd/HeaderSourceSwitch.cpp
+++ b/clang-tools-extra/clangd/HeaderSourceSwitch.cpp
@@ -18,7 +18,7 @@
 namespace clang {
 namespace clangd {
 
-llvm::Optional<Path> getCorrespondingHeaderOrSource(
+std::optional<Path> getCorrespondingHeaderOrSource(
     PathRef OriginalFile, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
   llvm::StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
                                         ".c++", ".m", ".mm"};
@@ -64,9 +64,9 @@ llvm::Optional<Path> getCorrespondingHeaderOrSource(
   return std::nullopt;
 }
 
-llvm::Optional<Path> getCorrespondingHeaderOrSource(PathRef OriginalFile,
-                                                    ParsedAST &AST,
-                                                    const SymbolIndex *Index) {
+std::optional<Path> getCorrespondingHeaderOrSource(PathRef OriginalFile,
+                                                   ParsedAST &AST,
+                                                   const SymbolIndex *Index) {
   if (!Index) {
     // FIXME: use the AST to do the inference.
     return std::nullopt;

diff  --git a/clang-tools-extra/clangd/HeaderSourceSwitch.h b/clang-tools-extra/clangd/HeaderSourceSwitch.h
index 1cf9da969e24b..aa1d73e5807a2 100644
--- a/clang-tools-extra/clangd/HeaderSourceSwitch.h
+++ b/clang-tools-extra/clangd/HeaderSourceSwitch.h
@@ -18,14 +18,14 @@ namespace clangd {
 
 /// Given a header file, returns the best matching source file, and vice visa.
 /// It only uses the filename heuristics to do the inference.
-llvm::Optional<Path> getCorrespondingHeaderOrSource(
+std::optional<Path> getCorrespondingHeaderOrSource(
     PathRef OriginalFile, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS);
 
 /// Given a header file, returns the best matching source file, and vice visa.
 /// The heuristics incorporate with the AST and the index (if provided).
-llvm::Optional<Path> getCorrespondingHeaderOrSource(PathRef OriginalFile,
-                                                    ParsedAST &AST,
-                                                    const SymbolIndex *Index);
+std::optional<Path> getCorrespondingHeaderOrSource(PathRef OriginalFile,
+                                                   ParsedAST &AST,
+                                                   const SymbolIndex *Index);
 
 /// Returns all indexable decls that are present in the main file of the AST.
 /// Exposed for unittests.

diff  --git a/clang-tools-extra/clangd/Headers.cpp b/clang-tools-extra/clangd/Headers.cpp
index fd058e8cfd894..3e5fefb071307 100644
--- a/clang-tools-extra/clangd/Headers.cpp
+++ b/clang-tools-extra/clangd/Headers.cpp
@@ -235,7 +235,7 @@ void IncludeStructure::collect(const CompilerInstance &CI) {
   CI.getPreprocessor().addPPCallbacks(std::move(Collector));
 }
 
-llvm::Optional<IncludeStructure::HeaderID>
+std::optional<IncludeStructure::HeaderID>
 IncludeStructure::getID(const FileEntry *Entry) const {
   // HeaderID of the main file is always 0;
   if (Entry == MainFileEntry) {
@@ -315,7 +315,7 @@ bool IncludeInserter::shouldInsertInclude(
   return !Included(DeclaringHeader) && !Included(InsertedHeader.File);
 }
 
-llvm::Optional<std::string>
+std::optional<std::string>
 IncludeInserter::calculateIncludePath(const HeaderFile &InsertedHeader,
                                       llvm::StringRef IncludingFile) const {
   assert(InsertedHeader.valid());
@@ -345,10 +345,10 @@ IncludeInserter::calculateIncludePath(const HeaderFile &InsertedHeader,
   return Suggested;
 }
 
-llvm::Optional<TextEdit>
+std::optional<TextEdit>
 IncludeInserter::insert(llvm::StringRef VerbatimHeader,
                         tooling::IncludeDirective Directive) const {
-  llvm::Optional<TextEdit> Edit;
+  std::optional<TextEdit> Edit;
   if (auto Insertion =
           Inserter.insert(VerbatimHeader.trim("\"<>"),
                           VerbatimHeader.startswith("<"), Directive))

diff  --git a/clang-tools-extra/clangd/Headers.h b/clang-tools-extra/clangd/Headers.h
index 68ccf935fbd43..8a5b885a680e9 100644
--- a/clang-tools-extra/clangd/Headers.h
+++ b/clang-tools-extra/clangd/Headers.h
@@ -72,7 +72,7 @@ struct Inclusion {
   unsigned HashOffset = 0; // Byte offset from start of file to #.
   int HashLine = 0;        // Line number containing the directive, 0-indexed.
   SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
-  llvm::Optional<unsigned> HeaderID;
+  std::optional<unsigned> HeaderID;
   bool BehindPragmaKeep = false; // Has IWYU pragma: keep right after.
 };
 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Inclusion &);
@@ -143,7 +143,7 @@ class IncludeStructure {
   // file builds.
   enum class HeaderID : unsigned {};
 
-  llvm::Optional<HeaderID> getID(const FileEntry *Entry) const;
+  std::optional<HeaderID> getID(const FileEntry *Entry) const;
   HeaderID getOrCreateID(FileEntryRef Entry);
 
   StringRef getRealPath(HeaderID ID) const {
@@ -243,14 +243,14 @@ class IncludeInserter {
   ///
   /// \return A quoted "path" or <path> to be included, or std::nullopt if it
   /// couldn't be shortened.
-  llvm::Optional<std::string>
+  std::optional<std::string>
   calculateIncludePath(const HeaderFile &InsertedHeader,
                        llvm::StringRef IncludingFile) const;
 
   /// Calculates an edit that inserts \p VerbatimHeader into code. If the header
   /// is already included, this returns std::nullopt.
-  llvm::Optional<TextEdit> insert(llvm::StringRef VerbatimHeader,
-                                  tooling::IncludeDirective Directive) const;
+  std::optional<TextEdit> insert(llvm::StringRef VerbatimHeader,
+                                 tooling::IncludeDirective Directive) const;
 
 private:
   StringRef FileName;

diff  --git a/clang-tools-extra/clangd/Hover.cpp b/clang-tools-extra/clangd/Hover.cpp
index ca6301999f2c5..456b54440b549 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -402,8 +402,8 @@ static llvm::FormattedNumber printHex(const llvm::APSInt &V) {
   return llvm::format_hex(Bits, 0);
 }
 
-llvm::Optional<std::string> printExprValue(const Expr *E,
-                                           const ASTContext &Ctx) {
+std::optional<std::string> printExprValue(const Expr *E,
+                                          const ASTContext &Ctx) {
   // InitListExpr has two forms, syntactic and semantic. They are the same thing
   // (refer to a same AST node) in most cases.
   // When they are 
diff erent, RAV returns the syntactic form, and we should feed
@@ -451,8 +451,8 @@ llvm::Optional<std::string> printExprValue(const Expr *E,
   return Constant.Val.getAsString(Ctx, T);
 }
 
-llvm::Optional<std::string> printExprValue(const SelectionTree::Node *N,
-                                           const ASTContext &Ctx) {
+std::optional<std::string> printExprValue(const SelectionTree::Node *N,
+                                          const ASTContext &Ctx) {
   for (; N; N = N->Parent) {
     // Try to evaluate the first evaluatable enclosing expression.
     if (const Expr *E = N->ASTNode.get<Expr>()) {
@@ -471,7 +471,7 @@ llvm::Optional<std::string> printExprValue(const SelectionTree::Node *N,
   return std::nullopt;
 }
 
-llvm::Optional<StringRef> fieldName(const Expr *E) {
+std::optional<StringRef> fieldName(const Expr *E) {
   const auto *ME = llvm::dyn_cast<MemberExpr>(E->IgnoreCasts());
   if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
     return std::nullopt;
@@ -482,7 +482,7 @@ llvm::Optional<StringRef> fieldName(const Expr *E) {
 }
 
 // If CMD is of the form T foo() { return FieldName; } then returns "FieldName".
-llvm::Optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
+std::optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
   assert(CMD->hasBody());
   if (CMD->getNumParams() != 0 || CMD->isVariadic())
     return std::nullopt;
@@ -501,7 +501,7 @@ llvm::Optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
 //   void foo(T arg) { FieldName = std::move(arg); }
 //   R foo(T arg) { FieldName = std::move(arg); return *this; }
 // then returns "FieldName"
-llvm::Optional<StringRef> setterVariableName(const CXXMethodDecl *CMD) {
+std::optional<StringRef> setterVariableName(const CXXMethodDecl *CMD) {
   assert(CMD->hasBody());
   if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
     return std::nullopt;
@@ -1283,8 +1283,8 @@ markup::Document HoverInfo::present() const {
 
 // If the backtick at `Offset` starts a probable quoted range, return the range
 // (including the quotes).
-llvm::Optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
-                                                      unsigned Offset) {
+std::optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
+                                                     unsigned Offset) {
   assert(Line[Offset] == '`');
 
   // The open-quote is usually preceded by whitespace.

diff  --git a/clang-tools-extra/clangd/Hover.h b/clang-tools-extra/clangd/Hover.h
index a2c4e60949493..e63ff95b400b3 100644
--- a/clang-tools-extra/clangd/Hover.h
+++ b/clang-tools-extra/clangd/Hover.h
@@ -33,7 +33,7 @@ struct HoverInfo {
     /// Pretty-printed type
     std::string Type;
     /// Desugared type
-    llvm::Optional<std::string> AKA;
+    std::optional<std::string> AKA;
   };
 
   /// Represents parameters of a function, a template or a macro.
@@ -44,11 +44,11 @@ struct HoverInfo {
   struct Param {
     /// The printable parameter type, e.g. "int", or "typename" (in
     /// TemplateParameters), might be std::nullopt for macro parameters.
-    llvm::Optional<PrintedType> Type;
+    std::optional<PrintedType> Type;
     /// std::nullopt for unnamed parameters.
     std::optional<std::string> Name;
     /// std::nullopt if no default is provided.
-    llvm::Optional<std::string> Default;
+    std::optional<std::string> Default;
   };
 
   /// For a variable named Bar, declared in clang::clangd::Foo::getFoo the
@@ -61,13 +61,13 @@ struct HoverInfo {
   /// auto/decltype.
   /// Contains all of the enclosing namespaces, empty string means global
   /// namespace.
-  llvm::Optional<std::string> NamespaceScope;
+  std::optional<std::string> NamespaceScope;
   /// Remaining named contexts in symbol's qualified name, empty string means
   /// symbol is not local.
   std::string LocalScope;
   /// Name of the symbol, does not contain any "::".
   std::string Name;
-  llvm::Optional<Range> SymRange;
+  std::optional<Range> SymRange;
   index::SymbolKind Kind = index::SymbolKind::Unknown;
   std::string Documentation;
   /// Source code containing the definition of the symbol.
@@ -78,24 +78,24 @@ struct HoverInfo {
   std::string AccessSpecifier;
   /// Printable variable type.
   /// Set only for variables.
-  llvm::Optional<PrintedType> Type;
+  std::optional<PrintedType> Type;
   /// Set for functions and lambdas.
-  llvm::Optional<PrintedType> ReturnType;
+  std::optional<PrintedType> ReturnType;
   /// Set for functions, lambdas and macros with parameters.
-  llvm::Optional<std::vector<Param>> Parameters;
+  std::optional<std::vector<Param>> Parameters;
   /// Set for all templates(function, class, variable).
-  llvm::Optional<std::vector<Param>> TemplateParameters;
+  std::optional<std::vector<Param>> TemplateParameters;
   /// Contains the evaluated value of the symbol if available.
-  llvm::Optional<std::string> Value;
+  std::optional<std::string> Value;
   /// Contains the byte-size of fields and types where it's interesting.
-  llvm::Optional<uint64_t> Size;
+  std::optional<uint64_t> Size;
   /// Contains the offset of fields within the enclosing class.
-  llvm::Optional<uint64_t> Offset;
+  std::optional<uint64_t> Offset;
   /// Contains the padding following a field within the enclosing class.
-  llvm::Optional<uint64_t> Padding;
+  std::optional<uint64_t> Padding;
   // Set when symbol is inside function call. Contains information extracted
   // from the callee definition about the argument this is passed as.
-  llvm::Optional<Param> CalleeArgInfo;
+  std::optional<Param> CalleeArgInfo;
   struct PassType {
     // How the variable is passed to callee.
     enum PassMode { Ref, ConstRef, Value };
@@ -106,7 +106,7 @@ struct HoverInfo {
     bool Converted = false;
   };
   // Set only if CalleeArgInfo is set.
-  llvm::Optional<PassType> CallPassType;
+  std::optional<PassType> CallPassType;
 
   /// Produce a user-readable information.
   markup::Document present() const;

diff  --git a/clang-tools-extra/clangd/IncludeCleaner.cpp b/clang-tools-extra/clangd/IncludeCleaner.cpp
index daac976a41e79..dbed805142b71 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.cpp
+++ b/clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -345,7 +345,7 @@ ReferencedLocations findReferencedLocations(ParsedAST &AST) {
 ReferencedFiles findReferencedFiles(
     const ReferencedLocations &Locs, const SourceManager &SM,
     llvm::function_ref<FileID(FileID)> HeaderResponsible,
-    llvm::function_ref<Optional<StringRef>(FileID)> UmbrellaHeader) {
+    llvm::function_ref<std::optional<StringRef>(FileID)> UmbrellaHeader) {
   std::vector<SourceLocation> Sorted{Locs.User.begin(), Locs.User.end()};
   llvm::sort(Sorted); // Group by FileID.
   ReferencedFilesBuilder Builder(SM);
@@ -390,7 +390,7 @@ ReferencedFiles findReferencedFiles(const ReferencedLocations &Locs,
       [&SM, &Includes](FileID ID) {
         return headerResponsible(ID, SM, Includes);
       },
-      [&SM, &CanonIncludes](FileID ID) -> Optional<StringRef> {
+      [&SM, &CanonIncludes](FileID ID) -> std::optional<StringRef> {
         auto Entry = SM.getFileEntryRefForID(ID);
         if (!Entry)
           return std::nullopt;

diff  --git a/clang-tools-extra/clangd/IncludeCleaner.h b/clang-tools-extra/clangd/IncludeCleaner.h
index fc3d04da78a8e..8d8a5f75b3d3a 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.h
+++ b/clang-tools-extra/clangd/IncludeCleaner.h
@@ -77,7 +77,7 @@ struct ReferencedFiles {
 ReferencedFiles findReferencedFiles(
     const ReferencedLocations &Locs, const SourceManager &SM,
     llvm::function_ref<FileID(FileID)> HeaderResponsible,
-    llvm::function_ref<Optional<StringRef>(FileID)> UmbrellaHeader);
+    llvm::function_ref<std::optional<StringRef>(FileID)> UmbrellaHeader);
 ReferencedFiles findReferencedFiles(const ReferencedLocations &Locs,
                                     const IncludeStructure &Includes,
                                     const CanonicalIncludes &CanonIncludes,

diff  --git a/clang-tools-extra/clangd/IncludeFixer.cpp b/clang-tools-extra/clangd/IncludeFixer.cpp
index 5ab993230709e..f6b397747a69e 100644
--- a/clang-tools-extra/clangd/IncludeFixer.cpp
+++ b/clang-tools-extra/clangd/IncludeFixer.cpp
@@ -50,8 +50,8 @@ namespace clang {
 namespace clangd {
 namespace {
 
-llvm::Optional<llvm::StringRef> getArgStr(const clang::Diagnostic &Info,
-                                          unsigned Index) {
+std::optional<llvm::StringRef> getArgStr(const clang::Diagnostic &Info,
+                                         unsigned Index) {
   switch (Info.getArgKind(Index)) {
   case DiagnosticsEngine::ak_c_string:
     return llvm::StringRef(Info.getArgCStr(Index));
@@ -62,7 +62,7 @@ llvm::Optional<llvm::StringRef> getArgStr(const clang::Diagnostic &Info,
   }
 }
 
-std::vector<Fix> only(llvm::Optional<Fix> F) {
+std::vector<Fix> only(std::optional<Fix> F) {
   if (F)
     return {std::move(*F)};
   return {};
@@ -248,7 +248,7 @@ std::vector<Fix> IncludeFixer::fix(DiagnosticsEngine::Level DiagLevel,
   return {};
 }
 
-llvm::Optional<Fix> IncludeFixer::insertHeader(llvm::StringRef Spelled,
+std::optional<Fix> IncludeFixer::insertHeader(llvm::StringRef Spelled,
                                                llvm::StringRef Symbol,
                                                tooling::IncludeDirective Directive) const {
   Fix F;
@@ -282,7 +282,7 @@ std::vector<Fix> IncludeFixer::fixIncompleteType(const Type &T) const {
   auto ID = getSymbolID(TD);
   if (!ID)
     return {};
-  llvm::Optional<const SymbolSlab *> Symbols = lookupCached(ID);
+  std::optional<const SymbolSlab *> Symbols = lookupCached(ID);
   if (!Symbols)
     return {};
   const SymbolSlab &Syms = **Symbols;
@@ -347,7 +347,7 @@ std::vector<Fix> IncludeFixer::fixesForSymbols(const SymbolSlab &Syms) const {
 // "::X::Y" that is qualified by unresolved name "clangd":
 //     clang::clangd::X::Y
 //            ~
-llvm::Optional<std::string> qualifiedByUnresolved(const SourceManager &SM,
+std::optional<std::string> qualifiedByUnresolved(const SourceManager &SM,
                                                   SourceLocation Loc,
                                                   const LangOptions &LangOpts) {
   std::string Result;
@@ -373,15 +373,15 @@ struct CheapUnresolvedName {
   // This is the part of what was typed that was resolved, and it's in its
   // resolved form not its typed form (think `namespace clang { clangd::x }` -->
   // `clang::clangd::`).
-  llvm::Optional<std::string> ResolvedScope;
+  std::optional<std::string> ResolvedScope;
 
   // Unresolved part of the scope. When the unresolved name is a specifier, we
   // use the name that comes after it as the alternative name to resolve and use
   // the specifier as the extra scope in the accessible scopes.
-  llvm::Optional<std::string> UnresolvedScope;
+  std::optional<std::string> UnresolvedScope;
 };
 
-llvm::Optional<std::string> getSpelledSpecifier(const CXXScopeSpec &SS,
+std::optional<std::string> getSpelledSpecifier(const CXXScopeSpec &SS,
     const SourceManager &SM) {
   // Support specifiers written within a single macro argument.
   if (!SM.isWrittenInSameFile(SS.getBeginLoc(), SS.getEndLoc()))
@@ -395,7 +395,7 @@ llvm::Optional<std::string> getSpelledSpecifier(const CXXScopeSpec &SS,
 
 // Extracts unresolved name and scope information around \p Unresolved.
 // FIXME: try to merge this with the scope-wrangling code in CodeComplete.
-llvm::Optional<CheapUnresolvedName> extractUnresolvedNameCheaply(
+std::optional<CheapUnresolvedName> extractUnresolvedNameCheaply(
     const SourceManager &SM, const DeclarationNameInfo &Unresolved,
     CXXScopeSpec *SS, const LangOptions &LangOpts, bool UnresolvedIsSpecifier) {
   CheapUnresolvedName Result;
@@ -406,7 +406,7 @@ llvm::Optional<CheapUnresolvedName> extractUnresolvedNameCheaply(
         Result.ResolvedScope = "";
       } else if (const auto *NS = Nested->getAsNamespace()) {
         std::string SpecifiedNS = printNamespaceScope(*NS);
-        llvm::Optional<std::string> Spelling = getSpelledSpecifier(*SS, SM);
+        std::optional<std::string> Spelling = getSpelledSpecifier(*SS, SM);
 
         // Check the specifier spelled in the source.
         // If the resolved scope doesn't end with the spelled scope, the
@@ -491,7 +491,7 @@ collectAccessibleScopes(Sema &Sem, const DeclarationNameInfo &Typo, Scope *S,
 
 class IncludeFixer::UnresolvedNameRecorder : public ExternalSemaSource {
 public:
-  UnresolvedNameRecorder(llvm::Optional<UnresolvedName> &LastUnresolvedName)
+  UnresolvedNameRecorder(std::optional<UnresolvedName> &LastUnresolvedName)
       : LastUnresolvedName(LastUnresolvedName) {}
 
   void InitializeSema(Sema &S) override { this->SemaPtr = &S; }
@@ -544,7 +544,7 @@ class IncludeFixer::UnresolvedNameRecorder : public ExternalSemaSource {
 private:
   Sema *SemaPtr = nullptr;
 
-  llvm::Optional<UnresolvedName> &LastUnresolvedName;
+  std::optional<UnresolvedName> &LastUnresolvedName;
 };
 
 llvm::IntrusiveRefCntPtr<ExternalSemaSource>
@@ -565,13 +565,13 @@ std::vector<Fix> IncludeFixer::fixUnresolvedName() const {
   Req.RestrictForCodeCompletion = true;
   Req.Limit = 100;
 
-  if (llvm::Optional<const SymbolSlab *> Syms = fuzzyFindCached(Req))
+  if (std::optional<const SymbolSlab *> Syms = fuzzyFindCached(Req))
     return fixesForSymbols(**Syms);
 
   return {};
 }
 
-llvm::Optional<const SymbolSlab *>
+std::optional<const SymbolSlab *>
 IncludeFixer::fuzzyFindCached(const FuzzyFindRequest &Req) const {
   auto ReqStr = llvm::formatv("{0}", toJSON(Req)).str();
   auto I = FuzzyFindCache.find(ReqStr);
@@ -594,7 +594,7 @@ IncludeFixer::fuzzyFindCached(const FuzzyFindRequest &Req) const {
   return &E.first->second;
 }
 
-llvm::Optional<const SymbolSlab *>
+std::optional<const SymbolSlab *>
 IncludeFixer::lookupCached(const SymbolID &ID) const {
   LookupRequest Req;
   Req.IDs.insert(ID);

diff  --git a/clang-tools-extra/clangd/IncludeFixer.h b/clang-tools-extra/clangd/IncludeFixer.h
index 2a74c23ffa8ea..0c51ad9ff9ba4 100644
--- a/clang-tools-extra/clangd/IncludeFixer.h
+++ b/clang-tools-extra/clangd/IncludeFixer.h
@@ -56,10 +56,10 @@ class IncludeFixer {
   /// Generates header insertion fixes for all symbols. Fixes are deduplicated.
   std::vector<Fix> fixesForSymbols(const SymbolSlab &Syms) const;
 
-  llvm::Optional<Fix>
-  insertHeader(llvm::StringRef Name, llvm::StringRef Symbol = "",
-               tooling::IncludeDirective Directive =
-                   tooling::IncludeDirective::Include) const;
+  std::optional<Fix> insertHeader(llvm::StringRef Name,
+                                  llvm::StringRef Symbol = "",
+                                  tooling::IncludeDirective Directive =
+                                      tooling::IncludeDirective::Include) const;
 
   struct UnresolvedName {
     std::string Name;   // E.g. "X" in foo::X.
@@ -84,7 +84,7 @@ class IncludeFixer {
 
   // These collect the last unresolved name so that we can associate it with the
   // diagnostic.
-  llvm::Optional<UnresolvedName> LastUnresolvedName;
+  std::optional<UnresolvedName> LastUnresolvedName;
 
   // There can be multiple diagnostics that are caused by the same unresolved
   // name or incomplete type in one parse, especially when code is
@@ -93,9 +93,9 @@ class IncludeFixer {
   mutable llvm::StringMap<SymbolSlab> FuzzyFindCache;
   mutable llvm::DenseMap<SymbolID, SymbolSlab> LookupCache;
   // Returns std::nullopt if the number of index requests has reached the limit.
-  llvm::Optional<const SymbolSlab *>
+  std::optional<const SymbolSlab *>
   fuzzyFindCached(const FuzzyFindRequest &Req) const;
-  llvm::Optional<const SymbolSlab *> lookupCached(const SymbolID &ID) const;
+  std::optional<const SymbolSlab *> lookupCached(const SymbolID &ID) const;
 };
 
 } // namespace clangd

diff  --git a/clang-tools-extra/clangd/InlayHints.cpp b/clang-tools-extra/clangd/InlayHints.cpp
index 20a8adcecc731..30c7c05e3c02f 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -648,7 +648,7 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
   }
 
   // Get the range of the main file that *exactly* corresponds to R.
-  llvm::Optional<Range> getHintRange(SourceRange R) {
+  std::optional<Range> getHintRange(SourceRange R) {
     const auto &SM = AST.getSourceManager();
     auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(R));
     // TokenBuffer will return null if e.g. R corresponds to only part of a

diff  --git a/clang-tools-extra/clangd/JSONTransport.cpp b/clang-tools-extra/clangd/JSONTransport.cpp
index 50b1833a75752..9dc0df807aa34 100644
--- a/clang-tools-extra/clangd/JSONTransport.cpp
+++ b/clang-tools-extra/clangd/JSONTransport.cpp
@@ -164,12 +164,12 @@ bool JSONTransport::handleMessage(llvm::json::Value Message,
   // Message must be an object with "jsonrpc":"2.0".
   auto *Object = Message.getAsObject();
   if (!Object ||
-      Object->getString("jsonrpc") != llvm::Optional<llvm::StringRef>("2.0")) {
+      Object->getString("jsonrpc") != std::optional<llvm::StringRef>("2.0")) {
     elog("Not a JSON-RPC 2.0 message: {0:2}", Message);
     return false;
   }
   // ID may be any JSON value. If absent, this is a notification.
-  llvm::Optional<llvm::json::Value> ID;
+  std::optional<llvm::json::Value> ID;
   if (auto *I = Object->get("id"))
     ID = std::move(*I);
   auto Method = Object->getString("method");

diff  --git a/clang-tools-extra/clangd/ParsedAST.cpp b/clang-tools-extra/clangd/ParsedAST.cpp
index c2846749a7082..cd814c8287027 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -339,7 +339,7 @@ void applyWarningOptions(llvm::ArrayRef<std::string> ExtraArgs,
 
 } // namespace
 
-llvm::Optional<ParsedAST>
+std::optional<ParsedAST>
 ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
                  std::unique_ptr<clang::CompilerInvocation> CI,
                  llvm::ArrayRef<Diag> CompilerInvocationDiags,
@@ -376,7 +376,7 @@ ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
                        [&](const auto &L) { L->sawDiagnostic(D, Diag); });
       });
 
-  llvm::Optional<PreamblePatch> Patch;
+  std::optional<PreamblePatch> Patch;
   bool PreserveDiags = true;
   // We might use an ignoring diagnostic consumer if they are going to be
   // dropped later on to not pay for extra latency by processing them.
@@ -465,10 +465,10 @@ ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
   // In practice almost all checks work well without modifications.
   std::vector<std::unique_ptr<tidy::ClangTidyCheck>> CTChecks;
   ast_matchers::MatchFinder CTFinder;
-  llvm::Optional<tidy::ClangTidyContext> CTContext;
+  std::optional<tidy::ClangTidyContext> CTContext;
   // Must outlive FixIncludes.
   auto BuildDir = VFS->getCurrentWorkingDirectory();
-  llvm::Optional<IncludeFixer> FixIncludes;
+  std::optional<IncludeFixer> FixIncludes;
   llvm::DenseMap<diag::kind, DiagnosticsEngine::Level> OverriddenSeverity;
   // No need to run clang-tidy or IncludeFixerif we are not going to surface
   // diagnostics.
@@ -653,7 +653,7 @@ ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
   // CompilerInstance won't run this callback, do it directly.
   ASTDiags.EndSourceFile();
 
-  llvm::Optional<std::vector<Diag>> Diags;
+  std::optional<std::vector<Diag>> Diags;
   // FIXME: Also skip generation of diagnostics alltogether to speed up ast
   // builds when we are patching a stale preamble.
   if (PreserveDiags) {
@@ -770,7 +770,7 @@ ParsedAST::ParsedAST(PathRef TUPath, llvm::StringRef Version,
                      syntax::TokenBuffer Tokens, MainFileMacros Macros,
                      std::vector<PragmaMark> Marks,
                      std::vector<Decl *> LocalTopLevelDecls,
-                     llvm::Optional<std::vector<Diag>> Diags,
+                     std::optional<std::vector<Diag>> Diags,
                      IncludeStructure Includes, CanonicalIncludes CanonIncludes)
     : TUPath(TUPath), Version(Version), Preamble(std::move(Preamble)),
       Clang(std::move(Clang)), Action(std::move(Action)),
@@ -783,7 +783,7 @@ ParsedAST::ParsedAST(PathRef TUPath, llvm::StringRef Version,
   assert(this->Action);
 }
 
-llvm::Optional<llvm::StringRef> ParsedAST::preambleVersion() const {
+std::optional<llvm::StringRef> ParsedAST::preambleVersion() const {
   if (!Preamble)
     return std::nullopt;
   return llvm::StringRef(Preamble->Version);

diff  --git a/clang-tools-extra/clangd/ParsedAST.h b/clang-tools-extra/clangd/ParsedAST.h
index 8f74c17992d41..f0085d7e35874 100644
--- a/clang-tools-extra/clangd/ParsedAST.h
+++ b/clang-tools-extra/clangd/ParsedAST.h
@@ -49,7 +49,7 @@ class ParsedAST {
   /// Attempts to run Clang and store the parsed AST.
   /// If \p Preamble is non-null it is reused during parsing.
   /// This function does not check if preamble is valid to reuse.
-  static llvm::Optional<ParsedAST>
+  static std::optional<ParsedAST>
   build(llvm::StringRef Filename, const ParseInputs &Inputs,
         std::unique_ptr<clang::CompilerInvocation> CI,
         llvm::ArrayRef<Diag> CompilerInvocationDiags,
@@ -88,7 +88,7 @@ class ParsedAST {
   /// (These should be const, but RecursiveASTVisitor requires Decl*).
   ArrayRef<Decl *> getLocalTopLevelDecls();
 
-  const llvm::Optional<std::vector<Diag>> &getDiagnostics() const {
+  const std::optional<std::vector<Diag>> &getDiagnostics() const {
     return Diags;
   }
 
@@ -115,7 +115,7 @@ class ParsedAST {
 
   /// Returns the version of the ParseInputs used to build Preamble part of this
   /// AST. Might be std::nullopt if no Preamble is used.
-  llvm::Optional<llvm::StringRef> preambleVersion() const;
+  std::optional<llvm::StringRef> preambleVersion() const;
 
   const HeuristicResolver *getHeuristicResolver() const {
     return Resolver.get();
@@ -128,7 +128,7 @@ class ParsedAST {
             std::unique_ptr<FrontendAction> Action, syntax::TokenBuffer Tokens,
             MainFileMacros Macros, std::vector<PragmaMark> Marks,
             std::vector<Decl *> LocalTopLevelDecls,
-            llvm::Optional<std::vector<Diag>> Diags, IncludeStructure Includes,
+            std::optional<std::vector<Diag>> Diags, IncludeStructure Includes,
             CanonicalIncludes CanonIncludes);
 
   Path TUPath;
@@ -155,7 +155,7 @@ class ParsedAST {
   std::vector<PragmaMark> Marks;
   // Data, stored after parsing. std::nullopt if AST was built with a stale
   // preamble.
-  llvm::Optional<std::vector<Diag>> Diags;
+  std::optional<std::vector<Diag>> Diags;
   // Top-level decls inside the current file. Not that this does not include
   // top-level decls from the preamble.
   std::vector<Decl *> LocalTopLevelDecls;

diff  --git a/clang-tools-extra/clangd/Protocol.h b/clang-tools-extra/clangd/Protocol.h
index 9cd1955ba95be..9056ae6cebf00 100644
--- a/clang-tools-extra/clangd/Protocol.h
+++ b/clang-tools-extra/clangd/Protocol.h
@@ -416,7 +416,7 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, MarkupKind);
 struct ClientCapabilities {
   /// The supported set of SymbolKinds for workspace/symbol.
   /// workspace.symbol.symbolKind.valueSet
-  llvm::Optional<SymbolKindBitset> WorkspaceSymbolKinds;
+  std::optional<SymbolKindBitset> WorkspaceSymbolKinds;
 
   /// Whether the client accepts diagnostics with codeActions attached inline.
   /// textDocument.publishDiagnostics.codeActionsInline.
@@ -469,7 +469,7 @@ struct ClientCapabilities {
 
   /// The supported set of CompletionItemKinds for textDocument/completion.
   /// textDocument.completion.completionItemKind.valueSet
-  llvm::Optional<CompletionItemKindBitset> CompletionItemKinds;
+  std::optional<CompletionItemKindBitset> CompletionItemKinds;
 
   /// The documentation format that should be used for textDocument/completion.
   /// textDocument.completion.completionItem.documentationFormat
@@ -490,7 +490,7 @@ struct ClientCapabilities {
   bool TheiaSemanticHighlighting = false;
 
   /// Supported encodings for LSP character offsets. (clangd extension).
-  llvm::Optional<std::vector<OffsetEncoding>> offsetEncoding;
+  std::optional<std::vector<OffsetEncoding>> offsetEncoding;
 
   /// The content format that should be used for Hover requests.
   /// textDocument.hover.contentEncoding
@@ -651,14 +651,14 @@ struct WorkDoneProgressReport {
   ///
   /// Clients that don't support cancellation or don't support control
   /// the button's enablement state are allowed to ignore the setting.
-  llvm::Optional<bool> cancellable;
+  std::optional<bool> cancellable;
 
   /// Optional, more detailed associated progress message. Contains
   /// complementary information to the `title`.
   ///
   /// Examples: "3/25 files", "project/src/module2", "node_modules/some_dep".
   /// If unset, the previous progress message (if any) is still valid.
-  llvm::Optional<std::string> message;
+  std::optional<std::string> message;
 
   /// Optional progress percentage to display (value 100 is considered 100%).
   /// If not provided infinite progress is assumed and clients are allowed
@@ -666,7 +666,7 @@ struct WorkDoneProgressReport {
   ///
   /// The value should be steadily rising. Clients are free to ignore values
   /// that are not following this rule.
-  llvm::Optional<unsigned> percentage;
+  std::optional<unsigned> percentage;
 };
 llvm::json::Value toJSON(const WorkDoneProgressReport &);
 //
@@ -674,7 +674,7 @@ llvm::json::Value toJSON(const WorkDoneProgressReport &);
 struct WorkDoneProgressEnd {
   /// Optional, a final message indicating to for example indicate the outcome
   /// of the operation.
-  llvm::Optional<std::string> message;
+  std::optional<std::string> message;
 };
 llvm::json::Value toJSON(const WorkDoneProgressEnd &);
 
@@ -879,7 +879,7 @@ struct Diagnostic {
   std::string code;
 
   /// An optional property to describe the error code.
-  llvm::Optional<CodeDescription> codeDescription;
+  std::optional<CodeDescription> codeDescription;
 
   /// A human-readable string describing the source of this
   /// diagnostic, e.g. 'typescript' or 'super lint'.
@@ -1019,13 +1019,13 @@ struct CodeAction {
 
   /// The kind of the code action.
   /// Used to filter code actions.
-  llvm::Optional<std::string> kind;
+  std::optional<std::string> kind;
   const static llvm::StringLiteral QUICKFIX_KIND;
   const static llvm::StringLiteral REFACTOR_KIND;
   const static llvm::StringLiteral INFO_KIND;
 
   /// The diagnostics that this code action resolves.
-  llvm::Optional<std::vector<Diagnostic>> diagnostics;
+  std::optional<std::vector<Diagnostic>> diagnostics;
 
   /// Marks this as a preferred action. Preferred actions are used by the
   /// `auto fix` command and can be targeted by keybindings.
@@ -1035,11 +1035,11 @@ struct CodeAction {
   bool isPreferred = false;
 
   /// The workspace edit this code action performs.
-  llvm::Optional<WorkspaceEdit> edit;
+  std::optional<WorkspaceEdit> edit;
 
   /// A command this code action executes. If a code action provides an edit
   /// and a command, first the edit is executed and then the command.
-  llvm::Optional<Command> command;
+  std::optional<Command> command;
 };
 llvm::json::Value toJSON(const CodeAction &);
 
@@ -1097,7 +1097,7 @@ struct SymbolInformation {
   /// This can be used to re-rank results as the user types, using client-side
   /// fuzzy-matching (that score should be multiplied with this one).
   /// This is a clangd extension, set only for workspace/symbol responses.
-  llvm::Optional<float> score;
+  std::optional<float> score;
 };
 llvm::json::Value toJSON(const SymbolInformation &);
 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolInformation &);
@@ -1118,9 +1118,9 @@ struct SymbolDetails {
 
   SymbolID ID;
 
-  llvm::Optional<Location> declarationRange;
+  std::optional<Location> declarationRange;
 
-  llvm::Optional<Location> definitionRange;
+  std::optional<Location> definitionRange;
 };
 llvm::json::Value toJSON(const SymbolDetails &);
 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolDetails &);
@@ -1202,7 +1202,7 @@ struct Hover {
 
   /// An optional range is a range inside a text document
   /// that is used to visualize a hover, e.g. by changing the background color.
-  llvm::Optional<Range> range;
+  std::optional<Range> range;
 };
 llvm::json::Value toJSON(const Hover &H);
 
@@ -1261,7 +1261,7 @@ struct CompletionItem {
   ///
   /// Note: The range of the edit must be a single line range and it must
   /// contain the position at which completion has been requested.
-  llvm::Optional<TextEdit> textEdit;
+  std::optional<TextEdit> textEdit;
 
   /// An optional array of additional text edits that are applied when selecting
   /// this completion. Edits must not overlap with the main edit nor with
@@ -1312,7 +1312,7 @@ struct ParameterInformation {
   /// label.
   /// Offsets are computed by lspLength(), which counts UTF-16 code units by
   /// default but that can be overriden, see its documentation for details.
-  llvm::Optional<std::pair<unsigned, unsigned>> labelOffsets;
+  std::optional<std::pair<unsigned, unsigned>> labelOffsets;
 
   /// The documentation of this parameter. Optional.
   std::string documentation;
@@ -1731,9 +1731,9 @@ llvm::json::Value toJSON(const SemanticTokensEdit &);
 struct SemanticTokensOrDelta {
   std::string resultId;
   /// Set if we computed edits relative to a previous set of tokens.
-  llvm::Optional<std::vector<SemanticTokensEdit>> edits;
+  std::optional<std::vector<SemanticTokensEdit>> edits;
   /// Set if we computed a fresh set of tokens.
-  llvm::Optional<std::vector<SemanticToken>> tokens; // encoded as integer array
+  std::optional<std::vector<SemanticToken>> tokens; // encoded as integer array
 };
 llvm::json::Value toJSON(const SemanticTokensOrDelta &);
 
@@ -1870,7 +1870,7 @@ struct ASTNode {
   std::string arcana;
   /// The range of the original source file covered by this node.
   /// May be missing for implicit nodes, or those created by macro expansion.
-  llvm::Optional<Range> range;
+  std::optional<Range> range;
   /// Nodes nested within this one, such as the operands of a BinaryOperator.
   std::vector<ASTNode> children;
 };

diff  --git a/clang-tools-extra/clangd/Quality.cpp b/clang-tools-extra/clangd/Quality.cpp
index 72e3154bdbab6..318488f269f8c 100644
--- a/clang-tools-extra/clangd/Quality.cpp
+++ b/clang-tools-extra/clangd/Quality.cpp
@@ -368,7 +368,7 @@ static float scopeProximityScore(unsigned ScopeDistance) {
   return std::max(0.65, 2.0 * std::pow(0.6, ScopeDistance / 2.0));
 }
 
-static llvm::Optional<llvm::StringRef>
+static std::optional<llvm::StringRef>
 wordMatching(llvm::StringRef Name, const llvm::StringSet<> *ContextWords) {
   if (ContextWords)
     for (const auto &Word : ContextWords->keys())

diff  --git a/clang-tools-extra/clangd/Quality.h b/clang-tools-extra/clangd/Quality.h
index 2a4efe934f580..5fe70454f5cf5 100644
--- a/clang-tools-extra/clangd/Quality.h
+++ b/clang-tools-extra/clangd/Quality.h
@@ -106,7 +106,7 @@ struct SymbolRelevanceSignals {
 
   // Scope proximity is only considered (both index and sema) when this is set.
   ScopeDistance *ScopeProximityMatch = nullptr;
-  llvm::Optional<llvm::StringRef> SymbolScope;
+  std::optional<llvm::StringRef> SymbolScope;
   // A symbol from sema should be accessible from the current scope.
   bool SemaSaysInScope = false;
 

diff  --git a/clang-tools-extra/clangd/Selection.cpp b/clang-tools-extra/clangd/Selection.cpp
index 56836fd850953..f46da8e41f589 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -513,7 +513,7 @@ class SelectionTester {
   }
 
   // Decomposes Loc and returns the offset if the file ID is SelFile.
-  llvm::Optional<unsigned> offsetInSelFile(SourceLocation Loc) const {
+  std::optional<unsigned> offsetInSelFile(SourceLocation Loc) const {
     // Decoding Loc with SM.getDecomposedLoc is relatively expensive.
     // But SourceLocations for a file are numerically contiguous, so we
     // can use cheap integer operations instead.
@@ -1060,7 +1060,7 @@ bool SelectionTree::createEach(ASTContext &AST,
 SelectionTree SelectionTree::createRight(ASTContext &AST,
                                          const syntax::TokenBuffer &Tokens,
                                          unsigned int Begin, unsigned int End) {
-  llvm::Optional<SelectionTree> Result;
+  std::optional<SelectionTree> Result;
   createEach(AST, Tokens, Begin, End, [&](SelectionTree T) {
     Result = std::move(T);
     return true;

diff  --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index eaed8870fcbe9..db346efe19f38 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -83,10 +83,10 @@ bool isUniqueDefinition(const NamedDecl *Decl) {
          isa<ObjCImplDecl>(Decl);
 }
 
-llvm::Optional<HighlightingKind> kindForType(const Type *TP,
-                                             const HeuristicResolver *Resolver);
-llvm::Optional<HighlightingKind>
-kindForDecl(const NamedDecl *D, const HeuristicResolver *Resolver) {
+std::optional<HighlightingKind> kindForType(const Type *TP,
+                                            const HeuristicResolver *Resolver);
+std::optional<HighlightingKind> kindForDecl(const NamedDecl *D,
+                                            const HeuristicResolver *Resolver) {
   if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
     if (auto *Target = USD->getTargetDecl())
       D = Target;
@@ -164,8 +164,8 @@ kindForDecl(const NamedDecl *D, const HeuristicResolver *Resolver) {
   }
   return std::nullopt;
 }
-llvm::Optional<HighlightingKind>
-kindForType(const Type *TP, const HeuristicResolver *Resolver) {
+std::optional<HighlightingKind> kindForType(const Type *TP,
+                                            const HeuristicResolver *Resolver) {
   if (!TP)
     return std::nullopt;
   if (TP->isBuiltinType()) // Builtins are special, they do not have decls.
@@ -332,8 +332,8 @@ unsigned evaluateHighlightPriority(const HighlightingToken &Tok) {
 //
 // In particular, heuristically resolved dependent names get their heuristic
 // kind, plus the dependent modifier.
-llvm::Optional<HighlightingToken> resolveConflict(const HighlightingToken &A,
-                                                  const HighlightingToken &B) {
+std::optional<HighlightingToken> resolveConflict(const HighlightingToken &A,
+                                                 const HighlightingToken &B) {
   unsigned Priority1 = evaluateHighlightPriority(A);
   unsigned Priority2 = evaluateHighlightPriority(B);
   if (Priority1 == Priority2 && A.Kind != B.Kind)
@@ -342,13 +342,14 @@ llvm::Optional<HighlightingToken> resolveConflict(const HighlightingToken &A,
   Result.Modifiers = A.Modifiers | B.Modifiers;
   return Result;
 }
-llvm::Optional<HighlightingToken>
+std::optional<HighlightingToken>
 resolveConflict(ArrayRef<HighlightingToken> Tokens) {
   if (Tokens.size() == 1)
     return Tokens[0];
 
   assert(Tokens.size() >= 2);
-  Optional<HighlightingToken> Winner = resolveConflict(Tokens[0], Tokens[1]);
+  std::optional<HighlightingToken> Winner =
+      resolveConflict(Tokens[0], Tokens[1]);
   for (size_t I = 2; Winner && I < Tokens.size(); ++I)
     Winner = resolveConflict(*Winner, Tokens[I]);
   return Winner;
@@ -474,7 +475,7 @@ class HighlightingsBuilder {
   const HeuristicResolver *getResolver() const { return Resolver; }
 
 private:
-  llvm::Optional<Range> getRangeForSourceLocation(SourceLocation Loc) {
+  std::optional<Range> getRangeForSourceLocation(SourceLocation Loc) {
     Loc = getHighlightableSpellingToken(Loc, SourceMgr);
     if (Loc.isInvalid())
       return std::nullopt;
@@ -496,7 +497,7 @@ class HighlightingsBuilder {
   HighlightingToken InvalidHighlightingToken;
 };
 
-llvm::Optional<HighlightingModifier> scopeModifier(const NamedDecl *D) {
+std::optional<HighlightingModifier> scopeModifier(const NamedDecl *D) {
   const DeclContext *DC = D->getDeclContext();
   // Injected "Foo" within the class "Foo" has file scope, not class scope.
   if (auto *R = dyn_cast_or_null<RecordDecl>(D))
@@ -524,7 +525,7 @@ llvm::Optional<HighlightingModifier> scopeModifier(const NamedDecl *D) {
   return HighlightingModifier::GlobalScope;
 }
 
-llvm::Optional<HighlightingModifier> scopeModifier(const Type *T) {
+std::optional<HighlightingModifier> scopeModifier(const Type *T) {
   if (!T)
     return std::nullopt;
   if (T->isBuiltinType())
@@ -672,7 +673,7 @@ class CollectExtraHighlightings
       return;
     }
 
-    llvm::Optional<SourceLocation> Location;
+    std::optional<SourceLocation> Location;
 
     // FIXME Add "unwrapping" for ArraySubscriptExpr,
     //  e.g. highlight `a` in `a[i]`

diff  --git a/clang-tools-extra/clangd/SemanticSelection.cpp b/clang-tools-extra/clangd/SemanticSelection.cpp
index fe01c1577bff5..b3f3d2856d7ab 100644
--- a/clang-tools-extra/clangd/SemanticSelection.cpp
+++ b/clang-tools-extra/clangd/SemanticSelection.cpp
@@ -41,8 +41,8 @@ void addIfDistinct(const Range &R, std::vector<Range> &Result) {
   }
 }
 
-llvm::Optional<FoldingRange> toFoldingRange(SourceRange SR,
-                                            const SourceManager &SM) {
+std::optional<FoldingRange> toFoldingRange(SourceRange SR,
+                                           const SourceManager &SM) {
   const auto Begin = SM.getDecomposedLoc(SR.getBegin()),
              End = SM.getDecomposedLoc(SR.getEnd());
   // Do not produce folding ranges if either range ends is not within the main
@@ -58,7 +58,7 @@ llvm::Optional<FoldingRange> toFoldingRange(SourceRange SR,
   return Range;
 }
 
-llvm::Optional<FoldingRange>
+std::optional<FoldingRange>
 extractFoldingRange(const syntax::Node *Node,
                     const syntax::TokenBufferTokenManager &TM) {
   if (const auto *Stmt = dyn_cast<syntax::CompoundStatement>(Node)) {

diff  --git a/clang-tools-extra/clangd/SourceCode.cpp b/clang-tools-extra/clangd/SourceCode.cpp
index 90dd37f82f04b..b53e9adeef6aa 100644
--- a/clang-tools-extra/clangd/SourceCode.cpp
+++ b/clang-tools-extra/clangd/SourceCode.cpp
@@ -422,9 +422,9 @@ bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM) {
   return FID == SM.getMainFileID() || FID == SM.getPreambleFileID();
 }
 
-llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
-                                                const LangOptions &LangOpts,
-                                                SourceRange R) {
+std::optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
+                                               const LangOptions &LangOpts,
+                                               SourceRange R) {
   SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts);
   if (!isValidFileRange(SM, R1))
     return std::nullopt;
@@ -512,8 +512,8 @@ std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
   return Edits;
 }
 
-llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
-                                             const SourceManager &SourceMgr) {
+std::optional<std::string> getCanonicalPath(const FileEntry *F,
+                                            const SourceManager &SourceMgr) {
   if (!F)
     return std::nullopt;
 
@@ -570,7 +570,7 @@ FileDigest digest(llvm::StringRef Content) {
   return Result;
 }
 
-llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
+std::optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
   bool Invalid = false;
   llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
   if (Invalid)
@@ -924,9 +924,9 @@ static bool isLikelyIdentifier(llvm::StringRef Word, llvm::StringRef Before,
   return false;
 }
 
-llvm::Optional<SpelledWord> SpelledWord::touching(SourceLocation SpelledLoc,
-                                                  const syntax::TokenBuffer &TB,
-                                                  const LangOptions &LangOpts) {
+std::optional<SpelledWord> SpelledWord::touching(SourceLocation SpelledLoc,
+                                                 const syntax::TokenBuffer &TB,
+                                                 const LangOptions &LangOpts) {
   const auto &SM = TB.sourceManager();
   auto Touching = syntax::spelledTokensTouching(SpelledLoc, TB);
   for (const auto &T : Touching) {
@@ -974,8 +974,8 @@ llvm::Optional<SpelledWord> SpelledWord::touching(SourceLocation SpelledLoc,
   return Result;
 }
 
-llvm::Optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
-                                           Preprocessor &PP) {
+std::optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
+                                          Preprocessor &PP) {
   if (SpelledTok.kind() != tok::identifier)
     return std::nullopt;
   SourceLocation Loc = SpelledTok.location();
@@ -1196,7 +1196,7 @@ EligibleRegion getEligiblePoints(llvm::StringRef Code,
 }
 
 bool isHeaderFile(llvm::StringRef FileName,
-                  llvm::Optional<LangOptions> LangOpts) {
+                  std::optional<LangOptions> LangOpts) {
   // Respect the langOpts, for non-file-extension cases, e.g. standard library
   // files.
   if (LangOpts && LangOpts->IsHeaderFile)

diff  --git a/clang-tools-extra/clangd/SourceCode.h b/clang-tools-extra/clangd/SourceCode.h
index 69626c2678d5e..7527fd944ea98 100644
--- a/clang-tools-extra/clangd/SourceCode.h
+++ b/clang-tools-extra/clangd/SourceCode.h
@@ -41,7 +41,7 @@ namespace clangd {
 // of hashing function at every place that needs to store this information.
 using FileDigest = std::array<uint8_t, 8>;
 FileDigest digest(StringRef Content);
-Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID);
+std::optional<FileDigest> digestFile(const SourceManager &SM, FileID FID);
 
 // This context variable controls the behavior of functions in this file
 // that convert between LSP offsets and native clang byte offsets.
@@ -111,9 +111,9 @@ bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM);
 /// User input (e.g. cursor position) is expressed as a file location, so this
 /// function can be viewed as a way to normalize the ranges used in the clang
 /// AST so that they are comparable with ranges coming from the user input.
-llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &Mgr,
-                                                const LangOptions &LangOpts,
-                                                SourceRange R);
+std::optional<SourceRange> toHalfOpenFileRange(const SourceManager &Mgr,
+                                               const LangOptions &LangOpts,
+                                               SourceRange R);
 
 /// Returns true iff all of the following conditions hold:
 ///   - start and end locations are valid,
@@ -163,8 +163,8 @@ TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
 /// This function should be used when paths needs to be used outside the
 /// component that generate it, so that paths are normalized as much as
 /// possible.
-llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
-                                             const SourceManager &SourceMgr);
+std::optional<std::string> getCanonicalPath(const FileEntry *F,
+                                            const SourceManager &SourceMgr);
 
 /// Choose the clang-format style we should apply to a certain file.
 /// This will usually use FS to look for .clang-format directories.
@@ -252,9 +252,9 @@ struct SpelledWord {
   const syntax::Token *ExpandedToken = nullptr;
 
   // Find the unique word that contains SpelledLoc or starts/ends there.
-  static llvm::Optional<SpelledWord> touching(SourceLocation SpelledLoc,
-                                              const syntax::TokenBuffer &TB,
-                                              const LangOptions &LangOpts);
+  static std::optional<SpelledWord> touching(SourceLocation SpelledLoc,
+                                             const syntax::TokenBuffer &TB,
+                                             const LangOptions &LangOpts);
 };
 
 /// Return true if the \p TokenName is in the list of reversed keywords of the
@@ -315,13 +315,13 @@ struct DefinedMacro {
 };
 /// Gets the macro referenced by \p SpelledTok. It must be a spelled token
 /// aligned to the beginning of an identifier.
-llvm::Optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
-                                           Preprocessor &PP);
+std::optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
+                                          Preprocessor &PP);
 
 /// Infers whether this is a header from the FileName and LangOpts (if
 /// presents).
 bool isHeaderFile(llvm::StringRef FileName,
-                  llvm::Optional<LangOptions> LangOpts = std::nullopt);
+                  std::optional<LangOptions> LangOpts = std::nullopt);
 
 /// Returns true if the given location is in a generated protobuf file.
 bool isProtoFile(SourceLocation Loc, const SourceManager &SourceMgr);

diff  --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
index d78d56e367c8e..c334697e1e238 100644
--- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -75,7 +75,7 @@ bool isValidTarget(llvm::StringRef Triple) {
   return bool(Target);
 }
 
-llvm::Optional<DriverInfo> parseDriverOutput(llvm::StringRef Output) {
+std::optional<DriverInfo> parseDriverOutput(llvm::StringRef Output) {
   DriverInfo Info;
   const char SIS[] = "#include <...> search starts here:";
   const char SIE[] = "End of search list.";
@@ -136,7 +136,7 @@ llvm::Optional<DriverInfo> parseDriverOutput(llvm::StringRef Output) {
   return std::move(Info);
 }
 
-llvm::Optional<DriverInfo>
+std::optional<DriverInfo>
 extractSystemIncludesAndTarget(llvm::SmallString<128> Driver,
                                llvm::StringRef Lang,
                                llvm::ArrayRef<std::string> CommandLine,
@@ -226,7 +226,7 @@ extractSystemIncludesAndTarget(llvm::SmallString<128> Driver,
     return std::nullopt;
   }
 
-  llvm::Optional<DriverInfo> Info =
+  std::optional<DriverInfo> Info =
       parseDriverOutput(BufOrError->get()->getBuffer());
   if (!Info)
     return std::nullopt;
@@ -361,7 +361,7 @@ class SystemIncludeExtractor {
 
 private:
   // Caches includes extracted from a driver. Key is driver:lang.
-  Memoize<llvm::StringMap<llvm::Optional<DriverInfo>>> QueriedDrivers;
+  Memoize<llvm::StringMap<std::optional<DriverInfo>>> QueriedDrivers;
   llvm::Regex QueryDriverRegex;
 };
 } // namespace

diff  --git a/clang-tools-extra/clangd/TUScheduler.cpp b/clang-tools-extra/clangd/TUScheduler.cpp
index 50802d2c8b377..b50d47af2261f 100644
--- a/clang-tools-extra/clangd/TUScheduler.cpp
+++ b/clang-tools-extra/clangd/TUScheduler.cpp
@@ -137,7 +137,7 @@ class ASTWorker;
 
 static clang::clangd::Key<std::string> FileBeingProcessed;
 
-llvm::Optional<llvm::StringRef> TUScheduler::getFileBeingProcessedInContext() {
+std::optional<llvm::StringRef> TUScheduler::getFileBeingProcessedInContext() {
   if (auto *File = Context::current().get(FileBeingProcessed))
     return llvm::StringRef(*File);
   return std::nullopt;
@@ -184,7 +184,7 @@ class TUScheduler::ASTCache {
   /// the cache anymore. If nullptr was cached for \p K, this function will
   /// return a null unique_ptr wrapped into an optional.
   /// If \p AccessMetric is set records whether there was a hit or miss.
-  llvm::Optional<std::unique_ptr<ParsedAST>>
+  std::optional<std::unique_ptr<ParsedAST>>
   take(Key K, const trace::Metric *AccessMetric = nullptr) {
     // Record metric after unlocking the mutex.
     std::unique_lock<std::mutex> Lock(Mut);
@@ -201,7 +201,7 @@ class TUScheduler::ASTCache {
     // GCC 4.8 fails to compile `return V;`, as it tries to call the copy
     // constructor of unique_ptr, so we call the move ctor explicitly to avoid
     // this miscompile.
-    return llvm::Optional<std::unique_ptr<ParsedAST>>(std::move(V));
+    return std::optional<std::unique_ptr<ParsedAST>>(std::move(V));
   }
 
 private:
@@ -465,7 +465,7 @@ class PreambleThread {
 
   void run() {
     while (true) {
-      llvm::Optional<PreambleThrottlerRequest> Throttle;
+      std::optional<PreambleThrottlerRequest> Throttle;
       {
         std::unique_lock<std::mutex> Lock(Mutex);
         assert(!CurrentReq && "Already processing a request?");
@@ -476,7 +476,7 @@ class PreambleThread {
 
         {
           Throttle.emplace(FileName, Throttler, ReqCV);
-          llvm::Optional<trace::Span> Tracer;
+          std::optional<trace::Span> Tracer;
           // If acquire succeeded synchronously, avoid status jitter.
           if (!Throttle->satisfied()) {
             Tracer.emplace("PreambleThrottle");
@@ -564,8 +564,8 @@ class PreambleThread {
 
   mutable std::mutex Mutex;
   bool Done = false;                  /* GUARDED_BY(Mutex) */
-  llvm::Optional<Request> NextReq;    /* GUARDED_BY(Mutex) */
-  llvm::Optional<Request> CurrentReq; /* GUARDED_BY(Mutex) */
+  std::optional<Request> NextReq;     /* GUARDED_BY(Mutex) */
+  std::optional<Request> CurrentReq;  /* GUARDED_BY(Mutex) */
   // Signaled whenever a thread populates NextReq or worker thread builds a
   // Preamble.
   mutable std::condition_variable ReqCV; /* GUARDED_BY(Mutex) */
@@ -681,7 +681,7 @@ class ASTWorker {
 
   /// Adds a new task to the end of the request queue.
   void startTask(llvm::StringRef Name, llvm::unique_function<void()> Task,
-                 llvm::Optional<UpdateType> Update,
+                 std::optional<UpdateType> Update,
                  TUScheduler::ASTActionInvalidation);
   /// Runs a task synchronously.
   void runTask(llvm::StringRef Name, llvm::function_ref<void()> Task);
@@ -699,8 +699,8 @@ class ASTWorker {
     std::string Name;
     steady_clock::time_point AddTime;
     Context Ctx;
-    llvm::Optional<Context> QueueCtx;
-    llvm::Optional<UpdateType> Update;
+    std::optional<Context> QueueCtx;
+    std::optional<UpdateType> Update;
     TUScheduler::ASTActionInvalidation InvalidationPolicy;
     Canceler Invalidate;
   };
@@ -734,7 +734,7 @@ class ASTWorker {
   /// Set to true to signal run() to finish processing.
   bool Done;                              /* GUARDED_BY(Mutex) */
   std::deque<Request> Requests;           /* GUARDED_BY(Mutex) */
-  llvm::Optional<Request> CurrentRequest; /* GUARDED_BY(Mutex) */
+  std::optional<Request> CurrentRequest;  /* GUARDED_BY(Mutex) */
   /// Signalled whenever a new request has been scheduled or processing of a
   /// request has completed.
   mutable std::condition_variable RequestsCV;
@@ -742,7 +742,7 @@ class ASTWorker {
   /// Latest build preamble for current TU.
   /// None means no builds yet, null means there was an error while building.
   /// Only written by ASTWorker's thread.
-  llvm::Optional<std::shared_ptr<const PreambleData>> LatestPreamble;
+  std::optional<std::shared_ptr<const PreambleData>> LatestPreamble;
   std::deque<Request> PreambleRequests; /* GUARDED_BY(Mutex) */
   /// Signaled whenever LatestPreamble changes state or there's a new
   /// PreambleRequest.
@@ -965,7 +965,7 @@ void ASTWorker::runWithAST(
   auto Task = [=, Action = std::move(Action)]() mutable {
     if (auto Reason = isCancelled())
       return Action(llvm::make_error<CancelledError>(Reason));
-    llvm::Optional<std::unique_ptr<ParsedAST>> AST =
+    std::optional<std::unique_ptr<ParsedAST>> AST =
         IdleASTs.take(this, &ASTAccessForRead);
     if (!AST) {
       StoreDiags CompilerInvocationDiagConsumer;
@@ -977,7 +977,7 @@ void ASTWorker::runWithAST(
       // FIXME: We might need to build a patched ast once preamble thread starts
       // running async. Currently getPossiblyStalePreamble below will always
       // return a compatible preamble as ASTWorker::update blocks.
-      llvm::Optional<ParsedAST> NewAST;
+      std::optional<ParsedAST> NewAST;
       if (Invocation) {
         NewAST = ParsedAST::build(FileName, FileInputs, std::move(Invocation),
                                   CompilerInvocationDiagConsumer.take(),
@@ -1184,11 +1184,11 @@ void ASTWorker::generateDiagnostics(
   // We might be able to reuse the last we've built for a read request.
   // FIXME: It might be better to not reuse this AST. That way queued AST builds
   // won't be required for diags.
-  llvm::Optional<std::unique_ptr<ParsedAST>> AST =
+  std::optional<std::unique_ptr<ParsedAST>> AST =
       IdleASTs.take(this, &ASTAccessForDiag);
   if (!AST || !InputsAreLatest) {
     auto RebuildStartTime = DebouncePolicy::clock::now();
-    llvm::Optional<ParsedAST> NewAST = ParsedAST::build(
+    std::optional<ParsedAST> NewAST = ParsedAST::build(
         FileName, Inputs, std::move(Invocation), CIDiags, *LatestPreamble);
     auto RebuildDuration = DebouncePolicy::clock::now() - RebuildStartTime;
     ++ASTBuildCount;
@@ -1307,7 +1307,7 @@ void ASTWorker::runTask(llvm::StringRef Name, llvm::function_ref<void()> Task) {
 
 void ASTWorker::startTask(llvm::StringRef Name,
                           llvm::unique_function<void()> Task,
-                          llvm::Optional<UpdateType> Update,
+                          std::optional<UpdateType> Update,
                           TUScheduler::ASTActionInvalidation Invalidation) {
   if (RunSync) {
     assert(!Done && "running a task after stop()");
@@ -1338,7 +1338,7 @@ void ASTWorker::startTask(llvm::StringRef Name,
     }
     // Trace the time the request spends in the queue, and the requests that
     // it's going to wait for.
-    llvm::Optional<Context> QueueCtx;
+    std::optional<Context> QueueCtx;
     if (trace::enabled()) {
       // Tracers that follow threads and need strict nesting will see a tiny
       // instantaneous event "we're enqueueing", and sometime later it runs.
@@ -1385,8 +1385,8 @@ void ASTWorker::run() {
         }
 
         // Tracing: we have a next request, attribute this sleep to it.
-        llvm::Optional<WithContext> Ctx;
-        llvm::Optional<trace::Span> Tracer;
+        std::optional<WithContext> Ctx;
+        std::optional<trace::Span> Tracer;
         if (!Requests.empty()) {
           Ctx.emplace(Requests.front().Ctx.clone());
           Tracer.emplace("Debounce");

diff  --git a/clang-tools-extra/clangd/TUScheduler.h b/clang-tools-extra/clangd/TUScheduler.h
index f9582a6f3f42f..7e2343c2b8c3d 100644
--- a/clang-tools-extra/clangd/TUScheduler.h
+++ b/clang-tools-extra/clangd/TUScheduler.h
@@ -353,7 +353,7 @@ class TUScheduler {
   // FIXME: remove this when there is proper index support via build system
   // integration.
   // FIXME: move to ClangdServer via createProcessingContext.
-  static llvm::Optional<llvm::StringRef> getFileBeingProcessedInContext();
+  static std::optional<llvm::StringRef> getFileBeingProcessedInContext();
 
   void profile(MemoryTree &MT) const;
 
@@ -371,8 +371,8 @@ class TUScheduler {
   std::unique_ptr<HeaderIncluderCache> HeaderIncluders;
   // None when running tasks synchronously and non-None when running tasks
   // asynchronously.
-  llvm::Optional<AsyncTaskRunner> PreambleTasks;
-  llvm::Optional<AsyncTaskRunner> WorkerThreads;
+  std::optional<AsyncTaskRunner> PreambleTasks;
+  std::optional<AsyncTaskRunner> WorkerThreads;
   // Used to create contexts for operations that are not bound to a particular
   // file (e.g. index queries).
   std::string LastActiveFile;

diff  --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp
index da33b722876fe..ee677fee07f82 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -117,8 +117,8 @@ void logIfOverflow(const SymbolLocation &Loc) {
 // TUPath is used to resolve the path of URI.
 // FIXME: figure out a good home for it, and share the implementation with
 // FindSymbols.
-llvm::Optional<Location> toLSPLocation(const SymbolLocation &Loc,
-                                       llvm::StringRef TUPath) {
+std::optional<Location> toLSPLocation(const SymbolLocation &Loc,
+                                      llvm::StringRef TUPath) {
   if (!Loc)
     return std::nullopt;
   auto Uri = URI::parse(Loc.FileURI);
@@ -206,8 +206,8 @@ getDeclAtPosition(ParsedAST &AST, SourceLocation Pos, DeclRelationSet Relations,
 
 // Expects Loc to be a SpellingLocation, will bail out otherwise as it can't
 // figure out a filename.
-llvm::Optional<Location> makeLocation(const ASTContext &AST, SourceLocation Loc,
-                                      llvm::StringRef TUPath) {
+std::optional<Location> makeLocation(const ASTContext &AST, SourceLocation Loc,
+                                     llvm::StringRef TUPath) {
   const auto &SM = AST.getSourceManager();
   const FileEntry *F = SM.getFileEntryForID(SM.getFileID(Loc));
   if (!F)
@@ -228,9 +228,9 @@ llvm::Optional<Location> makeLocation(const ASTContext &AST, SourceLocation Loc,
 }
 
 // Treat #included files as symbols, to enable go-to-definition on them.
-llvm::Optional<LocatedSymbol> locateFileReferent(const Position &Pos,
-                                                 ParsedAST &AST,
-                                                 llvm::StringRef MainFilePath) {
+std::optional<LocatedSymbol> locateFileReferent(const Position &Pos,
+                                                ParsedAST &AST,
+                                                llvm::StringRef MainFilePath) {
   for (auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
     if (!Inc.Resolved.empty() && Inc.HashLine == Pos.line) {
       LocatedSymbol File;
@@ -247,7 +247,7 @@ llvm::Optional<LocatedSymbol> locateFileReferent(const Position &Pos,
 
 // Macros are simple: there's no declaration/definition distinction.
 // As a consequence, there's no need to look them up in the index either.
-llvm::Optional<LocatedSymbol>
+std::optional<LocatedSymbol>
 locateMacroReferent(const syntax::Token &TouchedIdentifier, ParsedAST &AST,
                     llvm::StringRef MainFilePath) {
   if (auto M = locateMacroAt(TouchedIdentifier, AST.getPreprocessor())) {
@@ -1201,8 +1201,8 @@ DocumentHighlight toHighlight(const ReferenceFinder::Reference &Ref,
   return DH;
 }
 
-llvm::Optional<DocumentHighlight> toHighlight(SourceLocation Loc,
-                                              const syntax::TokenBuffer &TB) {
+std::optional<DocumentHighlight> toHighlight(SourceLocation Loc,
+                                             const syntax::TokenBuffer &TB) {
   Loc = TB.sourceManager().getFileLoc(Loc);
   if (const auto *Tok = TB.spelledTokenAt(Loc)) {
     DocumentHighlight Result;
@@ -1303,7 +1303,7 @@ void getOverriddenMethods(const CXXMethodDecl *CMD,
   }
 }
 
-llvm::Optional<std::string>
+std::optional<std::string>
 stringifyContainerForMainFileRef(const Decl *Container) {
   // FIXME We might also want to display the signature here
   // When doing so, remember to also add the Signature to index results!
@@ -1329,7 +1329,7 @@ ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit,
 
   const auto *IdentifierAtCursor =
       syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
-  llvm::Optional<DefinedMacro> Macro;
+  std::optional<DefinedMacro> Macro;
   if (IdentifierAtCursor)
     Macro = locateMacroAt(*IdentifierAtCursor, AST.getPreprocessor());
   if (Macro) {
@@ -1607,7 +1607,7 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
 }
 
 template <typename HierarchyItem>
-static llvm::Optional<HierarchyItem>
+static std::optional<HierarchyItem>
 declToHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
   ASTContext &Ctx = ND.getASTContext();
   auto &SM = Ctx.getSourceManager();
@@ -1649,7 +1649,7 @@ declToHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
   return HI;
 }
 
-static llvm::Optional<TypeHierarchyItem>
+static std::optional<TypeHierarchyItem>
 declToTypeHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
   auto Result = declToHierarchyItem<TypeHierarchyItem>(ND, TUPath);
   if (Result) {
@@ -1663,7 +1663,7 @@ declToTypeHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
   return Result;
 }
 
-static llvm::Optional<CallHierarchyItem>
+static std::optional<CallHierarchyItem>
 declToCallHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
   auto Result = declToHierarchyItem<CallHierarchyItem>(ND, TUPath);
   if (!Result)
@@ -1676,8 +1676,8 @@ declToCallHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
 }
 
 template <typename HierarchyItem>
-static llvm::Optional<HierarchyItem> symbolToHierarchyItem(const Symbol &S,
-                                                           PathRef TUPath) {
+static std::optional<HierarchyItem> symbolToHierarchyItem(const Symbol &S,
+                                                          PathRef TUPath) {
   auto Loc = symbolToLocation(S, TUPath);
   if (!Loc) {
     elog("Failed to convert symbol to hierarchy item: {0}", Loc.takeError());
@@ -1695,7 +1695,7 @@ static llvm::Optional<HierarchyItem> symbolToHierarchyItem(const Symbol &S,
   return HI;
 }
 
-static llvm::Optional<TypeHierarchyItem>
+static std::optional<TypeHierarchyItem>
 symbolToTypeHierarchyItem(const Symbol &S, PathRef TUPath) {
   auto Result = symbolToHierarchyItem<TypeHierarchyItem>(S, TUPath);
   if (Result) {
@@ -1705,7 +1705,7 @@ symbolToTypeHierarchyItem(const Symbol &S, PathRef TUPath) {
   return Result;
 }
 
-static llvm::Optional<CallHierarchyItem>
+static std::optional<CallHierarchyItem>
 symbolToCallHierarchyItem(const Symbol &S, PathRef TUPath) {
   auto Result = symbolToHierarchyItem<CallHierarchyItem>(S, TUPath);
   if (!Result)
@@ -1723,7 +1723,7 @@ static void fillSubTypes(const SymbolID &ID,
   Req.Subjects.insert(ID);
   Req.Predicate = RelationKind::BaseOf;
   Index->relations(Req, [&](const SymbolID &Subject, const Symbol &Object) {
-    if (Optional<TypeHierarchyItem> ChildSym =
+    if (std::optional<TypeHierarchyItem> ChildSym =
             symbolToTypeHierarchyItem(Object, TUPath)) {
       if (Levels > 1) {
         ChildSym->children.emplace();
@@ -1755,7 +1755,7 @@ static void fillSuperTypes(const CXXRecordDecl &CXXRD, llvm::StringRef TUPath,
   }
 
   for (const CXXRecordDecl *ParentDecl : typeParents(&CXXRD)) {
-    if (Optional<TypeHierarchyItem> ParentSym =
+    if (std::optional<TypeHierarchyItem> ParentSym =
             declToTypeHierarchyItem(*ParentDecl, TUPath)) {
       fillSuperTypes(*ParentDecl, TUPath, *ParentSym, RPSet);
       Item.data.parents->emplace_back(ParentSym->data);
@@ -2087,7 +2087,7 @@ getTypeHierarchy(ParsedAST &AST, Position Pos, int ResolveLevels,
         CXXRD = CTSD->getTemplateInstantiationPattern();
     }
 
-    Optional<TypeHierarchyItem> Result =
+    std::optional<TypeHierarchyItem> Result =
         declToTypeHierarchyItem(*CXXRD, AST.tuPath());
     if (!Result)
       continue;

diff  --git a/clang-tools-extra/clangd/XRefs.h b/clang-tools-extra/clangd/XRefs.h
index 8af5106078b4e..c4f7952364e0f 100644
--- a/clang-tools-extra/clangd/XRefs.h
+++ b/clang-tools-extra/clangd/XRefs.h
@@ -45,7 +45,7 @@ struct LocatedSymbol {
   // The canonical or best declaration: where most users find its interface.
   Location PreferredDeclaration;
   // Where the symbol is defined, if known. May equal PreferredDeclaration.
-  llvm::Optional<Location> Definition;
+  std::optional<Location> Definition;
   // SymbolID of the located symbol if available.
   SymbolID ID;
 };

diff  --git a/clang-tools-extra/clangd/index/Background.cpp b/clang-tools-extra/clangd/index/Background.cpp
index f09fb5d293018..117c766eea0dd 100644
--- a/clang-tools-extra/clangd/index/Background.cpp
+++ b/clang-tools-extra/clangd/index/Background.cpp
@@ -124,7 +124,7 @@ BackgroundQueue::Task BackgroundIndex::changedFilesTask(
   BackgroundQueue::Task T([this, ChangedFiles] {
     trace::Span Tracer("BackgroundIndexEnqueue");
 
-    llvm::Optional<WithContext> WithProvidedContext;
+    std::optional<WithContext> WithProvidedContext;
     if (ContextProvider)
       WithProvidedContext.emplace(ContextProvider(/*Path=*/""));
 
@@ -157,7 +157,7 @@ BackgroundQueue::Task BackgroundIndex::indexFileTask(std::string Path) {
   std::string Tag = filenameWithoutExtension(Path).str();
   uint64_t Key = llvm::xxHash64(Path);
   BackgroundQueue::Task T([this, Path(std::move(Path))] {
-    llvm::Optional<WithContext> WithProvidedContext;
+    std::optional<WithContext> WithProvidedContext;
     if (ContextProvider)
       WithProvidedContext.emplace(ContextProvider(Path));
     auto Cmd = CDB.getCompileCommand(Path);

diff  --git a/clang-tools-extra/clangd/index/Background.h b/clang-tools-extra/clangd/index/Background.h
index 45f679a16617c..0d719ffdb957e 100644
--- a/clang-tools-extra/clangd/index/Background.h
+++ b/clang-tools-extra/clangd/index/Background.h
@@ -62,7 +62,7 @@ class BackgroundIndexStorage {
   // CDBDirectory is the first directory containing a CDB in parent directories
   // of a file, or user cache directory if none was found, e.g. stdlib headers.
   static Factory createDiskBackedStorageFactory(
-      std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo);
+      std::function<std::optional<ProjectInfo>(PathRef)> GetProjectInfo);
 };
 
 // A priority queue of tasks which can be run on (external) worker threads.
@@ -112,7 +112,7 @@ class BackgroundQueue {
   // Only affects tasks that run after the call.
   static void preventThreadStarvationInTests();
   [[nodiscard]] bool
-  blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds);
+  blockUntilIdleForTest(std::optional<double> TimeoutSeconds);
 
 private:
   void notifyProgress() const; // Requires lock Mu
@@ -174,7 +174,7 @@ class BackgroundIndex : public SwapIndex {
 
   // Wait until the queue is empty, to allow deterministic testing.
   [[nodiscard]] bool
-  blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds = 10) {
+  blockUntilIdleForTest(std::optional<double> TimeoutSeconds = 10) {
     return Queue.blockUntilIdleForTest(TimeoutSeconds);
   }
 

diff  --git a/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp b/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp
index c7bbd98a32cec..27c9c91ad633d 100644
--- a/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp
+++ b/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp
@@ -99,7 +99,7 @@ class NullStorage : public BackgroundIndexStorage {
 class DiskBackedIndexStorageManager {
 public:
   DiskBackedIndexStorageManager(
-      std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo)
+      std::function<std::optional<ProjectInfo>(PathRef)> GetProjectInfo)
       : IndexStorageMapMu(std::make_unique<std::mutex>()),
         GetProjectInfo(std::move(GetProjectInfo)) {
     llvm::SmallString<128> FallbackDir;
@@ -136,14 +136,14 @@ class DiskBackedIndexStorageManager {
   llvm::StringMap<std::unique_ptr<BackgroundIndexStorage>> IndexStorageMap;
   std::unique_ptr<std::mutex> IndexStorageMapMu;
 
-  std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo;
+  std::function<std::optional<ProjectInfo>(PathRef)> GetProjectInfo;
 };
 
 } // namespace
 
 BackgroundIndexStorage::Factory
 BackgroundIndexStorage::createDiskBackedStorageFactory(
-    std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo) {
+    std::function<std::optional<ProjectInfo>(PathRef)> GetProjectInfo) {
   return DiskBackedIndexStorageManager(std::move(GetProjectInfo));
 }
 

diff  --git a/clang-tools-extra/clangd/index/BackgroundQueue.cpp b/clang-tools-extra/clangd/index/BackgroundQueue.cpp
index 5fb1511353ee2..6023f48ccd3b3 100644
--- a/clang-tools-extra/clangd/index/BackgroundQueue.cpp
+++ b/clang-tools-extra/clangd/index/BackgroundQueue.cpp
@@ -21,7 +21,7 @@ void BackgroundQueue::preventThreadStarvationInTests() {
 
 void BackgroundQueue::work(std::function<void()> OnIdle) {
   while (true) {
-    llvm::Optional<Task> Task;
+    std::optional<Task> Task;
     {
       std::unique_lock<std::mutex> Lock(Mu);
       CV.wait(Lock, [&] { return ShouldStop || !Queue.empty(); });
@@ -134,7 +134,7 @@ void BackgroundQueue::boost(llvm::StringRef Tag, unsigned NewPriority) {
 }
 
 bool BackgroundQueue::blockUntilIdleForTest(
-    llvm::Optional<double> TimeoutSeconds) {
+    std::optional<double> TimeoutSeconds) {
   std::unique_lock<std::mutex> Lock(Mu);
   return wait(Lock, CV, timeoutSeconds(TimeoutSeconds),
               [&] { return Queue.empty() && Stat.Active == 0; });

diff  --git a/clang-tools-extra/clangd/index/FileIndex.cpp b/clang-tools-extra/clangd/index/FileIndex.cpp
index 95bda42a796c4..348f15e073173 100644
--- a/clang-tools-extra/clangd/index/FileIndex.cpp
+++ b/clang-tools-extra/clangd/index/FileIndex.cpp
@@ -189,7 +189,7 @@ std::vector<llvm::StringRef> FileShardedIndex::getAllSources() const {
   return Result;
 }
 
-llvm::Optional<IndexFileIn>
+std::optional<IndexFileIn>
 FileShardedIndex::getShard(llvm::StringRef Uri) const {
   auto It = Shards.find(Uri);
   if (It == Shards.end())

diff  --git a/clang-tools-extra/clangd/index/FileIndex.h b/clang-tools-extra/clangd/index/FileIndex.h
index 31757d13eb40c..34ecbf41e09a1 100644
--- a/clang-tools-extra/clangd/index/FileIndex.h
+++ b/clang-tools-extra/clangd/index/FileIndex.h
@@ -179,7 +179,7 @@ struct FileShardedIndex {
   /// a copy of all the relevant data.
   /// Returned index will always have Symbol/Refs/Relation Slabs set, even if
   /// they are empty.
-  llvm::Optional<IndexFileIn> getShard(llvm::StringRef Uri) const;
+  std::optional<IndexFileIn> getShard(llvm::StringRef Uri) const;
 
 private:
   // Contains all the information that belongs to a single file.

diff  --git a/clang-tools-extra/clangd/index/Index.h b/clang-tools-extra/clangd/index/Index.h
index e836d459c2ee2..db5c967b6e1af 100644
--- a/clang-tools-extra/clangd/index/Index.h
+++ b/clang-tools-extra/clangd/index/Index.h
@@ -72,7 +72,7 @@ struct RefsRequest {
   /// If set, limit the number of refers returned from the index. The index may
   /// choose to return less than this, e.g. it tries to avoid returning stale
   /// results.
-  llvm::Optional<uint32_t> Limit;
+  std::optional<uint32_t> Limit;
   /// If set, populates the container of the reference.
   /// Index implementations may chose to populate containers no matter what.
   bool WantContainer = false;
@@ -82,7 +82,7 @@ struct RelationsRequest {
   llvm::DenseSet<SymbolID> Subjects;
   RelationKind Predicate;
   /// If set, limit the number of relations returned from the index.
-  llvm::Optional<uint32_t> Limit;
+  std::optional<uint32_t> Limit;
 };
 
 /// Describes what data is covered by an index.

diff  --git a/clang-tools-extra/clangd/index/IndexAction.cpp b/clang-tools-extra/clangd/index/IndexAction.cpp
index d97dc40e03a6b..6588f4d513232 100644
--- a/clang-tools-extra/clangd/index/IndexAction.cpp
+++ b/clang-tools-extra/clangd/index/IndexAction.cpp
@@ -29,7 +29,7 @@ namespace clang {
 namespace clangd {
 namespace {
 
-llvm::Optional<std::string> toURI(OptionalFileEntryRef File) {
+std::optional<std::string> toURI(OptionalFileEntryRef File) {
   if (!File)
     return std::nullopt;
   auto AbsolutePath = File->getFileEntry().tryGetRealPathName();

diff  --git a/clang-tools-extra/clangd/index/Serialization.h b/clang-tools-extra/clangd/index/Serialization.h
index fceaefed4c0cc..b6890d63d2c38 100644
--- a/clang-tools-extra/clangd/index/Serialization.h
+++ b/clang-tools-extra/clangd/index/Serialization.h
@@ -41,13 +41,13 @@ enum class IndexFileFormat {
 
 // Holds the contents of an index file that was read.
 struct IndexFileIn {
-  llvm::Optional<SymbolSlab> Symbols;
-  llvm::Optional<RefSlab> Refs;
-  llvm::Optional<RelationSlab> Relations;
+  std::optional<SymbolSlab> Symbols;
+  std::optional<RefSlab> Refs;
+  std::optional<RelationSlab> Relations;
   // Keys are URIs of the source files.
-  llvm::Optional<IncludeGraph> Sources;
+  std::optional<IncludeGraph> Sources;
   // This contains only the Directory and CommandLine.
-  llvm::Optional<tooling::CompileCommand> Cmd;
+  std::optional<tooling::CompileCommand> Cmd;
 };
 // Parse an index file. The input must be a RIFF or YAML file.
 llvm::Expected<IndexFileIn> readIndexFile(llvm::StringRef, SymbolOrigin);

diff  --git a/clang-tools-extra/clangd/index/StdLib.cpp b/clang-tools-extra/clangd/index/StdLib.cpp
index ab9a8ed8cfb32..399bd2ffaff6b 100644
--- a/clang-tools-extra/clangd/index/StdLib.cpp
+++ b/clang-tools-extra/clangd/index/StdLib.cpp
@@ -286,8 +286,8 @@ bool StdLibSet::isBest(const LangOptions &LO) const {
          Best[langFromOpts(LO)].load(std::memory_order_acquire);
 }
 
-llvm::Optional<StdLibLocation> StdLibSet::add(const LangOptions &LO,
-                                              const HeaderSearch &HS) {
+std::optional<StdLibLocation> StdLibSet::add(const LangOptions &LO,
+                                             const HeaderSearch &HS) {
   Lang L = langFromOpts(LO);
   int OldVersion = Best[L].load(std::memory_order_acquire);
   int NewVersion = standardFromOpts(LO);

diff  --git a/clang-tools-extra/clangd/index/StdLib.h b/clang-tools-extra/clangd/index/StdLib.h
index 6c170dceba9c7..2ed5eae61f856 100644
--- a/clang-tools-extra/clangd/index/StdLib.h
+++ b/clang-tools-extra/clangd/index/StdLib.h
@@ -67,7 +67,7 @@ class StdLibSet {
   // Returns the location where the standard library was found.
   //
   // This function is threadsafe.
-  llvm::Optional<StdLibLocation> add(const LangOptions &, const HeaderSearch &);
+  std::optional<StdLibLocation> add(const LangOptions &, const HeaderSearch &);
 
   // Indicates whether a built index should be used.
   // It should not be used if a newer version has subsequently been added.

diff  --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index 5f9c8bbb4ee9d..822f3cb9b9563 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -146,7 +146,7 @@ RefKind toRefKind(index::SymbolRoleSet Roles, bool Spelled = false) {
   return Result;
 }
 
-llvm::Optional<RelationKind> indexableRelation(const index::SymbolRelation &R) {
+std::optional<RelationKind> indexableRelation(const index::SymbolRelation &R) {
   if (R.Roles & static_cast<unsigned>(index::SymbolRole::RelationBaseOf))
     return RelationKind::BaseOf;
   if (R.Roles & static_cast<unsigned>(index::SymbolRole::RelationOverrideOf))
@@ -178,10 +178,10 @@ bool isSpelled(SourceLocation Loc, const NamedDecl &ND) {
 class SymbolCollector::HeaderFileURICache {
   struct FrameworkUmbrellaSpelling {
     // Spelling for the public umbrella header, e.g. <Foundation/Foundation.h>
-    llvm::Optional<std::string> PublicHeader;
+    std::optional<std::string> PublicHeader;
     // Spelling for the private umbrella header, e.g.
     // <Foundation/Foundation_Private.h>
-    llvm::Optional<std::string> PrivateHeader;
+    std::optional<std::string> PrivateHeader;
   };
   // Weird double-indirect access to PP, which might not be ready yet when
   // HeaderFiles is created but will be by the time it's used.
@@ -263,7 +263,7 @@ class SymbolCollector::HeaderFileURICache {
     bool IsPrivateHeader;
   };
 
-  llvm::Optional<FrameworkHeaderPath>
+  std::optional<FrameworkHeaderPath>
   splitFrameworkHeaderPath(llvm::StringRef Path) {
     using namespace llvm::sys;
     path::reverse_iterator I = path::rbegin(Path);
@@ -296,7 +296,7 @@ class SymbolCollector::HeaderFileURICache {
   // <Foundation/Foundation_Private.h> instead of
   // <Foundation/NSObject_Private.h> which should be used instead of directly
   // importing the header.
-  llvm::Optional<std::string> getFrameworkUmbrellaSpelling(
+  std::optional<std::string> getFrameworkUmbrellaSpelling(
       llvm::StringRef Framework, SrcMgr::CharacteristicKind HeadersDirKind,
       HeaderSearch &HS, FrameworkHeaderPath &HeaderPath) {
     auto Res = CacheFrameworkToUmbrellaHeaderSpelling.try_emplace(Framework);
@@ -340,7 +340,7 @@ class SymbolCollector::HeaderFileURICache {
   // named `Framework`, e.g. `NSObject.h` in framework `Foundation` would
   // give <Foundation/Foundation.h> if the umbrella header exists, otherwise
   // <Foundation/NSObject.h>.
-  llvm::Optional<llvm::StringRef> getFrameworkHeaderIncludeSpelling(
+  std::optional<llvm::StringRef> getFrameworkHeaderIncludeSpelling(
       const FileEntry *FE, llvm::StringRef Framework, HeaderSearch &HS) {
     auto Res = CachePathToFrameworkSpelling.try_emplace(FE->getName());
     auto *CachedHeaderSpelling = &Res.first->second;
@@ -414,7 +414,7 @@ class SymbolCollector::HeaderFileURICache {
 };
 
 // Return the symbol location of the token at \p TokLoc.
-llvm::Optional<SymbolLocation>
+std::optional<SymbolLocation>
 SymbolCollector::getTokenLocation(SourceLocation TokLoc) {
   const auto &SM = ASTCtx->getSourceManager();
   auto *FE = SM.getFileEntryForID(SM.getFileID(TokLoc));
@@ -941,7 +941,7 @@ const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND, SymbolID ID,
   std::string ReturnType = getReturnType(*CCS);
   S.ReturnType = ReturnType;
 
-  llvm::Optional<OpaqueType> TypeStorage;
+  std::optional<OpaqueType> TypeStorage;
   if (S.Flags & Symbol::IndexedForCodeCompletion) {
     TypeStorage = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion);
     if (TypeStorage)

diff  --git a/clang-tools-extra/clangd/index/SymbolCollector.h b/clang-tools-extra/clangd/index/SymbolCollector.h
index 6acce1f3e3c40..265554429a2da 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.h
+++ b/clang-tools-extra/clangd/index/SymbolCollector.h
@@ -156,9 +156,9 @@ class SymbolCollector : public index::IndexDataConsumer {
   void processRelations(const NamedDecl &ND, const SymbolID &ID,
                         ArrayRef<index::SymbolRelation> Relations);
 
-  llvm::Optional<SymbolLocation> getTokenLocation(SourceLocation TokLoc);
+  std::optional<SymbolLocation> getTokenLocation(SourceLocation TokLoc);
 
-  llvm::Optional<std::string> getIncludeHeader(const Symbol &S, FileID);
+  std::optional<std::string> getIncludeHeader(const Symbol &S, FileID);
 
   SymbolID getSymbolIDCached(const Decl *D);
   SymbolID getSymbolIDCached(const llvm::StringRef MacroName,

diff  --git a/clang-tools-extra/clangd/index/YAMLSerialization.cpp b/clang-tools-extra/clangd/index/YAMLSerialization.cpp
index c51489fd5dc66..2892d8cd8769f 100644
--- a/clang-tools-extra/clangd/index/YAMLSerialization.cpp
+++ b/clang-tools-extra/clangd/index/YAMLSerialization.cpp
@@ -42,11 +42,11 @@ using RefBundle =
     std::pair<clang::clangd::SymbolID, std::vector<clang::clangd::Ref>>;
 // This is a pale imitation of std::variant<Symbol, RefBundle, Relation>
 struct VariantEntry {
-  llvm::Optional<clang::clangd::Symbol> Symbol;
-  llvm::Optional<RefBundle> Refs;
-  llvm::Optional<clang::clangd::Relation> Relation;
-  llvm::Optional<clang::clangd::IncludeGraphNode> Source;
-  llvm::Optional<clang::tooling::CompileCommand> Cmd;
+  std::optional<clang::clangd::Symbol> Symbol;
+  std::optional<RefBundle> Refs;
+  std::optional<clang::clangd::Relation> Relation;
+  std::optional<clang::clangd::IncludeGraphNode> Source;
+  std::optional<clang::tooling::CompileCommand> Cmd;
 };
 // A class helps YAML to serialize the 32-bit encoded position (Line&Column),
 // as YAMLIO can't directly map bitfields.
@@ -480,7 +480,7 @@ llvm::Expected<IndexFileIn> readYAML(llvm::StringRef Data,
   llvm::UniqueStringSaver Strings(Arena);
   llvm::yaml::Input Yin(Data, &Strings);
   IncludeGraph Sources;
-  llvm::Optional<tooling::CompileCommand> Cmd;
+  std::optional<tooling::CompileCommand> Cmd;
   while (Yin.setCurrentDocument()) {
     llvm::yaml::EmptyContext Ctx;
     VariantEntry Variant;

diff  --git a/clang-tools-extra/clangd/index/dex/Dex.cpp b/clang-tools-extra/clangd/index/dex/Dex.cpp
index 0e94f59187de6..8f504fb9b7ea3 100644
--- a/clang-tools-extra/clangd/index/dex/Dex.cpp
+++ b/clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -268,7 +268,7 @@ bool Dex::fuzzyFind(const FuzzyFindRequest &Req,
   for (const auto &IDAndScore : IDAndScores) {
     const DocID SymbolDocID = IDAndScore.first;
     const auto *Sym = Symbols[SymbolDocID];
-    const llvm::Optional<float> Score = Filter.match(Sym->Name);
+    const std::optional<float> Score = Filter.match(Sym->Name);
     if (!Score)
       continue;
     // Combine Fuzzy Matching score, precomputed symbol quality and boosting

diff  --git a/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp b/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
index 763382204dc27..392960d6d6660 100644
--- a/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
+++ b/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
@@ -443,6 +443,6 @@ int main(int argc, const char *argv[]) {
     return runCommand(ExecCommand, *Index) ? 0 : 1;
 
   llvm::LineEditor LE("dexp");
-  while (llvm::Optional<std::string> Request = LE.readLine())
+  while (std::optional<std::string> Request = LE.readLine())
     runCommand(std::move(*Request), *Index);
 }

diff  --git a/clang-tools-extra/clangd/index/remote/server/Server.cpp b/clang-tools-extra/clangd/index/remote/server/Server.cpp
index 5d2c82e2c86ad..e108d4d0b057b 100644
--- a/clang-tools-extra/clangd/index/remote/server/Server.cpp
+++ b/clang-tools-extra/clangd/index/remote/server/Server.cpp
@@ -504,7 +504,7 @@ int main(int argc, char *argv[]) {
   auto Logger = makeLogger(LogPrefix.getValue(), llvm::errs());
   clang::clangd::LoggingSession LoggingSession(*Logger);
 
-  llvm::Optional<llvm::raw_fd_ostream> TracerStream;
+  std::optional<llvm::raw_fd_ostream> TracerStream;
   std::unique_ptr<clang::clangd::trace::EventTracer> Tracer;
   if (!TraceFile.empty()) {
     std::error_code EC;
@@ -522,7 +522,7 @@ int main(int argc, char *argv[]) {
     }
   }
 
-  llvm::Optional<clang::clangd::trace::Session> TracingSession;
+  std::optional<clang::clangd::trace::Session> TracingSession;
   if (Tracer)
     TracingSession.emplace(*Tracer);
 

diff  --git a/clang-tools-extra/clangd/refactor/InsertionPoint.cpp b/clang-tools-extra/clangd/refactor/InsertionPoint.cpp
index ff17ddd420b7b..7f042c0cacb92 100644
--- a/clang-tools-extra/clangd/refactor/InsertionPoint.cpp
+++ b/clang-tools-extra/clangd/refactor/InsertionPoint.cpp
@@ -22,8 +22,8 @@ namespace {
 // Choose the decl to insert before, according to an anchor.
 // Nullptr means insert at end of DC.
 // None means no valid place to insert.
-llvm::Optional<const Decl *> insertionDecl(const DeclContext &DC,
-                                           const Anchor &A) {
+std::optional<const Decl *> insertionDecl(const DeclContext &DC,
+                                          const Anchor &A) {
   bool LastMatched = false;
   bool ReturnNext = false;
   for (const auto *D : DC.decls()) {

diff  --git a/clang-tools-extra/clangd/refactor/Rename.cpp b/clang-tools-extra/clangd/refactor/Rename.cpp
index afddab0073580..6362768f9b475 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -39,8 +39,8 @@ namespace clang {
 namespace clangd {
 namespace {
 
-llvm::Optional<std::string> filePath(const SymbolLocation &Loc,
-                                     llvm::StringRef HintFilePath) {
+std::optional<std::string> filePath(const SymbolLocation &Loc,
+                                    llvm::StringRef HintFilePath) {
   if (!Loc)
     return std::nullopt;
   auto Path = URI::resolve(Loc.FileURI, HintFilePath);
@@ -197,10 +197,10 @@ enum class ReasonToReject {
   SameName,
 };
 
-llvm::Optional<ReasonToReject> renameable(const NamedDecl &RenameDecl,
-                                          StringRef MainFilePath,
-                                          const SymbolIndex *Index,
-                                          const RenameOptions& Opts) {
+std::optional<ReasonToReject> renameable(const NamedDecl &RenameDecl,
+                                         StringRef MainFilePath,
+                                         const SymbolIndex *Index,
+                                         const RenameOptions &Opts) {
   trace::Span Tracer("Renameable");
   if (!Opts.RenameVirtual) {
     if (const auto *S = llvm::dyn_cast<CXXMethodDecl>(&RenameDecl)) {
@@ -501,13 +501,13 @@ static bool mayBeValidIdentifier(llvm::StringRef Ident) {
 
 // Check if we can rename the given RenameDecl into NewName.
 // Return details if the rename would produce a conflict.
-llvm::Optional<InvalidName> checkName(const NamedDecl &RenameDecl,
-                                      llvm::StringRef NewName) {
+std::optional<InvalidName> checkName(const NamedDecl &RenameDecl,
+                                     llvm::StringRef NewName) {
   trace::Span Tracer("CheckName");
   static constexpr trace::Metric InvalidNameMetric(
       "rename_name_invalid", trace::Metric::Counter, "invalid_kind");
   auto &ASTCtx = RenameDecl.getASTContext();
-  llvm::Optional<InvalidName> Result;
+  std::optional<InvalidName> Result;
   if (isKeyword(NewName, ASTCtx.getLangOpts()))
     Result = InvalidName{InvalidName::Keywords, NewName.str()};
   else if (!mayBeValidIdentifier(NewName))
@@ -911,7 +911,7 @@ llvm::Expected<Edit> buildRenameEdit(llvm::StringRef AbsFilePath,
 //          ranges onto candidates in a plausible way (e.g. guess that lines
 //          were inserted). If such a "near miss" is found, the rename is still
 //          possible
-llvm::Optional<std::vector<Range>>
+std::optional<std::vector<Range>>
 adjustRenameRanges(llvm::StringRef DraftCode, llvm::StringRef Identifier,
                    std::vector<Range> Indexed, const LangOptions &LangOpts) {
   trace::Span Tracer("AdjustRenameRanges");
@@ -923,8 +923,8 @@ adjustRenameRanges(llvm::StringRef DraftCode, llvm::StringRef Identifier,
   return getMappedRanges(Indexed, Lexed);
 }
 
-llvm::Optional<std::vector<Range>> getMappedRanges(ArrayRef<Range> Indexed,
-                                                   ArrayRef<Range> Lexed) {
+std::optional<std::vector<Range>> getMappedRanges(ArrayRef<Range> Indexed,
+                                                  ArrayRef<Range> Lexed) {
   trace::Span Tracer("GetMappedRanges");
   assert(!Indexed.empty());
   assert(llvm::is_sorted(Indexed));

diff  --git a/clang-tools-extra/clangd/refactor/Rename.h b/clang-tools-extra/clangd/refactor/Rename.h
index 6b917d5611801..91728ba59e5d8 100644
--- a/clang-tools-extra/clangd/refactor/Rename.h
+++ b/clang-tools-extra/clangd/refactor/Rename.h
@@ -84,7 +84,7 @@ llvm::Expected<Edit> buildRenameEdit(llvm::StringRef AbsFilePath,
 /// The API assumes that Indexed contains only named occurrences (each
 /// occurrence has the same length).
 /// REQUIRED: Indexed is sorted.
-llvm::Optional<std::vector<Range>>
+std::optional<std::vector<Range>>
 adjustRenameRanges(llvm::StringRef DraftCode, llvm::StringRef Identifier,
                    std::vector<Range> Indexed, const LangOptions &LangOpts);
 
@@ -94,8 +94,8 @@ adjustRenameRanges(llvm::StringRef DraftCode, llvm::StringRef Identifier,
 /// Exposed for testing only.
 ///
 /// REQUIRED: Indexed and Lexed are sorted.
-llvm::Optional<std::vector<Range>> getMappedRanges(ArrayRef<Range> Indexed,
-                                                   ArrayRef<Range> Lexed);
+std::optional<std::vector<Range>> getMappedRanges(ArrayRef<Range> Indexed,
+                                                  ArrayRef<Range> Lexed);
 /// Evaluates how good the mapped result is. 0 indicates a perfect match.
 ///
 /// Exposed for testing only.

diff  --git a/clang-tools-extra/clangd/refactor/Tweak.h b/clang-tools-extra/clangd/refactor/Tweak.h
index f91faf2aedcff..e35d34afc4d17 100644
--- a/clang-tools-extra/clangd/refactor/Tweak.h
+++ b/clang-tools-extra/clangd/refactor/Tweak.h
@@ -74,7 +74,7 @@ class Tweak {
 
   struct Effect {
     /// A message to be displayed to the user.
-    llvm::Optional<std::string> ShowMessage;
+    std::optional<std::string> ShowMessage;
     FileEdits ApplyEdits;
     /// Whether the edits should be formatted before presenting to the client.
     /// Note that it applies to all files.

diff  --git a/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp b/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
index 410dec0b91002..4e97b13062176 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
@@ -53,7 +53,7 @@ namespace {
 // Returns semicolon location for the given FD. Since AST doesn't contain that
 // information, searches for a semicolon by lexing from end of function decl
 // while skipping comments.
-llvm::Optional<SourceLocation> getSemicolonForDecl(const FunctionDecl *FD) {
+std::optional<SourceLocation> getSemicolonForDecl(const FunctionDecl *FD) {
   const SourceManager &SM = FD->getASTContext().getSourceManager();
   const LangOptions &LangOpts = FD->getASTContext().getLangOpts();
 
@@ -349,7 +349,7 @@ const SourceLocation getBeginLoc(const FunctionDecl *FD) {
   return FD->getBeginLoc();
 }
 
-llvm::Optional<tooling::Replacement>
+std::optional<tooling::Replacement>
 addInlineIfInHeader(const FunctionDecl *FD) {
   // This includes inline functions and constexpr functions.
   if (FD->isInlined() || llvm::isa<CXXMethodDecl>(FD))

diff  --git a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
index 1e09da9aa20b3..782d14ec9e9bc 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
@@ -59,8 +59,8 @@ const FunctionDecl *getSelectedFunction(const SelectionTree::Node *SelNode) {
   return nullptr;
 }
 
-llvm::Optional<Path> getSourceFile(llvm::StringRef FileName,
-                                   const Tweak::Selection &Sel) {
+std::optional<Path> getSourceFile(llvm::StringRef FileName,
+                                  const Tweak::Selection &Sel) {
   assert(Sel.FS);
   if (auto Source = getCorrespondingHeaderOrSource(FileName, Sel.FS))
     return *Source;
@@ -70,7 +70,7 @@ llvm::Optional<Path> getSourceFile(llvm::StringRef FileName,
 // Synthesize a DeclContext for TargetNS from CurContext. TargetNS must be empty
 // for global namespace, and endwith "::" otherwise.
 // Returns std::nullopt if TargetNS is not a prefix of CurContext.
-llvm::Optional<const DeclContext *>
+std::optional<const DeclContext *>
 findContextForNS(llvm::StringRef TargetNS, const DeclContext *CurContext) {
   assert(TargetNS.empty() || TargetNS.endswith("::"));
   // Skip any non-namespace contexts, e.g. TagDecls, functions/methods.

diff  --git a/clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp b/clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp
index 7a89ce7dc3cf5..e126e72ef2532 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp
@@ -56,7 +56,7 @@ class DumpAST : public Tweak {
     return N.get<Decl>() || N.get<Stmt>() || N.get<Type>();
   }
 
-  llvm::Optional<DynTypedNode> Node;
+  std::optional<DynTypedNode> Node;
 };
 REGISTER_TWEAK(DumpAST)
 

diff  --git a/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp b/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
index aabaed045c3d2..b87752117e161 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
@@ -114,7 +114,7 @@ bool ExpandAutoType::prepare(const Selection &Inputs) {
 Expected<Tweak::Effect> ExpandAutoType::apply(const Selection& Inputs) {
   auto &SrcMgr = Inputs.AST->getSourceManager();
 
-  llvm::Optional<clang::QualType> DeducedType =
+  std::optional<clang::QualType> DeducedType =
       getDeducedType(Inputs.AST->getASTContext(), AutoRange.getBegin());
 
   // if we can't resolve the type, return an error message

diff  --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
index a259deb0a9150..b47d0833868b1 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -265,9 +265,9 @@ const FunctionDecl *findEnclosingFunction(const Node *CommonAnc) {
 
 // Zone Range is the union of SourceRanges of all child Nodes in Parent since
 // all child Nodes are RootStmts
-llvm::Optional<SourceRange> findZoneRange(const Node *Parent,
-                                          const SourceManager &SM,
-                                          const LangOptions &LangOpts) {
+std::optional<SourceRange> findZoneRange(const Node *Parent,
+                                         const SourceManager &SM,
+                                         const LangOptions &LangOpts) {
   SourceRange SR;
   if (auto BeginFileRange = toHalfOpenFileRange(
           SM, LangOpts, Parent->Children.front()->ASTNode.getSourceRange()))
@@ -286,7 +286,7 @@ llvm::Optional<SourceRange> findZoneRange(const Node *Parent,
 // FIXME: check if EnclosingFunction has any attributes as the AST doesn't
 // always store the source range of the attributes and thus we end up extracting
 // between the attributes and the EnclosingFunction.
-llvm::Optional<SourceRange>
+std::optional<SourceRange>
 computeEnclosingFuncRange(const FunctionDecl *EnclosingFunction,
                           const SourceManager &SM,
                           const LangOptions &LangOpts) {
@@ -311,9 +311,9 @@ bool validSingleChild(const Node *Child, const FunctionDecl *EnclosingFunc) {
 
 // FIXME: Check we're not extracting from the initializer/condition of a control
 // flow structure.
-llvm::Optional<ExtractionZone> findExtractionZone(const Node *CommonAnc,
-                                                  const SourceManager &SM,
-                                                  const LangOptions &LangOpts) {
+std::optional<ExtractionZone> findExtractionZone(const Node *CommonAnc,
+                                                 const SourceManager &SM,
+                                                 const LangOptions &LangOpts) {
   ExtractionZone ExtZone;
   ExtZone.Parent = getParentOfRootStmts(CommonAnc);
   if (!ExtZone.Parent || ExtZone.Parent->Children.empty())
@@ -358,7 +358,7 @@ struct NewFunction {
   std::vector<Parameter> Parameters;
   SourceRange BodyRange;
   SourceLocation DefinitionPoint;
-  llvm::Optional<SourceLocation> ForwardDeclarationPoint;
+  std::optional<SourceLocation> ForwardDeclarationPoint;
   const CXXRecordDecl *EnclosingClass = nullptr;
   const NestedNameSpecifier *DefinitionQualifier = nullptr;
   const DeclContext *SemanticDC = nullptr;

diff  --git a/clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp b/clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp
index dbaf2a5d5c36a..c3f53219f2242 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp
@@ -90,7 +90,7 @@ struct MethodParameter {
     else // Could be a dynamic property or a property in a header.
       Assignee = ("self." + Name).str();
   }
-  static llvm::Optional<MethodParameter> parameterFor(const Decl &D) {
+  static std::optional<MethodParameter> parameterFor(const Decl &D) {
     if (const auto *ID = dyn_cast<ObjCIvarDecl>(&D))
       return MethodParameter(*ID);
     if (const auto *PD = dyn_cast<ObjCPropertyDecl>(&D))

diff  --git a/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp b/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
index 51d299ee63def..da32e00a0ee06 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
@@ -73,7 +73,7 @@ class FindSameUsings : public RecursiveASTVisitor<FindSameUsings> {
 llvm::Expected<tooling::Replacement>
 removeUsingDirective(ASTContext &Ctx, const UsingDirectiveDecl *D) {
   auto &SM = Ctx.getSourceManager();
-  llvm::Optional<Token> NextTok =
+  std::optional<Token> NextTok =
       Lexer::findNextToken(D->getEndLoc(), SM, Ctx.getLangOpts());
   if (!NextTok || NextTok->isNot(tok::semi))
     return error("no semicolon after using-directive");

diff  --git a/clang-tools-extra/clangd/tool/Check.cpp b/clang-tools-extra/clangd/tool/Check.cpp
index 3250571d4bce0..b0af90061dd29 100644
--- a/clang-tools-extra/clangd/tool/Check.cpp
+++ b/clang-tools-extra/clangd/tool/Check.cpp
@@ -126,7 +126,7 @@ class Checker {
   format::FormatStyle Style;
   // from buildAST
   std::shared_ptr<const PreambleData> Preamble;
-  llvm::Optional<ParsedAST> AST;
+  std::optional<ParsedAST> AST;
   FileIndex Index;
 
 public:
@@ -167,7 +167,7 @@ class Checker {
 
   // Prepare inputs and build CompilerInvocation (parsed compile command).
   bool buildInvocation(const ThreadsafeFS &TFS,
-                       llvm::Optional<std::string> Contents) {
+                       std::optional<std::string> Contents) {
     StoreDiags CaptureInvocationDiags;
     std::vector<std::string> CC1Args;
     Inputs.CompileCommand = Cmd;
@@ -438,7 +438,7 @@ bool check(llvm::StringRef File, const ThreadsafeFS &TFS,
   }
 
   llvm::SmallString<0> FakeFile;
-  llvm::Optional<std::string> Contents;
+  std::optional<std::string> Contents;
   if (File.empty()) {
     llvm::sys::path::system_temp_directory(false, FakeFile);
     llvm::sys::path::append(FakeFile, "test.cc");

diff  --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp b/clang-tools-extra/clangd/tool/ClangdMain.cpp
index fa6bda1c6d1ed..e0682f164c893 100644
--- a/clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -639,9 +639,9 @@ class FlagsConfigProvider : public config::Provider {
 
 public:
   FlagsConfigProvider() {
-    llvm::Optional<Config::CDBSearchSpec> CDBSearch;
-    llvm::Optional<Config::ExternalIndexSpec> IndexSpec;
-    llvm::Optional<Config::BackgroundPolicy> BGPolicy;
+    std::optional<Config::CDBSearchSpec> CDBSearch;
+    std::optional<Config::ExternalIndexSpec> IndexSpec;
+    std::optional<Config::BackgroundPolicy> BGPolicy;
 
     // If --compile-commands-dir arg was invoked, check value and override
     // default path.
@@ -784,7 +784,7 @@ clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment var
     clang::format::DefaultFallbackStyle = FallbackStyle.c_str();
 
   // Validate command line arguments.
-  llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
+  std::optional<llvm::raw_fd_ostream> InputMirrorStream;
   if (!InputMirrorFile.empty()) {
     std::error_code EC;
     InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC,
@@ -808,7 +808,7 @@ clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment var
   // Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a
   // trace flag in your editor's config is annoying, launching with
   // `CLANGD_TRACE=trace.json vim` is easier.
-  llvm::Optional<llvm::raw_fd_ostream> TracerStream;
+  std::optional<llvm::raw_fd_ostream> TracerStream;
   std::unique_ptr<trace::EventTracer> Tracer;
   const char *JSONTraceFile = getenv("CLANGD_TRACE");
   const char *MetricsCSVFile = getenv("CLANGD_METRICS");
@@ -828,7 +828,7 @@ clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment var
     }
   }
 
-  llvm::Optional<trace::Session> TracingSession;
+  std::optional<trace::Session> TracingSession;
   if (Tracer)
     TracingSession.emplace(*Tracer);
 

diff  --git a/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp b/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
index a9a30eac43682..4c6a238bbb261 100644
--- a/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
@@ -98,8 +98,8 @@ class LSPTest : public ::testing::Test {
 
   Logger L;
   LoggingSession LogSession;
-  llvm::Optional<ClangdLSPServer> Server;
-  llvm::Optional<std::thread> ServerThread;
+  std::optional<ClangdLSPServer> Server;
+  std::optional<std::thread> ServerThread;
   LSPClient Client;
 };
 
@@ -262,10 +262,11 @@ TEST_F(LSPTest, ModulesTest) {
               ElementsAre(llvm::json::Value(2), llvm::json::Value(10)));
 }
 
-// Creates a Callback that writes its received value into an Optional<Expected>.
+// Creates a Callback that writes its received value into an
+// std::optional<Expected>.
 template <typename T>
 llvm::unique_function<void(llvm::Expected<T>)>
-capture(llvm::Optional<llvm::Expected<T>> &Out) {
+capture(std::optional<llvm::Expected<T>> &Out) {
   Out.reset();
   return [&Out](llvm::Expected<T> V) { Out.emplace(std::move(V)); };
 }

diff  --git a/clang-tools-extra/clangd/unittests/ClangdTests.cpp b/clang-tools-extra/clangd/unittests/ClangdTests.cpp
index 05630629009c3..6e6036ece34ab 100644
--- a/clang-tools-extra/clangd/unittests/ClangdTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ClangdTests.cpp
@@ -1111,7 +1111,7 @@ TEST(ClangdServerTest, FallbackWhenWaitingForCompileCommand) {
     DelayedCompilationDatabase(Notification &CanReturnCommand)
         : CanReturnCommand(CanReturnCommand) {}
 
-    llvm::Optional<tooling::CompileCommand>
+    std::optional<tooling::CompileCommand>
     getCompileCommand(PathRef File) const override {
       // FIXME: make this timeout and fail instead of waiting forever in case
       // something goes wrong.

diff  --git a/clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp b/clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
index 8d434a2793e2e..16dd81a107e25 100644
--- a/clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
@@ -436,7 +436,7 @@ TEST_F(ConfigCompileTests, ExternalBlockDisablesBackgroundIndex) {
 
 TEST_F(ConfigCompileTests, ExternalBlockMountPoint) {
   auto GetFrag = [](llvm::StringRef Directory,
-                    llvm::Optional<const char *> MountPoint) {
+                    std::optional<const char *> MountPoint) {
     Fragment Frag;
     Frag.Source.Directory = Directory.str();
     Fragment::IndexBlock::ExternalBlock External;

diff  --git a/clang-tools-extra/clangd/unittests/ConfigTesting.h b/clang-tools-extra/clangd/unittests/ConfigTesting.h
index c06a061276733..dc92e1335e11f 100644
--- a/clang-tools-extra/clangd/unittests/ConfigTesting.h
+++ b/clang-tools-extra/clangd/unittests/ConfigTesting.h
@@ -50,7 +50,7 @@ struct CapturedDiags {
     std::string Message;
     llvm::SourceMgr::DiagKind Kind;
     Position Pos;
-    llvm::Optional<Range> Rng;
+    std::optional<Range> Rng;
 
     friend void PrintTo(const Diag &D, std::ostream *OS) {
       *OS << (D.Kind == llvm::SourceMgr::DK_Error ? "error: " : "warning: ")

diff  --git a/clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp b/clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp
index 839f4c8e57a56..afefa245f03e7 100644
--- a/clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp
+++ b/clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp
@@ -39,7 +39,7 @@ class ExpectedTypeConversionTest : public ::testing::Test {
   }
 
   /// An overload for convenience.
-  llvm::Optional<OpaqueType> fromCompletionResult(const NamedDecl *D) {
+  std::optional<OpaqueType> fromCompletionResult(const NamedDecl *D) {
     return OpaqueType::fromCompletionResult(
         astCtx(), CodeCompletionResult(D, CCP_Declaration));
   }
@@ -75,7 +75,7 @@ class ExpectedTypeConversionTest : public ::testing::Test {
 
 private:
   // Set after calling build().
-  llvm::Optional<ParsedAST> AST;
+  std::optional<ParsedAST> AST;
 };
 
 TEST_F(ExpectedTypeConversionTest, BasicTypes) {

diff  --git a/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp b/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
index 71bcb1234ba88..a2fc52ae6e7a8 100644
--- a/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
+++ b/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
@@ -64,7 +64,7 @@ static tooling::CompileCommand cmd(llvm::StringRef File, llvm::StringRef Arg) {
 class OverlayCDBTest : public ::testing::Test {
   class BaseCDB : public GlobalCompilationDatabase {
   public:
-    llvm::Optional<tooling::CompileCommand>
+    std::optional<tooling::CompileCommand>
     getCompileCommand(llvm::StringRef File) const override {
       if (File == testPath("foo.cc"))
         return cmd(File, "-DA=1");
@@ -76,7 +76,7 @@ class OverlayCDBTest : public ::testing::Test {
       return cmd(File, "-DA=2");
     }
 
-    llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const override {
+    std::optional<ProjectInfo> getProjectInfo(PathRef File) const override {
       return ProjectInfo{testRoot()};
     }
   };

diff  --git a/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp b/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
index f6bc9a6248cfa..6e280f5b085a9 100644
--- a/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
@@ -31,7 +31,7 @@ TEST(HeaderSourceSwitchTest, FileHeuristic) {
   FS.Files[FooCpp];
   FS.Files[FooH];
   FS.Files[Invalid];
-  Optional<Path> PathResult =
+  std::optional<Path> PathResult =
       getCorrespondingHeaderOrSource(FooCpp, FS.view(std::nullopt));
   EXPECT_TRUE(PathResult.has_value());
   ASSERT_EQ(*PathResult, FooH);
@@ -142,7 +142,7 @@ TEST(HeaderSourceSwitchTest, FromHeaderToSource) {
   // Test for switch from .h header to .cc source
   struct {
     llvm::StringRef HeaderCode;
-    llvm::Optional<std::string> ExpectedSource;
+    std::optional<std::string> ExpectedSource;
   } TestCases[] = {
       {"// empty, no header found", std::nullopt},
       {R"cpp(
@@ -211,7 +211,7 @@ TEST(HeaderSourceSwitchTest, FromSourceToHeader) {
   // Test for switching from .cc source file to .h header.
   struct {
     llvm::StringRef SourceCode;
-    llvm::Optional<std::string> ExpectedResult;
+    std::optional<std::string> ExpectedResult;
   } TestCases[] = {
       {"// empty, no header found", std::nullopt},
       {R"cpp(

diff  --git a/clang-tools-extra/clangd/unittests/HeadersTests.cpp b/clang-tools-extra/clangd/unittests/HeadersTests.cpp
index b14a14f0528b3..4fadb7c04aea6 100644
--- a/clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -119,8 +119,8 @@ class HeadersTest : public ::testing::Test {
     return Path.value_or("");
   }
 
-  llvm::Optional<TextEdit> insert(llvm::StringRef VerbatimHeader,
-                                  tooling::IncludeDirective Directive) {
+  std::optional<TextEdit> insert(llvm::StringRef VerbatimHeader,
+                                 tooling::IncludeDirective Directive) {
     Clang = setupClang();
     PreprocessOnlyAction Action;
     EXPECT_TRUE(

diff  --git a/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp b/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp
index b23c00edc99ea..03f787035b367 100644
--- a/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp
+++ b/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp
@@ -31,10 +31,11 @@ bool fromJSON(const llvm::json::Value &V, Foo &F, llvm::json::Path P) {
 }
 llvm::json::Value toJSON(const Foo &F) { return F.X; }
 
-// Creates a Callback that writes its received value into an Optional<Expected>.
+// Creates a Callback that writes its received value into an
+// std::optional<Expected>.
 template <typename T>
 llvm::unique_function<void(llvm::Expected<T>)>
-capture(llvm::Optional<llvm::Expected<T>> &Out) {
+capture(std::optional<llvm::Expected<T>> &Out) {
   Out.reset();
   return [&Out](llvm::Expected<T> V) { Out.emplace(std::move(V)); };
 }
@@ -90,7 +91,7 @@ TEST(LSPBinderTest, IncomingCalls) {
               UnorderedElementsAre("notify"));
   ASSERT_THAT(RawHandlers.CommandHandlers.keys(),
               UnorderedElementsAre("cmdPlusOne"));
-  llvm::Optional<llvm::Expected<llvm::json::Value>> Reply;
+  std::optional<llvm::Expected<llvm::json::Value>> Reply;
 
   auto &RawPlusOne = RawHandlers.MethodHandlers["plusOne"];
   RawPlusOne(1, capture(Reply));
@@ -136,14 +137,14 @@ TEST(LSPBinderTest, OutgoingCalls) {
   LSPBinder::OutgoingMethod<Foo, Foo> Fail;
   Fail = Binder.outgoingMethod("fail");
 
-  llvm::Optional<llvm::Expected<Foo>> Reply;
+  std::optional<llvm::Expected<Foo>> Reply;
   Echo(Foo{2}, capture(Reply));
   EXPECT_THAT(RawOutgoing.take("echo"), ElementsAre(llvm::json::Value(2)));
   ASSERT_TRUE(Reply.has_value());
   EXPECT_THAT_EXPECTED(*Reply, llvm::HasValue(Foo{2}));
 
   // JSON response is integer, can't be parsed as string.
-  llvm::Optional<llvm::Expected<std::string>> WrongTypeReply;
+  std::optional<llvm::Expected<std::string>> WrongTypeReply;
   WrongSignature(Foo{2}, capture(WrongTypeReply));
   EXPECT_THAT(RawOutgoing.take("wrongSignature"),
               ElementsAre(llvm::json::Value(2)));

diff  --git a/clang-tools-extra/clangd/unittests/LSPClient.cpp b/clang-tools-extra/clangd/unittests/LSPClient.cpp
index 027bf57a8a049..9361c0e29c91e 100644
--- a/clang-tools-extra/clangd/unittests/LSPClient.cpp
+++ b/clang-tools-extra/clangd/unittests/LSPClient.cpp
@@ -199,7 +199,7 @@ void LSPClient::didClose(llvm::StringRef Path) {
 
 void LSPClient::sync() { call("sync", nullptr).takeValue(); }
 
-llvm::Optional<std::vector<llvm::json::Value>>
+std::optional<std::vector<llvm::json::Value>>
 LSPClient::diagnostics(llvm::StringRef Path) {
   sync();
   auto Notifications = takeNotifications("textDocument/publishDiagnostics");

diff  --git a/clang-tools-extra/clangd/unittests/PreambleTests.cpp b/clang-tools-extra/clangd/unittests/PreambleTests.cpp
index eb071e39c41d9..1e95b62884f69 100644
--- a/clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ b/clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -190,8 +190,8 @@ TEST(PreamblePatchTest, PatchesPreambleIncludes) {
                                 Field(&Inclusion::Resolved, testPath("a.h")))));
 }
 
-llvm::Optional<ParsedAST> createPatchedAST(llvm::StringRef Baseline,
-                                           llvm::StringRef Modified) {
+std::optional<ParsedAST> createPatchedAST(llvm::StringRef Baseline,
+                                          llvm::StringRef Modified) {
   auto BaselinePreamble = TestTU::withCode(Baseline).preamble();
   if (!BaselinePreamble) {
     ADD_FAILURE() << "Failed to build baseline preamble";

diff  --git a/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp b/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
index eb5f60c3b9352..9d40702ca5cd2 100644
--- a/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
@@ -356,9 +356,9 @@ TEST(SourceCodeTests, CollectWords) {
 }
 
 class SpelledWordsTest : public ::testing::Test {
-  llvm::Optional<ParsedAST> AST;
+  std::optional<ParsedAST> AST;
 
-  llvm::Optional<SpelledWord> tryWord(const char *Text) {
+  std::optional<SpelledWord> tryWord(const char *Text) {
     llvm::Annotations A(Text);
     auto TU = TestTU::withCode(A.code());
     AST = TU.build();
@@ -663,7 +663,7 @@ TEST(SourceCodeTests, HalfOpenFileRangePathologicalPreprocessor) {
   const auto &Func = cast<FunctionDecl>(findDecl(AST, "test"));
   const auto &Body = cast<CompoundStmt>(Func.getBody());
   const auto &Loop = cast<WhileStmt>(*Body->child_begin());
-  llvm::Optional<SourceRange> Range = toHalfOpenFileRange(
+  std::optional<SourceRange> Range = toHalfOpenFileRange(
       AST.getSourceManager(), AST.getLangOpts(), Loop->getSourceRange());
   ASSERT_TRUE(Range) << "Failed to get file range";
   EXPECT_EQ(AST.getSourceManager().getFileOffset(Range->getBegin()),

diff  --git a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
index 08523edfc558b..a2bf1c0baf0b3 100644
--- a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
@@ -132,7 +132,7 @@ class ShouldCollectSymbolTest : public ::testing::Test {
   std::string HeaderName = "f.h";
   std::string FileName = "f.cpp";
   TestTU File;
-  llvm::Optional<ParsedAST> AST; // Initialized after build.
+  std::optional<ParsedAST> AST; // Initialized after build.
 };
 
 TEST_F(ShouldCollectSymbolTest, ShouldCollectSymbol) {
@@ -870,7 +870,7 @@ TEST_F(SymbolCollectorTest, RefContainers) {
   CollectorOpts.RefFilter = RefKind::All;
   CollectorOpts.CollectMainFileRefs = true;
   runSymbolCollector("", Code.code());
-  auto FindRefWithRange = [&](Range R) -> Optional<Ref> {
+  auto FindRefWithRange = [&](Range R) -> std::optional<Ref> {
     for (auto &Entry : Refs) {
       for (auto &Ref : Entry.second) {
         if (rangesMatch(Ref.Location, R))

diff  --git a/clang-tools-extra/clangd/unittests/SymbolInfoTests.cpp b/clang-tools-extra/clangd/unittests/SymbolInfoTests.cpp
index ad76d7dcf5547..6c91f3783a622 100644
--- a/clang-tools-extra/clangd/unittests/SymbolInfoTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SymbolInfoTests.cpp
@@ -377,7 +377,7 @@ TEST(SymbolInfoTests, All) {
 
     std::vector<SymbolDetails> Expected;
     for (const auto &Sym : T.second) {
-      llvm::Optional<Location> Decl, Def;
+      std::optional<Location> Decl, Def;
       if (Sym.DeclMarker)
         Decl = Location{URIForFile::canonicalize(testPath(TU.Filename), ""),
                         TestInput.range(Sym.DeclMarker)};

diff  --git a/clang-tools-extra/clangd/unittests/SyncAPI.cpp b/clang-tools-extra/clangd/unittests/SyncAPI.cpp
index 2c4fde7d18953..d48622eba5378 100644
--- a/clang-tools-extra/clangd/unittests/SyncAPI.cpp
+++ b/clang-tools-extra/clangd/unittests/SyncAPI.cpp
@@ -28,7 +28,7 @@ namespace {
 ///    T Result;
 ///    someAsyncFunc(Param1, Param2, /*Callback=*/capture(Result));
 template <typename T> struct CaptureProxy {
-  CaptureProxy(llvm::Optional<T> &Target) : Target(&Target) { assert(!Target); }
+  CaptureProxy(std::optional<T> &Target) : Target(&Target) { assert(!Target); }
 
   CaptureProxy(const CaptureProxy &) = delete;
   CaptureProxy &operator=(const CaptureProxy &) = delete;
@@ -55,7 +55,7 @@ template <typename T> struct CaptureProxy {
   }
 
 private:
-  llvm::Optional<T> *Target;
+  std::optional<T> *Target;
   // Using shared_ptr to workaround compilation errors with MSVC.
   // MSVC only allows default-constructible and copyable objects as future<>
   // arguments.
@@ -63,7 +63,7 @@ template <typename T> struct CaptureProxy {
   std::future<std::shared_ptr<T>> Future;
 };
 
-template <typename T> CaptureProxy<T> capture(llvm::Optional<T> &Target) {
+template <typename T> CaptureProxy<T> capture(std::optional<T> &Target) {
   return CaptureProxy<T>(Target);
 }
 } // namespace
@@ -71,7 +71,7 @@ template <typename T> CaptureProxy<T> capture(llvm::Optional<T> &Target) {
 llvm::Expected<CodeCompleteResult>
 runCodeComplete(ClangdServer &Server, PathRef File, Position Pos,
                 clangd::CodeCompleteOptions Opts) {
-  llvm::Optional<llvm::Expected<CodeCompleteResult>> Result;
+  std::optional<llvm::Expected<CodeCompleteResult>> Result;
   Server.codeComplete(File, Pos, Opts, capture(Result));
   return std::move(*Result);
 }
@@ -79,21 +79,21 @@ runCodeComplete(ClangdServer &Server, PathRef File, Position Pos,
 llvm::Expected<SignatureHelp> runSignatureHelp(ClangdServer &Server,
                                                PathRef File, Position Pos,
                                                MarkupKind DocumentationFormat) {
-  llvm::Optional<llvm::Expected<SignatureHelp>> Result;
+  std::optional<llvm::Expected<SignatureHelp>> Result;
   Server.signatureHelp(File, Pos, DocumentationFormat, capture(Result));
   return std::move(*Result);
 }
 
 llvm::Expected<std::vector<LocatedSymbol>>
 runLocateSymbolAt(ClangdServer &Server, PathRef File, Position Pos) {
-  llvm::Optional<llvm::Expected<std::vector<LocatedSymbol>>> Result;
+  std::optional<llvm::Expected<std::vector<LocatedSymbol>>> Result;
   Server.locateSymbolAt(File, Pos, capture(Result));
   return std::move(*Result);
 }
 
 llvm::Expected<std::vector<DocumentHighlight>>
 runFindDocumentHighlights(ClangdServer &Server, PathRef File, Position Pos) {
-  llvm::Optional<llvm::Expected<std::vector<DocumentHighlight>>> Result;
+  std::optional<llvm::Expected<std::vector<DocumentHighlight>>> Result;
   Server.findDocumentHighlights(File, Pos, capture(Result));
   return std::move(*Result);
 }
@@ -101,23 +101,23 @@ runFindDocumentHighlights(ClangdServer &Server, PathRef File, Position Pos) {
 llvm::Expected<RenameResult> runRename(ClangdServer &Server, PathRef File,
                                        Position Pos, llvm::StringRef NewName,
                                        const RenameOptions &RenameOpts) {
-  llvm::Optional<llvm::Expected<RenameResult>> Result;
+  std::optional<llvm::Expected<RenameResult>> Result;
   Server.rename(File, Pos, NewName, RenameOpts, capture(Result));
   return std::move(*Result);
 }
 
 llvm::Expected<RenameResult>
 runPrepareRename(ClangdServer &Server, PathRef File, Position Pos,
-                 llvm::Optional<std::string> NewName,
+                 std::optional<std::string> NewName,
                  const RenameOptions &RenameOpts) {
-  llvm::Optional<llvm::Expected<RenameResult>> Result;
+  std::optional<llvm::Expected<RenameResult>> Result;
   Server.prepareRename(File, Pos, NewName, RenameOpts, capture(Result));
   return std::move(*Result);
 }
 
 llvm::Expected<tooling::Replacements>
-runFormatFile(ClangdServer &Server, PathRef File, llvm::Optional<Range> Rng) {
-  llvm::Optional<llvm::Expected<tooling::Replacements>> Result;
+runFormatFile(ClangdServer &Server, PathRef File, std::optional<Range> Rng) {
+  std::optional<llvm::Expected<tooling::Replacements>> Result;
   Server.formatFile(File, Rng, capture(Result));
   return std::move(*Result);
 }
@@ -146,14 +146,14 @@ RefSlab getRefs(const SymbolIndex &Index, SymbolID ID) {
 llvm::Expected<std::vector<SelectionRange>>
 runSemanticRanges(ClangdServer &Server, PathRef File,
                   const std::vector<Position> &Pos) {
-  llvm::Optional<llvm::Expected<std::vector<SelectionRange>>> Result;
+  std::optional<llvm::Expected<std::vector<SelectionRange>>> Result;
   Server.semanticRanges(File, Pos, capture(Result));
   return std::move(*Result);
 }
 
-llvm::Expected<llvm::Optional<clangd::Path>>
+llvm::Expected<std::optional<clangd::Path>>
 runSwitchHeaderSource(ClangdServer &Server, PathRef File) {
-  llvm::Optional<llvm::Expected<llvm::Optional<clangd::Path>>> Result;
+  std::optional<llvm::Expected<std::optional<clangd::Path>>> Result;
   Server.switchSourceHeader(File, capture(Result));
   return std::move(*Result);
 }

diff  --git a/clang-tools-extra/clangd/unittests/SyncAPI.h b/clang-tools-extra/clangd/unittests/SyncAPI.h
index 6b4e3fc608e97..cf3de4f742e84 100644
--- a/clang-tools-extra/clangd/unittests/SyncAPI.h
+++ b/clang-tools-extra/clangd/unittests/SyncAPI.h
@@ -49,11 +49,11 @@ llvm::Expected<RenameResult> runRename(ClangdServer &Server, PathRef File,
 
 llvm::Expected<RenameResult>
 runPrepareRename(ClangdServer &Server, PathRef File, Position Pos,
-                 llvm::Optional<std::string> NewName,
+                 std::optional<std::string> NewName,
                  const clangd::RenameOptions &RenameOpts);
 
 llvm::Expected<tooling::Replacements>
-runFormatFile(ClangdServer &Server, PathRef File, llvm::Optional<Range>);
+runFormatFile(ClangdServer &Server, PathRef File, std::optional<Range>);
 
 SymbolSlab runFuzzyFind(const SymbolIndex &Index, StringRef Query);
 SymbolSlab runFuzzyFind(const SymbolIndex &Index, const FuzzyFindRequest &Req);
@@ -63,7 +63,7 @@ llvm::Expected<std::vector<SelectionRange>>
 runSemanticRanges(ClangdServer &Server, PathRef File,
                   const std::vector<Position> &Pos);
 
-llvm::Expected<llvm::Optional<clangd::Path>>
+llvm::Expected<std::optional<clangd::Path>>
 runSwitchHeaderSource(ClangdServer &Server, PathRef File);
 
 llvm::Error runCustomAction(ClangdServer &Server, PathRef File,

diff  --git a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
index c7e28a0e213a6..5b3cab16ddb61 100644
--- a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1204,7 +1204,7 @@ TEST_F(TUSchedulerTests, IncluderCache) {
                      OK = testPath("ok.h"),
                      NotIncluded = testPath("not_included.h");
   struct NoHeadersCDB : public GlobalCompilationDatabase {
-    llvm::Optional<tooling::CompileCommand>
+    std::optional<tooling::CompileCommand>
     getCompileCommand(PathRef File) const override {
       if (File == NoCmd || File == NotIncluded || FailAll)
         return std::nullopt;
@@ -1387,7 +1387,7 @@ TEST_F(TUSchedulerTests, PreambleThrottle) {
     std::vector<RequestID> Releases;
     llvm::DenseMap<RequestID, Callback> Callbacks;
     // If set, the notification is signalled after acquiring the specified ID.
-    llvm::Optional<std::pair<RequestID, Notification *>> Notify;
+    std::optional<std::pair<RequestID, Notification *>> Notify;
 
     RequestID acquire(llvm::StringRef Filename, Callback CB) override {
       RequestID ID;

diff  --git a/clang-tools-extra/clangd/unittests/TestFS.cpp b/clang-tools-extra/clangd/unittests/TestFS.cpp
index be26a6ccf25f3..1b313f78586a9 100644
--- a/clang-tools-extra/clangd/unittests/TestFS.cpp
+++ b/clang-tools-extra/clangd/unittests/TestFS.cpp
@@ -52,12 +52,12 @@ MockCompilationDatabase::MockCompilationDatabase(llvm::StringRef Directory,
   // -ffreestanding avoids implicit stdc-predef.h.
 }
 
-llvm::Optional<ProjectInfo>
+std::optional<ProjectInfo>
 MockCompilationDatabase::getProjectInfo(PathRef File) const {
   return ProjectInfo{std::string(Directory)};
 }
 
-llvm::Optional<tooling::CompileCommand>
+std::optional<tooling::CompileCommand>
 MockCompilationDatabase::getCompileCommand(PathRef File) const {
   if (ExtraClangFlags.empty())
     return std::nullopt;

diff  --git a/clang-tools-extra/clangd/unittests/TestFS.h b/clang-tools-extra/clangd/unittests/TestFS.h
index 3e4ac3bab1c92..a7a521c76d376 100644
--- a/clang-tools-extra/clangd/unittests/TestFS.h
+++ b/clang-tools-extra/clangd/unittests/TestFS.h
@@ -61,10 +61,10 @@ class MockCompilationDatabase : public GlobalCompilationDatabase {
   MockCompilationDatabase(StringRef Directory = StringRef(),
                           StringRef RelPathPrefix = StringRef());
 
-  llvm::Optional<tooling::CompileCommand>
+  std::optional<tooling::CompileCommand>
   getCompileCommand(PathRef File) const override;
 
-  llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const override;
+  std::optional<ProjectInfo> getProjectInfo(PathRef File) const override;
 
   std::vector<std::string> ExtraClangFlags;
 

diff  --git a/clang-tools-extra/clangd/unittests/TestWorkspace.cpp b/clang-tools-extra/clangd/unittests/TestWorkspace.cpp
index 662eef63d25a6..40c08fc5357d8 100644
--- a/clang-tools-extra/clangd/unittests/TestWorkspace.cpp
+++ b/clang-tools-extra/clangd/unittests/TestWorkspace.cpp
@@ -32,7 +32,7 @@ std::unique_ptr<SymbolIndex> TestWorkspace::index() {
   return Index;
 }
 
-Optional<ParsedAST> TestWorkspace::openFile(llvm::StringRef Filename) {
+std::optional<ParsedAST> TestWorkspace::openFile(llvm::StringRef Filename) {
   auto It = Inputs.find(Filename);
   if (It == Inputs.end()) {
     ADD_FAILURE() << "Accessing non-existing file: " << Filename;

diff  --git a/clang-tools-extra/clangd/unittests/TestWorkspace.h b/clang-tools-extra/clangd/unittests/TestWorkspace.h
index bc6aee1c58d1d..a5e688d8a7d78 100644
--- a/clang-tools-extra/clangd/unittests/TestWorkspace.h
+++ b/clang-tools-extra/clangd/unittests/TestWorkspace.h
@@ -39,7 +39,7 @@ class TestWorkspace {
 
   std::unique_ptr<SymbolIndex> index();
 
-  Optional<ParsedAST> openFile(llvm::StringRef Filename);
+  std::optional<ParsedAST> openFile(llvm::StringRef Filename);
 
 private:
   struct SourceFile {

diff  --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index ae19656f6f9a2..3bbcde267d3e9 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -272,7 +272,7 @@ TEST(HighlightsTest, ControlFlow) {
 }
 
 MATCHER_P3(sym, Name, Decl, DefOrNone, "") {
-  llvm::Optional<Range> Def = DefOrNone;
+  std::optional<Range> Def = DefOrNone;
   if (Name != arg.Name) {
     *result_listener << "Name is " << arg.Name;
     return false;
@@ -1003,8 +1003,8 @@ TEST(LocateSymbol, All) {
       )objc"};
   for (const char *Test : Tests) {
     Annotations T(Test);
-    llvm::Optional<Range> WantDecl;
-    llvm::Optional<Range> WantDef;
+    std::optional<Range> WantDecl;
+    std::optional<Range> WantDef;
     if (!T.ranges().empty())
       WantDecl = WantDef = T.range();
     if (!T.ranges("decl").empty())
@@ -1026,7 +1026,7 @@ TEST(LocateSymbol, All) {
       ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
       EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
       EXPECT_TRUE(Results[0].ID) << Test;
-      llvm::Optional<Range> GotDef;
+      std::optional<Range> GotDef;
       if (Results[0].Definition)
         GotDef = Results[0].Definition->range;
       EXPECT_EQ(WantDef, GotDef) << Test;
@@ -1061,7 +1061,7 @@ TEST(LocateSymbol, AllMulti) {
   //   N starts at 0.
   struct ExpectedRanges {
     Range WantDecl;
-    llvm::Optional<Range> WantDef;
+    std::optional<Range> WantDef;
   };
   const char *Tests[] = {
       R"objc(
@@ -1128,7 +1128,7 @@ TEST(LocateSymbol, AllMulti) {
     for (size_t Idx = 0; Idx < Ranges.size(); Idx++) {
       EXPECT_EQ(Results[Idx].PreferredDeclaration.range, Ranges[Idx].WantDecl)
           << "($decl" << Idx << ")" << Test;
-      llvm::Optional<Range> GotDef;
+      std::optional<Range> GotDef;
       if (Results[Idx].Definition)
         GotDef = Results[Idx].Definition->range;
       EXPECT_EQ(GotDef, Ranges[Idx].WantDef) << "($def" << Idx << ")" << Test;
@@ -1159,8 +1159,8 @@ TEST(LocateSymbol, Warnings) {
 
   for (const char *Test : Tests) {
     Annotations T(Test);
-    llvm::Optional<Range> WantDecl;
-    llvm::Optional<Range> WantDef;
+    std::optional<Range> WantDecl;
+    std::optional<Range> WantDef;
     if (!T.ranges().empty())
       WantDecl = WantDef = T.range();
     if (!T.ranges("decl").empty())
@@ -1179,7 +1179,7 @@ TEST(LocateSymbol, Warnings) {
     } else {
       ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
       EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
-      llvm::Optional<Range> GotDef;
+      std::optional<Range> GotDef;
       if (Results[0].Definition)
         GotDef = Results[0].Definition->range;
       EXPECT_EQ(WantDef, GotDef) << Test;
@@ -1233,7 +1233,7 @@ TEST(LocateSymbol, Textual) {
 
   for (const char *Test : Tests) {
     Annotations T(Test);
-    llvm::Optional<Range> WantDecl;
+    std::optional<Range> WantDecl;
     if (!T.ranges().empty())
       WantDecl = T.range();
 
@@ -1731,7 +1731,7 @@ TEST(LocateSymbol, NearbyIdentifier) {
     Annotations T(Test);
     auto AST = TestTU::withCode(T.code()).build();
     const auto &SM = AST.getSourceManager();
-    llvm::Optional<Range> Nearby;
+    std::optional<Range> Nearby;
     auto Word =
         SpelledWord::touching(cantFail(sourceLocationInMainFile(SM, T.point())),
                               AST.getTokens(), AST.getLangOpts());
@@ -2379,7 +2379,7 @@ TEST(FindReferences, NeedsIndexForMacro) {
 
 TEST(FindReferences, NoQueryForLocalSymbols) {
   struct RecordingIndex : public MemIndex {
-    mutable Optional<llvm::DenseSet<SymbolID>> RefIDs;
+    mutable std::optional<llvm::DenseSet<SymbolID>> RefIDs;
     bool refs(const RefsRequest &Req,
               llvm::function_ref<void(const Ref &)>) const override {
       RefIDs = Req.IDs;

diff  --git a/clang-tools-extra/clangd/unittests/support/FileCacheTests.cpp b/clang-tools-extra/clangd/unittests/support/FileCacheTests.cpp
index 133b83ba93fd1..840cad623d776 100644
--- a/clang-tools-extra/clangd/unittests/support/FileCacheTests.cpp
+++ b/clang-tools-extra/clangd/unittests/support/FileCacheTests.cpp
@@ -41,7 +41,7 @@ class TestCache : public FileCache {
     std::string Result;
     read(
         FS, FreshTime,
-        [&](llvm::Optional<llvm::StringRef> Data) {
+        [&](std::optional<llvm::StringRef> Data) {
           GotParse = true;
           Value = Data.value_or("").str();
         },

diff  --git a/clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp b/clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp
index 12836d0926e23..ee93436d708d2 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp
@@ -61,10 +61,10 @@ llvm::Annotations::Range rangeOrPoint(const llvm::Annotations &A) {
 
 // Prepare and apply the specified tweak based on the selection in Input.
 // Returns std::nullopt if and only if prepare() failed.
-llvm::Optional<llvm::Expected<Tweak::Effect>>
+std::optional<llvm::Expected<Tweak::Effect>>
 applyTweak(ParsedAST &AST, llvm::Annotations::Range Range, StringRef TweakID,
            const SymbolIndex *Index, llvm::vfs::FileSystem *FS) {
-  llvm::Optional<llvm::Expected<Tweak::Effect>> Result;
+  std::optional<llvm::Expected<Tweak::Effect>> Result;
   SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Range.Begin,
                             Range.End, [&](SelectionTree ST) {
                               Tweak::Selection S(Index, AST, Range.Begin,

diff  --git a/clang-tools-extra/clangd/xpc/XPCTransport.cpp b/clang-tools-extra/clangd/xpc/XPCTransport.cpp
index dac8e29efae1d..8f5b787f8f710 100644
--- a/clang-tools-extra/clangd/xpc/XPCTransport.cpp
+++ b/clang-tools-extra/clangd/xpc/XPCTransport.cpp
@@ -107,12 +107,13 @@ class XPCTransport : public Transport {
 bool XPCTransport::handleMessage(json::Value Message, MessageHandler &Handler) {
   // Message must be an object with "jsonrpc":"2.0".
   auto *Object = Message.getAsObject();
-  if (!Object || Object->getString("jsonrpc") != Optional<StringRef>("2.0")) {
+  if (!Object ||
+      Object->getString("jsonrpc") != std::optional<StringRef>("2.0")) {
     elog("Not a JSON-RPC 2.0 message: {0:2}", Message);
     return false;
   }
   // ID may be any JSON value. If absent, this is a notification.
-  Optional<json::Value> ID;
+  std::optional<json::Value> ID;
   if (auto *I = Object->get("id"))
     ID = std::move(*I);
   auto Method = Object->getString("method");

diff  --git a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unchecked-optional-access.rst b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unchecked-optional-access.rst
index 6e9a4e02e6d0e..256cb6d05e254 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unchecked-optional-access.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unchecked-optional-access.rst
@@ -8,7 +8,7 @@ results. Therefore, it may be more resource intensive (RAM, CPU) than the
 average clang-tidy check.
 
 This check identifies unsafe accesses to values contained in
-``std::optional<T>``, ``absl::optional<T>``, or ``base::Optional<T>``
+``std::optional<T>``, ``absl::optional<T>``, or ``base::std::optional<T>``
 objects. Below we will refer to all these types collectively as
 ``optional<T>``.
 

diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h b/clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h
index e8f4240b8fa3e..aeca616414c24 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h
@@ -83,7 +83,7 @@ struct DirectiveTree {
     /// None indicates no branch was taken (e.g. #if 0 ... #endif).
     /// The initial tree from `parse()` has no branches marked as taken.
     /// See `chooseConditionalBranches()`.
-    llvm::Optional<unsigned> Taken;
+    std::optional<unsigned> Taken;
   };
 
   /// Some piece of the file. {One of Code, Directive, Conditional}.

diff  --git a/clang-tools-extra/pseudo/lib/DirectiveTree.cpp b/clang-tools-extra/pseudo/lib/DirectiveTree.cpp
index 4e866815e63be..9e853e46edc23 100644
--- a/clang-tools-extra/pseudo/lib/DirectiveTree.cpp
+++ b/clang-tools-extra/pseudo/lib/DirectiveTree.cpp
@@ -48,7 +48,7 @@ class DirectiveParser {
   // If we reach an End or Else directive that ends Tree, returns it.
   // If TopLevel is true, then we do not expect End and always return
   // std::nullopt.
-  llvm::Optional<DirectiveTree::Directive> parse(DirectiveTree *Tree,
+  std::optional<DirectiveTree::Directive> parse(DirectiveTree *Tree,
                                                 bool TopLevel) {
     auto StartsDirective =
         [&, AllowDirectiveAt((const Token *)nullptr)]() mutable {
@@ -286,7 +286,7 @@ class BranchChooser {
 private:
   // Return true if the directive starts an always-taken conditional branch,
   // false if the branch is never taken, and std::nullopt otherwise.
-  llvm::Optional<bool> isTakenWhenReached(const DirectiveTree::Directive &Dir) {
+  std::optional<bool> isTakenWhenReached(const DirectiveTree::Directive &Dir) {
     switch (Dir.Kind) {
     case clang::tok::pp_if:
     case clang::tok::pp_elif:
@@ -304,7 +304,7 @@ class BranchChooser {
     // Does the condition consist of exactly one token?
     if (&Value >= Tokens.end() || &Value.nextNC() < Tokens.end())
       return std::nullopt;
-    return llvm::StringSwitch<llvm::Optional<bool>>(Value.text())
+    return llvm::StringSwitch<std::optional<bool>>(Value.text())
         .Cases("true", "1", true)
         .Cases("false", "0", false)
         .Default(std::nullopt);

diff  --git a/clang-tools-extra/pseudo/lib/Forest.cpp b/clang-tools-extra/pseudo/lib/Forest.cpp
index e6b2d2ec0f902..6162e02dab490 100644
--- a/clang-tools-extra/pseudo/lib/Forest.cpp
+++ b/clang-tools-extra/pseudo/lib/Forest.cpp
@@ -94,11 +94,10 @@ std::string ForestNode::dumpRecursive(const Grammar &G,
   llvm::DenseMap<const ForestNode *, size_t> ReferenceIds;
   std::string Result;
   constexpr Token::Index KEnd = std::numeric_limits<Token::Index>::max();
-  std::function<void(const ForestNode *, Token::Index, llvm::Optional<SymbolID>,
+  std::function<void(const ForestNode *, Token::Index, std::optional<SymbolID>,
                      LineDecoration &LineDec)>
       Dump = [&](const ForestNode *P, Token::Index End,
-                 llvm::Optional<SymbolID> ElidedParent,
-                 LineDecoration LineDec) {
+                 std::optional<SymbolID> ElidedParent, LineDecoration LineDec) {
         bool SharedNode = VisitCounts.find(P)->getSecond() > 1;
         llvm::ArrayRef<const ForestNode *> Children;
         auto EndOfElement = [&](size_t ChildIndex) {

diff  --git a/clang-tools-extra/pseudo/lib/GLR.cpp b/clang-tools-extra/pseudo/lib/GLR.cpp
index a4169dd96f4aa..35a81810de63b 100644
--- a/clang-tools-extra/pseudo/lib/GLR.cpp
+++ b/clang-tools-extra/pseudo/lib/GLR.cpp
@@ -134,7 +134,7 @@ void glrRecover(llvm::ArrayRef<const GSS::Node *> OldHeads,
   });
 
   // We may find multiple winners, but they will have the same range.
-  llvm::Optional<Token::Range> RecoveryRange;
+  std::optional<Token::Range> RecoveryRange;
   std::vector<const PlaceholderRecovery *> BestOptions;
   for (const PlaceholderRecovery &Option : Options) {
     // If this starts further left than options we've already found, then
@@ -564,7 +564,7 @@ class GLRReduce {
     if (!Sequences.empty() || Heads->size() != NextPopHead + 1)
       return false;
     const GSS::Node *Head = Heads->back();
-    llvm::Optional<RuleID> RID;
+    std::optional<RuleID> RID;
     for (RuleID R : Lang.Table.getReduceRules(Head->State)) {
       if (RID.has_value())
         return false;

diff  --git a/clang-tools-extra/pseudo/tool/ClangPseudo.cpp b/clang-tools-extra/pseudo/tool/ClangPseudo.cpp
index c22ea171c96cc..6a64760749cef 100644
--- a/clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ b/clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -108,9 +108,9 @@ int main(int argc, char *argv[]) {
 
   clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
   std::string SourceText;
-  llvm::Optional<clang::pseudo::TokenStream> RawStream;
-  llvm::Optional<TokenStream> PreprocessedStream;
-  llvm::Optional<clang::pseudo::TokenStream> ParseableStream;
+  std::optional<clang::pseudo::TokenStream> RawStream;
+  std::optional<TokenStream> PreprocessedStream;
+  std::optional<clang::pseudo::TokenStream> ParseableStream;
   if (Source.getNumOccurrences()) {
     SourceText = readOrDie(Source);
     RawStream = clang::pseudo::lex(SourceText, LangOpts);
@@ -119,7 +119,7 @@ int main(int argc, char *argv[]) {
     auto DirectiveStructure = clang::pseudo::DirectiveTree::parse(*RawStream);
     clang::pseudo::chooseConditionalBranches(DirectiveStructure, *RawStream);
 
-    llvm::Optional<TokenStream> Preprocessed;
+    std::optional<TokenStream> Preprocessed;
     if (StripDirectives) {
       Preprocessed = DirectiveStructure.stripDirectives(*Stream);
       Stream = &*Preprocessed;
@@ -151,7 +151,7 @@ int main(int argc, char *argv[]) {
   if (ParseableStream) {
     clang::pseudo::ForestArena Arena;
     clang::pseudo::GSS GSS;
-    llvm::Optional<clang::pseudo::SymbolID> StartSymID =
+    std::optional<clang::pseudo::SymbolID> StartSymID =
         Lang.G.findNonterminal(StartSymbol);
     if (!StartSymID) {
       llvm::errs() << llvm::formatv(

diff  --git a/clang-tools-extra/unittests/clang-tidy/AddConstTest.cpp b/clang-tools-extra/unittests/clang-tidy/AddConstTest.cpp
index 437d9b4df8fe0..dfae25f3f26eb 100644
--- a/clang-tools-extra/unittests/clang-tidy/AddConstTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/AddConstTest.cpp
@@ -27,7 +27,7 @@ class ConstTransform : public ClangTidyCheck {
   void check(const MatchFinder::MatchResult &Result) override {
     const auto *D = Result.Nodes.getNodeAs<VarDecl>("var");
     using utils::fixit::addQualifierToVarDecl;
-    Optional<FixItHint> Fix = addQualifierToVarDecl(
+    std::optional<FixItHint> Fix = addQualifierToVarDecl(
         *D, *Result.Context, DeclSpec::TQ::TQ_const, CT, CP);
     auto Diag = diag(D->getBeginLoc(), "doing const transformation");
     if (Fix)

diff  --git a/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp b/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
index d861e86284b3a..36b7d1b8065c7 100644
--- a/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
@@ -168,7 +168,7 @@ class DiagCollecter {
     std::string Message;
     llvm::SourceMgr::DiagKind Kind;
     size_t Pos;
-    Optional<llvm::Annotations::Range> Range;
+    std::optional<llvm::Annotations::Range> Range;
 
     friend void PrintTo(const Diag &D, std::ostream *OS) {
       *OS << (D.Kind == llvm::SourceMgr::DK_Error ? "error: " : "warning: ")

diff  --git a/clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp b/clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
index 964f5f74a2bf1..278d435c01ab7 100644
--- a/clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
@@ -15,7 +15,7 @@ namespace test {
 
 template <typename T>
 static std::string runCheck(StringRef Code, const Twine &Filename,
-                            Optional<StringRef> ExpectedWarning,
+                            std::optional<StringRef> ExpectedWarning,
                             std::map<StringRef, StringRef> PathsToContent =
                                 std::map<StringRef, StringRef>()) {
   std::vector<ClangTidyError> Errors;
@@ -30,15 +30,16 @@ static std::string runCheck(StringRef Code, const Twine &Filename,
   return Result;
 }
 
-static std::string runHeaderGuardCheck(StringRef Code, const Twine &Filename,
-                                       Optional<StringRef> ExpectedWarning) {
+static std::string
+runHeaderGuardCheck(StringRef Code, const Twine &Filename,
+                    std::optional<StringRef> ExpectedWarning) {
   return runCheck<LLVMHeaderGuardCheck>(Code, Filename,
                                         std::move(ExpectedWarning));
 }
 
 static std::string
 runIncludeOrderCheck(StringRef Code, const Twine &Filename,
-                     Optional<StringRef> ExpectedWarning,
+                     std::optional<StringRef> ExpectedWarning,
                      llvm::ArrayRef<llvm::StringLiteral> Includes) {
   std::map<StringRef, StringRef> PathsToContent;
   for (auto Include : Includes)
@@ -56,7 +57,7 @@ struct WithEndifComment : public LLVMHeaderGuardCheck {
 
 static std::string
 runHeaderGuardCheckWithEndif(StringRef Code, const Twine &Filename,
-                             Optional<StringRef> ExpectedWarning) {
+                             std::optional<StringRef> ExpectedWarning) {
   return runCheck<WithEndifComment>(Code, Filename, std::move(ExpectedWarning));
 }
 } // namespace

diff  --git a/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp b/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
index 873259414b74f..42d40d32bfa51 100644
--- a/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -211,7 +211,7 @@ TEST(TransformerClangTidyCheckTest, TwoMatchesInMacroExpansion) {
 }
 
 // A trivial rewrite-rule generator that requires Objective-C code.
-Optional<RewriteRuleWith<std::string>>
+std::optional<RewriteRuleWith<std::string>>
 needsObjC(const LangOptions &LangOpts,
           const ClangTidyCheck::OptionsView &Options) {
   if (!LangOpts.ObjC)
@@ -237,7 +237,7 @@ TEST(TransformerClangTidyCheckTest, DisableByLang) {
 }
 
 // A trivial rewrite rule generator that checks config options.
-Optional<RewriteRuleWith<std::string>>
+std::optional<RewriteRuleWith<std::string>>
 noSkip(const LangOptions &LangOpts,
        const ClangTidyCheck::OptionsView &Options) {
   if (Options.get("Skip", "false") == "true")


        


More information about the cfe-commits mailing list